context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/* ====================================================================
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 TestCases.HSSF.UserModel
{
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NUnit.Framework;
/**
* Tests the capabilities of the EscherGraphics class.
*
* All Tests have two escher groups available to them,
* one anchored at 0,0,1022,255 and another anchored
* at 20,30,500,200
*
* @author Glen Stampoultzis (glens at apache.org)
*/
[TestFixture]
public class TestEscherGraphics
{
private HSSFWorkbook workbook;
private HSSFPatriarch patriarch;
private HSSFShapeGroup escherGroupA;
private HSSFShapeGroup escherGroupB;
private EscherGraphics graphics;
[SetUp]
public void SetUp()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
workbook = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Test");
patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
escherGroupA = patriarch.CreateGroup(new HSSFClientAnchor(0, 0, 1022, 255, (short)0, 0, (short)0, 0));
escherGroupB = patriarch.CreateGroup(new HSSFClientAnchor(20, 30, 500, 200, (short)0, 0, (short)0, 0));
// escherGroup = new HSSFShapeGroup(null, new HSSFChildAnchor());
graphics = new EscherGraphics(this.escherGroupA, workbook, System.Drawing.Color.Black, 1.0f);
}
[Test]
public void TestGetFont()
{
System.Drawing.Font f = graphics.Font;
if (f.ToString().IndexOf("dialog") == -1 && f.ToString().IndexOf("Dialog") == -1)
{
//Assert.AreEqual("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", f.ToString());
Assert.AreEqual("[Font: Name=Arial, Size=10, Units=3, GdiCharSet=1, GdiVerticalFont=False]", f.ToString());
}
}
//public void TestGetFontMetrics()
//{
// Font f = graphics.Font;
// if (f.ToString().IndexOf("dialog") != -1 || f.ToString().IndexOf("Dialog") != -1)
// return;
// FontMetrics fontMetrics = graphics.GetFontMetrics(graphics.Font);
// Assert.AreEqual(7, fontMetrics.charWidth('X'));
// Assert.AreEqual("java.awt.Font[family=Arial,name=Arial,style=plain,size=10]", fontMetrics.GetFont().ToString());
//}
[Test]
public void TestSetFont()
{
System.Drawing.Font f = new System.Drawing.Font("Helvetica", 12,FontStyle.Regular);
graphics.SetFont(f);
Assert.AreEqual(f, graphics.Font);
}
[Test]
public void TestSetColor()
{
graphics.SetColor(System.Drawing.Color.Red);
Assert.AreEqual(System.Drawing.Color.Red, graphics.Color);
}
[Test]
public void TestFillRect()
{
graphics.FillRect(10, 10, 20, 20);
HSSFSimpleShape s = (HSSFSimpleShape)escherGroupA.Children[0];
Assert.AreEqual(HSSFSimpleShape.OBJECT_TYPE_RECTANGLE, s.ShapeType);
Assert.AreEqual(10, s.Anchor.Dx1);
Assert.AreEqual(10, s.Anchor.Dy1);
Assert.AreEqual(30, s.Anchor.Dy2);
Assert.AreEqual(30, s.Anchor.Dx2);
}
[Test]
public void TestDrawString()
{
graphics.DrawString("This is a Test", 10, 10);
HSSFTextbox t = (HSSFTextbox)escherGroupA.Children[0];
Assert.AreEqual("This is a Test", t.String.String.ToString());
}
[Test]
public void TestGetDataBackAgain()
{
HSSFSheet s;
HSSFShapeGroup s1;
HSSFShapeGroup s2;
patriarch.SetCoordinates(10, 20, 30, 40);
MemoryStream baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(0, s1.X1);
Assert.AreEqual(0, s1.Y1);
Assert.AreEqual(1023, s1.X2);
Assert.AreEqual(255, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Write and re-load once more, to Check that's ok
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(0, s1.X1);
Assert.AreEqual(0, s1.Y1);
Assert.AreEqual(1023, s1.X2);
Assert.AreEqual(255, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Change the positions of the first groups,
// but not of their anchors
s1.SetCoordinates(2, 3, 1021, 242);
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s =(HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups too
Assert.AreEqual(2, patriarch.CountOfAllChildren);
Assert.AreEqual(2, patriarch.Children.Count);
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
s1 = (HSSFShapeGroup)patriarch.Children[0];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(2, s1.X1);
Assert.AreEqual(3, s1.Y1);
Assert.AreEqual(1021, s1.X2);
Assert.AreEqual(242, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Now Add some text to one group, and some more
// to the base, and Check we can get it back again
HSSFTextbox tbox1 =
patriarch.CreateTextbox(new HSSFClientAnchor(1, 2, 3, 4, (short)0, 0, (short)0, 0)) as HSSFTextbox;
tbox1.String = (new HSSFRichTextString("I am text box 1"));
HSSFTextbox tbox2 =
s2.CreateTextbox(new HSSFChildAnchor(41, 42, 43, 44)) as HSSFTextbox;
tbox2.String = (new HSSFRichTextString("This is text box 2"));
Assert.AreEqual(3, patriarch.Children.Count);
baos = new MemoryStream();
workbook.Write(baos);
workbook = new HSSFWorkbook(new MemoryStream(baos.ToArray()));
s = (HSSFSheet)workbook.GetSheetAt(0);
patriarch = (HSSFPatriarch)s.DrawingPatriarch;
Assert.IsNotNull(patriarch);
Assert.AreEqual(10, patriarch.X1);
Assert.AreEqual(20, patriarch.Y1);
Assert.AreEqual(30, patriarch.X2);
Assert.AreEqual(40, patriarch.Y2);
// Check the two groups and the text
// Result of patriarch.countOfAllChildren() makes no sense:
// Returns 4 for 2 empty groups + 1 TextBox.
//Assert.AreEqual(3, patriarch.CountOfAllChildren);
Assert.AreEqual(3, patriarch.Children.Count);
// Should be two groups and a text
Assert.IsTrue(patriarch.Children[0] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[1] is HSSFShapeGroup);
Assert.IsTrue(patriarch.Children[2] is HSSFTextbox);
s1 = (HSSFShapeGroup)patriarch.Children[0];
tbox1 = (HSSFTextbox)patriarch.Children[2];
s2 = (HSSFShapeGroup)patriarch.Children[1];
Assert.AreEqual(2, s1.X1);
Assert.AreEqual(3, s1.Y1);
Assert.AreEqual(1021, s1.X2);
Assert.AreEqual(242, s1.Y2);
Assert.AreEqual(0, s2.X1);
Assert.AreEqual(0, s2.Y1);
Assert.AreEqual(1023, s2.X2);
Assert.AreEqual(255, s2.Y2);
Assert.AreEqual(0, s1.Anchor.Dx1);
Assert.AreEqual(0, s1.Anchor.Dy1);
Assert.AreEqual(1022, s1.Anchor.Dx2);
Assert.AreEqual(255, s1.Anchor.Dy2);
Assert.AreEqual(20, s2.Anchor.Dx1);
Assert.AreEqual(30, s2.Anchor.Dy1);
Assert.AreEqual(500, s2.Anchor.Dx2);
Assert.AreEqual(200, s2.Anchor.Dy2);
// Not working just yet
//Assert.AreEqual("I am text box 1", tbox1.String.String);
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ZXing.Common;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// This produces nearly optimal encodings of text into the first-level of
/// encoding used by Aztec code.
/// It uses a dynamic algorithm. For each prefix of the string, it determines
/// a set of encodings that could lead to this prefix. We repeatedly add a
/// character and generate a new set of optimal encodings until we have read
/// through the entire input.
/// @author Frank Yellin
/// @author Rustam Abdullaev
/// </summary>
public sealed class HighLevelEncoder
{
internal static String[] MODE_NAMES = {"UPPER", "LOWER", "DIGIT", "MIXED", "PUNCT"};
internal const int MODE_UPPER = 0; // 5 bits
internal const int MODE_LOWER = 1; // 5 bits
internal const int MODE_DIGIT = 2; // 4 bits
internal const int MODE_MIXED = 3; // 5 bits
internal const int MODE_PUNCT = 4; // 5 bits
// The Latch Table shows, for each pair of Modes, the optimal method for
// getting from one mode to another. In the worst possible case, this can
// be up to 14 bits. In the best possible case, we are already there!
// The high half-word of each entry gives the number of bits.
// The low half-word of each entry are the actual bits necessary to change
internal static readonly int[][] LATCH_TABLE = new int[][]
{
new[]
{
0,
(5 << 16) + 28, // UPPER -> LOWER
(5 << 16) + 30, // UPPER -> DIGIT
(5 << 16) + 29, // UPPER -> MIXED
(10 << 16) + (29 << 5) + 30, // UPPER -> MIXED -> PUNCT
},
new[]
{
(9 << 16) + (30 << 4) + 14, // LOWER -> DIGIT -> UPPER
0,
(5 << 16) + 30, // LOWER -> DIGIT
(5 << 16) + 29, // LOWER -> MIXED
(10 << 16) + (29 << 5) + 30, // LOWER -> MIXED -> PUNCT
},
new[]
{
(4 << 16) + 14, // DIGIT -> UPPER
(9 << 16) + (14 << 5) + 28, // DIGIT -> UPPER -> LOWER
0,
(9 << 16) + (14 << 5) + 29, // DIGIT -> UPPER -> MIXED
(14 << 16) + (14 << 10) + (29 << 5) + 30,
// DIGIT -> UPPER -> MIXED -> PUNCT
},
new[]
{
(5 << 16) + 29, // MIXED -> UPPER
(5 << 16) + 28, // MIXED -> LOWER
(10 << 16) + (29 << 5) + 30, // MIXED -> UPPER -> DIGIT
0,
(5 << 16) + 30, // MIXED -> PUNCT
},
new[]
{
(5 << 16) + 31, // PUNCT -> UPPER
(10 << 16) + (31 << 5) + 28, // PUNCT -> UPPER -> LOWER
(10 << 16) + (31 << 5) + 30, // PUNCT -> UPPER -> DIGIT
(10 << 16) + (31 << 5) + 29, // PUNCT -> UPPER -> MIXED
0,
},
};
// A reverse mapping from [mode][char] to the encoding for that character
// in that mode. An entry of 0 indicates no mapping exists.
internal static readonly int[][] CHAR_MAP = new int[5][];
// A map showing the available shift codes. (The shifts to BINARY are not shown
internal static readonly int[][] SHIFT_TABLE = new int[6][]; // mode shift codes, per table
private readonly byte[] text;
static HighLevelEncoder()
{
CHAR_MAP[0] = new int[256];
CHAR_MAP[1] = new int[256];
CHAR_MAP[2] = new int[256];
CHAR_MAP[3] = new int[256];
CHAR_MAP[4] = new int[256];
SHIFT_TABLE[0] = new int[6];
SHIFT_TABLE[1] = new int[6];
SHIFT_TABLE[2] = new int[6];
SHIFT_TABLE[3] = new int[6];
SHIFT_TABLE[4] = new int[6];
SHIFT_TABLE[5] = new int[6];
CHAR_MAP[MODE_UPPER][' '] = 1;
for (int c = 'A'; c <= 'Z'; c++)
{
CHAR_MAP[MODE_UPPER][c] = c - 'A' + 2;
}
CHAR_MAP[MODE_LOWER][' '] = 1;
for (int c = 'a'; c <= 'z'; c++)
{
CHAR_MAP[MODE_LOWER][c] = c - 'a' + 2;
}
CHAR_MAP[MODE_DIGIT][' '] = 1;
for (int c = '0'; c <= '9'; c++)
{
CHAR_MAP[MODE_DIGIT][c] = c - '0' + 2;
}
CHAR_MAP[MODE_DIGIT][','] = 12;
CHAR_MAP[MODE_DIGIT]['.'] = 13;
int[] mixedTable = {
'\0', ' ', 1, 2, 3, 4, 5, 6, 7, '\b', '\t', '\n', 11, '\f', '\r',
27, 28, 29, 30, 31, '@', '\\', '^', '_', '`', '|', '~', 127
};
for (int i = 0; i < mixedTable.Length; i++)
{
CHAR_MAP[MODE_MIXED][mixedTable[i]] = i;
}
int[] punctTable =
{
'\0', '\r', '\0', '\0', '\0', '\0', '!', '\'', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?',
'[', ']', '{', '}'
};
for (int i = 0; i < punctTable.Length; i++)
{
if (punctTable[i] > 0)
{
CHAR_MAP[MODE_PUNCT][punctTable[i]] = i;
}
}
foreach (int[] table in SHIFT_TABLE)
{
SupportClass.Fill(table, -1);
}
SHIFT_TABLE[MODE_UPPER][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_LOWER][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_LOWER][MODE_UPPER] = 28;
SHIFT_TABLE[MODE_MIXED][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT] = 0;
SHIFT_TABLE[MODE_DIGIT][MODE_UPPER] = 15;
}
public HighLevelEncoder(byte[] text)
{
this.text = text;
}
/// <summary>
/// Convert the text represented by this High Level Encoder into a BitArray.
/// </summary>
/// <returns>text represented by this encoder encoded as a <see cref="BitArray"/></returns>
public BitArray encode()
{
ICollection<State> states = new Collection<State>();
states.Add(State.INITIAL_STATE);
for (int index = 0; index < text.Length; index++)
{
int pairCode;
// don't remove the (int) type cast, mono compiler needs it
int nextChar = (index + 1 < text.Length) ? (int)text[index + 1] : 0;
switch (text[index])
{
case (byte)'\r':
pairCode = nextChar == '\n' ? 2 : 0;
break;
case (byte)'.':
pairCode = nextChar == ' ' ? 3 : 0;
break;
case (byte)',':
pairCode = nextChar == ' ' ? 4 : 0;
break;
case (byte)':':
pairCode = nextChar == ' ' ? 5 : 0;
break;
default:
pairCode = 0;
break;
}
if (pairCode > 0)
{
// We have one of the four special PUNCT pairs. Treat them specially.
// Get a new set of states for the two new characters.
states = updateStateListForPair(states, index, pairCode);
index++;
}
else
{
// Get a new set of states for the new character.
states = updateStateListForChar(states, index);
}
}
// We are left with a set of states. Find the shortest one.
State minState = null;
foreach (var state in states)
{
if (minState == null)
{
minState = state;
}
else
{
if (state.BitCount < minState.BitCount)
{
minState = state;
}
}
}
/*
State minState = Collections.min(states, new Comparator<State>() {
@Override
public int compare(State a, State b) {
return a.getBitCount() - b.getBitCount();
}
});
*/
// Convert it to a bit array, and return.
return minState.toBitArray(text);
}
// We update a set of states for a new character by updating each state
// for the new character, merging the results, and then removing the
// non-optimal states.
private ICollection<State> updateStateListForChar(IEnumerable<State> states, int index)
{
var result = new LinkedList<State>();
foreach (State state in states)
{
updateStateForChar(state, index, result);
}
return simplifyStates(result);
}
// Return a set of states that represent the possible ways of updating this
// state for the next character. The resulting set of states are added to
// the "result" list.
private void updateStateForChar(State state, int index, ICollection<State> result)
{
char ch = (char) (text[index] & 0xFF);
bool charInCurrentTable = CHAR_MAP[state.Mode][ch] > 0;
State stateNoBinary = null;
for (int mode = 0; mode <= MODE_PUNCT; mode++)
{
int charInMode = CHAR_MAP[mode][ch];
if (charInMode > 0)
{
if (stateNoBinary == null)
{
// Only create stateNoBinary the first time it's required.
stateNoBinary = state.endBinaryShift(index);
}
// Try generating the character by latching to its mode
if (!charInCurrentTable || mode == state.Mode || mode == MODE_DIGIT)
{
// If the character is in the current table, we don't want to latch to
// any other mode except possibly digit (which uses only 4 bits). Any
// other latch would be equally successful *after* this character, and
// so wouldn't save any bits.
var latchState = stateNoBinary.latchAndAppend(mode, charInMode);
result.Add(latchState);
}
// Try generating the character by switching to its mode.
if (!charInCurrentTable && SHIFT_TABLE[state.Mode][mode] >= 0)
{
// It never makes sense to temporarily shift to another mode if the
// character exists in the current mode. That can never save bits.
var shiftState = stateNoBinary.shiftAndAppend(mode, charInMode);
result.Add(shiftState);
}
}
}
if (state.BinaryShiftByteCount > 0 || CHAR_MAP[state.Mode][ch] == 0)
{
// It's never worthwhile to go into binary shift mode if you're not already
// in binary shift mode, and the character exists in your current mode.
// That can never save bits over just outputting the char in the current mode.
var binaryState = state.addBinaryShiftChar(index);
result.Add(binaryState);
}
}
private static ICollection<State> updateStateListForPair(IEnumerable<State> states, int index, int pairCode)
{
var result = new LinkedList<State>();
foreach (State state in states)
{
updateStateForPair(state, index, pairCode, result);
}
return simplifyStates(result);
}
private static void updateStateForPair(State state, int index, int pairCode, ICollection<State> result)
{
State stateNoBinary = state.endBinaryShift(index);
// Possibility 1. Latch to MODE_PUNCT, and then append this code
result.Add(stateNoBinary.latchAndAppend(MODE_PUNCT, pairCode));
if (state.Mode != MODE_PUNCT)
{
// Possibility 2. Shift to MODE_PUNCT, and then append this code.
// Every state except MODE_PUNCT (handled above) can shift
result.Add(stateNoBinary.shiftAndAppend(MODE_PUNCT, pairCode));
}
if (pairCode == 3 || pairCode == 4)
{
// both characters are in DIGITS. Sometimes better to just add two digits
var digitState = stateNoBinary
.latchAndAppend(MODE_DIGIT, 16 - pairCode) // period or comma in DIGIT
.latchAndAppend(MODE_DIGIT, 1); // space in DIGIT
result.Add(digitState);
}
if (state.BinaryShiftByteCount > 0)
{
// It only makes sense to do the characters as binary if we're already
// in binary mode.
State binaryState = state.addBinaryShiftChar(index).addBinaryShiftChar(index + 1);
result.Add(binaryState);
}
}
private static ICollection<State> simplifyStates(IEnumerable<State> states)
{
var result = new LinkedList<State>();
var removeList = new List<State>();
foreach (State newState in states)
{
bool add = true;
removeList.Clear();
foreach (var oldState in result)
{
if (oldState.isBetterThanOrEqualTo(newState))
{
add = false;
break;
}
if (newState.isBetterThanOrEqualTo(oldState))
{
removeList.Add(oldState);
}
}
if (add)
{
result.AddLast(newState);
}
foreach (var removeItem in removeList)
{
result.Remove(removeItem);
}
}
return result;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkSecurityGroupsOperations operations.
/// </summary>
public partial interface INetworkSecurityGroupsOperations
{
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network security group in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network security group in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;
using StructureMap.Graph;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class DynamicInjectionTester
{
private readonly IService _red = new ColorService("Red");
private readonly IService _blue = new ColorService("Blue");
private readonly IService _orange = new ColorService("Orange");
public interface IService<T>
{
}
public class Service1<T> : IService<T>
{
}
public class Service2<T> : IService<T>
{
}
public class Service3<T> : IService<T>
{
}
public interface IOtherService<T>
{
}
public class Service4 : IOtherService<string>
{
}
//[PluginFamily("Default")]
public interface IThingy
{
}
//[Pluggable("Default")]
public class TheThingy : IThingy
{
}
public class TheWidget : IWidget
{
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
[Test]
public void AddANewDefaultTypeForAPluginTypeThatAlreadyExists()
{
var container = new Container(x => x.For<ISomething>().Use<SomethingTwo>());
container.Configure(x => x.For<ISomething>().Use<SomethingOne>());
container.GetInstance<ISomething>().ShouldBeOfType<SomethingOne>();
}
[Test]
public void AddANewDefaultTypeForAPluginTypeThatAlreadyExists2()
{
var container = new Container(x => { x.For<ISomething>(); });
container.Configure(x => { x.For<ISomething>().Use<SomethingOne>(); });
container.GetInstance<ISomething>().ShouldBeOfType<SomethingOne>();
}
[Test]
public void AddInstanceFromContainer()
{
var one = new SomethingOne();
var container = new Container();
container.Inject<ISomething>(one);
one.ShouldBeTheSameAs(container.GetInstance<ISomething>());
}
[Test]
public void AddInstanceToInstanceManagerWhenTheInstanceFactoryDoesNotExist()
{
IContainer container = new Container(new PluginGraph());
container.Configure(r =>
{
r.For<IService>().AddInstances(x =>
{
x.Object(_red).Named("Red");
x.Object(_blue).Named("Blue");
});
});
_red.ShouldBeTheSameAs(container.GetInstance(typeof (IService), "Red"));
_blue.ShouldBeTheSameAs(container.GetInstance(typeof (IService), "Blue"));
}
[Test]
public void AddNamedInstanceByType()
{
var container = new Container(r =>
{
r.For<ISomething>().AddInstances(x =>
{
x.Type<SomethingOne>().Named("One");
x.Type<SomethingTwo>().Named("Two");
});
});
container.GetInstance<ISomething>("One").ShouldBeOfType<SomethingOne>();
container.GetInstance<ISomething>("Two").ShouldBeOfType<SomethingTwo>();
}
[Test]
public void AddNamedInstanceToobjectFactory()
{
var one = new SomethingOne();
var two = new SomethingOne();
var container = new Container(r =>
{
r.For<ISomething>().AddInstances(x =>
{
x.Object(one).Named("One");
x.Object(two).Named("Two");
});
});
one.ShouldBeTheSameAs(container.GetInstance<ISomething>("One"));
two.ShouldBeTheSameAs(container.GetInstance<ISomething>("Two"));
}
[Test]
public void AddPluginForTypeWhenThePluginDoesNotAlreadyExistsDoesNothing()
{
var pluginGraph = new PluginGraph();
IContainer container = new Container(pluginGraph);
container.Configure(
r => { r.For<ISomething>().Use<SomethingOne>(); });
container.GetAllInstances<ISomething>()
.Single()
.ShouldBeOfType<SomethingOne>();
}
[Test]
public void AddTypeThroughContainer()
{
var container = new Container(x => { x.For<ISomething>().Use<SomethingOne>(); });
container.GetInstance<ISomething>().ShouldBeOfType<SomethingOne>();
}
[Test]
public void Add_an_assembly_in_the_Configure()
{
var container = new Container();
container.Configure(registry =>
{
registry.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<IThingy>();
});
});
container.GetInstance<IThingy>().ShouldBeOfType<TheThingy>();
}
[Test]
public void Add_an_assembly_on_the_fly_and_pick_up_plugins()
{
var container = new Container();
container.Configure(
registry => registry.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<IWidget>();
}));
container.GetAllInstances<IWidget>().OfType<TheWidget>().Any().ShouldBeTrue();
}
[Test]
public void Add_an_assembly_on_the_fly_and_pick_up_plugins3()
{
var container = new Container();
container.Configure(
registry =>
{
registry.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf(typeof (IWidget));
});
}
);
container.GetAllInstances<IWidget>()
.OfType<TheWidget>()
.Any().ShouldBeTrue();
}
[Test]
public void Add_an_assembly_on_the_fly_and_pick_up_plugins4()
{
var container = new Container();
container.Configure(
registry => registry.Scan(
x =>
{
x.AssemblyContainingType(typeof (IOtherService<>));
x.AddAllTypesOf(typeof (IOtherService<>));
}));
var instances = container.GetAllInstances<IOtherService<string>>();
instances.Any(s => s is Service4).ShouldBeTrue();
}
[Test]
public void Add_generic_stuff_in_configure()
{
var container = new Container();
container.Configure(registry =>
{
registry.For(typeof (IService<>)).Add(typeof (Service1<>));
registry.For(typeof (IService<>)).Add(typeof (Service2<>));
});
container.GetAllInstances<IService<string>>().Count().ShouldBe(2);
}
[Test]
public void InjectType()
{
var container = new Container(
r => r.For<ISomething>().Use<SomethingOne>());
container.GetAllInstances<ISomething>()
.Single()
.ShouldBeOfType<SomethingOne>();
}
[Test]
public void JustAddATypeWithNoNameAndDefault()
{
var container = new Container(x => { x.For<ISomething>().Use<SomethingOne>(); });
container.GetInstance<ISomething>().ShouldBeOfType<SomethingOne>();
}
[Test]
public void OverwriteInstanceFromObjectFactory()
{
var one = new SomethingOne();
var two = new SomethingOne();
var container = new Container();
container.Inject<ISomething>(one);
container.Inject<ISomething>(two);
two.ShouldBeTheSameAs(container.GetInstance<ISomething>());
}
}
public class SomethingOne : ISomething
{
public void Go()
{
throw new NotImplementedException();
}
}
public class SomethingTwo : ISomething
{
public void Go()
{
throw new NotImplementedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Foundation;
using Google.Core;
using Google.SignIn;
using Toggl.Phoebe;
using Toggl.Phoebe.Analytics;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Logging;
using Toggl.Phoebe.Net;
using Toggl.Ross.Analytics;
using Toggl.Ross.Data;
using Toggl.Ross.Logging;
using Toggl.Ross.Net;
using Toggl.Ross.ViewControllers;
using Toggl.Ross.Views;
using UIKit;
using Xamarin;
using XPlatUtils;
namespace Toggl.Ross
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public class AppDelegate : UIApplicationDelegate, IPlatformInfo
{
private TogglWindow window;
private int systemVersion;
private const int minVersionWidget = 7;
public UIApplicationShortcutItem LaunchedShortcutItem { get; set; }
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
var versionString = UIDevice.CurrentDevice.SystemVersion;
systemVersion = Convert.ToInt32 ( versionString.Split ( new [] {"."}, StringSplitOptions.None)[0]);
// Component initialisation.
RegisterComponents ();
// Setup Google sign in
SetupGoogleServices ();
Toggl.Ross.Theme.Style.Initialize ();
// Start app
window = new TogglWindow (UIScreen.MainScreen.Bounds);
window.RootViewController = new MainViewController ();
window.MakeKeyAndVisible ();
// Make sure critical services are running are running:
ServiceContainer.Resolve<UpgradeManger> ().TryUpgrade ();
ServiceContainer.Resolve<ILoggerClient> ();
ServiceContainer.Resolve<LoggerUserManager> ();
ServiceContainer.Resolve<ITracker> ();
ServiceContainer.Resolve<APNSManager> ();
ServiceContainer.Resolve<QuickActions> ();
if (launchOptions != null) {
LaunchedShortcutItem = launchOptions [UIApplication.LaunchOptionsShortcutItemKey] as UIApplicationShortcutItem;
}
return LaunchedShortcutItem == null;
}
public override void PerformActionForShortcutItem (UIApplication application, UIApplicationShortcutItem shortcutItem, UIOperationHandler completionHandler)
{
var quickActions = ServiceContainer.Resolve<QuickActions> ();
completionHandler (quickActions.HandleShortcut (shortcutItem));
}
public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
{
Task.Run (async () => {
var service = ServiceContainer.Resolve<APNSManager> ();
await service.RegisteredForRemoteNotificationsAsync (application, deviceToken);
});
}
public override void FailedToRegisterForRemoteNotifications (UIApplication application, NSError error)
{
ServiceContainer.Resolve<APNSManager> ().FailedToRegisterForRemoteNotifications (application, error);
}
public override void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
Task.Run (async () => {
var service = ServiceContainer.Resolve<APNSManager> ();
await service.DidReceiveRemoteNotificationAsync (application, userInfo, completionHandler);
});
}
public override void OnActivated (UIApplication application)
{
// Make sure the user data is refreshed when the application becomes active
ServiceContainer.Resolve<ISyncManager> ().Run ();
ServiceContainer.Resolve<NetworkIndicatorManager> ();
if (systemVersion > minVersionWidget) {
ServiceContainer.Resolve<WidgetSyncManager>();
var widgetService = ServiceContainer.Resolve<WidgetUpdateService>();
widgetService.SetAppOnBackground (false);
}
if (LaunchedShortcutItem != null) {
ServiceContainer.Resolve<QuickActions> ().HandleShortcut (LaunchedShortcutItem, true);
LaunchedShortcutItem = null;
}
}
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
if (systemVersion > minVersionWidget) {
if (url.AbsoluteString.Contains (WidgetUpdateService.TodayUrlPrefix)) {
var widgetManager = ServiceContainer.Resolve<WidgetSyncManager>();
if (url.AbsoluteString.Contains (WidgetUpdateService.StartEntryUrlPrefix)) {
widgetManager.StartStopTimeEntry();
} else {
widgetManager.ContinueTimeEntry();
}
return true;
}
}
return SignIn.SharedInstance.HandleUrl (url, sourceApplication, annotation);
}
public override void DidEnterBackground (UIApplication application)
{
if (systemVersion > minVersionWidget) {
var widgetService = ServiceContainer.Resolve<WidgetUpdateService>();
widgetService.SetAppOnBackground (true);
}
}
public override void WillTerminate (UIApplication application)
{
if (systemVersion > minVersionWidget) {
var widgetService = ServiceContainer.Resolve<WidgetUpdateService>();
widgetService.SetAppActivated (false);
}
}
private void RegisterComponents ()
{
// Register platform info first.
ServiceContainer.Register<IPlatformInfo> (this);
// Register Phoebe services
Services.Register ();
// Override default implementation
ServiceContainer.Register<ITimeProvider> (() => new NSTimeProvider ());
// Register Ross components:
ServiceContainer.Register<ILogger> (() => new Logger ());
ServiceContainer.Register<SettingsStore> ();
ServiceContainer.Register<ISettingsStore> (() => ServiceContainer.Resolve<SettingsStore> ());
if (systemVersion > minVersionWidget) {
ServiceContainer.Register<WidgetUpdateService> (() => new WidgetUpdateService());
ServiceContainer.Register<IWidgetUpdateService> (() => ServiceContainer.Resolve<WidgetUpdateService> ());
}
ServiceContainer.Register<ExperimentManager> (() => new ExperimentManager (
typeof (Toggl.Phoebe.Analytics.Experiments),
typeof (Toggl.Ross.Analytics.Experiments)));
ServiceContainer.Register<ILoggerClient> (delegate {
return new LogClient (delegate {
#if DEBUG
Insights.Initialize (Insights.DebugModeKey);
#else
Insights.Initialize (Build.XamInsightsApiKey);
#endif
}) {
DeviceId = ServiceContainer.Resolve<SettingsStore> ().InstallId,
ProjectNamespaces = new List<string> () { "Toggl." },
};
});
ServiceContainer.Register<ITracker> (() => new Tracker());
ServiceContainer.Register<INetworkPresence> (() => new NetworkPresence ());
ServiceContainer.Register<NetworkIndicatorManager> ();
ServiceContainer.Register<TagChipCache> ();
ServiceContainer.Register<APNSManager> ();
ServiceContainer.Register<QuickActions> ();
}
private void SetupGoogleServices ()
{
// Set up Google Analytics
// the tracker ID isn't detected automatically from GoogleService-info.plist
// so, it's passed manually. Waiting for new versions of the library.
var gaiInstance = Google.Analytics.Gai.SharedInstance;
gaiInstance.DefaultTracker = gaiInstance.GetTracker (Build.GoogleAnalyticsId);
NSError configureError;
Context.SharedInstance.Configure (out configureError);
if (configureError != null) {
var log = ServiceContainer.Resolve<ILogger> ();
log.Info ("AppDelegate", string.Format ("Error configuring the Google context: {0}", configureError));
}
}
public static TogglWindow TogglWindow
{
get {
return ((AppDelegate)UIApplication.SharedApplication.Delegate).window;
}
}
string IPlatformInfo.AppIdentifier
{
get { return Build.AppIdentifier; }
}
private string appVersion;
string IPlatformInfo.AppVersion
{
get {
if (appVersion == null) {
appVersion = NSBundle.MainBundle.InfoDictionary.ObjectForKey (
new NSString ("CFBundleShortVersionString")).ToString ();
}
return appVersion;
}
}
bool IPlatformInfo.IsWidgetAvailable
{
get {
// iOS 8 is the version where Today Widgets are availables.
return systemVersion > minVersionWidget;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Compilation;
using NUnit.Framework;
using SqlCE4Umbraco;
using umbraco;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using Umbraco.Core;
using Umbraco.Core.IO;
using umbraco.DataLayer;
using umbraco.editorControls.tags;
using umbraco.interfaces;
using umbraco.MacroEngines;
using umbraco.uicontrols;
using Umbraco.Web.BaseRest;
namespace Umbraco.Tests.Plugins
{
/// <summary>
/// Tests for typefinder
/// </summary>
[TestFixture]
public class TypeFinderTests
{
/// <summary>
/// List of assemblies to scan
/// </summary>
private Assembly[] _assemblies;
[SetUp]
public void Initialize()
{
_assemblies = new[]
{
this.GetType().Assembly,
typeof(ApplicationStartupHandler).Assembly,
typeof(SqlCEHelper).Assembly,
typeof(CMSNode).Assembly,
typeof(System.Guid).Assembly,
typeof(NUnit.Framework.Assert).Assembly,
typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly,
typeof(System.Xml.NameTable).Assembly,
typeof(System.Configuration.GenericEnumConverter).Assembly,
typeof(System.Web.SiteMap).Assembly,
typeof(TabPage).Assembly,
typeof(System.Web.Mvc.ActionResult).Assembly,
typeof(TypeFinder).Assembly,
typeof(ISqlHelper).Assembly,
typeof(ICultureDictionary).Assembly,
typeof(Tag).Assembly,
typeof(global::UmbracoExamine.BaseUmbracoIndexer).Assembly
};
}
[Test]
public void Find_Class_Of_Type_With_Attribute()
{
var typesFound = TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies);
Assert.AreEqual(2, typesFound.Count());
}
[Test]
public void Find_Classes_Of_Type()
{
var typesFound = TypeFinder.FindClassesOfType<IApplicationStartupHandler>(_assemblies);
var originalTypesFound = TypeFinderOriginal.FindClassesOfType<IApplicationStartupHandler>(_assemblies);
Assert.AreEqual(originalTypesFound.Count(), typesFound.Count());
Assert.AreEqual(8, typesFound.Count());
Assert.AreEqual(8, originalTypesFound.Count());
}
[Test]
public void Find_Classes_With_Attribute()
{
var typesFound = TypeFinder.FindClassesWithAttribute<RestExtensionAttribute>(_assemblies);
Assert.AreEqual(1, typesFound.Count());
}
[Ignore]
[Test]
public void Benchmark_Original_Finder()
{
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test"))
{
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinderOriginal.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0);
}
}
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0);
}
}
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinderOriginal.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0);
}
}
}
}
[Ignore]
[Test]
public void Benchmark_New_Finder()
{
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test"))
{
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinder.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0);
}
}
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0);
}
}
using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute"))
{
for (var i = 0; i < 1000; i++)
{
Assert.Greater(TypeFinder.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0);
}
}
}
}
public class MyTag : ITag
{
public int Id { get; private set; }
public string TagCaption { get; private set; }
public string Group { get; private set; }
}
public class MySuperTag : MyTag
{
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class MyTestAttribute : Attribute
{
}
public abstract class TestEditor
{
}
[MyTest]
public class BenchmarkTestEditor : TestEditor
{
}
[MyTest]
public class MyOtherTestEditor : TestEditor
{
}
//USED FOR THE ABOVE TESTS
// see this issue for details: http://issues.umbraco.org/issue/U4-1187
internal static class TypeFinderOriginal
{
private static readonly ConcurrentBag<Assembly> LocalFilteredAssemblyCache = new ConcurrentBag<Assembly>();
private static readonly ReaderWriterLockSlim LocalFilteredAssemblyCacheLocker = new ReaderWriterLockSlim();
private static ReadOnlyCollection<Assembly> _allAssemblies = null;
private static ReadOnlyCollection<Assembly> _binFolderAssemblies = null;
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim();
/// <summary>
/// lazily load a reference to all assemblies and only local assemblies.
/// This is a modified version of: http://www.dominicpettifer.co.uk/Blog/44/how-to-get-a-reference-to-all-assemblies-in-the--bin-folder
/// </summary>
/// <remarks>
/// We do this because we cannot use AppDomain.Current.GetAssemblies() as this will return only assemblies that have been
/// loaded in the CLR, not all assemblies.
/// See these threads:
/// http://issues.umbraco.org/issue/U5-198
/// http://stackoverflow.com/questions/3552223/asp-net-appdomain-currentdomain-getassemblies-assemblies-missing-after-app
/// http://stackoverflow.com/questions/2477787/difference-between-appdomain-getassemblies-and-buildmanager-getreferencedassembl
/// </remarks>
internal static IEnumerable<Assembly> GetAllAssemblies()
{
if (_allAssemblies == null)
{
using (new WriteLock(Locker))
{
List<Assembly> assemblies = null;
try
{
var isHosted = HttpContext.Current != null;
try
{
if (isHosted)
{
assemblies = new List<Assembly>(BuildManager.GetReferencedAssemblies().Cast<Assembly>());
}
}
catch (InvalidOperationException e)
{
if (!(e.InnerException is SecurityException))
throw;
}
if (assemblies == null)
{
//NOTE: we cannot use AppDomain.CurrentDomain.GetAssemblies() because this only returns assemblies that have
// already been loaded in to the app domain, instead we will look directly into the bin folder and load each one.
var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory;
var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList();
assemblies = new List<Assembly>();
foreach (var a in binAssemblyFiles)
{
try
{
var assName = AssemblyName.GetAssemblyName(a);
var ass = Assembly.Load(assName);
assemblies.Add(ass);
}
catch (Exception e)
{
if (e is SecurityException || e is BadImageFormatException)
{
//swallow these exceptions
}
else
{
throw;
}
}
}
}
//if for some reason they are still no assemblies, then use the AppDomain to load in already loaded assemblies.
if (!assemblies.Any())
{
assemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies().ToList());
}
//here we are trying to get the App_Code assembly
var fileExtensions = new[] { ".cs", ".vb" }; //only vb and cs files are supported
var appCodeFolder = new DirectoryInfo(IOHelper.MapPath(IOHelper.ResolveUrl("~/App_code")));
//check if the folder exists and if there are any files in it with the supported file extensions
if (appCodeFolder.Exists && (fileExtensions.Any(x => appCodeFolder.GetFiles("*" + x).Any())))
{
var appCodeAssembly = Assembly.Load("App_Code");
if (!assemblies.Contains(appCodeAssembly)) // BuildManager will find App_Code already
assemblies.Add(appCodeAssembly);
}
//now set the _allAssemblies
_allAssemblies = new ReadOnlyCollection<Assembly>(assemblies);
}
catch (InvalidOperationException e)
{
if (!(e.InnerException is SecurityException))
throw;
_binFolderAssemblies = _allAssemblies;
}
}
}
return _allAssemblies;
}
/// <summary>
/// Returns only assemblies found in the bin folder that have been loaded into the app domain.
/// </summary>
/// <returns></returns>
/// <remarks>
/// This will be used if we implement App_Plugins from Umbraco v5 but currently it is not used.
/// </remarks>
internal static IEnumerable<Assembly> GetBinAssemblies()
{
if (_binFolderAssemblies == null)
{
using (new WriteLock(Locker))
{
var assemblies = GetAssembliesWithKnownExclusions().ToArray();
var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory;
var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList();
var domainAssemblyNames = binAssemblyFiles.Select(AssemblyName.GetAssemblyName);
var safeDomainAssemblies = new List<Assembly>();
var binFolderAssemblies = new List<Assembly>();
foreach (var a in assemblies)
{
try
{
//do a test to see if its queryable in med trust
var assemblyFile = a.GetAssemblyFile();
safeDomainAssemblies.Add(a);
}
catch (SecurityException)
{
//we will just ignore this because this will fail
//in medium trust for system assemblies, we get an exception but we just want to continue until we get to
//an assembly that is ok.
}
}
foreach (var assemblyName in domainAssemblyNames)
{
try
{
var foundAssembly = safeDomainAssemblies.FirstOrDefault(a => a.GetAssemblyFile() == assemblyName.GetAssemblyFile());
if (foundAssembly != null)
{
binFolderAssemblies.Add(foundAssembly);
}
}
catch (SecurityException)
{
//we will just ignore this because if we are trying to do a call to:
// AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName)))
//in medium trust for system assemblies, we get an exception but we just want to continue until we get to
//an assembly that is ok.
}
}
_binFolderAssemblies = new ReadOnlyCollection<Assembly>(binFolderAssemblies);
}
}
return _binFolderAssemblies;
}
/// <summary>
/// Return a list of found local Assemblies excluding the known assemblies we don't want to scan
/// and exluding the ones passed in and excluding the exclusion list filter, the results of this are
/// cached for perforance reasons.
/// </summary>
/// <param name="excludeFromResults"></param>
/// <returns></returns>
internal static IEnumerable<Assembly> GetAssembliesWithKnownExclusions(
IEnumerable<Assembly> excludeFromResults = null)
{
if (LocalFilteredAssemblyCache.Any()) return LocalFilteredAssemblyCache;
using (new WriteLock(LocalFilteredAssemblyCacheLocker))
{
var assemblies = GetFilteredAssemblies(excludeFromResults, KnownAssemblyExclusionFilter);
assemblies.ForEach(LocalFilteredAssemblyCache.Add);
}
return LocalFilteredAssemblyCache;
}
/// <summary>
/// Return a list of found local Assemblies and exluding the ones passed in and excluding the exclusion list filter
/// </summary>
/// <param name="excludeFromResults"></param>
/// <param name="exclusionFilter"></param>
/// <returns></returns>
private static IEnumerable<Assembly> GetFilteredAssemblies(
IEnumerable<Assembly> excludeFromResults = null,
string[] exclusionFilter = null)
{
if (excludeFromResults == null)
excludeFromResults = new List<Assembly>();
if (exclusionFilter == null)
exclusionFilter = new string[] { };
return GetAllAssemblies()
.Where(x => !excludeFromResults.Contains(x)
&& !x.GlobalAssemblyCache
&& !exclusionFilter.Any(f => x.FullName.StartsWith(f)));
}
/// <summary>
/// this is our assembly filter to filter out known types that def dont contain types we'd like to find or plugins
/// </summary>
/// <remarks>
/// NOTE the comma vs period... comma delimits the name in an Assembly FullName property so if it ends with comma then its an exact name match
/// </remarks>
internal static readonly string[] KnownAssemblyExclusionFilter = new[]
{
"mscorlib,",
"System.",
"Antlr3.",
"Autofac.",
"Autofac,",
"Castle.",
"ClientDependency.",
"DataAnnotationsExtensions.",
"DataAnnotationsExtensions,",
"Dynamic,",
"HtmlDiff,",
"Iesi.Collections,",
"log4net,",
"Microsoft.",
"Newtonsoft.",
"NHibernate.",
"NHibernate,",
"NuGet.",
"RouteDebugger,",
"SqlCE4Umbraco,",
"umbraco.datalayer,",
"umbraco.interfaces,",
"umbraco.providers,",
"Umbraco.Web.UI,",
"umbraco.webservices",
"Lucene.",
"Examine,",
"Examine.",
"ServiceStack.",
"MySql.",
"HtmlAgilityPack.",
"TidyNet.",
"ICSharpCode.",
"CookComputing.",
/* Mono */
"MonoDevelop.NUnit"
};
public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>()
where TAttribute : Attribute
{
return FindClassesOfTypeWithAttribute<T, TAttribute>(GetAssembliesWithKnownExclusions(), true);
}
public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies)
where TAttribute : Attribute
{
return FindClassesOfTypeWithAttribute<T, TAttribute>(assemblies, true);
}
public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
where TAttribute : Attribute
{
if (assemblies == null) throw new ArgumentNullException("assemblies");
var l = new List<Type>();
foreach (var a in assemblies)
{
var types = from t in GetTypesWithFormattedException(a)
where !t.IsInterface
&& typeof(T).IsAssignableFrom(t)
&& t.GetCustomAttributes<TAttribute>(false).Any()
&& (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract))
select t;
l.AddRange(types);
}
return l;
}
/// <summary>
/// Searches all filtered local assemblies specified for classes of the type passed in.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<Type> FindClassesOfType<T>()
{
return FindClassesOfType<T>(GetAssembliesWithKnownExclusions(), true);
}
/// <summary>
/// Returns all types found of in the assemblies specified of type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies"></param>
/// <param name="onlyConcreteClasses"></param>
/// <returns></returns>
public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
{
if (assemblies == null) throw new ArgumentNullException("assemblies");
return GetAssignablesFromType<T>(assemblies, onlyConcreteClasses);
}
/// <summary>
/// Returns all types found of in the assemblies specified of type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies"></param>
/// <returns></returns>
public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies)
{
return FindClassesOfType<T>(assemblies, true);
}
/// <summary>
/// Finds the classes with attribute.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies">The assemblies.</param>
/// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param>
/// <returns></returns>
public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
where T : Attribute
{
return FindClassesWithAttribute(typeof(T), assemblies, onlyConcreteClasses);
}
/// <summary>
/// Finds the classes with attribute.
/// </summary>
/// <param name="type">The attribute type </param>
/// <param name="assemblies">The assemblies.</param>
/// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param>
/// <returns></returns>
public static IEnumerable<Type> FindClassesWithAttribute(Type type, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
{
if (assemblies == null) throw new ArgumentNullException("assemblies");
if (!TypeHelper.IsTypeAssignableFrom<Attribute>(type))
throw new ArgumentException("The type specified: " + type + " is not an Attribute type");
var l = new List<Type>();
foreach (var a in assemblies)
{
var types = from t in GetTypesWithFormattedException(a)
where !t.IsInterface && t.GetCustomAttributes(type, false).Any() && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract))
select t;
l.AddRange(types);
}
return l;
}
/// <summary>
/// Finds the classes with attribute.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies">The assemblies.</param>
/// <returns></returns>
public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies)
where T : Attribute
{
return FindClassesWithAttribute<T>(assemblies, true);
}
/// <summary>
/// Finds the classes with attribute in filtered local assemblies
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IEnumerable<Type> FindClassesWithAttribute<T>()
where T : Attribute
{
return FindClassesWithAttribute<T>(GetAssembliesWithKnownExclusions());
}
#region Private methods
/// <summary>
/// Gets a collection of assignables of type T from a collection of assemblies
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assemblies"></param>
/// <param name="onlyConcreteClasses"></param>
/// <returns></returns>
private static IEnumerable<Type> GetAssignablesFromType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
{
return GetTypes(typeof(T), assemblies, onlyConcreteClasses);
}
private static IEnumerable<Type> GetTypes(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
{
var l = new List<Type>();
foreach (var a in assemblies)
{
var types = from t in GetTypesWithFormattedException(a)
where !t.IsInterface && assignTypeFrom.IsAssignableFrom(t) && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract))
select t;
l.AddRange(types);
}
return l;
}
private static IEnumerable<Type> GetTypesWithFormattedException(Assembly a)
{
//if the assembly is dynamic, do not try to scan it
if (a.IsDynamic)
return Enumerable.Empty<Type>();
try
{
return a.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
var sb = new StringBuilder();
sb.AppendLine("Could not load types from assembly " + a.FullName + ", errors:");
foreach (var loaderException in ex.LoaderExceptions.WhereNotNull())
{
sb.AppendLine("Exception: " + loaderException.ToString());
}
throw new ReflectionTypeLoadException(ex.Types, ex.LoaderExceptions, sb.ToString());
}
}
#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 Xunit;
namespace System.Text.Tests
{
public class DecoderConvert2Decoder : Decoder
{
private Decoder _decoder = null;
public DecoderConvert2Decoder()
{
_decoder = Encoding.UTF8.GetDecoder();
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return _decoder.GetCharCount(bytes, index, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return _decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
public override void Reset()
{
_decoder.Reset();
}
}
// Convert(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@)
public class DecoderConvert2
{
private const int c_SIZE_OF_ARRAY = 127;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
// PosTest1: Call Convert to convert a arbitrary byte array to character array by using ASCII decoder
[Fact]
public void PosTest1()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = _generator.GetByte(-55);
}
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
}
// PosTest2: Call Convert to convert a arbitrary byte array to character array by using Unicode decoder"
[Fact]
public void PosTest2()
{
Decoder decoder = Encoding.Unicode.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = _generator.GetByte(-55);
}
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed);
decoder.Reset();
}
// PosTest3: Call Convert to convert a ASCII byte array to character array by using ASCII decoder
[Fact]
public void PosTest3()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[c_SIZE_OF_ARRAY];
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] expected = new char[c_SIZE_OF_ARRAY];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
for (int i = 0; i < expected.Length; ++i)
{
expected[i] = (char)('\0' + i);
}
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "003.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "003.2");
decoder.Reset();
}
// PosTest4: Call Convert to convert a ASCII byte array with user implemented decoder
[Fact]
public void PosTest4()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
char[] expected = new char[bytes.Length];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
for (int i = 0; i < expected.Length; ++i)
{
expected[i] = (char)('\0' + i);
}
Decoder decoder = new DecoderConvert2Decoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "004.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "004.2");
decoder.Reset();
}
// PosTest5: Call Convert to convert partial of a ASCII byte array with ASCII decoder
[Fact]
public void PosTest5()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.UTF8.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, false, 1, 1, true, "005.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, true, 1, 1, true, "005.2");
decoder.Reset();
// Verify maxBytes is large than character count
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, false, bytes.Length - 1, chars.Length - 1, false, "005.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, true, bytes.Length - 1, chars.Length - 1, false, "005.4");
decoder.Reset();
}
// PosTest6: Call Convert to convert a ASCII character array with Unicode encoder
[Fact]
public void PosTest6()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length / 2, true, "006.1");
decoder.Reset();
// There will be 1 byte left unconverted after previous statement, and set flush = false should left this 1 byte in the buffer.
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length / 2 + 1, true, "006.2");
decoder.Reset();
}
// PosTest7: Call Convert to convert partial of a ASCII character array with Unicode encoder
[Fact]
public void PosTest7()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, "007.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, "007.2");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, "007.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, "007.4");
decoder.Reset();
}
// PosTest8: Call Convert to convert a Unicode character array with Unicode encoder
[Fact]
public void PosTest8()
{
char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray();
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
char[] chars = new char[expected.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "008.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "008.2");
decoder.Reset();
}
// PosTest9: Call Convert to convert partial of a Unicode character array with Unicode encoder
[Fact]
public void PosTest9()
{
char[] expected = "\u8FD9".ToCharArray();
char[] chars = new char[expected.Length];
byte[] bytes = new byte[] {
217,
143,
42,
78,
0,
78,
42,
78,
75,
109,
213,
139
};
Decoder decoder = Encoding.Unicode.GetDecoder();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, expected, "009.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, expected, "009.2");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, expected, "009.3");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, expected, "009.4");
decoder.Reset();
}
// PosTest10: Call Convert with ASCII decoder and convert nothing
[Fact]
public void PosTest10()
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
char[] chars = new char[bytes.Length];
Decoder decoder = Encoding.Unicode.GetDecoder();
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = (byte)i;
}
VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, false, 0, 0, true, "010.1");
decoder.Reset();
VerificationHelper(decoder, bytes, 0, 0, chars, 0, chars.Length, true, 0, 0, true, "010.2");
decoder.Reset();
}
// NegTest1: ArgumentNullException should be thrown when chars or bytes is a null reference
[Fact]
public void NegTest1()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte[] b = new byte[c_SIZE_OF_ARRAY];
char[] c = new char[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, c, 0, 0, true, typeof(ArgumentNullException), "101.1");
VerificationHelper<ArgumentNullException>(decoder, b, 0, 0, null, 0, 0, true, typeof(ArgumentNullException), "101.2");
VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, c, 0, 0, false, typeof(ArgumentNullException), "101.3");
VerificationHelper<ArgumentNullException>(decoder, b, 0, 0, null, 0, 0, false, typeof(ArgumentNullException), "101.4");
}
// NegTest2: ArgumentOutOfRangeException should be thrown when charIndex, charCount, byteIndex, or byteCount is less than zero.
[Fact]
public void NegTest2()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte[] b = new byte[c_SIZE_OF_ARRAY];
char[] c = new char[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, -1, 0, c, 0, 0, true, typeof(ArgumentOutOfRangeException), "102.1");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, -1, 0, true, typeof(ArgumentOutOfRangeException), "102.2");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, -1, 0, c, 0, 0, false, typeof(ArgumentOutOfRangeException), "102.3");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, -1, 0, false, typeof(ArgumentOutOfRangeException), "102.4");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, -1, c, 0, 0, true, typeof(ArgumentOutOfRangeException), "102.5");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, 0, -1, true, typeof(ArgumentOutOfRangeException), "102.6");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, -1, c, 0, 0, false, typeof(ArgumentOutOfRangeException), "102.7");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, 0, -1, false, typeof(ArgumentOutOfRangeException), "102.8");
}
// NegTest3: ArgumentException should be thrown when The output buffer is too small to contain any of the converted input
[Fact]
public void NegTest3()
{
Decoder decoder = Encoding.Unicode.GetDecoder();
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
for (int i = 0; i < bytes.Length; ++i)
{
bytes[i] = _generator.GetByte(-55);
}
char[] chars = new char[0];
VerificationHelper<ArgumentException>(decoder, bytes, 0, c_SIZE_OF_ARRAY, chars, 0, 0, true, typeof(ArgumentException), "103.1");
}
// NegTest4: ArgumentOutOfRangeException should be thrown when The length of chars - charIndex is less than charCount.
[Fact]
public void NegTest4()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte[] b = new byte[c_SIZE_OF_ARRAY];
char[] c = new char[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, 1, c, 1, c.Length, true, typeof(ArgumentOutOfRangeException), "104.1");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 1, c, c.Length, 1, true, typeof(ArgumentOutOfRangeException), "104.2");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, 1, c, 1, c.Length, false, typeof(ArgumentOutOfRangeException), "104.3");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 1, c, c.Length, 1, true, typeof(ArgumentOutOfRangeException), "104.4");
}
// NegTest5: ArgumentOutOfRangeException should be thrown when The length of bytes - byteIndex is less than byteCount
[Fact]
public void NegTest5()
{
Decoder decoder = Encoding.UTF8.GetDecoder();
byte[] b = new byte[c_SIZE_OF_ARRAY];
char[] c = new char[c_SIZE_OF_ARRAY];
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, b.Length, c, 1, 0, true, typeof(ArgumentOutOfRangeException), "105.1");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, b.Length, 1, c, 0, 1, true, typeof(ArgumentOutOfRangeException), "105.2");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, b.Length, c, 1, 0, false, typeof(ArgumentOutOfRangeException), "105.3");
VerificationHelper<ArgumentOutOfRangeException>(decoder, b, b.Length, 1, c, 0, 1, true, typeof(ArgumentOutOfRangeException), "105.4");
}
private void VerificationHelper(Decoder decoder, byte[] bytes,
int byteIndex,
int byteCount,
char[] chars,
int charIndex,
int charCount,
bool flush,
int desiredBytesUsed,
int desiredCharsUsed,
bool desiredCompleted,
string errorno)
{
int bytesUsed;
int charsUsed;
bool completed;
decoder.Convert(bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, out bytesUsed,
out charsUsed, out completed);
Assert.Equal(desiredBytesUsed, bytesUsed);
Assert.Equal(desiredCharsUsed, charsUsed);
Assert.Equal(desiredCompleted, completed);
}
private void VerificationHelper(Decoder decoder, byte[] bytes,
int byteIndex,
int byteCount,
char[] chars,
int charIndex,
int charCount,
bool flush,
int desiredBytesUsed,
int desiredCharsUsed,
bool desiredCompleted,
char[] desiredChars,
string errorno)
{
VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, desiredBytesUsed,
desiredCharsUsed, desiredCompleted, errorno + ".1");
Assert.Equal(desiredChars.Length, chars.Length);
for (int i = 0; i < chars.Length; ++i)
{
Assert.Equal(desiredChars[i], chars[i]);
}
}
private void VerificationHelper<T>(Decoder decoder, byte[] bytes,
int byteIndex,
int byteCount,
char[] chars,
int charIndex,
int charCount,
bool flush,
Type expected,
string errorno) where T : Exception
{
string str = null;
int bytesUsed;
int charsUsed;
bool completed;
str = new string(chars);
Assert.Throws<T>(() =>
{
decoder.Convert(bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, out bytesUsed,
out charsUsed, out completed);
});
}
}
}
| |
namespace Nancy.Tests.Unit
{
using System;
using FakeItEasy;
using Nancy.Bootstrapper;
using Nancy.Diagnostics;
using Nancy.ErrorHandling;
using Nancy.Extensions;
using Nancy.Routing;
using Nancy.Tests.Fakes;
using Xunit;
using Nancy.Culture;
public class NancyEngineFixture
{
private readonly INancyEngine engine;
private readonly IRouteResolver resolver;
private readonly FakeRoute route;
private readonly NancyContext context;
private readonly INancyContextFactory contextFactory;
private readonly Response response;
private readonly IStatusCodeHandler statusCodeHandler;
private readonly IRouteInvoker routeInvoker;
private readonly IRequestDispatcher requestDispatcher;
private readonly DiagnosticsConfiguration diagnosticsConfiguration;
public NancyEngineFixture()
{
this.resolver = A.Fake<IRouteResolver>();
this.response = new Response();
this.route = new FakeRoute(response);
this.context = new NancyContext();
this.statusCodeHandler = A.Fake<IStatusCodeHandler>();
this.requestDispatcher = A.Fake<IRequestDispatcher>();
this.diagnosticsConfiguration = new DiagnosticsConfiguration();
A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._)).Invokes(x => this.context.Response = new Response());
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);
contextFactory = A.Fake<INancyContextFactory>();
A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);
var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);
var applicationPipelines = new Pipelines();
this.routeInvoker = A.Fake<IRouteInvoker>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
{
return (Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1]);
});
this.engine =
new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider())
{
RequestPipelinesFactory = ctx => applicationPipelines
};
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_dispatcher()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider()));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_context_factory()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider()));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_status_handler()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider()));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request()
{
// Given,
Request request = null;
// When
var exception = Record.Exception(() => engine.HandleRequest(request));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void HandleRequest_should_get_context_from_context_factory()
{
// Given
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void HandleRequest_should_set_correct_response_on_returned_context()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.requestDispatcher.Dispatch(this.context)).Invokes(x => this.context.Response = this.response);
// When
var result = this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(this.response);
}
[Fact]
public void Should_not_add_nancy_version_number_header_on_returned_response()
{
// NOTE: Regression for removal of nancy-version from response headers
// Given
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Response.Headers.ContainsKey("Nancy-Version").ShouldBeFalse();
}
[Fact]
public void Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { BeforeRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
this.engine.HandleRequest(request);
}
[Fact]
public void Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { AfterRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
this.engine.HandleRequest(request);
}
[Fact]
public void Should_call_pre_request_hook_should_be_invoked_with_request_from_context()
{
// Given
Request passedRequest = null;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>
{
passedRequest = ctx.Request;
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
this.context.Request = request;
// When
this.engine.HandleRequest(request);
// Then
passedRequest.ShouldBeSameAs(request);
}
[Fact]
public void Should_return_response_from_pre_request_hook_when_not_null()
{
// Given
var returnedResponse = A.Fake<Response>();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(returnedResponse);
}
[Fact]
public void Should_allow_post_request_hook_to_modify_context_items()
{
// Given
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
{
ctx.Items.Add("PostReqTest", new object());
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Items.ContainsKey("PostReqTest").ShouldBeTrue();
}
[Fact]
public void Should_allow_post_request_hook_to_replace_response()
{
// Given
var newResponse = new Response();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(newResponse);
}
[Fact]
public void HandleRequest_prereq_returns_response_should_still_run_postreq()
{
// Given
var returnedResponse = A.Fake<Response>();
var postReqCalled = false;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
postReqCalled.ShouldBeTrue();
}
[Fact]
public void Should_ask_status_handler_if_it_can_handle_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_not_invoke_status_handler_if_not_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();
}
[Fact]
public void Should_invoke_status_handler_if_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_set_status_code_to_500_if_route_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(new NotImplementedException());
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
}
[Fact]
public void Should_store_exception_details_if_dispatcher_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(new NotImplementedException());
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.GetExceptionDetails().ShouldContain("NotImplementedException");
}
[Fact]
public void Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws()
{
// Given
var testEx = new Exception();
var errorRoute =
new Route("GET", "/", null, x => { throw testEx; });
var resolvedRoute = new ResolveResult(
errorRoute,
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(testEx);
Exception handledException = null;
NancyContext handledContext = null;
var errorResponse = new Response();
Func<NancyContext, Exception, Response> routeErrorHook = (ctx, ex) =>
{
handledContext = ctx;
handledException = ex;
return errorResponse;
};
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
Assert.Equal(testEx, handledException);
Assert.Equal(result, handledContext);
Assert.Equal(result.Response, errorResponse);
}
[Fact]
public void Should_add_unhandled_exception_to_context_as_requestexecutionexception()
{
// Given
var routeUnderTest =
new Route("GET", "/", null, x => { throw new Exception(); });
var resolved =
new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved);
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<DynamicDictionary>._, A<NancyContext>._)).Invokes((x) =>
{
routeUnderTest.Action.Invoke(DynamicDictionary.Empty);
});
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(new Exception());
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue();
result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>();
}
[Fact]
public void Should_persist_original_exception_in_requestexecutionexception()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(expectedException);
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public void Should_add_requestexecutionexception_to_context_when_pipeline_is_null()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(new Exception());
var pipelines = new Pipelines { OnError = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
// Then
result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue();
result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>();
}
[Fact]
public void Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(expectedException);
var pipelines = new Pipelines { OnError = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public void Should_return_static_content_response_if_one_returned()
{
var localResponse = new Response();
var staticContent = A.Fake<IStaticContentProvider>();
A.CallTo(() => staticContent.GetContent(A<NancyContext>._))
.Returns(localResponse);
var localEngine = new NancyEngine(
this.requestDispatcher,
this.contextFactory,
new[] { this.statusCodeHandler },
A.Fake<IRequestTracing>(),
this.diagnosticsConfiguration,
staticContent);
var request = new Request("GET", "/", "http");
var result = localEngine.HandleRequest(request);
result.Response.ShouldBeSameAs(localResponse);
}
}
}
| |
namespace FluentNHibernate.Cfg.Db
{
public class IfxDRDAConnectionStringBuilder : ConnectionStringBuilder
{
private string authentication = "";
private string database = "";
private string hostVarParameter = "";
private string isolationLevel = "";
private string maxPoolSize = "";
private string minPoolSize = "";
private string password = "";
private string pooling = "";
private string server = "";
private string username = "";
private string otherOptions = "";
/// <summary>
/// The type of authentication to be used. Acceptable values:
/// <list type="bullet">
/// <item>
/// SERVER
/// </item>
/// <item>
/// SERVER_ENCRYPT
/// </item>
/// <item>
/// DATA_ENCRYPT
/// </item>
/// <item>
/// KERBEROS
/// </item>
/// <item>
/// GSSPLUGIN
/// </item>
/// </list>
/// </summary>
/// <param name="authentication"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Authentication(string authentication)
{
this.authentication = authentication;
IsDirty = true;
return this;
}
/// <summary>
/// The name of the database within the server instance.
/// </summary>
/// <param name="database"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Database(string database)
{
this.database = database;
IsDirty = true;
return this;
}
/// <summary>
/// <list type="bullet">
/// <item>
/// <term>true</term>
/// <description> - host variable (:param) support enabled.</description>
/// </item>
/// <item>
/// <term>false (default)</term>
/// <description> - host variable support disabled.</description>
/// </item>
/// </list>
/// </summary>
/// <param name="hostVarParameter"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder HostVarParameter(string hostVarParameter)
{
this.hostVarParameter = hostVarParameter;
IsDirty = true;
return this;
}
/// <summary>
/// Isolation level for the connection. Possible values:
/// <list type="bullet">
/// <item>
/// ReadCommitted
/// </item>
/// <item>
/// ReadUncommitted
/// </item>
/// <item>
/// RepeatableRead
/// </item>
/// <item>
/// Serializable
/// </item>
/// <item>
/// Transaction
/// </item>
/// </list>
/// This keyword is only supported for applications participating in a
/// distributed transaction.
/// </summary>
/// <param name="isolationLevel"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder IsolationLevel(string isolationLevel)
{
this.isolationLevel = isolationLevel;
IsDirty = true;
return this;
}
/// <summary>
/// The maximum number of connections allowed in the pool.
/// </summary>
/// <param name="maxPoolSize"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder MaxPoolSize(string maxPoolSize)
{
this.maxPoolSize = maxPoolSize;
IsDirty = true;
return this;
}
/// <summary>
/// The minimum number of connections allowed in the pool. Default value 0.
/// </summary>
/// <param name="minPoolSize"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder MinPoolSize(string minPoolSize)
{
this.minPoolSize = minPoolSize;
IsDirty = true;
return this;
}
/// <summary>
/// The password associated with the User ID.
/// </summary>
/// <param name="password"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Password(string password)
{
this.password = password;
IsDirty = true;
return this;
}
/// <summary>
/// When set to true, the IfxConnection object is drawn from
/// the appropriate pool, or if necessary, it is created and added
/// to the appropriate pool. Default value 'true'.
/// </summary>
/// <param name="pooling"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Pooling(string pooling)
{
this.pooling = pooling;
IsDirty = true;
return this;
}
/// <summary>
/// Server name with optional port number for direct connection using either
/// IPv4 notation (<![CDATA[<server name/ip address>[:<port>]]]>) or IPv6 notation.
/// </summary>
/// <param name="server"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Server(string server)
{
this.server = server;
IsDirty = true;
return this;
}
/// <summary>
/// The login account.
/// </summary>
/// <param name="username"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder Username(string username)
{
this.username = username;
IsDirty = true;
return this;
}
/// <summary>
/// Other options: Connection Lifetime, Connection Reset, Connection Timeout, CurrentSchema, Enlist,
/// Interrupt, Persist Security Info, ResultArrayAsReturnValue, Security, TrustedContextSystemUserID,
/// TrustedContextSystemPassword
/// </summary>
/// <param name="otherOptions"></param>
/// <returns>IfxDRDAConnectionStringBuilder object</returns>
public IfxDRDAConnectionStringBuilder OtherOptions(string otherOptions)
{
this.otherOptions = otherOptions;
IsDirty = true;
return this;
}
protected internal override string Create()
{
var connectionString = base.Create();
if (!string.IsNullOrEmpty(connectionString))
return connectionString;
if (this.authentication.Length > 0)
{
connectionString += string.Format("Authentication={0};", this.authentication);
}
if (this.database.Length > 0)
{
connectionString += string.Format("Database={0};", this.database);
}
if (this.hostVarParameter.Length > 0)
{
connectionString += string.Format("HostVarParameter={0};", this.hostVarParameter);
}
if (this.isolationLevel.Length > 0)
{
connectionString += string.Format("IsolationLevel={0};", this.isolationLevel);
}
if (this.maxPoolSize.Length > 0)
{
connectionString += string.Format("Max Pool Size={0};", this.maxPoolSize);
}
if (this.minPoolSize.Length > 0)
{
connectionString += string.Format("Min Pool Size={0};", this.minPoolSize);
}
if (this.password.Length > 0)
{
connectionString += string.Format("PWD={0};", this.password);
}
if (this.pooling.Length > 0)
{
connectionString += string.Format("Pooling={0};", this.pooling);
}
if (this.server.Length > 0)
{
connectionString += string.Format("Server={0};", this.server);
}
if (this.username.Length > 0)
{
connectionString += string.Format("UID={0};", this.username);
}
if (this.otherOptions.Length > 0)
{
connectionString += this.otherOptions;
}
return connectionString;
}
}
}
| |
using System;
using Spruce.Attribs;
using Spruce.Tokens;
using XSharp.Tokens;
using XSharp.x86.Params;
using Identifier = XSharp.Tokens.Identifier;
using Reg = XSharp.Tokens.Reg;
using Reg08 = XSharp.Tokens.Reg08;
using Reg16 = XSharp.Tokens.Reg16;
using Reg32 = XSharp.Tokens.Reg32;
using Size = XSharp.Tokens.Size;
namespace XSharp.x86.Emitters
{
/// <summary>
/// Class that processes conditional branches for X#.
/// </summary>
/// <seealso cref="XSharp.x86.Emitters.Emitters" />
public class Branching : Emitters
{
public Branching(Compiler aCompiler, x86.Assemblers.Assembler aAsm) : base(aCompiler, aAsm)
{
}
#region if return
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Reg), typeof(Return))]
[Emitter(typeof(If), typeof(Reg08), typeof(OpCompare), typeof(Int08u), typeof(Return))]
[Emitter(typeof(If), typeof(Reg16), typeof(OpCompare), typeof(Int16u), typeof(Return))]
[Emitter(typeof(If), typeof(Reg32), typeof(OpCompare), typeof(Int32u), typeof(Return))]
protected void IfRegisterConditionRegisterReturn(string aOpIf, Register aRegister, string aOpCompare, object aValue, object aOpReturn)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
Asm.Emit(xJumpOpCode, Compiler.CurrentFunctionExitLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Const), typeof(Return))]
protected void IfRegisterConditionConstReturn(string aOpIf, Register aRegister, string aOpCompare, string aValue, object aOpReturn)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName($"Const_{aValue}");
Asm.Emit(OpCode.Cmp, aRegister, xValue);
Asm.Emit(xJumpOpCode, Compiler.CurrentFunctionExitLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Variable), typeof(Return))]
protected void IfRegisterConditionVariableReturn(string aOpIf, Register aRegister, string aOpCompare, Address aValue, object aOpReturn)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
aValue.AddPrefix(Compiler.CurrentNamespace);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
Asm.Emit(xJumpOpCode, Compiler.CurrentFunctionExitLabel);
}
[Emitter(typeof(If), typeof(Size), typeof(Reg), typeof(OpCompare), typeof(Variable), typeof(Return))]
protected void IfSizeRegisterConditionVariableReturn(string aOpIf, string aSize, Register aRegister, string aOpCompare, Address aValue, object aOpReturn)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
aValue.AddPrefix(Compiler.CurrentNamespace);
Asm.Emit(OpCode.Cmp, aSize, aRegister, aValue);
Asm.Emit(xJumpOpCode, Compiler.CurrentFunctionExitLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(VariableAddress), typeof(Return))]
protected void IfRegisterConditionVariableAddressReturn(string aOpIf, Register aRegister, string aOpCompare, string aValue, object aOpReturn)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName(aValue);
Asm.Emit(OpCode.Cmp, aRegister, xValue);
Asm.Emit(xJumpOpCode, Compiler.CurrentFunctionExitLabel);
}
#endregion
#region if {
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Reg), typeof(OpOpenBrace))]
protected void IfRegisterConditionRegister(string aOpIf, Register aLeftRegister, string aOpCompare, Register aRightRegister, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
Asm.Emit(OpCode.Cmp, aLeftRegister, aRightRegister);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
[Emitter(typeof(If), typeof(Reg08), typeof(OpCompare), typeof(Int08u), typeof(OpOpenBrace))]
[Emitter(typeof(If), typeof(Reg16), typeof(OpCompare), typeof(Int16u), typeof(OpOpenBrace))]
[Emitter(typeof(If), typeof(Reg32), typeof(OpCompare), typeof(Int32u), typeof(OpOpenBrace))]
protected void IfRegisterConditionConst(string aOpIf, Register aRegister, string aOpCompare, object aValue, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Const), typeof(OpOpenBrace))]
protected void IfRegisterConditionConst(string aOpIf, Register aRegister, string aOpCompare, string aValue, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName($"Const_{aValue}");
Asm.Emit(OpCode.Cmp, aRegister, xValue);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Variable), typeof(OpOpenBrace))]
protected void IfRegisterConditionVariable(string aOpIf, Register aRegister, string aOpCompare, Address aValue, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
aValue.AddPrefix(Compiler.CurrentNamespace);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(VariableAddress), typeof(OpOpenBrace))]
protected void IfRegisterConditionVariableAddress(string aOpIf, Register aRegister, string aOpCompare, string aValue, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName(aValue);
Asm.Emit(OpCode.Cmp, aRegister, xValue);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
[Emitter(typeof(If), typeof(Size), typeof(Variable), typeof(OpCompare), typeof(Const), typeof(OpOpenBrace))]
protected void IfSizeAdressConditionConst(string aOpIf, string aSize, Address aAdress, string aOpCompare, string aConstant, object aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
var xJumpOpCode = GetOppositeJumpOpCode(aOpCompare);
aAdress.AddPrefix(Compiler.CurrentNamespace);
string xConstant = Compiler.GetFullName($"Const_{aConstant}");
Asm.Emit(OpCode.Cmp, aSize, aAdress, xConstant);
Asm.Emit(xJumpOpCode, Compiler.Blocks.EndBlockLabel);
}
#endregion
#region if goto
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Reg), typeof(GotoKeyword), typeof(Identifier))]
protected void IfRegisterConditionRegisterGoto(string aOpIf, Register aLeftRegister, string aOpCompare, Register aRightRegister, string aGotoKeyword, string aLabel)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
Asm.Emit(OpCode.Cmp, aLeftRegister, aRightRegister);
string xLabel = Compiler.GetFullName(aLabel, true);
Asm.Emit(xJumpOpCode, xLabel);
}
[Emitter(typeof(If), typeof(Reg08), typeof(OpCompare), typeof(Int08u), typeof(GotoKeyword), typeof(Identifier))]
[Emitter(typeof(If), typeof(Reg16), typeof(OpCompare), typeof(Int16u), typeof(GotoKeyword), typeof(Identifier))]
[Emitter(typeof(If), typeof(Reg32), typeof(OpCompare), typeof(Int32u), typeof(GotoKeyword), typeof(Identifier))]
protected void IfRegisterConditionIntGoto(string aOpIf, Register aRegister, string aOpCompare, object aValue, string aGotoKeyword, string aLabel)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
string xLabel = Compiler.GetFullName(aLabel, true);
Asm.Emit(xJumpOpCode, xLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Const), typeof(GotoKeyword), typeof(Identifier))]
protected void IfRegisterConditionConstGoto(string aOpIf, Register aRegister, string aOpCompare, string aValue, string aGotoKeyword, string aLabel)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName($"Const_{aValue}");
Asm.Emit(OpCode.Cmp, aRegister, xValue);
string xLabel = Compiler.GetFullName(aLabel, true);
Asm.Emit(xJumpOpCode, xLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(Variable), typeof(GotoKeyword), typeof(Identifier))]
protected void IfRegisterConditionVariable(string aOpIf, Register aRegister, string aOpCompare, Address aValue, string aGotoKeyword, string aLabel)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
aValue.AddPrefix(Compiler.CurrentNamespace);
Asm.Emit(OpCode.Cmp, aRegister, aValue);
string xLabel = Compiler.GetFullName(aLabel, true);
Asm.Emit(xJumpOpCode, xLabel);
}
[Emitter(typeof(If), typeof(Reg), typeof(OpCompare), typeof(VariableAddress), typeof(GotoKeyword), typeof(Identifier))]
protected void IfRegisterConditionVariableAddressGoto(string aOpIf, Register aRegister, string aOpCompare, string aValue, string aGotoKeyword, string aLabel)
{
var xJumpOpCode = GetJumpOpCode(aOpCompare);
string xValue = Compiler.GetFullName(aValue);
Asm.Emit(OpCode.Cmp, aRegister, xValue);
string xLabel = Compiler.GetFullName(aLabel, true);
Asm.Emit(xJumpOpCode, xLabel);
}
#endregion
// if AL = goto lLabel123
[Emitter(typeof(If), typeof(Size), typeof(CompareVar), typeof(GotoKeyword), typeof(Identifier))]
protected void IfConditionGoto(string aOpIf, string aSize, object[] aCompareData, string aGotoKeyword, string aLabel)
{
aCompareData[0] = GetFullNameOrAddPrefix(aCompareData[0]);
aCompareData[2] = GetFullNameOrAddPrefix(aCompareData[2]);
}
// If = return
[Emitter(typeof(If), typeof(OpPureComparators), typeof(Return))]
protected void IfConditionPureReturn(string aOpIf, string aPureComparator, string aReturns)
{
}
[Emitter(typeof(If), typeof(OpPureComparators), typeof(OpOpenBrace))]
protected void IfConditionPureBlockStart(string aOpIf, string aOpPureComparators, string aOpOpenBrace)
{
Compiler.Blocks.StartBlock(Compiler.BlockType.If);
}
[Emitter(typeof(If), typeof(OpPureComparators), typeof(GotoKeyword), typeof(Identifier))]
protected void IfConditionPureGoto(string aOpIf, string aOpPureComparators, string aGotoKeyword, string aLabel)
{
}
private static OpCode GetJumpOpCode(string aCompare)
{
switch (aCompare)
{
case "<":
return OpCode.Jb;
case "<=":
return OpCode.Jbe;
case ">":
return OpCode.Ja;
case ">=":
return OpCode.Jae;
case "=":
return OpCode.Je;
case "!=":
return OpCode.Jne;
default:
throw new Exception($"Unknown comparison opcode '{aCompare}'");
}
}
private static OpCode GetOppositeJumpOpCode(string aCompare)
{
switch (aCompare)
{
case "<":
return OpCode.Jae;
case "<=":
return OpCode.Ja;
case ">":
return OpCode.Jbe;
case ">=":
return OpCode.Jb;
case "=":
return OpCode.Jne;
case "!=":
return OpCode.Je;
default:
throw new Exception($"Unknown comparison opcode '{aCompare}'");
}
}
private object GetFullNameOrAddPrefix(object aOperand)
{
if (aOperand is x86.Params.Address xAddress)
{
xAddress.AddPrefix(Compiler.CurrentNamespace);
return xAddress;
}
else if (aOperand is string s)
{
aOperand = Compiler.GetFullName(s);
}
return aOperand;
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Linq;
using NLog.Internal;
/// <summary>
/// Nested Diagnostics Context - a thread-local structure that keeps a stack
/// of strings and provides methods to output them in layouts
/// Mostly for compatibility with log4net.
/// </summary>
public static class NestedDiagnosticsContext
{
private static readonly object dataSlot = ThreadLocalStorageHelper.AllocateDataSlot();
/// <summary>
/// Gets the top NDC message but doesn't remove it.
/// </summary>
/// <returns>The top message. .</returns>
public static string TopMessage => FormatHelper.ConvertToString(TopObject, null);
/// <summary>
/// Gets the top NDC object but doesn't remove it.
/// </summary>
/// <returns>The object at the top of the NDC stack if defined; otherwise <c>null</c>.</returns>
public static object TopObject => PeekObject();
private static Stack<object> GetThreadStack(bool create = true)
{
return ThreadLocalStorageHelper.GetDataForSlot<Stack<object>>(dataSlot, create);
}
/// <summary>
/// Pushes the specified text on current thread NDC.
/// </summary>
/// <param name="text">The text to be pushed.</param>
/// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
public static IDisposable Push(string text)
{
return Push((object)text);
}
/// <summary>
/// Pushes the specified object on current thread NDC.
/// </summary>
/// <param name="value">The object to be pushed.</param>
/// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
public static IDisposable Push(object value)
{
Stack<object> stack = GetThreadStack(true);
int previousCount = stack.Count;
stack.Push(value);
return new StackPopper(stack, previousCount);
}
/// <summary>
/// Pops the top message off the NDC stack.
/// </summary>
/// <returns>The top message which is no longer on the stack.</returns>
public static string Pop()
{
return Pop(null);
}
/// <summary>
/// Pops the top message from the NDC stack.
/// </summary>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting the value to a string.</param>
/// <returns>The top message, which is removed from the stack, as a string value.</returns>
public static string Pop(IFormatProvider formatProvider)
{
return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider);
}
/// <summary>
/// Pops the top object off the NDC stack.
/// </summary>
/// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns>
public static object PopObject()
{
Stack<object> stack = GetThreadStack(true);
return (stack.Count > 0) ? stack.Pop() : null;
}
/// <summary>
/// Peeks the first object on the NDC stack
/// </summary>
/// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns>
public static object PeekObject()
{
Stack<object> stack = GetThreadStack(false);
return (stack?.Count > 0) ? stack.Peek() : null;
}
/// <summary>
/// Clears current thread NDC stack.
/// </summary>
public static void Clear()
{
Stack<object> stack = GetThreadStack(false);
stack?.Clear();
}
/// <summary>
/// Gets all messages on the stack.
/// </summary>
/// <returns>Array of strings on the stack.</returns>
public static string[] GetAllMessages()
{
return GetAllMessages(null);
}
/// <summary>
/// Gets all messages from the stack, without removing them.
/// </summary>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param>
/// <returns>Array of strings.</returns>
public static string[] GetAllMessages(IFormatProvider formatProvider)
{
Stack<object> stack = GetThreadStack(false);
if (stack == null)
return ArrayHelper.Empty<string>();
else
return stack.Select((o) => FormatHelper.ConvertToString(o, formatProvider)).ToArray();
}
/// <summary>
/// Gets all objects on the stack.
/// </summary>
/// <returns>Array of objects on the stack.</returns>
public static object[] GetAllObjects()
{
Stack<object> stack = GetThreadStack(false);
if (stack == null)
return ArrayHelper.Empty<object>();
else
return stack.ToArray();
}
/// <summary>
/// Resets the stack to the original count during <see cref="IDisposable.Dispose"/>.
/// </summary>
private class StackPopper : IDisposable
{
private readonly Stack<object> _stack;
private readonly int _previousCount;
/// <summary>
/// Initializes a new instance of the <see cref="StackPopper" /> class.
/// </summary>
/// <param name="stack">The stack.</param>
/// <param name="previousCount">The previous count.</param>
public StackPopper(Stack<object> stack, int previousCount)
{
_stack = stack;
_previousCount = previousCount;
}
/// <summary>
/// Reverts the stack to original item count.
/// </summary>
void IDisposable.Dispose()
{
while (_stack.Count > _previousCount)
{
_stack.Pop();
}
}
}
}
}
| |
/*
* Deed API
*
* Land Registry Deed API
*
* OpenAPI spec version: 2.3.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter;
namespace IO.Swagger.Model
{
/// <summary>
/// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed.
/// </summary>
[DataContract]
public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class.
/// </summary>
/// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param>
/// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param>
/// <param name="Borrowers">Borrowers.</param>
/// <param name="ChargeClause">ChargeClause.</param>
/// <param name="AdditionalProvisions">AdditionalProvisions.</param>
/// <param name="Lender">Lender.</param>
/// <param name="EffectiveClause">Text to display the make effective clause.</param>
/// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param>
/// <param name="Reference">A conveyancer reference. Can be displayed on the deed if the mortgage document template permits..</param>
/// <param name="DateOfMortgageOffer">Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits..</param>
/// <param name="DeedStatus">Current state of the deed.</param>
/// <param name="EffectiveDate">An effective date is shown if the deed is made effective.</param>
public OperativeDeedDeed(string TitleNumber = default(string), string MdRef = default(string), OpBorrowers Borrowers = default(OpBorrowers), ChargeClause ChargeClause = default(ChargeClause), AdditionalProvisions AdditionalProvisions = default(AdditionalProvisions), Lender Lender = default(Lender), string EffectiveClause = default(string), string PropertyAddress = default(string), string Reference = default(string), string DateOfMortgageOffer = default(string), string DeedStatus = default(string), string EffectiveDate = default(string))
{
this.TitleNumber = TitleNumber;
this.MdRef = MdRef;
this.Borrowers = Borrowers;
this.ChargeClause = ChargeClause;
this.AdditionalProvisions = AdditionalProvisions;
this.Lender = Lender;
this.EffectiveClause = EffectiveClause;
this.PropertyAddress = PropertyAddress;
this.Reference = Reference;
this.DateOfMortgageOffer = DateOfMortgageOffer;
this.DeedStatus = DeedStatus;
this.EffectiveDate = EffectiveDate;
}
/// <summary>
/// Unique Land Registry identifier for the registered estate.
/// </summary>
/// <value>Unique Land Registry identifier for the registered estate.</value>
[DataMember(Name="title_number", EmitDefaultValue=false)]
public string TitleNumber { get; set; }
/// <summary>
/// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)
/// </summary>
/// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value>
[DataMember(Name="md_ref", EmitDefaultValue=false)]
public string MdRef { get; set; }
/// <summary>
/// Gets or Sets Borrowers
/// </summary>
[DataMember(Name="borrowers", EmitDefaultValue=false)]
public OpBorrowers Borrowers { get; set; }
/// <summary>
/// Gets or Sets ChargeClause
/// </summary>
[DataMember(Name="charge_clause", EmitDefaultValue=false)]
public ChargeClause ChargeClause { get; set; }
/// <summary>
/// Gets or Sets AdditionalProvisions
/// </summary>
[DataMember(Name="additional_provisions", EmitDefaultValue=false)]
public AdditionalProvisions AdditionalProvisions { get; set; }
/// <summary>
/// Gets or Sets Lender
/// </summary>
[DataMember(Name="lender", EmitDefaultValue=false)]
public Lender Lender { get; set; }
/// <summary>
/// Text to display the make effective clause
/// </summary>
/// <value>Text to display the make effective clause</value>
[DataMember(Name="effective_clause", EmitDefaultValue=false)]
public string EffectiveClause { get; set; }
/// <summary>
/// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA
/// </summary>
/// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value>
[DataMember(Name="property_address", EmitDefaultValue=false)]
public string PropertyAddress { get; set; }
/// <summary>
/// A conveyancer reference. Can be displayed on the deed if the mortgage document template permits.
/// </summary>
/// <value>A conveyancer reference. Can be displayed on the deed if the mortgage document template permits.</value>
[DataMember(Name="reference", EmitDefaultValue=false)]
public string Reference { get; set; }
/// <summary>
/// Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits.
/// </summary>
/// <value>Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits.</value>
[DataMember(Name="date_of_mortgage_offer", EmitDefaultValue=false)]
public string DateOfMortgageOffer { get; set; }
/// <summary>
/// Current state of the deed
/// </summary>
/// <value>Current state of the deed</value>
[DataMember(Name="deed_status", EmitDefaultValue=false)]
public string DeedStatus { get; set; }
/// <summary>
/// An effective date is shown if the deed is made effective
/// </summary>
/// <value>An effective date is shown if the deed is made effective</value>
[DataMember(Name="effective_date", EmitDefaultValue=false)]
public string EffectiveDate { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OperativeDeedDeed {\n");
sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n");
sb.Append(" MdRef: ").Append(MdRef).Append("\n");
sb.Append(" Borrowers: ").Append(Borrowers).Append("\n");
sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n");
sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n");
sb.Append(" Lender: ").Append(Lender).Append("\n");
sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n");
sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n");
sb.Append(" Reference: ").Append(Reference).Append("\n");
sb.Append(" DateOfMortgageOffer: ").Append(DateOfMortgageOffer).Append("\n");
sb.Append(" DeedStatus: ").Append(DeedStatus).Append("\n");
sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OperativeDeedDeed);
}
/// <summary>
/// Returns true if OperativeDeedDeed instances are equal
/// </summary>
/// <param name="other">Instance of OperativeDeedDeed to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OperativeDeedDeed other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TitleNumber == other.TitleNumber ||
this.TitleNumber != null &&
this.TitleNumber.Equals(other.TitleNumber)
) &&
(
this.MdRef == other.MdRef ||
this.MdRef != null &&
this.MdRef.Equals(other.MdRef)
) &&
(
this.Borrowers == other.Borrowers ||
this.Borrowers != null &&
this.Borrowers.Equals(other.Borrowers)
) &&
(
this.ChargeClause == other.ChargeClause ||
this.ChargeClause != null &&
this.ChargeClause.Equals(other.ChargeClause)
) &&
(
this.AdditionalProvisions == other.AdditionalProvisions ||
this.AdditionalProvisions != null &&
this.AdditionalProvisions.Equals(other.AdditionalProvisions)
) &&
(
this.Lender == other.Lender ||
this.Lender != null &&
this.Lender.Equals(other.Lender)
) &&
(
this.EffectiveClause == other.EffectiveClause ||
this.EffectiveClause != null &&
this.EffectiveClause.Equals(other.EffectiveClause)
) &&
(
this.PropertyAddress == other.PropertyAddress ||
this.PropertyAddress != null &&
this.PropertyAddress.Equals(other.PropertyAddress)
) &&
(
this.Reference == other.Reference ||
this.Reference != null &&
this.Reference.Equals(other.Reference)
) &&
(
this.DateOfMortgageOffer == other.DateOfMortgageOffer ||
this.DateOfMortgageOffer != null &&
this.DateOfMortgageOffer.Equals(other.DateOfMortgageOffer)
) &&
(
this.DeedStatus == other.DeedStatus ||
this.DeedStatus != null &&
this.DeedStatus.Equals(other.DeedStatus)
) &&
(
this.EffectiveDate == other.EffectiveDate ||
this.EffectiveDate != null &&
this.EffectiveDate.Equals(other.EffectiveDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TitleNumber != null)
hash = hash * 59 + this.TitleNumber.GetHashCode();
if (this.MdRef != null)
hash = hash * 59 + this.MdRef.GetHashCode();
if (this.Borrowers != null)
hash = hash * 59 + this.Borrowers.GetHashCode();
if (this.ChargeClause != null)
hash = hash * 59 + this.ChargeClause.GetHashCode();
if (this.AdditionalProvisions != null)
hash = hash * 59 + this.AdditionalProvisions.GetHashCode();
if (this.Lender != null)
hash = hash * 59 + this.Lender.GetHashCode();
if (this.EffectiveClause != null)
hash = hash * 59 + this.EffectiveClause.GetHashCode();
if (this.PropertyAddress != null)
hash = hash * 59 + this.PropertyAddress.GetHashCode();
if (this.Reference != null)
hash = hash * 59 + this.Reference.GetHashCode();
if (this.DateOfMortgageOffer != null)
hash = hash * 59 + this.DateOfMortgageOffer.GetHashCode();
if (this.DeedStatus != null)
hash = hash * 59 + this.DeedStatus.GetHashCode();
if (this.EffectiveDate != null)
hash = hash * 59 + this.EffectiveDate.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Reference (string) maxLength
if(this.Reference != null && this.Reference.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Reference, length must be less than 50.", new [] { "Reference" });
}
// Reference (string) pattern
Regex regexReference = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant);
if (false == regexReference.Match(this.Reference).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Reference, must match a pattern of " + regexReference, new [] { "Reference" });
}
// DateOfMortgageOffer (string) maxLength
if(this.DateOfMortgageOffer != null && this.DateOfMortgageOffer.Length > 50)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DateOfMortgageOffer, length must be less than 50.", new [] { "DateOfMortgageOffer" });
}
// DateOfMortgageOffer (string) pattern
Regex regexDateOfMortgageOffer = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant);
if (false == regexDateOfMortgageOffer.Match(this.DateOfMortgageOffer).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DateOfMortgageOffer, must match a pattern of " + regexDateOfMortgageOffer, new [] { "DateOfMortgageOffer" });
}
yield break;
}
}
}
| |
/* 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:
*
* * 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 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.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Dialogs;
using XenAPI;
using System.Linq;
using System.IO;
using XenAdmin.Alerts;
using XenAdmin.Core;
namespace XenAdmin.Wizards.PatchingWizard
{
public enum WizardMode { SingleUpdate, AutomatedUpdates, NewVersion }
/// <summary>
/// Remember that equals for patches dont work across connections because
/// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_path or Host_patch
/// You should do it manually or use delegates.
/// </summary>
public partial class PatchingWizard : XenWizardBase
{
private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage;
private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage;
private readonly PatchingWizard_ModePage PatchingWizard_ModePage;
private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers;
private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage;
private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage;
private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage;
private readonly PatchingWizard_AutomatedUpdatesPage PatchingWizard_AutomatedUpdatesPage;
public PatchingWizard()
{
InitializeComponent();
PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage();
PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage();
PatchingWizard_ModePage = new PatchingWizard_ModePage();
PatchingWizard_SelectServers = new PatchingWizard_SelectServers();
PatchingWizard_UploadPage = new PatchingWizard_UploadPage();
PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage();
PatchingWizard_FirstPage = new PatchingWizard_FirstPage();
PatchingWizard_AutomatedUpdatesPage = new PatchingWizard_AutomatedUpdatesPage();
AddPage(PatchingWizard_FirstPage);
AddPage(PatchingWizard_SelectPatchPage);
AddPage(PatchingWizard_SelectServers);
AddPage(PatchingWizard_UploadPage);
AddPage(PatchingWizard_PrecheckPage);
AddPage(PatchingWizard_ModePage);
AddPage(PatchingWizard_PatchingPage);
}
public void AddAlert(XenServerPatchAlert alert)
{
PatchingWizard_SelectPatchPage.SelectDownloadAlert(alert);
PatchingWizard_SelectPatchPage.SelectedUpdateAlert = alert;
PatchingWizard_SelectServers.SelectedUpdateAlert = alert;
PatchingWizard_PrecheckPage.UpdateAlert = alert;
PatchingWizard_UploadPage.SelectedUpdateAlert = alert;
}
public void AddFile(string path)
{
PatchingWizard_SelectPatchPage.AddFile(path);
}
public void SelectServers(List<Host> selectedServers)
{
PatchingWizard_SelectServers.SelectServers(selectedServers);
PatchingWizard_SelectServers.DisableUnselectedServers();
}
protected override void UpdateWizardContent(XenTabPage senderPage)
{
var prevPageType = senderPage.GetType();
if (prevPageType == typeof(PatchingWizard_SelectPatchPage))
{
var wizardMode = PatchingWizard_SelectPatchPage.WizardMode;
var wizardIsInAutomatedUpdatesMode = wizardMode == WizardMode.AutomatedUpdates;
var updateType = wizardIsInAutomatedUpdatesMode ? UpdateType.NewRetail : PatchingWizard_SelectPatchPage.SelectedUpdateType;
var newPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedNewPatch;
var existPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedExistingPatch;
var alertPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.SelectedUpdateAlert;
var fileFromDiskAlertPatch = wizardIsInAutomatedUpdatesMode ? null : PatchingWizard_SelectPatchPage.FileFromDiskAlert;
PatchingWizard_SelectServers.WizardMode = wizardMode;
PatchingWizard_SelectServers.SelectedUpdateType = updateType;
PatchingWizard_SelectServers.Patch = existPatch;
PatchingWizard_SelectServers.SelectedUpdateAlert = alertPatch;
PatchingWizard_SelectServers.FileFromDiskAlert = fileFromDiskAlertPatch;
RemovePage(PatchingWizard_UploadPage);
RemovePage(PatchingWizard_ModePage);
RemovePage(PatchingWizard_PatchingPage);
RemovePage(PatchingWizard_AutomatedUpdatesPage);
if (wizardMode == WizardMode.SingleUpdate)
{
AddAfterPage(PatchingWizard_SelectServers, PatchingWizard_UploadPage);
AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_ModePage);
AddAfterPage(PatchingWizard_ModePage, PatchingWizard_PatchingPage);
}
else // AutomatedUpdates or NewVersion
{
AddAfterPage(PatchingWizard_PrecheckPage, PatchingWizard_AutomatedUpdatesPage);
}
PatchingWizard_UploadPage.SelectedUpdateType = updateType;
PatchingWizard_UploadPage.SelectedExistingPatch = existPatch;
PatchingWizard_UploadPage.SelectedNewPatchPath = newPatch;
PatchingWizard_UploadPage.SelectedUpdateAlert = alertPatch;
PatchingWizard_ModePage.Patch = existPatch;
PatchingWizard_ModePage.SelectedUpdateType = updateType;
PatchingWizard_PrecheckPage.WizardMode = wizardMode;
PatchingWizard_PrecheckPage.Patch = existPatch;
PatchingWizard_PrecheckPage.PoolUpdate = null; //reset the PoolUpdate property; it will be updated on leaving the Upload page, if this page is visible
PatchingWizard_PrecheckPage.SelectedUpdateType = updateType;
PatchingWizard_PrecheckPage.UpdateAlert = alertPatch ?? fileFromDiskAlertPatch;
PatchingWizard_AutomatedUpdatesPage.WizardMode = wizardMode;
PatchingWizard_AutomatedUpdatesPage.UpdateAlert = alertPatch ?? fileFromDiskAlertPatch;
PatchingWizard_PatchingPage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.Patch = existPatch;
PatchingWizard_PatchingPage.SelectedNewPatch = newPatch;
}
else if (prevPageType == typeof(PatchingWizard_SelectServers))
{
var selectedServers = PatchingWizard_SelectServers.SelectedServers;
var selectedPools = PatchingWizard_SelectServers.SelectedPools;
var selectedMasters = PatchingWizard_SelectServers.SelectedMasters;
var applyUpdatesToNewVersion = PatchingWizard_SelectServers.ApplyUpdatesToNewVersion;
PatchingWizard_PrecheckPage.SelectedServers = selectedServers;
PatchingWizard_PrecheckPage.ApplyUpdatesToNewVersion = applyUpdatesToNewVersion;
PatchingWizard_ModePage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedMasters = selectedMasters;
PatchingWizard_PatchingPage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedPools = selectedPools;
PatchingWizard_UploadPage.SelectedMasters = selectedMasters;
PatchingWizard_UploadPage.SelectedServers = selectedServers;
PatchingWizard_AutomatedUpdatesPage.SelectedPools = selectedPools;
PatchingWizard_AutomatedUpdatesPage.ApplyUpdatesToNewVersion = applyUpdatesToNewVersion;
}
else if (prevPageType == typeof(PatchingWizard_UploadPage))
{
if (PatchingWizard_SelectPatchPage.SelectedUpdateType == UpdateType.NewRetail)
{
PatchingWizard_SelectPatchPage.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectPatchPage.SelectedExistingPatch = PatchingWizard_UploadPage.Patch;
PatchingWizard_SelectServers.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectServers.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PrecheckPage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_ModePage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PatchingPage.Patch = PatchingWizard_UploadPage.Patch;
}
PatchingWizard_PrecheckPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_PatchingPage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_ModePage.PoolUpdate = PatchingWizard_UploadPage.PoolUpdate;
PatchingWizard_PatchingPage.SuppPackVdis = PatchingWizard_UploadPage.SuppPackVdis;
}
else if (prevPageType == typeof(PatchingWizard_ModePage))
{
PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions;
PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode;
PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile;
}
else if (prevPageType == typeof(PatchingWizard_PrecheckPage))
{
PatchingWizard_PatchingPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck;
PatchingWizard_PatchingPage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_ModePage.LivePatchCodesByHost = PatchingWizard_PrecheckPage.LivePatchCodesByHost;
PatchingWizard_AutomatedUpdatesPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck;
}
}
private delegate List<AsyncAction> GetActionsDelegate();
private List<AsyncAction> BuildSubActions(params GetActionsDelegate[] getActionsDelegate)
{
List<AsyncAction> result = new List<AsyncAction>();
foreach (GetActionsDelegate getActionDelegate in getActionsDelegate)
{
var list = getActionDelegate();
if (list != null && list.Count > 0)
result.AddRange(list);
}
return result;
}
private List<AsyncAction> GetUnwindChangesActions()
{
if (PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck == null)
return null;
var actionList = (from problem in PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck
where problem.SolutionActionCompleted
select problem.UnwindChanges());
return actionList.Where(action => action != null &&
action.Connection != null &&
action.Connection.IsConnected).ToList();
}
private List<AsyncAction> GetRemovePatchActions(List<Pool_patch> patchesToRemove)
{
if (patchesToRemove == null)
return null;
List<AsyncAction> list = new List<AsyncAction>();
foreach (Pool_patch patch in patchesToRemove)
{
if (patch.Connection != null && patch.Connection.IsConnected)
{
if (patch.HostsAppliedTo().Count == 0)
{
list.Add(new RemovePatchAction(patch));
}
else
{
list.Add(new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref)));
}
}
}
return list;
}
private List<AsyncAction> GetRemovePatchActions()
{
return GetRemovePatchActions(PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList());
}
private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove)
{
if (vdisToRemove == null)
return null;
var list = (from vdi in vdisToRemove
where vdi.Connection != null && vdi.Connection.IsConnected
select new DestroyDiskAction(vdi));
return list.OfType<AsyncAction>().ToList();
}
private List<AsyncAction> GetRemoveVdiActions()
{
return GetRemoveVdiActions(PatchingWizard_UploadPage.AllCreatedSuppPackVdis); ;
}
private void RunMultipleActions(string title, string startDescription, string endDescription,
List<AsyncAction> subActions)
{
if (subActions.Count > 0)
{
using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription,
endDescription, subActions, false, true))
{
using (var dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks))
dialog.ShowDialog(Program.MainWindow);
}
}
}
protected override void OnCancel()
{
base.OnCancel();
List<AsyncAction> subActions = BuildSubActions(GetUnwindChangesActions, GetRemovePatchActions, GetRemoveVdiActions, GetCleanUpPoolUpdateActions);
RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES,
Messages.REVERTED_WIZARD_CHANGES, subActions);
RemoveDownloadedPatches();
}
private void RemoveUnwantedPatches(List<Pool_patch> patchesToRemove)
{
List<AsyncAction> subActions = GetRemovePatchActions(patchesToRemove);
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void RemoveTemporaryVdis()
{
List<AsyncAction> subActions = GetRemoveVdiActions();
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void CleanUpPoolUpdates()
{
var subActions = GetCleanUpPoolUpdateActions();
RunMultipleActions(Messages.PATCHINGWIZARD_REMOVE_UPDATES, Messages.PATCHINGWIZARD_REMOVING_UPDATES, Messages.PATCHINGWIZARD_REMOVED_UPDATES, subActions);
}
private void RemoveDownloadedPatches()
{
List<string> listOfDownloadedFiles = new List<string>();
if (PatchingWizard_SelectPatchPage.WizardMode != WizardMode.SingleUpdate) // AutomatedUpdates or NewVersion
{
listOfDownloadedFiles.AddRange(PatchingWizard_AutomatedUpdatesPage.AllDownloadedPatches.Values);
}
else
{
listOfDownloadedFiles.AddRange(PatchingWizard_UploadPage.AllDownloadedPatches.Values);
listOfDownloadedFiles.AddRange(PatchingWizard_SelectPatchPage.UnzippedUpdateFiles);
}
foreach (string downloadedPatch in listOfDownloadedFiles)
{
try
{
if (File.Exists(downloadedPatch))
{
File.Delete(downloadedPatch);
}
}
catch
{
log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch);
}
}
}
protected override void FinishWizard()
{
if (PatchingWizard_UploadPage.NewUploadedPatches != null)
{
List<Pool_patch> patchesToRemove =
PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList().Where(
patch => !string.Equals(patch.uuid, PatchingWizard_UploadPage.Patch.uuid, System.StringComparison.OrdinalIgnoreCase)).ToList();
RemoveUnwantedPatches(patchesToRemove);
}
if (PatchingWizard_UploadPage.AllCreatedSuppPackVdis != null)
RemoveTemporaryVdis();
CleanUpPoolUpdates();
RemoveDownloadedPatches();
Updates.CheckServerPatches();
base.FinishWizard();
}
private List<AsyncAction> GetCleanUpPoolUpdateActions()
{
if (PatchingWizard_UploadPage.AllIntroducedPoolUpdates != null && PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Count > 0)
{
return PatchingWizard_UploadPage.AllIntroducedPoolUpdates.Keys.Select(GetCleanUpPoolUpdateAction).ToList();
}
return new List<AsyncAction>();
}
private static AsyncAction GetCleanUpPoolUpdateAction(Pool_update poolUpdate)
{
return
new DelegatedAsyncAction(poolUpdate.Connection, Messages.REMOVE_PATCH, "", "", session =>
{
try
{
Pool_update.pool_clean(session, poolUpdate.opaque_ref);
if(!poolUpdate.AppliedOnHosts().Any())
Pool_update.destroy(session, poolUpdate.opaque_ref);
}
catch (Failure f)
{
log.Error("Clean up failed", f);
}
});
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.S3.Model
{
/// <summary>
/// The parameters to request upload of a part in a multipart upload operation.
/// </summary>
/// <remarks>
/// <para>
/// If PartSize is not specified then the rest of the content from the file
/// or stream will be sent to Amazon S3.
/// </para>
/// <para>
/// You must set either the FilePath or InputStream. If FilePath is set then the FilePosition
/// property must be set.
/// </para>
/// </remarks>
public partial class UploadPartRequest : AmazonWebServiceRequest
{
private Stream inputStream;
private string bucketName;
private string key;
private int? partNumber;
private string uploadId;
private long? partSize;
private string md5Digest;
private ServerSideEncryptionCustomerMethod serverSideCustomerEncryption;
private string serverSideEncryptionCustomerProvidedKey;
private string serverSideEncryptionCustomerProvidedKeyMD5;
private string filePath;
private long? filePosition;
private bool lastPart;
internal int IVSize { get; set; }
/// <summary>
/// Caller needs to set this to true when uploading the last part. This property only needs to be set
/// when using the AmazonS3EncryptionClient.
/// </summary>
public bool IsLastPart
{
get { return this.lastPart; }
set { this.lastPart = value; }
}
/// <summary>
/// Input stream for the request; content for the request will be read from the stream.
/// </summary>
public Stream InputStream
{
get { return this.inputStream; }
set { this.inputStream = value; }
}
// Check to see if Body property is set
internal bool IsSetInputStream()
{
return this.inputStream != null;
}
/// <summary>
/// The name of the bucket containing the object to receive the part.
/// </summary>
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
// Check to see if Bucket property is set
internal bool IsSetBucketName()
{
return this.bucketName != null;
}
/// <summary>
/// The key of the object.
/// </summary>
public string Key
{
get { return this.key; }
set { this.key = value; }
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this.key != null;
}
/// <summary>
/// Part number of part being uploaded.
///
/// </summary>
public int PartNumber
{
get { return this.partNumber.GetValueOrDefault(); }
set { this.partNumber = value; }
}
// Check to see if PartNumber property is set
internal bool IsSetPartNumber()
{
return this.partNumber.HasValue;
}
/// <summary>
/// The size of the part to be uploaded.
/// </summary>
public long PartSize
{
get { return this.partSize.GetValueOrDefault(); }
set { this.partSize = value; }
}
/// <summary>
/// Checks if PartSize property is set.
/// </summary>
/// <returns>true if PartSize property is set.</returns>
internal bool IsSetPartSize()
{
return this.partSize.HasValue;
}
/// <summary>
/// Upload ID identifying the multipart upload whose part is being uploaded.
///
/// </summary>
public string UploadId
{
get { return this.uploadId; }
set { this.uploadId = value; }
}
// Check to see if UploadId property is set
internal bool IsSetUploadId()
{
return this.uploadId != null;
}
/// <summary>
/// An MD5 digest for the part.
/// </summary>
public string MD5Digest
{
get { return this.md5Digest; }
set { this.md5Digest = value; }
}
/// <summary>
/// The Server-side encryption algorithm to be used with the customer provided key.
///
/// </summary>
public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod
{
get { return this.serverSideCustomerEncryption; }
set { this.serverSideCustomerEncryption = value; }
}
// Check to see if ServerSideEncryptionCustomerMethod property is set
internal bool IsSetServerSideEncryptionCustomerMethod()
{
return this.serverSideCustomerEncryption != null && this.serverSideCustomerEncryption != ServerSideEncryptionCustomerMethod.None;
}
/// <summary>
/// The base64-encoded encryption key for Amazon S3 to use to encrypt the object
/// <para>
/// Using the encryption key you provide as part of your request Amazon S3 manages both the encryption, as it writes
/// to disks, and decryption, when you access your objects. Therefore, you don't need to maintain any data encryption code. The only
/// thing you do is manage the encryption keys you provide.
/// </para>
/// <para>
/// When you retrieve an object, you must provide the same encryption key as part of your request. Amazon S3 first verifies
/// the encryption key you provided matches, and then decrypts the object before returning the object data to you.
/// </para>
/// <para>
/// Important: Amazon S3 does not store the encryption key you provide.
/// </para>
/// </summary>
public string ServerSideEncryptionCustomerProvidedKey
{
get { return this.serverSideEncryptionCustomerProvidedKey; }
set { this.serverSideEncryptionCustomerProvidedKey = value; }
}
/// <summary>
/// Checks if ServerSideEncryptionCustomerProvidedKey property is set.
/// </summary>
/// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns>
internal bool IsSetServerSideEncryptionCustomerProvidedKey()
{
return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKey);
}
/// <summary>
/// The MD5 of the customer encryption key specified in the ServerSideEncryptionCustomerProvidedKey property. The MD5 is
/// base 64 encoded. This field is optional, the SDK will calculate the MD5 if this is not set.
/// </summary>
public string ServerSideEncryptionCustomerProvidedKeyMD5
{
get { return this.serverSideEncryptionCustomerProvidedKeyMD5; }
set { this.serverSideEncryptionCustomerProvidedKeyMD5 = value; }
}
/// <summary>
/// Checks if ServerSideEncryptionCustomerProvidedKeyMD5 property is set.
/// </summary>
/// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns>
internal bool IsSetServerSideEncryptionCustomerProvidedKeyMD5()
{
return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKeyMD5);
}
/// <summary>
/// <para>
/// Full path and name of a file from which the content for the part is retrieved.
/// </para>
/// <para>
/// For WinRT and Windows Phone this property must be in the form of "ms-appdata:///local/file.txt".
/// </para>
/// </summary>
public string FilePath
{
get { return this.filePath; }
set { this.filePath = value; }
}
/// <summary>
/// Checks if the FilePath property is set.
/// </summary>
/// <returns>true if FilePath property is set.</returns>
internal bool IsSetFilePath()
{
return !string.IsNullOrEmpty(this.filePath);
}
/// <summary>
/// Position in the file specified by FilePath from which to retrieve the content of the part.
/// This field is required when a file path is specified. It is ignored when using the InputStream property.
/// </summary>
public long FilePosition
{
get { return this.filePosition.GetValueOrDefault(); }
set { this.filePosition = value; }
}
/// <summary>
/// Checks if the FilePosition property is set.
/// </summary>
/// <returns>true if FilePosition property is set.</returns>
internal bool IsSetFilePosition()
{
return this.filePosition.HasValue;
}
/// <summary>
/// Checks if the MD5Digest property is set.
/// </summary>
/// <returns>true if Md5Digest property is set.</returns>
internal bool IsSetMD5Digest()
{
return !string.IsNullOrEmpty(this.md5Digest);
}
/// <summary>
/// Attach a callback that will be called as data is being sent to the AWS Service.
/// </summary>
public EventHandler<Amazon.Runtime.StreamTransferProgressArgs> StreamTransferProgress
{
get
{
return ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this).StreamUploadProgressCallback;
}
set
{
((Amazon.Runtime.Internal.IAmazonWebServiceRequest)this).StreamUploadProgressCallback = value;
}
}
/// <summary>
/// Overriden to turn off sending SHA256 header.
/// </summary>
protected override bool IncludeSHA256Header
{
get
{
return false;
}
}
/// <summary>
/// Overriden to turn on Expect 100 continue.
/// </summary>
protected override bool Expect100Continue
{
get
{
return true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class SerialStream_BeginWrite_Generic : PortsTest
{
// Set bounds fore random timeout values.
// If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
// If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
// If the percentage difference between the expected timeout and the actual timeout
// found through Stopwatch is greater then 10% then the timeout value was not correctly
// to the write method and the testcase fails.
public static double maxPercentageDifference = .15;
// The byte size used when veryifying exceptions that write will throw
private const int BYTE_SIZE_EXCEPTION = 4;
// The byte size used when veryifying timeout
private const int BYTE_SIZE_TIMEOUT = 4;
// The byte size used when veryifying BytesToWrite
private const int BYTE_SIZE_BYTES_TO_WRITE = 4;
// The bytes size used when veryifying Handshake
private const int BYTE_SIZE_HANDSHAKE = 8;
private const int MAX_WAIT = 250;
private const int ITERATION_WAIT = 50;
private const int NUM_TRYS = 5;
private const int MAX_WAIT_THREAD = 1000;
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
Stream serialStream = com.BaseStream;
com.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterSerialStreamClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to BaseStream.Close()");
com.Open();
Stream serialStream = com.BaseStream;
com.BaseStream.Close();
VerifyWriteException(serialStream, typeof(ObjectDisposedException));
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Timeout()
{
var rndGen = new Random(-55);
int writeTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying WriteTimeout={0}", writeTimeout);
VerifyTimeout(writeTimeout);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var elapsedTime = 0;
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com1.Handshake = Handshake.RequestToSend;
com1.Open();
com2.Open();
com1.WriteTimeout = MAX_WAIT;
IAsyncResult writeAsyncResult = WriteRndByteArray(com1, BYTE_SIZE_BYTES_TO_WRITE);
Thread.Sleep(100);
while (elapsedTime < MAX_WAIT && BYTE_SIZE_BYTES_TO_WRITE != com1.BytesToWrite)
{
elapsedTime += ITERATION_WAIT;
Thread.Sleep(ITERATION_WAIT);
}
if (elapsedTime >= MAX_WAIT)
{
Fail("Err_2257asap!!! Expcted BytesToWrite={0} actual {1} after first write",
BYTE_SIZE_BYTES_TO_WRITE, com1.BytesToWrite);
}
com2.RtsEnable = true;
// Wait for write method to complete
elapsedTime = 0;
while (!writeAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_THREAD)
{
Thread.Sleep(50);
elapsedTime += 50;
}
if (MAX_WAIT_THREAD <= elapsedTime)
{
Fail("Err_40888ajhied!!!: Expected write method to complete");
}
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
// Write a random byte[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
IAsyncResult writeAsyncResult = WriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE);
// Wait for both write methods to timeout
while (!writeAsyncResult.IsCompleted)
Thread.Sleep(100);
if (0 != com.BytesToWrite)
{
Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite);
}
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
#endregion
#region Verification for Test Cases
private IAsyncResult WriteRndByteArray(SerialPort com, int byteLength)
{
var buffer = new byte[byteLength];
var rndGen = new Random(-55);
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)rndGen.Next(0, 256);
}
return com.BaseStream.BeginWrite(buffer, 0, buffer.Length, null, null);
}
private static void VerifyWriteException(Stream serialStream, Type expectedException)
{
Assert.Throws(expectedException, () =>
{
IAsyncResult writeAsyncResult = serialStream.BeginWrite(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION, null, null);
serialStream.EndWrite(writeAsyncResult);
});
}
private void VerifyTimeout(int writeTimeout)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
var asyncRead = new AsyncWrite(com1);
var asyncEndWrite = new Task(asyncRead.EndWrite);
var asyncCallbackCalled = false;
com1.Open();
com2.Open();
com1.Handshake = Handshake.RequestToSend;
com1.WriteTimeout = writeTimeout;
IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(new byte[8], 0, 8, ar => asyncCallbackCalled = true, null);
asyncRead.WriteAsyncResult = writeAsyncResult;
Thread.Sleep(100 > com1.WriteTimeout ? 2 * com1.WriteTimeout : 200);
// Sleep for 200ms or 2 times the WriteTimeout
if (writeAsyncResult.IsCompleted)
{
// Verify the IAsyncResult has not completed
Fail("Err_565088aueiud!!!: Expected read to not have completed");
}
asyncEndWrite.Start();
TCSupport.WaitForTaskToStart(asyncEndWrite);
Thread.Sleep(100 < com1.WriteTimeout ? 2 * com1.WriteTimeout : 200);
// Sleep for 200ms or 2 times the WriteTimeout
if (asyncEndWrite.IsCompleted)
{
// Verify EndRead is blocking and is still alive
Fail("Err_4085858aiehe!!!: Expected read to not have completed");
}
if (asyncCallbackCalled)
{
Fail("Err_750551aiuehd!!!: Expected AsyncCallback not to be called");
}
com2.RtsEnable = true;
TCSupport.WaitForTaskCompletion(asyncEndWrite);
var waitTime = 0;
while (!asyncCallbackCalled && waitTime < 5000)
{
Thread.Sleep(50);
waitTime += 50;
}
if (!asyncCallbackCalled)
{
Fail(
"Err_21208aheide!!!: Expected AsyncCallback to be called after some data was written to the port");
}
}
}
private void Verify_Handshake(Handshake handshake)
{
using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
bool rts = Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake;
bool xonxoff = Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake;
Assert.True(rts || xonxoff);
com1.Handshake = handshake;
com2.ReadTimeout = 200;
com1.Open();
com2.Open();
// Setup to ensure write will block with type of handshake method being used
if (rts)
{
com2.RtsEnable = false;
}
if (xonxoff)
{
IAsyncResult ar = com2.BaseStream.BeginWrite(new byte[] { XOnOff.XOFF }, 0, 1, null, null);
com2.BaseStream.EndWrite(ar);
Thread.Sleep(250);
}
com1.BaseStream.BeginWrite(new byte[] { (byte)'A' }, 0, 1, null, null);
Thread.Sleep(250);
Assert.Throws<TimeoutException>(
() => Console.WriteLine($"Read unexpected byte: {com2.ReadByte()}"));
// Setup to ensure write will succeed
if (rts)
{
Assert.False(com1.CtsHolding);
com2.RtsEnable = true;
}
if (xonxoff)
{
IAsyncResult ar = com2.BaseStream.BeginWrite(new byte[] { XOnOff.XON }, 0, 1, null, null);
com2.BaseStream.EndWrite(ar);
}
Assert.Equal((byte)'A', com2.ReadByte());
Assert.Throws<TimeoutException>(
() => Console.WriteLine($"Read unexpected byte: {com2.ReadByte()}"));
Assert.Equal(0, com1.BytesToWrite);
// Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if (rts)
{
Assert.True(com1.CtsHolding);
}
}
}
private class AsyncWrite
{
private readonly SerialPort _com;
private IAsyncResult _writeAsyncResult;
public AsyncWrite(SerialPort com)
{
_com = com;
}
public IAsyncResult WriteAsyncResult
{
get
{
return _writeAsyncResult;
}
set
{
_writeAsyncResult = value;
}
}
public void EndWrite()
{
_com.BaseStream.EndWrite(_writeAsyncResult);
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CaseStatement.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.ExpressionBuilder;
using System.Data.Common.Utils;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data.Mapping.ViewGeneration.CqlGeneration;
using System.Data.Metadata.Edm;
using System.Diagnostics;
namespace System.Data.Mapping.ViewGeneration.Structures
{
/// <summary>
/// A class to denote a case statement:
/// CASE
/// WHEN condition1 THEN value1
/// WHEN condition2 THEN value2
/// ...
/// END
/// </summary>
internal sealed class CaseStatement : InternalBase
{
#region Constructors
/// <summary>
/// Creates a case statement for the <paramref name="memberPath"/> with no clauses.
/// </summary>
internal CaseStatement(MemberPath memberPath)
{
m_memberPath = memberPath;
m_clauses = new List<WhenThen>();
}
#endregion
#region Fields
/// <summary>
/// The field.
/// </summary>
private readonly MemberPath m_memberPath;
/// <summary>
/// All the WHEN THENs.
/// </summary>
private List<WhenThen> m_clauses;
/// <summary>
/// Value for the else clause.
/// </summary>
private ProjectedSlot m_elseValue;
private bool m_simplified = false;
#endregion
#region Properties
internal MemberPath MemberPath
{
get { return m_memberPath; }
}
internal List<WhenThen> Clauses
{
get { return m_clauses; }
}
internal ProjectedSlot ElseValue
{
get { return m_elseValue; }
}
#endregion
#region Methods
/// <summary>
/// Recursively qualifies all <see cref="ProjectedSlot"/>s and returns a new deeply qualified <see cref="CaseStatement"/>.
/// </summary>
internal CaseStatement DeepQualify(CqlBlock block)
{
// Go through the whenthens and else and make a new case statement with qualified slots as needed.
CaseStatement result = new CaseStatement(m_memberPath);
foreach (WhenThen whenThen in m_clauses)
{
WhenThen newClause = whenThen.ReplaceWithQualifiedSlot(block);
result.m_clauses.Add(newClause);
}
if (m_elseValue != null)
{
result.m_elseValue = m_elseValue.DeepQualify(block);
}
result.m_simplified = m_simplified;
return result;
}
/// <summary>
/// Adds an expression of the form "WHEN <paramref name="condition"/> THEN <paramref name="value"/>".
/// This operation is not allowed after the <see cref="Simplify"/> call.
/// </summary>
internal void AddWhenThen(BoolExpression condition, ProjectedSlot value)
{
Debug.Assert(!m_simplified, "Attempt to modify a simplified case statement");
Debug.Assert(value != null);
condition.ExpensiveSimplify();
m_clauses.Add(new WhenThen(condition, value));
}
/// <summary>
/// Returns true if the <see cref="CaseStatement"/> depends on (projects) its slot in THEN value or ELSE value.
/// </summary>
internal bool DependsOnMemberValue
{
get
{
if (m_elseValue is MemberProjectedSlot)
{
Debug.Assert(m_memberPath.Equals(((MemberProjectedSlot)m_elseValue).MemberPath), "case statement slot (ELSE) must depend only on its own slot value");
return true;
}
foreach (WhenThen whenThen in m_clauses)
{
if (whenThen.Value is MemberProjectedSlot)
{
Debug.Assert(m_memberPath.Equals(((MemberProjectedSlot)whenThen.Value).MemberPath), "case statement slot (THEN) must depend only on its own slot value");
return true;
}
}
return false;
}
}
internal IEnumerable<EdmType> InstantiatedTypes
{
get
{
foreach (WhenThen whenThen in m_clauses)
{
EdmType type;
if (TryGetInstantiatedType(whenThen.Value, out type))
{
yield return type;
}
}
EdmType elseType;
if (TryGetInstantiatedType(m_elseValue, out elseType))
{
yield return elseType;
}
}
}
private bool TryGetInstantiatedType(ProjectedSlot slot, out EdmType type)
{
type = null;
ConstantProjectedSlot constantSlot = slot as ConstantProjectedSlot;
if (constantSlot != null)
{
TypeConstant typeConstant = constantSlot.CellConstant as TypeConstant;
if (typeConstant != null)
{
type = typeConstant.EdmType;
return true;
}
}
return false;
}
/// <summary>
/// Simplifies the <see cref="CaseStatement"/> so that unnecessary WHEN/THENs for nulls/undefined values are eliminated.
/// Also, adds an ELSE clause if possible.
/// </summary>
internal void Simplify()
{
if (m_simplified)
{
return;
}
List<CaseStatement.WhenThen> clauses = new List<CaseStatement.WhenThen>();
// remove all WHEN clauses where the value gets set to "undefined"
// We eliminate the last clause for now - we could determine the
// "most complicated" WHEN clause and eliminate it
bool eliminatedNullClauses = false;
foreach (WhenThen clause in m_clauses)
{
ConstantProjectedSlot constantSlot = clause.Value as ConstantProjectedSlot;
// If null or undefined, remove it
if (constantSlot != null && (constantSlot.CellConstant.IsNull() || constantSlot.CellConstant.IsUndefined()))
{
eliminatedNullClauses = true;
}
else
{
clauses.Add(clause);
if (clause.Condition.IsTrue)
{
// none of subsequent case statements will be evaluated - ignore them
break;
}
}
}
if (eliminatedNullClauses && clauses.Count == 0)
{
// There is nothing left -- we should add a null as the value
m_elseValue = new ConstantProjectedSlot(Constant.Null, m_memberPath);
}
// If we eliminated some undefined or null clauses, we do not want an else clause
if (clauses.Count > 0 && false == eliminatedNullClauses)
{
// turn the last WHEN clause into an ELSE
int lastIndex = clauses.Count - 1;
m_elseValue = clauses[lastIndex].Value;
clauses.RemoveAt(lastIndex);
}
m_clauses = clauses;
m_simplified = true;
}
/// <summary>
/// Generates eSQL for the current <see cref="CaseStatement"/>.
/// </summary>
internal StringBuilder AsEsql(StringBuilder builder, IEnumerable<WithRelationship> withRelationships, string blockAlias, int indentLevel)
{
if (this.Clauses.Count == 0)
{
// This is just a single ELSE: no condition at all.
Debug.Assert(this.ElseValue != null, "CASE statement with no WHEN/THENs must have ELSE.");
CaseSlotValueAsEsql(builder, this.ElseValue, this.MemberPath, blockAlias, withRelationships, indentLevel);
return builder;
}
// Generate the Case WHEN .. THEN ..., WHEN ... THEN ..., END
builder.Append("CASE");
foreach (CaseStatement.WhenThen clause in this.Clauses)
{
StringUtil.IndentNewLine(builder, indentLevel + 2);
builder.Append("WHEN ");
clause.Condition.AsEsql(builder, blockAlias);
builder.Append(" THEN ");
CaseSlotValueAsEsql(builder, clause.Value, this.MemberPath, blockAlias, withRelationships, indentLevel + 2);
}
if (this.ElseValue != null)
{
StringUtil.IndentNewLine(builder, indentLevel + 2);
builder.Append("ELSE ");
CaseSlotValueAsEsql(builder, this.ElseValue, this.MemberPath, blockAlias, withRelationships, indentLevel + 2);
}
StringUtil.IndentNewLine(builder, indentLevel + 1);
builder.Append("END");
return builder;
}
/// <summary>
/// Generates CQT for the current <see cref="CaseStatement"/>.
/// </summary>
internal DbExpression AsCqt(DbExpression row, IEnumerable<WithRelationship> withRelationships)
{
// Generate the Case WHEN .. THEN ..., WHEN ... THEN ..., END
List<DbExpression> conditions = new List<DbExpression>();
List<DbExpression> values = new List<DbExpression>();
foreach (CaseStatement.WhenThen clause in this.Clauses)
{
conditions.Add(clause.Condition.AsCqt(row));
values.Add(CaseSlotValueAsCqt(row, clause.Value, this.MemberPath, withRelationships));
}
// Generate ELSE
DbExpression elseValue = this.ElseValue != null ?
CaseSlotValueAsCqt(row, this.ElseValue, this.MemberPath, withRelationships) :
Constant.Null.AsCqt(row, this.MemberPath);
if (this.Clauses.Count > 0)
{
return DbExpressionBuilder.Case(conditions, values, elseValue);
}
else
{
Debug.Assert(elseValue != null, "CASE statement with no WHEN/THENs must have ELSE.");
return elseValue;
}
}
private static StringBuilder CaseSlotValueAsEsql(StringBuilder builder, ProjectedSlot slot, MemberPath outputMember, string blockAlias, IEnumerable<WithRelationship> withRelationships, int indentLevel)
{
// We should never have THEN as a BooleanProjectedSlot.
Debug.Assert(slot is MemberProjectedSlot || slot is QualifiedSlot || slot is ConstantProjectedSlot,
"Case statement THEN can only have constants or members.");
slot.AsEsql(builder, outputMember, blockAlias, 1);
WithRelationshipsClauseAsEsql(builder, withRelationships, blockAlias, indentLevel, slot);
return builder;
}
private static void WithRelationshipsClauseAsEsql(StringBuilder builder, IEnumerable<WithRelationship> withRelationships, string blockAlias, int indentLevel, ProjectedSlot slot)
{
bool first = true;
WithRelationshipsClauseAsCql(
// emitWithRelationship action
(withRelationship) =>
{
if (first)
{
builder.Append(" WITH ");
first = false;
}
withRelationship.AsEsql(builder, blockAlias, indentLevel);
},
withRelationships,
slot);
}
private static DbExpression CaseSlotValueAsCqt(DbExpression row, ProjectedSlot slot, MemberPath outputMember, IEnumerable<WithRelationship> withRelationships)
{
// We should never have THEN as a BooleanProjectedSlot.
Debug.Assert(slot is MemberProjectedSlot || slot is QualifiedSlot || slot is ConstantProjectedSlot,
"Case statement THEN can only have constants or members.");
DbExpression cqt = slot.AsCqt(row, outputMember);
cqt = WithRelationshipsClauseAsCqt(row, cqt, withRelationships, slot);
return cqt;
}
private static DbExpression WithRelationshipsClauseAsCqt(DbExpression row, DbExpression slotValueExpr, IEnumerable<WithRelationship> withRelationships, ProjectedSlot slot)
{
List<DbRelatedEntityRef> relatedEntityRefs = new List<DbRelatedEntityRef>();
WithRelationshipsClauseAsCql(
// emitWithRelationship action
(withRelationship) =>
{
relatedEntityRefs.Add(withRelationship.AsCqt(row));
},
withRelationships,
slot);
if (relatedEntityRefs.Count > 0)
{
DbNewInstanceExpression typeConstructor = slotValueExpr as DbNewInstanceExpression;
Debug.Assert(typeConstructor != null && typeConstructor.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.EntityType,
"WITH RELATIONSHIP clauses should be specified for entity type constructors only.");
return DbExpressionBuilder.CreateNewEntityWithRelationshipsExpression(
(EntityType)typeConstructor.ResultType.EdmType,
typeConstructor.Arguments,
relatedEntityRefs);
}
else
{
return slotValueExpr;
}
}
private static void WithRelationshipsClauseAsCql(Action<WithRelationship> emitWithRelationship, IEnumerable<WithRelationship> withRelationships, ProjectedSlot slot)
{
if (withRelationships != null && withRelationships.Count() > 0)
{
ConstantProjectedSlot constantSlot = slot as ConstantProjectedSlot;
Debug.Assert(constantSlot != null, "WITH RELATIONSHIP clauses should be specified for type constant slots only.");
TypeConstant typeConstant = constantSlot.CellConstant as TypeConstant;
Debug.Assert(typeConstant != null, "WITH RELATIONSHIP clauses should be there for type constants only.");
EdmType fromType = typeConstant.EdmType;
foreach (WithRelationship withRelationship in withRelationships)
{
// Add With statement for the types that participate in the association.
if (withRelationship.FromEndEntityType.IsAssignableFrom(fromType))
{
emitWithRelationship(withRelationship);
}
}
}
}
internal override void ToCompactString(StringBuilder builder)
{
builder.AppendLine("CASE");
foreach (WhenThen clause in m_clauses)
{
builder.Append(" WHEN ");
clause.Condition.ToCompactString(builder);
builder.Append(" THEN ");
clause.Value.ToCompactString(builder);
builder.AppendLine();
}
if (m_elseValue != null)
{
builder.Append(" ELSE ");
m_elseValue.ToCompactString(builder);
builder.AppendLine();
}
builder.Append(" END AS ");
m_memberPath.ToCompactString(builder);
}
#endregion
/// <summary>
/// A class that stores WHEN condition THEN value.
/// </summary>
internal sealed class WhenThen : InternalBase
{
#region Constructor
/// <summary>
/// Creates WHEN condition THEN value.
/// </summary>
internal WhenThen(BoolExpression condition, ProjectedSlot value)
{
m_condition = condition;
m_value = value;
}
#endregion
#region Fields
private readonly BoolExpression m_condition;
private readonly ProjectedSlot m_value;
#endregion
#region Properties
/// <summary>
/// Returns WHEN condition.
/// </summary>
internal BoolExpression Condition
{
get { return m_condition; }
}
/// <summary>
/// Returns THEN value.
/// </summary>
internal ProjectedSlot Value
{
get { return m_value; }
}
#endregion
#region String Methods
internal WhenThen ReplaceWithQualifiedSlot(CqlBlock block)
{
// Change the THEN part
ProjectedSlot newValue = m_value.DeepQualify(block);
return new WhenThen(m_condition, newValue);
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append("WHEN ");
m_condition.ToCompactString(builder);
builder.Append("THEN ");
m_value.ToCompactString(builder);
}
#endregion
}
}
}
| |
//
// NSData.cs:
// Author:
// Miguel de Icaza
//
// Copyright 2010, Novell, Inc.
// Copyright 2011, 2012 Xamarin 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 MonoMac.ObjCRuntime;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
namespace MonoMac.Foundation {
public partial class NSData : IEnumerable, IEnumerable<byte> {
// some API, like SecItemCopyMatching, returns a retained NSData
internal NSData (IntPtr handle, bool owns)
: base (handle)
{
if (!owns)
Release ();
}
IEnumerator IEnumerable.GetEnumerator ()
{
IntPtr source = Bytes;
int top = (int) Length;
for (int i = 0; i < top; i++){
yield return Marshal.ReadByte (source, i);
}
}
IEnumerator<byte> IEnumerable<byte>.GetEnumerator ()
{
IntPtr source = Bytes;
int top = (int) Length;
for (int i = 0; i < top; i++)
yield return Marshal.ReadByte (source, i);
}
public static NSData FromString (string s)
{
if (s == null)
throw new ArgumentNullException ("s");
return new NSString (s).Encode (NSStringEncoding.UTF8);
}
public static NSData FromArray (byte [] buffer)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (buffer.Length == 0)
return FromBytes (IntPtr.Zero, 0);
unsafe {
fixed (byte *ptr = &buffer [0]){
return FromBytes ((IntPtr) ptr, (uint) buffer.Length);
}
}
}
public static NSData FromStream (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (!stream.CanRead)
return null;
NSMutableData ret = null;
long len;
try {
len = stream.Length;
} catch {
len = 8192;
}
ret = NSMutableData.FromCapacity ((int)len);
byte [] buffer = new byte [32*1024];
int n;
try {
unsafe {
while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
fixed (byte *ptr = &buffer [0])
ret.AppendBytes ((IntPtr) ptr, (uint) n);
}
}
} catch {
return null;
}
return ret;
}
//
// Keeps a ref to the source NSData
//
unsafe class UnmanagedMemoryStreamWithRef : UnmanagedMemoryStream {
NSData source;
public UnmanagedMemoryStreamWithRef (NSData source, byte *pointer, long length) : base (pointer, length)
{
this.source = source;
}
protected override void Dispose (bool disposing)
{
source = null;
base.Dispose (disposing);
}
}
public virtual Stream AsStream ()
{
if (this is NSMutableData)
throw new Exception ("Wrapper for NSMutableData is not supported, call new UnmanagedMemoryStream ((Byte*) mutableData.Bytes, mutableData.Length) instead");
unsafe {
return new UnmanagedMemoryStreamWithRef (this, (byte *) Bytes, Length);
}
}
public static NSData FromString (string s, NSStringEncoding encoding)
{
return new NSString (s).Encode (encoding);
}
public static implicit operator NSData (string s)
{
return new NSString (s).Encode (NSStringEncoding.UTF8);
}
public NSString ToString (NSStringEncoding encoding)
{
return NSString.FromData (this, encoding);
}
public override string ToString ()
{
return ToString (NSStringEncoding.UTF8);
}
public bool Save (string file, bool auxiliaryFile, out NSError error)
{
unsafe {
IntPtr val;
IntPtr val_addr = (IntPtr) ((IntPtr *) &val);
bool ret = _Save (file, auxiliaryFile ? 1 : 0, val_addr);
error = (NSError) Runtime.GetNSObject (val);
return ret;
}
}
public bool Save (string file, NSDataWritingOptions options, out NSError error)
{
unsafe {
IntPtr val;
IntPtr val_addr = (IntPtr) ((IntPtr *) &val);
bool ret = _Save (file, (int) options, val_addr);
error = (NSError) Runtime.GetNSObject (val);
return ret;
}
}
public bool Save (NSUrl url, bool auxiliaryFile, out NSError error)
{
unsafe {
IntPtr val;
IntPtr val_addr = (IntPtr) ((IntPtr *) &val);
bool ret = _Save (url, auxiliaryFile ? 1 : 0, val_addr);
error = (NSError) Runtime.GetNSObject (val);
return ret;
}
}
public virtual byte this [int idx] {
get {
if (idx < 0 || idx >= Int32.MaxValue || idx > (int) Length)
throw new ArgumentException ("idx");
return Marshal.ReadByte (Bytes, idx);
}
set {
throw new NotImplementedException ("NSData arrays can not be modified, use an NSMUtableData instead");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Owin;
using DotVVM.Framework.Configuration;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Parser;
using DotVVM.Framework.ViewModel;
using DotVVM.Framework.Runtime;
using DotVVM.Framework.Runtime.Filters;
using DotVVM.Framework.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using DotVVM.Framework.Binding;
namespace DotVVM.Framework.Hosting
{
public class DotvvmPresenter : IDotvvmPresenter
{
public IDotvvmViewBuilder DotvvmViewBuilder { get; private set; }
public IViewModelLoader ViewModelLoader { get; private set; }
public IViewModelSerializer ViewModelSerializer { get; private set; }
public IOutputRenderer OutputRenderer { get; private set; }
public ICsrfProtector CsrfProtector { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmPresenter"/> class.
/// </summary>
public DotvvmPresenter(DotvvmConfiguration configuration)
{
DotvvmViewBuilder = configuration.ServiceLocator.GetService<IDotvvmViewBuilder>();
ViewModelLoader = configuration.ServiceLocator.GetService<IViewModelLoader>();
ViewModelSerializer = configuration.ServiceLocator.GetService<IViewModelSerializer>();
OutputRenderer = configuration.ServiceLocator.GetService<IOutputRenderer>();
CsrfProtector = configuration.ServiceLocator.GetService<ICsrfProtector>();
}
/// <summary>
/// Initializes a new instance of the <see cref="DotvvmPresenter"/> class.
/// </summary>
public DotvvmPresenter(
IDotvvmViewBuilder dotvvmViewBuilder,
IViewModelLoader viewModelLoader,
IViewModelSerializer viewModelSerializer,
IOutputRenderer outputRenderer,
ICsrfProtector csrfProtector
)
{
DotvvmViewBuilder = dotvvmViewBuilder;
ViewModelLoader = viewModelLoader;
ViewModelSerializer = viewModelSerializer;
OutputRenderer = outputRenderer;
CsrfProtector = csrfProtector;
}
/// <summary>
/// Processes the request.
/// </summary>
public async Task ProcessRequest(DotvvmRequestContext context)
{
bool failedAsUnauthorized = false;
Exception exception = null;
try
{
await ProcessRequestCore(context);
}
catch (DotvvmInterruptRequestExecutionException)
{
// the response has already been generated, do nothing
return;
}
catch (UnauthorizedAccessException ex)
{
failedAsUnauthorized = true;
exception = ex;
}
if (failedAsUnauthorized)
{
// unauthorized error
context.OwinContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await DotvvmErrorPageMiddleware.RenderErrorResponse(context.OwinContext, exception);
}
}
public async Task ProcessRequestCore(DotvvmRequestContext context)
{
if (context.OwinContext.Request.Method != "GET" && context.OwinContext.Request.Method != "POST")
{
// unknown HTTP method
context.OwinContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
throw new DotvvmHttpException("Only GET and POST methods are supported!");
}
if (context.OwinContext.Request.Headers["X-PostbackType"] == "StaticCommand")
{
ProcessStaticCommandRequest(context);
return;
}
var isPostBack = DetermineIsPostBack(context.OwinContext);
context.IsPostBack = isPostBack;
context.ChangeCurrentCulture(context.Configuration.DefaultCulture);
// build the page view
var page = DotvvmViewBuilder.BuildView(context);
// run the preinit phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnPreInit(context));
// run the init phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnInit(context));
// locate and create the view model
context.ViewModel = ViewModelLoader.InitializeViewModel(context, page);
page.DataContext = context.ViewModel;
// get action filters
var globalFilters = context.Configuration.Runtime.GlobalFilters.ToList();
var viewModelFilters = context.ViewModel.GetType().GetCustomAttributes<ActionFilterAttribute>(true).ToList();
// run OnViewModelCreated on action filters
foreach (var filter in globalFilters.Concat(viewModelFilters))
{
filter.OnViewModelCreated(context);
}
// init the view model lifecycle
if (context.ViewModel is IDotvvmViewModel)
{
((IDotvvmViewModel)context.ViewModel).Context = context;
await ((IDotvvmViewModel)context.ViewModel).Init();
}
if (!isPostBack)
{
// perform standard get
if (context.ViewModel is IDotvvmViewModel)
{
await ((IDotvvmViewModel)context.ViewModel).Load();
}
// run the load phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnLoad(context));
}
else
{
// perform the postback
string postData;
using (var sr = new StreamReader(context.OwinContext.Request.Body))
{
postData = await sr.ReadToEndAsync();
}
ViewModelSerializer.PopulateViewModel(context, page, postData);
// validate CSRF token
CsrfProtector.VerifyToken(context, context.CsrfToken);
if (context.ViewModel is IDotvvmViewModel)
{
await ((IDotvvmViewModel)context.ViewModel).Load();
}
// run the load phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnLoad(context));
// invoke the postback command
ActionInfo actionInfo;
ViewModelSerializer.ResolveCommand(context, page, postData, out actionInfo);
if (actionInfo != null)
{
var methodFilters = actionInfo.Binding.ActionFilters == null ? globalFilters.Concat(viewModelFilters).ToArray() :
globalFilters.Concat(viewModelFilters).Concat(actionInfo.Binding.ActionFilters).ToArray();
// run OnCommandExecuting on action filters
foreach (var filter in methodFilters)
{
filter.OnCommandExecuting(context, actionInfo);
}
Exception commandException = null;
try
{
actionInfo.Action();
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
ex = ex.InnerException;
}
if (ex is DotvvmInterruptRequestExecutionException)
{
throw new DotvvmInterruptRequestExecutionException("The request execution was interrupted in the command!", ex);
}
commandException = ex;
}
// run OnCommandExecuted on action filters
foreach (var filter in methodFilters)
{
filter.OnCommandExecuted(context, actionInfo, commandException);
}
if (commandException != null && !context.IsCommandExceptionHandled)
{
throw new Exception("Unhandled exception occured in the command!", commandException);
}
}
}
if (context.ViewModel is IDotvvmViewModel)
{
await ((IDotvvmViewModel)context.ViewModel).PreRender();
}
// run the prerender phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnPreRender(context));
// run the prerender complete phase in the page
InvokePageLifeCycleEventRecursive(page, c => c.OnPreRenderComplete(context));
// generate CSRF token if required
if (string.IsNullOrEmpty(context.CsrfToken))
{
context.CsrfToken = CsrfProtector.GenerateToken(context);
}
// run OnResponseRendering on action filters
foreach (var filter in globalFilters.Concat(viewModelFilters))
{
filter.OnResponseRendering(context);
}
// render the output
ViewModelSerializer.BuildViewModel(context, page);
OutputRenderer.RenderPage(context, page);
if (!context.IsInPartialRenderingMode)
{
// standard get
await OutputRenderer.WriteHtmlResponse(context);
}
else
{
// postback or SPA content
ViewModelSerializer.AddPostBackUpdatedControls(context);
await OutputRenderer.WriteViewModelResponse(context, page);
}
if (context.ViewModel != null)
{
ViewModelLoader.DisposeViewModel(context.ViewModel);
}
}
public void ProcessStaticCommandRequest(DotvvmRequestContext context)
{
JObject postData;
using (var jsonReader = new JsonTextReader(new StreamReader(context.OwinContext.Request.Body)))
{
postData = JObject.Load(jsonReader);
}
// validate csrf token
context.CsrfToken = postData["$csrfToken"].Value<string>();
CsrfProtector.VerifyToken(context, context.CsrfToken);
var command = postData["command"].Value<string>();
var arguments = postData["args"].ToObject<object[]>();
var lastDot = command.LastIndexOf('.');
var typeName = command.Remove(lastDot);
var methodName = command.Substring(lastDot + 1);
var methodInfo = Type.GetType(typeName).GetMethod(methodName);
if (!Attribute.IsDefined(methodInfo, typeof(StaticCommandCallableAttribute)))
{
throw new DotvvmHttpException("method validation failed");
}
var actionInfo = new ActionInfo()
{
IsControlCommand = false,
Action = () => methodInfo.Invoke(null, arguments)
};
var filters = methodInfo.GetCustomAttributes<ActionFilterAttribute>();
foreach (var filter in filters)
{
filter.OnCommandExecuting(context, actionInfo);
}
Exception exception = null;
object result = null;
try
{
result = methodInfo.Invoke(null, arguments);
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
ex = ex.InnerException;
}
if (ex is DotvvmInterruptRequestExecutionException)
{
throw new DotvvmInterruptRequestExecutionException("The request execution was interrupted in the command!", ex);
}
exception = ex;
}
foreach (var filter in filters)
{
filter.OnCommandExecuted(context, actionInfo, exception);
}
if (exception != null)
{
throw new Exception("unhandled exception in command", exception);
}
if (result != null)
{
using (var writer = new StreamWriter(context.OwinContext.Response.Body))
{
writer.WriteLine(JsonConvert.SerializeObject(result));
}
}
}
public static bool DetermineIsPostBack(IOwinContext context)
{
return context.Request.Method == "POST";
}
public static bool DetermineSpaRequest(IOwinContext context)
{
return !string.IsNullOrEmpty(context.Request.Headers[Constants.SpaContentPlaceHolderHeaderName]);
}
public static bool DeterminePartialRendering(IOwinContext context)
{
return DetermineIsPostBack(context) || DetermineSpaRequest(context);
}
public static string DetermineSpaContentPlaceHolderUniqueId(IOwinContext context)
{
return context.Request.Headers[Constants.SpaContentPlaceHolderHeaderName];
}
/// <summary>
/// Invokes the specified method on all controls in the page control tree.
/// </summary>
private void InvokePageLifeCycleEventRecursive(DotvvmControl control, Action<DotvvmControl> action)
{
foreach (var child in control.GetThisAndAllDescendants())
{
action(child);
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Describes a .proto file, including everything defined within.
/// IDescriptor is implemented such that the File property returns this descriptor,
/// and the FullName is the same as the Name.
/// </summary>
public sealed class FileDescriptor : IDescriptor
{
private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedCodeInfo generatedCodeInfo)
{
SerializedData = descriptorData;
DescriptorPool = pool;
Proto = proto;
Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
pool.AddPackage(Package, this);
MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
(message, index) =>
new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(enumType, index) =>
new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) =>
new ServiceDescriptor(service, this, index));
}
/// <summary>
/// Computes the full name of a descriptor within this file, with an optional parent message.
/// </summary>
internal string ComputeFullName(MessageDescriptor parent, string name)
{
if (parent != null)
{
return parent.FullName + "." + name;
}
if (Package.Length > 0)
{
return Package + "." + name;
}
return name;
}
/// <summary>
/// Extracts public dependencies from direct dependencies. This is a static method despite its
/// first parameter, as the value we're in the middle of constructing is only used for exceptions.
/// </summary>
private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
{
var nameToFileMap = new Dictionary<string, FileDescriptor>();
foreach (var file in dependencies)
{
nameToFileMap[file.Name] = file;
}
var publicDependencies = new List<FileDescriptor>();
for (int i = 0; i < proto.PublicDependency.Count; i++)
{
int index = proto.PublicDependency[i];
if (index < 0 || index >= proto.Dependency.Count)
{
throw new DescriptorValidationException(@this, "Invalid public dependency index.");
}
string name = proto.Dependency[index];
FileDescriptor file = nameToFileMap[name];
if (file == null)
{
if (!allowUnknownDependencies)
{
throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
}
else
{
publicDependencies.Add(file);
}
}
return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
}
/// <value>
/// The descriptor in its protocol message representation.
/// </value>
internal FileDescriptorProto Proto { get; }
/// <value>
/// The file name.
/// </value>
public string Name => Proto.Name;
/// <summary>
/// The package as declared in the .proto file. This may or may not
/// be equivalent to the .NET namespace of the generated classes.
/// </summary>
public string Package => Proto.Package;
/// <value>
/// Unmodifiable list of top-level message types declared in this file.
/// </value>
public IList<MessageDescriptor> MessageTypes { get; }
/// <value>
/// Unmodifiable list of top-level enum types declared in this file.
/// </value>
public IList<EnumDescriptor> EnumTypes { get; }
/// <value>
/// Unmodifiable list of top-level services declared in this file.
/// </value>
public IList<ServiceDescriptor> Services { get; }
/// <value>
/// Unmodifiable list of this file's dependencies (imports).
/// </value>
public IList<FileDescriptor> Dependencies { get; }
/// <value>
/// Unmodifiable list of this file's public dependencies (public imports).
/// </value>
public IList<FileDescriptor> PublicDependencies { get; }
/// <value>
/// The original serialized binary form of this descriptor.
/// </value>
public ByteString SerializedData { get; }
/// <value>
/// Implementation of IDescriptor.FullName - just returns the same as Name.
/// </value>
string IDescriptor.FullName => Name;
/// <value>
/// Implementation of IDescriptor.File - just returns this descriptor.
/// </value>
FileDescriptor IDescriptor.File => this;
/// <value>
/// Pool containing symbol descriptors.
/// </value>
internal DescriptorPool DescriptorPool { get; }
/// <summary>
/// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
/// </summary>
/// <param name="name">The unqualified type name to look for.</param>
/// <typeparam name="T">The type of descriptor to look for</typeparam>
/// <returns>The type's descriptor, or null if not found.</returns>
public T FindTypeByName<T>(String name)
where T : class, IDescriptor
{
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.IndexOf('.') != -1)
{
return null;
}
if (Package.Length > 0)
{
name = Package + "." + name;
}
T result = DescriptorPool.FindSymbol<T>(name);
if (result != null && result.File == this)
{
return result;
}
return null;
}
/// <summary>
/// Builds a FileDescriptor from its protocol buffer representation.
/// </summary>
/// <param name="descriptorData">The original serialized descriptor data.
/// We have only limited proto2 support, so serializing FileDescriptorProto
/// would not necessarily give us this.</param>
/// <param name="proto">The protocol message form of the FileDescriptor.</param>
/// <param name="dependencies">FileDescriptors corresponding to all of the
/// file's dependencies, in the exact order listed in the .proto file. May be null,
/// in which case it is treated as an empty array.</param>
/// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
/// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
/// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
/// a valid descriptor. This can occur for a number of reasons, such as a field
/// having an undefined type or because two messages were defined with the same name.</exception>
private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedCodeInfo generatedCodeInfo)
{
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
// constructor), we build an object tree mirroring the
// FileDescriptorProto's tree and put all of the descriptors into the
// DescriptorPool's lookup tables. In the linking step, we look up all
// type references in the DescriptorPool, so that, for example, a
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
if (dependencies == null)
{
dependencies = new FileDescriptor[0];
}
DescriptorPool pool = new DescriptorPool(dependencies);
FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
// Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
// need.
if (dependencies.Length != proto.Dependency.Count)
{
throw new DescriptorValidationException(
result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto.");
}
for (int i = 0; i < proto.Dependency.Count; i++)
{
if (dependencies[i].Name != proto.Dependency[i])
{
throw new DescriptorValidationException(
result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto. Expected: " +
proto.Dependency[i] + " but was: " + dependencies[i].Name);
}
}
result.CrossLink();
return result;
}
private void CrossLink()
{
foreach (MessageDescriptor message in MessageTypes)
{
message.CrossLink();
}
foreach (ServiceDescriptor service in Services)
{
service.CrossLink();
}
}
/// <summary>
/// Creates a descriptor for generated code.
/// </summary>
/// <remarks>
/// This method is only designed to be used by the results of generating code with protoc,
/// which creates the appropriate dependencies etc. It has to be public because the generated
/// code is "external", but should not be called directly by end users.
/// </remarks>
public static FileDescriptor FromGeneratedCode(
byte[] descriptorData,
FileDescriptor[] dependencies,
GeneratedCodeInfo generatedCodeInfo)
{
FileDescriptorProto proto;
try
{
proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
}
catch (InvalidProtocolBufferException e)
{
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
}
try
{
// When building descriptors for generated code, we allow unknown
// dependencies by default.
return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
}
catch (DescriptorValidationException e)
{
throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return $"FileDescriptor for {Name}";
}
/// <summary>
/// Returns the file descriptor for descriptor.proto.
/// </summary>
/// <remarks>
/// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
/// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
/// runtime for reflection purposes. The messages are internal to the runtime as they would require
/// proto2 semantics for full support, but the file descriptor is available via this property. The
/// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
/// </remarks>
/// <value>
/// The file descriptor for <c>descriptor.proto</c>.
/// </value>
public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Maw.Domain;
using Maw.Domain.Photos;
namespace Maw.Data
{
public class PhotoRepository
: Repository, IPhotoRepository
{
public PhotoRepository(string connectionString)
: base(connectionString)
{
}
public Task<IEnumerable<short>> GetYearsAsync(string[] roles)
{
return RunAsync(conn =>
conn.QueryAsync<short>(
"SELECT * FROM photo.get_years(@roles);",
new
{
roles
}
)
);
}
public Task<IEnumerable<Category>> GetAllCategoriesAsync(string[] roles)
{
return InternalGetCategoriesAsync(roles);
}
public Task<IEnumerable<Category>> GetCategoriesForYearAsync(short year, string[] roles)
{
return InternalGetCategoriesAsync(roles, year);
}
public Task<IEnumerable<Category>> GetRecentCategoriesAsync(short sinceId, string[] roles)
{
return InternalGetCategoriesAsync(roles, sinceCategoryId: sinceId);
}
public async Task<Category> GetCategoryAsync(short categoryId, string[] roles)
{
var result = await InternalGetCategoriesAsync(roles, categoryId: categoryId).ConfigureAwait(false);
return result.FirstOrDefault();
}
public Task<IEnumerable<Photo>> GetPhotosForCategoryAsync(short categoryId, string[] roles)
{
return InternalGetPhotosAsync(roles, categoryId);
}
public async Task<Photo> GetPhotoAsync(int photoId, string[] roles)
{
var result = await InternalGetPhotosAsync(roles, photoId: photoId).ConfigureAwait(false);
return result.FirstOrDefault();
}
public async Task<Photo> GetRandomAsync(string[] roles)
{
var results = await GetRandomAsync(1, roles).ConfigureAwait(false);
return results.First();
}
public Task<IEnumerable<Photo>> GetRandomAsync(byte count, string[] roles)
{
return RunAsync(async conn =>
{
var rows = await conn.QueryAsync(
"SELECT * FROM photo.get_random_photos(@roles, @count)",
new
{
roles,
count
}
).ConfigureAwait(false);
return rows.Select(BuildPhoto);
});
}
public Task<Detail> GetDetailAsync(int photoId, string[] roles)
{
return RunAsync(conn =>
conn.QuerySingleOrDefaultAsync<Detail>(
"SELECT * FROM photo.get_photo_metadata(@roles, @photoId);",
new
{
roles,
photoId
}
)
);
}
public Task<IEnumerable<Comment>> GetCommentsAsync(int photoId, string[] roles)
{
return RunAsync(conn =>
conn.QueryAsync<Comment>(
"SELECT * FROM photo.get_comments(@photoId, @roles);",
new
{
photoId,
roles
}
)
);
}
public Task<Rating> GetRatingsAsync(int photoId, string username, string[] roles)
{
return RunAsync(conn =>
conn.QuerySingleOrDefaultAsync<Rating>(
"SELECT * FROM photo.get_ratings(@photoId, @username, @roles);",
new
{
photoId,
username = username?.ToLowerInvariant(),
roles
}
)
);
}
public Task<GpsDetail> GetGpsDetailAsync(int photoId, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QuerySingleOrDefaultAsync<GpsSourceOverride>(
"SELECT * FROM photo.get_gps(@photoId, @roles);",
new
{
photoId,
roles
}
).ConfigureAwait(false);
if (result == null)
{
return null;
}
var detail = new GpsDetail();
if (result.SourceLatitude != null && result.SourceLongitude != null)
{
detail.Source = new GpsCoordinate()
{
Latitude = (float)result.SourceLatitude,
Longitude = (float)result.SourceLongitude
};
}
if (result.OverrideLatitude != null && result.OverrideLongitude != null)
{
detail.Override = new GpsCoordinate()
{
Latitude = (float)result.OverrideLatitude,
Longitude = (float)result.OverrideLongitude
};
}
return detail;
});
}
public Task<int> InsertCommentAsync(int photoId, string username, string comment, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QuerySingleOrDefaultAsync<int>(
"SELECT * FROM photo.save_comment(@username, @photoId, @message, @entryDate, @roles);",
new
{
username = username.ToLowerInvariant(),
photoId,
message = comment,
entryDate = DateTime.Now,
roles
}
).ConfigureAwait(false);
if (result <= 0)
{
throw new Exception("Did not save photo comment!");
}
return result;
});
}
public Task<float?> SaveRatingAsync(int photoId, string username, short rating, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QueryAsync<long>(
"SELECT * FROM photo.save_rating(@photoId, @username, @score, @roles);",
new
{
photoId,
username = username.ToLowerInvariant(),
score = rating,
roles
}
).ConfigureAwait(false);
return (await GetRatingsAsync(photoId, username, roles).ConfigureAwait(false))?.AverageRating;
});
}
public Task<float?> RemoveRatingAsync(int photoId, string username, string[] roles)
{
return RunAsync(async conn =>
{
var result = await conn.QueryAsync<long>(
"SELECT * FROM photo.save_rating(@photoId, @username, @score, @roles);",
new
{
photoId,
username = username.ToLowerInvariant(),
score = 0,
roles
}
).ConfigureAwait(false);
return (await GetRatingsAsync(photoId, username, roles).ConfigureAwait(false))?.AverageRating;
});
}
public Task SetGpsOverrideAsync(int photoId, GpsCoordinate gps, string username)
{
return RunAsync(conn =>
conn.QueryAsync<long>(
"SELECT * FROM photo.set_gps_override(@photoId, @latitude, @longitude, @username, @updateDate);",
new
{
photoId,
latitude = gps.Latitude,
longitude = gps.Longitude,
username = username.ToLowerInvariant(),
updateDate = DateTime.Now
}
)
);
}
public Task<long> SetCategoryTeaserAsync(short categoryId, int photoId)
{
return RunAsync(conn =>
conn.QueryFirstAsync<long>(
@"SELECT * FROM photo.set_category_teaser(@categoryId, @photoId);",
new
{
categoryId,
photoId
}
)
);
}
Task<IEnumerable<Category>> InternalGetCategoriesAsync(string[] roles, short? year = null, short? categoryId = null, short? sinceCategoryId = null)
{
return RunAsync(async conn =>
{
var rows = await conn.QueryAsync(
"SELECT * FROM photo.get_categories(@roles, @year, @categoryId, @sinceCategoryId);",
new
{
roles,
year,
categoryId,
sinceCategoryId
}
).ConfigureAwait(false);
return rows.Select(BuildCategory);
});
}
Task<IEnumerable<Photo>> InternalGetPhotosAsync(string[] roles, short? categoryId = null, int? photoId = null)
{
return RunAsync(async conn =>
{
var rows = await conn.QueryAsync(
"SELECT * FROM photo.get_photos(@roles, @categoryId, @photoId);",
new
{
roles,
categoryId,
photoId
}
).ConfigureAwait(false);
return rows.Select(BuildPhoto);
});
}
Category BuildCategory(dynamic row)
{
var category = new Category();
category.Id = (short)row.id;
category.Year = (short)row.year;
category.Name = (string)row.name;
category.CreateDate = GetValueOrDefault<DateTime>(row.create_date);
category.Latitude = row.latitude;
category.Longitude = row.longitude;
category.PhotoCount = GetValueOrDefault<int>(row.photo_count);
category.TotalSizeXs = GetValueOrDefault<long>(row.total_size_xs);
category.TotalSizeXsSq = GetValueOrDefault<long>(row.total_size_xs_sq);
category.TotalSizeSm = GetValueOrDefault<long>(row.total_size_sm);
category.TotalSizeMd = GetValueOrDefault<long>(row.total_size_md);
category.TotalSizeLg = GetValueOrDefault<long>(row.total_size_lg);
category.TotalSizePrt = GetValueOrDefault<long>(row.total_size_prt);
category.TotalSizeSrc = GetValueOrDefault<long>(row.total_size_src);
category.TotalSize = GetValueOrDefault<long>(row.total_size);
category.IsMissingGpsData = GetValueOrDefault<bool>(row.is_missing_gps_data);
category.TeaserImage = BuildMultimediaInfo(row.teaser_photo_path, row.teaser_photo_width, row.teaser_photo_height, row.teaser_photo_size);
category.TeaserImageSq = BuildMultimediaInfo(row.teaser_photo_sq_path, row.teaser_photo_sq_width, row.teaser_photo_sq_height, row.teaser_photo_sq_size);
return category;
}
Photo BuildPhoto(dynamic row)
{
var photo = new Photo();
photo.Id = (int)row.id;
photo.CategoryId = (short)row.category_id;
photo.CreateDate = GetValueOrDefault<DateTime>(row.create_date);
photo.Latitude = row.latitude;
photo.Longitude = row.longitude;
photo.XsInfo = BuildMultimediaInfo(row.xs_path, row.xs_width, row.xs_height, row.xs_size);
photo.XsSqInfo = BuildMultimediaInfo(row.xs_sq_path, row.xs_sq_width, row.xs_sq_height, row.xs_sq_size);
photo.SmInfo = BuildMultimediaInfo(row.sm_path, row.sm_width, row.sm_height, row.sm_size);
photo.MdInfo = BuildMultimediaInfo(row.md_path, row.md_width, row.md_height, row.md_size);
photo.LgInfo = BuildMultimediaInfo(row.lg_path, row.lg_width, row.lg_height, row.lg_size);
photo.PrtInfo = BuildMultimediaInfo(row.prt_path, row.prt_width, row.prt_height, row.prt_size);
photo.SrcInfo = BuildMultimediaInfo(row.src_path, row.src_width, row.src_height, row.src_size);
return photo;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.OLE.Interop;
using System.Runtime.InteropServices;
using System.Threading;
using MICore;
namespace Microsoft.MIDebugEngine
{
internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback
{
// If we store the event callback in a normal IDebugEventCallback2 member, COM interop will attempt to call back to the main UI
// thread the first time that we invoke the call back. To work around this, we will instead store the event call back in the
// global interface table like we would if we implemented this code in native.
private readonly uint _cookie;
// NOTE: The GIT doesn't aggregate the free threaded marshaler, so we can't store it in an RCW
// or the CLR will just call right back to the main thread to try and marshal it.
private readonly IntPtr _pGIT;
private readonly AD7Engine _engine;
private Guid _IID_IDebugEventCallback2 = typeof(IDebugEventCallback2).GUID;
private readonly object _cacheLock = new object();
private int _cachedEventCallbackThread;
private IDebugEventCallback2 _cacheEventCallback;
public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback)
{
// Obtain the GIT from COM, and store the event callback in it
Guid CLSID_StdGlobalInterfaceTable = new Guid("00000323-0000-0000-C000-000000000046");
Guid IID_IGlobalInterfaceTable = typeof(IGlobalInterfaceTable).GUID;
const int CLSCTX_INPROC_SERVER = 0x1;
_pGIT = NativeMethods.CoCreateInstance(ref CLSID_StdGlobalInterfaceTable, IntPtr.Zero, CLSCTX_INPROC_SERVER, ref IID_IGlobalInterfaceTable);
var git = GetGlobalInterfaceTable();
git.RegisterInterfaceInGlobal(ad7Callback, ref _IID_IDebugEventCallback2, out _cookie);
Marshal.ReleaseComObject(git);
_engine = engine;
}
~EngineCallback()
{
// NOTE: This object does NOT implement the dispose pattern. The reasons are --
// 1. The underlying thing we are disposing is the SDM's IDebugEventCallback2. We are not going to get
// deterministic release of this without both implementing the dispose pattern on this object but also
// switching to use Marshal.ReleaseComObject everywhere. Marshal.ReleaseComObject is difficult to get
// right and there isn't a large need to deterministically release the SDM's event callback.
// 2. There is some risk of deadlock if we tried to implement the dispose pattern because of the trickiness
// of releasing cross-thread COM interfaces. We could avoid this by doing an async dispose, but then
// we losing the primary benefit of dispose which is the deterministic release.
if (_cookie != 0)
{
var git = GetGlobalInterfaceTable();
git.RevokeInterfaceFromGlobal(_cookie);
Marshal.ReleaseComObject(git);
}
if (_pGIT != IntPtr.Zero)
{
Marshal.Release(_pGIT);
}
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread)
{
uint attributes;
Guid riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
var callback = GetEventCallback();
EngineUtils.RequireOk(callback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes));
}
private IGlobalInterfaceTable GetGlobalInterfaceTable()
{
Debug.Assert(_pGIT != IntPtr.Zero, "GetGlobalInterfaceTable called before the m_pGIT is initialized");
// NOTE: We want to use GetUniqueObjectForIUnknown since the GIT will exist in both the STA and the MTA, and we don't want
// them to be the same rcw
return (IGlobalInterfaceTable)Marshal.GetUniqueObjectForIUnknown(_pGIT);
}
private IDebugEventCallback2 GetEventCallback()
{
Debug.Assert(_cookie != 0, "GetEventCallback called before m_cookie is initialized");
// We send esentially all events from the same thread, so lets optimize the common case
int currentThreadId = Thread.CurrentThread.ManagedThreadId;
if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId)
{
lock (_cacheLock)
{
if (_cacheEventCallback != null && _cachedEventCallbackThread == currentThreadId)
{
return _cacheEventCallback;
}
}
}
var git = GetGlobalInterfaceTable();
IntPtr pCallback;
git.GetInterfaceFromGlobal(_cookie, ref _IID_IDebugEventCallback2, out pCallback);
Marshal.ReleaseComObject(git);
var eventCallback = (IDebugEventCallback2)Marshal.GetObjectForIUnknown(pCallback);
Marshal.Release(pCallback);
lock (_cacheLock)
{
_cachedEventCallbackThread = currentThreadId;
_cacheEventCallback = eventCallback;
}
return eventCallback;
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread)
{
IDebugProgram2 program = _engine;
if (!_engine.ProgramCreateEventSent)
{
// Any events before programe create shouldn't include the program
program = null;
}
Send(eventObject, iidEvent, program, thread);
}
public void OnError(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Error, isAsync: true);
}
/// <summary>
/// Sends an error to the user, blocking until the user dismisses the error
/// </summary>
/// <param name="message">string to display to the user</param>
public void OnErrorImmediate(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Error, isAsync: false);
}
public void OnWarning(string message)
{
SendMessage(message, AD7MessageEvent.Severity.Warning, isAsync: true);
}
public void OnModuleLoad(DebuggedModule debuggedModule)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event
// for the exe.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
debuggedModule.Client = ad7Module;
// The sample engine does not support binding breakpoints as modules load since the primary exe is the only module
// symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded.
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnModuleUnload(DebuggedModule debuggedModule)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Module ad7Module = (AD7Module)debuggedModule.Client;
Debug.Assert(ad7Module != null);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */);
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnOutputString(string outputString)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString);
Send(eventObject, AD7OutputDebugStringEvent.IID, null);
}
public void OnOutputMessage(string outputMessage, enum_MESSAGETYPE messageType)
{
try
{
var eventObject = new AD7MessageEvent(outputMessage, messageType, isAsync: false, severity: AD7MessageEvent.Severity.Warning);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
public void OnProcessExit(uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
try
{
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
catch (InvalidOperationException)
{
// If debugging has already stopped, this can throw
}
}
public void OnEntryPoint(DebuggedThread thread)
{
AD7EntryPointEvent eventObject = new AD7EntryPointEvent();
Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client);
}
public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client;
Debug.Assert(ad7Thread != null);
AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode);
Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread);
}
public void OnThreadStart(DebuggedThread debuggedThread)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event
// for the main thread of the application.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent();
Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client);
}
public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count];
int i = 0;
foreach (object objCurrentBreakpoint in clients)
{
boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint;
i++;
}
// An engine that supports more advanced breakpoint features such as hit counts, conditions and filters
// should notify each bound breakpoint that it has been hit and evaluate conditions here.
// The sample engine does not support these features.
AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7BreakpointEvent.IID, ad7Thread);
}
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointState state = ExceptionBreakpointState.None)
{
AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7ExceptionEvent.IID, ad7Thread);
}
public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null)
{
AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(var, prop);
Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client);
}
public void OnStepComplete(DebuggedThread thread)
{
// Step complete is sent when a step has finished
AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent();
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread);
}
public void OnAsyncBreakComplete(DebuggedThread thread)
{
// This will get called when the engine receives the breakpoint event that is created when the user
// hits the pause button in vs.
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent();
Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread);
}
public void OnLoadComplete(DebuggedThread thread)
{
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent();
Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread);
}
public void OnProgramDestroy(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
// Engines notify the debugger about the results of a symbol serach by sending an instance
// of IDebugSymbolSearchEvent2
public void OnSymbolSearch(DebuggedModule module, string status, uint dwStatusFlags)
{
enum_MODULE_INFO_FLAGS statusFlags = (enum_MODULE_INFO_FLAGS)dwStatusFlags;
string statusString = ((statusFlags & enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED) != 0 ? "Symbols Loaded - " : "No symbols loaded") + status;
AD7Module ad7Module = new AD7Module(module, _engine.DebuggedProcess);
AD7SymbolSearchEvent eventObject = new AD7SymbolSearchEvent(ad7Module, statusString, statusFlags);
Send(eventObject, AD7SymbolSearchEvent.IID, null);
}
// Engines notify the debugger that a breakpoint has bound through the breakpoint bound event.
public void OnBreakpointBound(object objBoundBreakpoint)
{
AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint;
IDebugPendingBreakpoint2 pendingBreakpoint;
((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint);
AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint);
Send(eventObject, AD7BreakpointBoundEvent.IID, null);
}
// Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event
public void OnBreakpointError(AD7ErrorBreakpoint bperr)
{
AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr);
Send(eventObject, AD7BreakpointErrorEvent.IID, null);
}
// Engines notify the SDM that a bound breakpoint change resulted in an error
public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason);
Send(eventObject, AD7BreakpointUnboundEvent.IID, null);
}
public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2);
Send(eventObject, AD7CustomDebugEvent.IID, null);
}
private void SendMessage(string message, AD7MessageEvent.Severity severity, bool isAsync)
{
try
{
// IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine.
// The sample engine doesn't take advantage of this.
AD7MessageEvent eventObject = new AD7MessageEvent(message, enum_MESSAGETYPE.MT_MESSAGEBOX, isAsync, severity);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
private static class NativeMethods
{
[DllImport("ole32.dll", ExactSpelling = true, PreserveSig = false)]
public static extern IntPtr CoCreateInstance(
[In] ref Guid clsid,
IntPtr punkOuter,
int context,
[In] ref Guid iid);
}
}
}
| |
// 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.
// Test cases showing interaction of inlining and inline pinvoke,
// along with the impact of EH.
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace PInvokeTest
{
static class PInvokeExampleNative
{
public static int GetConstant()
{
return GetConstantInternal();
}
[DllImport(nameof(PInvokeExampleNative))]
private extern static int GetConstantInternal();
}
internal class Test
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int AsForceInline()
{
return PInvokeExampleNative.GetConstant();
}
static int AsNormalInline()
{
return PInvokeExampleNative.GetConstant();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int AsNoInline()
{
return PInvokeExampleNative.GetConstant();
}
static bool FromTryCatch()
{
bool result = false;
try
{
// All pinvokes should be inline, except on x64
result = (PInvokeExampleNative.GetConstant() == AsNormalInline());
}
catch (Exception)
{
result = false;
}
return result;
}
static bool FromTryFinally()
{
bool result = false;
bool result1 = false;
bool result2 = false;
try
{
// All pinvokes should be inline, except on x64
result1 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
result2 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
}
finally
{
result = result1 && result2;
}
return result;
}
static bool FromTryFinally2()
{
bool result = false;
bool result1 = false;
bool result2 = false;
try
{
// These two pinvokes should be inline, except on x64
result1 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
}
finally
{
// These two pinvokes should *not* be inline (finally)
result2 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
result = result1 && result2;
}
return result;
}
static bool FromTryFinally3()
{
bool result = false;
bool result1 = false;
bool result2 = false;
try
{
// These two pinvokes should be inline, except on x64
result1 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
}
finally
{
try
{
// These two pinvokes should *not* be inline (finally)
result2 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
}
catch (Exception)
{
result2 = false;
}
result = result1 && result2;
}
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool FromInline()
{
// These two pinvokes should be inline
bool result = (PInvokeExampleNative.GetConstant() == AsForceInline());
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool FromInline2()
{
// These four pinvokes should be inline
bool result1 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
bool result2 = (PInvokeExampleNative.GetConstant() == AsForceInline());
return result1 && result2;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool FromNoInline()
{
// The only pinvoke should be inline
bool result = (PInvokeExampleNative.GetConstant() == AsNoInline());
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool FromNoInline2()
{
// Three pinvokes should be inline
bool result1 = (PInvokeExampleNative.GetConstant() == AsNormalInline());
bool result2 = (PInvokeExampleNative.GetConstant() == AsNoInline());
return result1 && result2;
}
static bool FromFilter()
{
bool result = false;
try
{
throw new Exception("expected");
}
// These two pinvokes should *not* be inline (filter)
//
// For the first call the jit won't inline the wrapper, so
// it just calls GetConstant().
//
// For the second call, the force inline works, and the
// subsequent inline of GetConstant() exposes a call
// to the pinvoke GetConstantInternal(). This pinvoke will
// not be inline.
catch (Exception) when (PInvokeExampleNative.GetConstant() == AsForceInline())
{
result = true;
}
return result;
}
static bool FromColdCode()
{
int yield = -1;
bool result1 = false;
bool result2 = false;
try
{
// This pinvoke should not be inline (cold)
yield = PInvokeExampleNative.GetConstant();
throw new Exception("expected");
}
catch (Exception)
{
// These two pinvokes should not be inline (catch)
//
// For the first call the jit won't inline the
// wrapper, so it just calls GetConstant().
//
// For the second call, the force inline works, and
// the subsequent inline of GetConstant() exposes
// a call to the pinvoke GetConstantInternal(). This
// pinvoke will not be inline.
result1 = (yield == PInvokeExampleNative.GetConstant());
result2 = (yield == AsForceInline());
}
return result1 && result2;
}
private static int Main()
{
bool result = true;
result &= FromTryCatch();
result &= FromTryFinally();
result &= FromTryFinally2();
result &= FromTryFinally3();
result &= FromInline();
result &= FromInline2();
result &= FromNoInline();
result &= FromNoInline2();
result &= FromFilter();
result &= FromColdCode();
return (result ? 100 : -1);
}
}
}
| |
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// DeathmatchGame
// ----------------------------------------------------------------------------
// Depends on methods found in gameCore.cs. Those added here are specific to
// this game type and/or over-ride the "default" game functionaliy.
//
// The desired Game Type must be added to each mission's LevelInfo object.
// - gameType = "Deathmatch";
// If this information is missing then the GameCore will default to Deathmatch.
// ----------------------------------------------------------------------------
function DeathMatchGame::initGameVars(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> DeathMatchGame::initGameVars");
//-----------------------------------------------------------------------------
// What kind of "player" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
// Leave $Game::defaultPlayerClass and $Game::defaultPlayerDataBlock as empty strings ("")
// to spawn a the $Game::defaultCameraClass as the control object.
$Game::defaultPlayerClass = "Player";
$Game::defaultPlayerDataBlock = "DefaultPlayerData";
$Game::defaultPlayerSpawnGroups = "PlayerSpawnPoints PlayerDropPoints";
//-----------------------------------------------------------------------------
// What kind of "camera" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
// These override the values set in core/scripts/server/spawn.cs
//-----------------------------------------------------------------------------
$Game::defaultCameraClass = "Camera";
$Game::defaultCameraDataBlock = "Observer";
$Game::defaultCameraSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
// Set the gameplay parameters
%game.duration = 30 * 60;
%game.endgameScore = 20;
%game.endgamePause = 10;
%game.allowCycling = false; // Is mission cycling allowed?
}
function DeathMatchGame::onGameDurationEnd(%game)
{
// This "redirect" is here so that we can abort the game cycle if
// the $Game::Duration variable has been cleared, without having
// to have a function to cancel the schedule.
if ($Game::Duration && !(EditorIsActive() && GuiEditorIsActive()))
Game.onGameDurationEnd();
}
function DeathMatchGame::onClientEnterGame(%this, %client)
{
// This function currently relies on some helper functions defined in
// core/scripts/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onClientEntergame");
// Sync the client's clocks to the server's
commandToClient(%client, 'SyncClock', $Sim::Time - $Game::StartTime);
//Set the player name based on the client's connection data
%client.setPlayerName(%client.connectData);
// Find a spawn point for the camera
// This function currently relies on some helper functions defined in
// core/scripts/server/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
%cameraSpawnPoint = pickCameraSpawnPoint($Game::DefaultCameraSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%client.spawnCamera(%cameraSpawnPoint);
// Setup game parameters, the onConnect method currently starts
// everyone with a 0 score.
%client.score = 0;
%client.kills = 0;
%client.deaths = 0;
// weaponHUD
%client.RefreshWeaponHud(0, "", "");
// Prepare the player object.
%this.preparePlayer(%client);
// Inform the client of all the other clients
%count = ClientGroup.getCount();
for (%cl = 0; %cl < %count; %cl++)
{
%other = ClientGroup.getObject(%cl);
if ((%other != %client))
{
// These should be "silent" versions of these messages...
messageClient(%client, 'MsgClientJoin', "",
%other.playerName,
%other,
%other.sendGuid,
%other.team,
%other.score,
%other.kills,
%other.deaths,
%other.isAIControlled(),
%other.isAdmin,
%other.isSuperAdmin);
}
}
// Inform the client we've joined up
messageClient(%client,
'MsgClientJoin', '\c2Welcome to the Torque demo app %1.',
%client.playerName,
%client,
%client.sendGuid,
%client.team,
%client.score,
%client.kills,
%client.deaths,
%client.isAiControlled(),
%client.isAdmin,
%client.isSuperAdmin);
// Inform all the other clients of the new guy
messageAllExcept(%client, -1, 'MsgClientJoin', '\c1%1 joined the game.',
%client.playerName,
%client,
%client.sendGuid,
%client.team,
%client.score,
%client.kills,
%client.deaths,
%client.isAiControlled(),
%client.isAdmin,
%client.isSuperAdmin);
}
function DeathMatchGame::onClientLeaveGame(%this, %client)
{
// Cleanup the camera
if (isObject(%this.camera))
%this.camera.delete();
}
//-----------------------------------------------------------------------------
// The server has started up so do some game start up
//-----------------------------------------------------------------------------
function DeathMatchGame::onMissionStart(%this)
{
//set up the game and game variables
%this.initGameVars();
$Game::Duration = %this.duration;
$Game::EndGameScore = %this.endgameScore;
$Game::EndGamePause = %this.endgamePause;
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onStartGame");
if ($Game::Running)
{
error("startGame: End the game first!");
return;
}
// Inform the client we're starting up
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
{
%cl = ClientGroup.getObject(%clientIndex);
commandToClient(%cl, 'GameStart');
// Other client specific setup..
%cl.score = 0;
%cl.kills = 0;
%cl.deaths = 0;
}
// Start the game timer
if ($Game::Duration)
$Game::Schedule = %this.schedule($Game::Duration * 1000, "onGameDurationEnd");
$Game::Running = true;
$Game = %this;
}
function DeathMatchGame::onMissionEnded(%this)
{
if (!$Game::Running)
{
error("endGame: No game running!");
return;
}
// Stop any game timers
cancel($Game::Schedule);
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
{
%cl = ClientGroup.getObject(%clientIndex);
commandToClient(%cl, 'GameEnd', $Game::EndGamePause);
}
$Game::Running = false;
$Game::Cycling = false;
$Game = "";
}
function DeathMatchGame::onMissionReset(%this)
{
// Called by resetMission(), after all the temporary mission objects
// have been deleted.
%this.initGameVars();
$Game::Duration = %this.duration;
$Game::EndGameScore = %this.endgameScore;
$Game::EndGamePause = %this.endgamePause;
}
//-----------------------------------------------------------------------------
// Functions that implement game-play
// These are here for backwards compatibilty only, games and/or mods should
// really be overloading the server and mission functions listed ubove.
//-----------------------------------------------------------------------------
// Added this stage to creating a player so game types can override it easily.
// This is a good place to initiate team selection.
function DeathMatchGame::preparePlayer(%this, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::preparePlayer");
// Find a spawn point for the player
// This function currently relies on some helper functions defined in
// core/scripts/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
%playerSpawnPoint = pickPlayerSpawnPoint($Game::DefaultPlayerSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
//%client.spawnPlayer(%playerSpawnPoint);
%this.spawnPlayer(%client, %playerSpawnPoint);
// Starting equipment
%this.loadOut(%client.player);
}
function DeathMatchGame::loadOut(%game, %player)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::loadOut");
%player.clearWeaponCycle();
%player.setInventory(Ryder, 1);
%player.setInventory(RyderClip, %player.maxInventory(RyderClip));
%player.setInventory(RyderAmmo, %player.maxInventory(RyderAmmo)); // Start the gun loaded
%player.addToWeaponCycle(Ryder);
%player.setInventory(Lurker, 1);
%player.setInventory(LurkerClip, %player.maxInventory(LurkerClip));
%player.setInventory(LurkerAmmo, %player.maxInventory(LurkerAmmo)); // Start the gun loaded
%player.addToWeaponCycle(Lurker);
%player.setInventory(LurkerGrenadeLauncher, 1);
%player.setInventory(LurkerGrenadeAmmo, %player.maxInventory(LurkerGrenadeAmmo));
%player.addToWeaponCycle(LurkerGrenadeLauncher);
%player.setInventory(ProxMine, %player.maxInventory(ProxMine));
%player.addToWeaponCycle(ProxMine);
%player.setInventory(DeployableTurret, %player.maxInventory(DeployableTurret));
%player.addToWeaponCycle(DeployableTurret);
if (%player.getDatablock().mainWeapon.image !$= "")
{
%player.mountImage(%player.getDatablock().mainWeapon.image, 0);
}
else
{
%player.mountImage(Ryder, 0);
}
}
// Customized kill message for falling deaths
function sendMsgClientKilled_Impact( %msgType, %client, %sourceClient, %damLoc )
{
messageAll( %msgType, '%1 fell to his death!', %client.playerName );
}
// Customized kill message for suicides
function sendMsgClientKilled_Suicide( %msgType, %client, %sourceClient, %damLoc )
{
messageAll( %msgType, '%1 takes his own life!', %client.playerName );
}
// Default death message
function sendMsgClientKilled_Default( %msgType, %client, %sourceClient, %damLoc )
{
if ( %sourceClient == %client )
sendMsgClientKilled_Suicide(%client, %sourceClient, %damLoc);
else if ( %sourceClient.team !$= "" && %sourceClient.team $= %client.team )
messageAll( %msgType, '%1 killed by %2 - friendly fire!', %client.playerName, %sourceClient.playerName );
else
messageAll( %msgType, '%1 gets nailed by %2!', %client.playerName, %sourceClient.playerName );
}
function DeathMatchGame::onDeath(%game, %client, %sourceObject, %sourceClient, %damageType, %damLoc)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onDeath");
// clear the weaponHUD
%client.RefreshWeaponHud(0, "", "");
// Clear out the name on the corpse
%client.player.setShapeName("");
// Switch the client over to the death cam and unhook the player object.
if (isObject(%client.camera) && isObject(%client.player))
{
%client.camera.setMode("Corpse", %client.player);
%client.setControlObject(%client.camera);
}
%client.player = 0;
// Display damage appropriate kill message
%sendMsgFunction = "sendMsgClientKilled_" @ %damageType;
if ( !isFunction( %sendMsgFunction ) )
%sendMsgFunction = "sendMsgClientKilled_Default";
call( %sendMsgFunction, 'MsgClientKilled', %client, %sourceClient, %damLoc );
// Dole out points and check for win
if (( %damageType $= "Suicide" || %sourceClient == %client ) && isObject(%sourceClient))
{
%game.incDeaths( %client, 1, true );
%game.incScore( %client, -1, false );
}
else
{
%game.incDeaths( %client, 1, false );
%game.incScore( %sourceClient, 1, true );
%game.incKills( %sourceClient, 1, false );
// If the game may be ended by a client getting a particular score, check that now.
if ( $Game::EndGameScore > 0 && %sourceClient.kills >= $Game::EndGameScore )
%game.cycleGame();
}
}
// ----------------------------------------------------------------------------
// Scoring
// ----------------------------------------------------------------------------
function DeathMatchGame::incKills(%game, %client, %kill, %dontMessageAll)
{
%client.kills += %kill;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function DeathMatchGame::incDeaths(%game, %client, %death, %dontMessageAll)
{
%client.deaths += %death;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function DeathMatchGame::incScore(%game, %client, %score, %dontMessageAll)
{
%client.score += %score;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function DeathMatchGame::getScore(%client) { return %client.score; }
function DeathMatchGame::getKills(%client) { return %client.kills; }
function DeathMatchGame::getDeaths(%client) { return %client.deaths; }
function DeathMatchGame::getTeamScore(%client)
{
%score = %client.score;
if ( %client.team !$= "" )
{
// Compute team score
for (%i = 0; %i < ClientGroup.getCount(); %i++)
{
%other = ClientGroup.getObject(%i);
if ((%other != %client) && (%other.team $= %client.team))
%score += %other.score;
}
}
return %score;
}
// ----------------------------------------------------------------------------
// Spawning
// ----------------------------------------------------------------------------
function DeathMatchGame::spawnPlayer(%game, %client, %spawnPoint, %noControl)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::spawnPlayer");
if (isObject(%client.player))
{
// The client should not already have a player. Assigning
// a new one could result in an uncontrolled player object.
error("Attempting to create a player for a client that already has one!");
}
// Attempt to treat %spawnPoint as an object
if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))
{
// Defaults
%spawnClass = $Game::DefaultPlayerClass;
%spawnDataBlock = $Game::DefaultPlayerDataBlock;
// Overrides by the %spawnPoint
if (isDefined("%spawnPoint.spawnClass"))
{
%spawnClass = %spawnPoint.spawnClass;
%spawnDataBlock = %spawnPoint.spawnDatablock;
}
else if (isDefined("%spawnPoint.spawnDatablock"))
{
// This may seem redundant given the above but it allows
// the SpawnSphere to override the datablock without
// overriding the default player class
%spawnDataBlock = %spawnPoint.spawnDatablock;
}
%spawnProperties = %spawnPoint.spawnProperties;
%spawnScript = %spawnPoint.spawnScript;
// Spawn with the engine's Sim::spawnObject() function
%player = spawnObject(%spawnClass, %spawnDatablock, "",
%spawnProperties, %spawnScript);
// If we have an object do some initial setup
if (isObject(%player))
{
// Pick a location within the spawn sphere.
%spawnLocation = %game.pickPointInSpawnSphere(%player, %spawnPoint);
%player.setTransform(%spawnLocation);
}
else
{
// If we weren't able to create the player object then warn the user
// When the player clicks OK in one of these message boxes, we will fall through
// to the "if (!isObject(%player))" check below.
if (isDefined("%spawnDatablock"))
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
" and datablock " @ %spawnDatablock @ ".\n\nStarting as an Observer instead.",
"");
}
else
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
".\n\nStarting as an Observer instead.",
"");
}
}
}
else
{
// Create a default player
%player = spawnObject($Game::DefaultPlayerClass, $Game::DefaultPlayerDataBlock);
if (!%player.isMemberOfClass("Player"))
warn("Trying to spawn a class that does not derive from Player.");
// Treat %spawnPoint as a transform
%player.setTransform(%spawnPoint);
}
// If we didn't actually create a player object then bail
if (!isObject(%player))
{
// Make sure we at least have a camera
%client.spawnCamera(%spawnPoint);
return;
}
// Update the default camera to start with the player
if (isObject(%client.camera) && !isDefined("%noControl"))
{
if (%player.getClassname() $= "Player")
%client.camera.setTransform(%player.getEyeTransform());
else
%client.camera.setTransform(%player.getTransform());
}
// Add the player object to MissionCleanup so that it
// won't get saved into the level files and will get
// cleaned up properly
MissionCleanup.add(%player);
// Store the client object on the player object for
// future reference
%player.client = %client;
// If the player's client has some owned turrets, make sure we let them
// know that we're a friend too.
if (%client.ownedTurrets)
{
for (%i=0; %i<%client.ownedTurrets.getCount(); %i++)
{
%turret = %client.ownedTurrets.getObject(%i);
%turret.addToIgnoreList(%player);
}
}
// Player setup...
if (%player.isMethod("setShapeName"))
%player.setShapeName(%client.playerName);
if (%player.isMethod("setEnergyLevel"))
%player.setEnergyLevel(%player.getDataBlock().maxEnergy);
if (!isDefined("%client.skin"))
{
// Determine which character skins are not already in use
%availableSkins = %player.getDatablock().availableSkins; // TAB delimited list of skin names
%count = ClientGroup.getCount();
for (%cl = 0; %cl < %count; %cl++)
{
%other = ClientGroup.getObject(%cl);
if (%other != %client)
{
%availableSkins = strreplace(%availableSkins, %other.skin, "");
%availableSkins = strreplace(%availableSkins, "\t\t", ""); // remove empty fields
}
}
// Choose a random, unique skin for this client
%count = getFieldCount(%availableSkins);
%client.skin = addTaggedString( getField(%availableSkins, getRandom(%count)) );
}
%player.setSkinName(%client.skin);
// Give the client control of the player
%client.player = %player;
// Give the client control of the camera if in the editor
if( $startWorldEditor )
{
%control = %client.camera;
%control.mode = "Fly";
EditorGui.syncCameraGui();
}
else
%control = %player;
// Allow the player/camera to receive move data from the GameConnection. Without this
// the user is unable to control the player/camera.
if (!isDefined("%noControl"))
%client.setControlObject(%control);
}
function DeathMatchGame::pickPointInSpawnSphere(%this, %objectToSpawn, %spawnSphere)
{
%SpawnLocationFound = false;
%attemptsToSpawn = 0;
while(!%SpawnLocationFound && (%attemptsToSpawn < 5))
{
%sphereLocation = %spawnSphere.getTransform();
// Attempt to spawn the player within the bounds of the spawnsphere.
%angleY = mDegToRad(getRandom(0, 100) * m2Pi());
%angleXZ = mDegToRad(getRandom(0, 100) * m2Pi());
%sphereLocation = setWord( %sphereLocation, 0, getWord(%sphereLocation, 0) + (mCos(%angleY) * mSin(%angleXZ) * getRandom(-%spawnSphere.radius, %spawnSphere.radius)));
%sphereLocation = setWord( %sphereLocation, 1, getWord(%sphereLocation, 1) + (mCos(%angleXZ) * getRandom(-%spawnSphere.radius, %spawnSphere.radius)));
%SpawnLocationFound = true;
// Now have to check that another object doesn't already exist at this spot.
// Use the bounding box of the object to check if where we are about to spawn in is
// clear.
%boundingBoxSize = %objectToSpawn.getDatablock().boundingBox;
%searchRadius = getWord(%boundingBoxSize, 0);
%boxSizeY = getWord(%boundingBoxSize, 1);
// Use the larger dimention as the radius to search
if (%boxSizeY > %searchRadius)
%searchRadius = %boxSizeY;
// Search a radius about the area we're about to spawn for players.
initContainerRadiusSearch( %sphereLocation, %searchRadius, $TypeMasks::PlayerObjectType );
while ( (%objectNearExit = containerSearchNext()) != 0 )
{
// If any player is found within this radius, mark that we need to look
// for another spot.
%SpawnLocationFound = false;
break;
}
// If the attempt at finding a clear spawn location failed
// try no more than 5 times.
%attemptsToSpawn++;
}
// If we couldn't find a spawn location after 5 tries, spawn the object
// At the center of the sphere and give a warning.
if (!%SpawnLocationFound)
{
%sphereLocation = %spawnSphere.getTransform();
warn("WARNING: Could not spawn player after" SPC %attemptsToSpawn
SPC "tries in spawnsphere" SPC %spawnSphere SPC "without overlapping another player. Attempting spawn in center of sphere.");
}
return %sphereLocation;
}
// ----------------------------------------------------------------------------
// Observer
// ----------------------------------------------------------------------------
function DeathMatchGame::spawnObserver(%game, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::spawnObserver");
// Position the camera on one of our observer spawn points
%client.camera.setTransform(%game.pickObserverSpawnPoint());
// Set control to the camera
%client.setControlObject(%client.camera);
}
function DeathMatchGame::pickObserverSpawnPoint(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::pickObserverSpawnPoint");
%groupName = "MissionGroup/ObserverSpawnPoints";
%group = nameToID(%groupName);
if (%group != -1)
{
%count = %group.getCount();
if (%count != 0)
{
%index = getRandom(%count-1);
%spawn = %group.getObject(%index);
return %spawn.getTransform();
}
else
error("No spawn points found in "@ %groupName);
}
else
error("Missing spawn points group "@ %groupName);
// Could be no spawn points, in which case we'll stick the
// player at the center of the world.
return "0 0 300 1 0 0 0";
}
// ----------------------------------------------------------------------------
// Server
// ----------------------------------------------------------------------------
// Called by GameCore::cycleGame() when we need to destroy the server
// because we're done playing. We don't want to call destroyServer()
// directly so we can first check that we're about to destroy the
// correct server session.
function DeathMatchGame::DestroyServer(%serverSession)
{
if (%serverSession == $Server::Session)
{
if (isObject(LocalClientConnection))
{
// We're a local connection so issue a disconnect. The server will
// be automatically destroyed for us.
disconnect();
}
else
{
// We're a stand alone server
destroyServer();
}
}
}
// ----------------------------------------------------------------------------
// weapon HUD
// ----------------------------------------------------------------------------
function GameConnection::setAmmoAmountHud(%client, %amount, %amountInClips )
{
commandToClient(%client, 'SetAmmoAmountHud', %amount, %amountInClips);
}
function GameConnection::RefreshWeaponHud(%client, %amount, %preview, %ret, %zoomRet, %amountInClips)
{
commandToClient(%client, 'RefreshWeaponHud', %amount, %preview, %ret, %zoomRet, %amountInClips);
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: Defines the settings that the loader uses to find assemblies in an
** AppDomain
**
**
=============================================================================*/
namespace System
{
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Policy;
using Path = System.IO.Path;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
[Serializable]
internal sealed class AppDomainSetup
{
[Serializable]
internal enum LoaderInformation
{
// If you add a new value, add the corresponding property
// to AppDomain.GetData() and SetData()'s switch statements,
// as well as fusionsetup.h.
ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE
ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE
DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE
DevPathValue = 3, // LOADER_DEVPATH
ApplicationNameValue = 4, // LOADER_APPLICATION_NAME
PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH
PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE
ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES
ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES
CachePathValue = 9, // LOADER_CACHE_PATH
LicenseFileValue = 10, // LOADER_LICENSE_FILE
DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY
DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD
DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS
DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING
ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
LoaderMaximum = 18 // LOADER_MAXIMUM
}
// Constants from fusionsetup.h.
private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION";
private const string ACTAG_APP_BASE_URL = "APPBASE";
// This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order
// of these fields or add new ones.
private string[] _Entries;
private LoaderOptimization _LoaderOptimization;
#pragma warning disable 169
private String _AppBase; // for compat with v1.1
#pragma warning restore 169
[OptionalField(VersionAdded = 2)]
private AppDomainInitializer _AppDomainInitializer;
[OptionalField(VersionAdded = 2)]
private string[] _AppDomainInitializerArguments;
// On the CoreCLR, this contains just the name of the permission set that we install in the new appdomain.
// Not the ToXml().ToString() of an ApplicationTrust object.
[OptionalField(VersionAdded = 2)]
private string _ApplicationTrust;
[OptionalField(VersionAdded = 2)]
private byte[] _ConfigurationBytes;
#if FEATURE_COMINTEROP
[OptionalField(VersionAdded = 3)]
private bool _DisableInterfaceCache = false;
#endif // FEATURE_COMINTEROP
[OptionalField(VersionAdded = 4)]
private string _AppDomainManagerAssembly;
[OptionalField(VersionAdded = 4)]
private string _AppDomainManagerType;
// A collection of strings used to indicate which breaking changes shouldn't be applied
// to an AppDomain. We only use the keys, the values are ignored.
[OptionalField(VersionAdded = 4)]
private Dictionary<string, object> _CompatFlags;
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private String _TargetFrameworkName;
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _CheckedForTargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _UseRandomizedStringHashing;
#endif
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
if (copy != null)
{
string[] other = copy.Value;
int mineSize = _Entries.Length;
int otherSize = other.Length;
int size = (otherSize < mineSize) ? otherSize : mineSize;
for (int i = 0; i < size; i++)
mine[i] = other[i];
if (size < mineSize)
{
// This case can happen when the copy is a deserialized version of
// an AppDomainSetup object serialized by Everett.
for (int i = size; i < mineSize; i++)
mine[i] = null;
}
_LoaderOptimization = copy._LoaderOptimization;
_AppDomainInitializerArguments = copy.AppDomainInitializerArguments;
_ApplicationTrust = copy._ApplicationTrust;
if (copyDomainBoundData)
_AppDomainInitializer = copy.AppDomainInitializer;
else
_AppDomainInitializer = null;
_ConfigurationBytes = null;
#if FEATURE_COMINTEROP
_DisableInterfaceCache = copy._DisableInterfaceCache;
#endif // FEATURE_COMINTEROP
_AppDomainManagerAssembly = copy.AppDomainManagerAssembly;
_AppDomainManagerType = copy.AppDomainManagerType;
if (copy._CompatFlags != null)
{
SetCompatibilitySwitches(copy._CompatFlags.Keys);
}
_TargetFrameworkName = copy._TargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = copy._UseRandomizedStringHashing;
#endif
}
else
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
public AppDomainSetup()
{
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false)
{
char[] sep = { '\\', '/' };
int i = imageLocation.LastIndexOfAny(sep);
if (i == -1)
{
ApplicationName = imageLocation;
}
else
{
ApplicationName = imageLocation.Substring(i + 1);
string appBase = imageLocation.Substring(0, i + 1);
if (imageLocationAlreadyNormalized)
Value[(int)LoaderInformation.ApplicationBaseValue] = appBase;
else
ApplicationBase = appBase;
}
}
internal string[] Value
{
get
{
if (_Entries == null)
_Entries = new String[(int)LoaderInformation.LoaderMaximum];
return _Entries;
}
}
public string AppDomainManagerAssembly
{
get { return _AppDomainManagerAssembly; }
set { _AppDomainManagerAssembly = value; }
}
public string AppDomainManagerType
{
get { return _AppDomainManagerType; }
set { _AppDomainManagerType = value; }
}
public String ApplicationBase
{
[Pure]
get
{
return Value[(int)LoaderInformation.ApplicationBaseValue];
}
set
{
Value[(int)LoaderInformation.ApplicationBaseValue] = (value == null || value.Length == 0)?null:Path.GetFullPath(value);
}
}
// only needed by AppDomain.Setup(). Not really needed by users.
internal Dictionary<string, object> GetCompatibilityFlags()
{
return _CompatFlags;
}
public void SetCompatibilitySwitches(IEnumerable<String> switches)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = false;
#endif
if (switches != null)
{
_CompatFlags = new Dictionary<string, object>();
foreach (String str in switches)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str))
{
_UseRandomizedStringHashing = true;
}
#endif
_CompatFlags.Add(str, null);
}
}
else
{
_CompatFlags = null;
}
}
// A target Framework moniker, in a format parsible by the FrameworkName class.
public String TargetFrameworkName
{
get
{
return _TargetFrameworkName;
}
set
{
_TargetFrameworkName = value;
}
}
public String ApplicationName
{
get
{
return Value[(int)LoaderInformation.ApplicationNameValue];
}
set
{
Value[(int)LoaderInformation.ApplicationNameValue] = value;
}
}
public AppDomainInitializer AppDomainInitializer
{
get
{
return _AppDomainInitializer;
}
set
{
_AppDomainInitializer = value;
}
}
public string[] AppDomainInitializerArguments
{
get
{
return _AppDomainInitializerArguments;
}
set
{
_AppDomainInitializerArguments = value;
}
}
internal ApplicationTrust InternalGetApplicationTrust()
{
if (_ApplicationTrust == null) return null;
ApplicationTrust grantSet = new ApplicationTrust();
return grantSet;
}
internal void InternalSetApplicationTrust(String permissionSetName)
{
_ApplicationTrust = permissionSetName;
}
internal ApplicationTrust ApplicationTrust
{
get
{
return InternalGetApplicationTrust();
}
}
public LoaderOptimization LoaderOptimization
{
get
{
return _LoaderOptimization;
}
set
{
_LoaderOptimization = value;
}
}
internal static string LoaderOptimizationKey
{
get
{
return LOADER_OPTIMIZATION;
}
}
static internal int Locate(String s)
{
if (String.IsNullOrEmpty(s))
return -1;
Debug.Assert('A' == ACTAG_APP_BASE_URL[0], "Assumption violated");
if (s[0] == 'A' && s == ACTAG_APP_BASE_URL)
return (int)LoaderInformation.ApplicationBaseValue;
return -1;
}
#if FEATURE_COMINTEROP
public bool SandboxInterop
{
get
{
return _DisableInterfaceCache;
}
set
{
_DisableInterfaceCache = value;
}
}
#endif // FEATURE_COMINTEROP
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Text;
namespace Encog.Util
{
/// <summary>
/// A utility for generating HTML reports.
/// </summary>
public class HTMLReport
{
/// <summary>
/// Text.
/// </summary>
private readonly StringBuilder _text;
/// <summary>
/// Construct the object.
/// </summary>
public HTMLReport()
{
_text = new StringBuilder();
}
/// <summary>
/// Begin an HTML tag.
/// </summary>
public void BeginHTML()
{
_text.Append("<html>");
}
/// <summary>
/// End an HTML tag.
/// </summary>
public void EndHTML()
{
_text.Append("</html>");
}
/// <summary>
/// Set the title.
/// </summary>
/// <param name="str">The title.</param>
public void Title(String str)
{
_text.Append("<head><title>");
_text.Append(str);
_text.Append("</title></head>");
}
/// <summary>
/// Begin an HTML para.
/// </summary>
public void BeginPara()
{
_text.Append("<p>");
}
/// <summary>
/// End an HTML para.
/// </summary>
public void EndPara()
{
_text.Append("</p>");
}
/// <summary>
/// Display in bold.
/// </summary>
/// <param name="str"></param>
public void Bold(String str)
{
_text.Append("<b>");
_text.Append(Encode(str));
_text.Append("</b>");
}
/// <summary>
/// Display a para.
/// </summary>
/// <param name="str">The para to display.</param>
public void Para(String str)
{
_text.Append("<p>");
_text.Append(Encode(str));
_text.Append("</p>");
}
/// <summary>
/// Clear the report.
/// </summary>
public void Clear()
{
_text.Length = 0;
}
/// <summary>
/// Convert the report to a string.
/// </summary>
/// <returns>The report text.</returns>
public override String ToString()
{
return _text.ToString();
}
/// <summary>
/// Begin the HTML body.
/// </summary>
public void BeginBody()
{
_text.Append("<body>");
}
/// <summary>
/// End the HTML body.
/// </summary>
public void EndBody()
{
_text.Append("</body>");
}
/// <summary>
/// Create a H1.
/// </summary>
/// <param name="title"></param>
public void H1(String title)
{
_text.Append("<h1>");
_text.Append(Encode(title));
_text.Append("</h1>");
}
/// <summary>
/// Begin a table.
/// </summary>
public void BeginTable()
{
_text.Append("<table border=\"1\">");
}
/// <summary>
/// End a table.
/// </summary>
public void EndTable()
{
_text.Append("</table>");
}
/// <summary>
/// Begin a row of a table.
/// </summary>
public void BeginRow()
{
_text.Append("<tr>");
}
/// <summary>
/// End a row of a table.
/// </summary>
public void EndRow()
{
_text.Append("</tr>");
}
/// <summary>
/// Add a header cell.
/// </summary>
/// <param name="head">The text to use.</param>
public void Header(String head)
{
_text.Append("<th>");
_text.Append(Encode(head));
_text.Append("</th>");
}
/// <summary>
/// Add a cell, no column span.
/// </summary>
/// <param name="head">The head of that call.</param>
public void Cell(String head)
{
Cell(head, 0);
}
/// <summary>
/// Add a cell to a table.
/// </summary>
/// <param name="head">The text for the cell.</param>
/// <param name="colSpan">The col span.</param>
public void Cell(String head, int colSpan)
{
_text.Append("<td");
if (colSpan > 0)
{
_text.Append(" colspan=\"");
_text.Append(colSpan);
_text.Append("\"");
}
_text.Append(">");
_text.Append(Encode(head));
_text.Append("</td>");
}
/// <summary>
/// Add a name-value pair to a table. This includes a row.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="v">The value.</param>
public void TablePair(String name, String v)
{
BeginRow();
_text.Append("<td><b>" + Encode(name) + "</b></td>");
Cell(v);
EndRow();
}
/// <summary>
/// Add a H2.
/// </summary>
/// <param name="title">The title.</param>
public void H2(String title)
{
_text.Append("<h2>");
_text.Append(Encode(title));
_text.Append("</h2>");
}
/// <summary>
/// Add a H3.
/// </summary>
/// <param name="title">The title.</param>
public void H3(String title)
{
_text.Append("<h3>");
_text.Append(Encode(title));
_text.Append("</h3>");
}
/// <summary>
/// Begin a list.
/// </summary>
public void BeginList()
{
_text.Append("<ul>");
}
/// <summary>
/// Add a list item.
/// </summary>
/// <param name="str">The item added.</param>
public void ListItem(String str)
{
_text.Append("<li>");
_text.Append(Encode(str));
}
/// <summary>
/// End a list.
/// </summary>
public void EndList()
{
_text.Append("</ul>");
}
/// <summary>
/// Begin a new table in a cell.
/// </summary>
/// <param name="colSpan">The column span.</param>
public void BeginTableInCell(int colSpan)
{
_text.Append("<td");
if (colSpan > 0)
{
_text.Append(" colspan=\"");
_text.Append(colSpan);
_text.Append("\"");
}
_text.Append(">");
_text.Append("<table border=\"1\" width=\"100%\">");
}
/// <summary>
/// End a table in a cell.
/// </summary>
public void EndTableInCell()
{
_text.Append("</table></td>");
}
/// <summary>
/// Encode a string for HTML.
/// </summary>
/// <param name="str">The string to encode.</param>
/// <returns>The encoded string.</returns>
public static String Encode(String str)
{
var result = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
if (ch == '<')
{
result.Append("<");
}
else if (ch == '>')
{
result.Append(">");
}
else if (ch == '&')
{
result.Append("&");
}
else
{
result.Append(ch);
}
}
return result.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.CodeDom;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
namespace Thinktecture.Tools.Web.Services.CodeGeneration
{
/// <summary>
/// This class contains the code decorator implementation for generating the
/// service type.
/// </summary>
internal class ServiceTypeGenerator : ICodeDecorator
{
ExtendedCodeDomTree code;
CustomCodeGenerationOptions options;
string serviceTypeName;
#region ICodeDecorator Members
public void Decorate(ExtendedCodeDomTree code, CustomCodeGenerationOptions options)
{
// Some validations to make debugging easier.
Debug.Assert(code != null, "code parameter could not be null.");
Debug.Assert(options != null, "options parameter could not be null.");
// We execute this decorator only if we are generating the service side code.
if (options.GenerateService)
{
// Initialize the state.
this.code = code;
this.options = options;
CreateServiceType();
}
}
#endregion
#region Private Methods
private void CreateServiceType()
{
// We can create the service type(s) only if we have one or more service
// contract.
if (code.ServiceContracts.Count > 0)
{
// Take a reference to the first ServiceContract available.
// IMPORTANT!:(Currently we only support single service type)
// May be want to support multiple service contracts in the next version.
CodeTypeExtension srvContract = code.ServiceContracts[0];
// Notify if srvContract is null. This would mean that we have constructed a bad
// GeneratedCode instance from our CodeFactory.
Debug.Assert(srvContract != null, "Generated service contract could not be null.");
// Construct the service type name by removing the leading "I" character from
// the service contract name that was added for generation of the interface.
string srvTypeName = srvContract.ExtendedObject.Name.Substring(1);
// Create a new instance of CodeTypeDeclaration type representing the service type.
CodeTypeDeclaration srvType = new CodeTypeDeclaration(srvTypeName);
// Also wrap the CodeTypeDeclaration in an extension.
CodeTypeExtension typeExt = new CodeTypeExtension(srvType);
// This class.
srvType.IsClass = true;
switch (options.MethodImplementation)
{
case MethodImplementation.PartialClassMethodCalls:
// The service type is partial so that the implementation methods can be written in separate file.
srvType.IsPartial = true;
break;
case MethodImplementation.AbstractMethods:
// The service type is abstract so that the operation methods can be made abstract.
srvType.TypeAttributes |= TypeAttributes.Abstract;
break;
}
// And this implements the service contract interface.
if (code.CodeLanguauge == CodeLanguage.VisualBasic)
{
srvType.Members.Add(new CodeSnippetTypeMember("Implements " + srvContract.ExtendedObject.Name));
}
else
{
srvType.BaseTypes.Add(new CodeTypeReference(srvContract.ExtendedObject.Name));
}
// Now itterate the srvContractObject.Members and add each and every method in
// the service contract type to the new type being created.
foreach (CodeTypeMemberExtension methodExtension in srvContract.Methods)
{
// Get a referece to the actual CodeMemberMethod object extended
// by ext.
CodeMemberMethod method = methodExtension.ExtendedObject as CodeMemberMethod;
// Create a new CodeMemeberMethod and copy the attributes.
CodeMemberMethod newMethod = new CodeMemberMethod();
newMethod.Name = method.Name;
// Implemented method has to be public.
newMethod.Attributes = MemberAttributes.Public;
// Notify that this member is implementing a method in the service contract.
if (code.CodeLanguauge == CodeLanguage.VisualBasic)
{
newMethod.ImplementationTypes.Add(new CodeTypeReference(srvContract.ExtendedObject.Name));
}
else
{
newMethod.ImplementationTypes.Add(srvType.BaseTypes[0]);
}
// Add all parametes to the newly created method.
foreach (CodeParameterDeclarationExpression cpde in method.Parameters)
{
newMethod.Parameters.Add(cpde);
}
// Set the return type.
newMethod.ReturnType = method.ReturnType;
switch (options.MethodImplementation)
{
case MethodImplementation.PartialClassMethodCalls:
{
// Gather the parameters from the operation to pass into the implementation method.
IEnumerable<CodeArgumentReferenceExpression> parameters = newMethod.Parameters
.OfType<CodeParameterDeclarationExpression>()
.Select(p => new CodeArgumentReferenceExpression(p.Name));
// Create an expression to invoke the implementation method.
CodeMethodInvokeExpression methodInvocation = new CodeMethodInvokeExpression(null, newMethod.Name + "Implementation", parameters.ToArray());
// Check if the method has a return type.
if (newMethod.ReturnType.BaseType != "System.Void")
{
// Make sure the call to the implementation method is returned.
CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(methodInvocation);
newMethod.Statements.Add(returnStatement);
}
else
{
// Add the call to the implementation method without a return.
newMethod.Statements.Add(methodInvocation);
}
}
break;
case MethodImplementation.NotImplementedException:
{
// Create a new code statement to throw NotImplementedExcption.
CodeThrowExceptionStatement niex = new CodeThrowExceptionStatement(
new CodeObjectCreateExpression(
new CodeTypeReference(typeof(NotImplementedException)), new CodeExpression[] { })
);
// Add it to the statements collection in the new method.
newMethod.Statements.Add(niex);
}
break;
case MethodImplementation.AbstractMethods:
{
// No statement is required for the abstract methods.
newMethod.Attributes |= MemberAttributes.Abstract;
break;
}
}
// Wrap the CodeMemberMethod in an extension. This could be useful for other extensions.
CodeTypeMemberExtension newMethodExt = new CodeTypeMemberExtension(newMethod, typeExt);
srvType.Members.Add(newMethodExt);
}
// Add the ServiceBehaviorAttribute attribute.
CodeAttributeDeclaration serviceBehaviorAttribute = new CodeAttributeDeclaration(
new CodeTypeReference(typeof(ServiceBehaviorAttribute)));
if (!string.IsNullOrEmpty(options.InstanceContextMode))
{
CodeTypeReferenceExpression instanceContextModeEnum = new CodeTypeReferenceExpression(typeof(InstanceContextMode));
CodeFieldReferenceExpression instanceContextModeValue = new CodeFieldReferenceExpression(instanceContextModeEnum, options.InstanceContextMode);
CodeAttributeArgument instanceContextModeArgument = new CodeAttributeArgument("InstanceContextMode", instanceContextModeValue);
serviceBehaviorAttribute.Arguments.Add(instanceContextModeArgument);
}
if (!string.IsNullOrEmpty(options.ConcurrencyMode))
{
CodeTypeReferenceExpression concurrencyModeEnum = new CodeTypeReferenceExpression(typeof(ConcurrencyMode));
CodeFieldReferenceExpression concurrencyModeValue = new CodeFieldReferenceExpression(concurrencyModeEnum, options.ConcurrencyMode);
CodeAttributeArgument concurrencyModeArgument = new CodeAttributeArgument("ConcurrencyMode", concurrencyModeValue);
serviceBehaviorAttribute.Arguments.Add(concurrencyModeArgument);
}
if (!options.UseSynchronizationContext)
{
CodeAttributeArgument useSynchronizationContextAttribute = new CodeAttributeArgument("UseSynchronizationContext", new CodePrimitiveExpression(false));
serviceBehaviorAttribute.Arguments.Add(useSynchronizationContextAttribute);
}
typeExt.AddAttribute(serviceBehaviorAttribute);
this.serviceTypeName = srvType.Name;
// Finally add the newly created type to the code being generated.
code.ServiceTypes.Add(typeExt);
}
}
#endregion
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections;
using PdfSharp.Drawing;
// Review: CountOpen does not work. - StL/14-10-05
namespace PdfSharp.Pdf
{
/// <summary>
/// Represents a collection of outlines.
/// </summary>
public class PdfOutlineCollection : PdfObject, ICollection<PdfOutline>, IList<PdfOutline>
{
/// <summary>
/// Can only be created as part of PdfOutline.
/// </summary>
internal PdfOutlineCollection(PdfDocument document, PdfOutline parent)
: base(document)
{
_parent = parent;
}
/// <summary>
/// Indicates whether the outline collection has at least one entry.
/// </summary>
[Obsolete("Use 'Count > 0' - HasOutline will throw exception.")]
public bool HasOutline // DELETE: 15-10-01
{
get
{
//return Count > 0;
throw new InvalidOperationException("Use 'Count > 0'");
}
}
/// <summary>
/// Removes the first occurrence of a specific item from the collection.
/// </summary>
public bool Remove(PdfOutline item)
{
if (_outlines.Remove(item))
{
RemoveFromOutlinesTree(item);
return true;
}
return false;
}
/// <summary>
/// Gets the number of entries in this collection.
/// </summary>
public int Count
{
get { return _outlines.Count; }
}
/// <summary>
/// Returns false.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Adds the specified outline.
/// </summary>
public void Add(PdfOutline outline)
{
if (outline == null)
throw new ArgumentNullException("outline");
// DestinationPage is optional. PDFsharp does not yet support outlines with action ("/A") instead of destination page ("/DEST")
if (outline.DestinationPage != null && !ReferenceEquals(Owner, outline.DestinationPage.Owner))
throw new ArgumentException("Destination page must belong to this document.");
//// TODO check the parent problems...
////outline.Document = Owner;
////outline.Parent = _parent;
////Owner._irefTable.Add(outline);
AddToOutlinesTree(outline);
_outlines.Add(outline);
if (outline.Opened)
{
outline = _parent;
while (outline != null)
{
outline.OpenCount++;
outline = outline.Parent;
}
}
}
/// <summary>
/// Removes all elements form the collection.
/// </summary>
public void Clear()
{
if (Count > 0)
{
PdfOutline[] array = new PdfOutline[Count];
_outlines.CopyTo(array);
_outlines.Clear();
foreach (PdfOutline item in array)
{
RemoveFromOutlinesTree(item);
}
}
}
/// <summary>
/// Determines whether the specified element is in the collection.
/// </summary>
public bool Contains(PdfOutline item)
{
return _outlines.Contains(item);
}
/// <summary>
/// Copies the collection to an array, starting at the specified index of the target array.
/// </summary>
public void CopyTo(PdfOutline[] array, int arrayIndex)
{
_outlines.CopyTo(array, arrayIndex);
}
/// <summary>
/// Adds the specified outline entry.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
/// <param name="style">The font style used to draw the outline text.</param>
/// <param name="textColor">The color used to draw the outline text.</param>
public PdfOutline Add(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style, XColor textColor)
{
PdfOutline outline = new PdfOutline(title, destinationPage, opened, style, textColor);
Add(outline);
return outline;
}
/// <summary>
/// Adds the specified outline entry.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
/// <param name="style">The font style used to draw the outline text.</param>
public PdfOutline Add(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style)
{
PdfOutline outline = new PdfOutline(title, destinationPage, opened, style);
Add(outline);
return outline;
}
/// <summary>
/// Adds the specified outline entry.
/// </summary>
/// <param name="title">The outline text.</param>
/// <param name="destinationPage">The destination page.</param>
/// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param>
public PdfOutline Add(string title, PdfPage destinationPage, bool opened)
{
PdfOutline outline = new PdfOutline(title, destinationPage, opened);
Add(outline);
return outline;
}
/// <summary>
/// Creates a PdfOutline and adds it into the outline collection.
/// </summary>
public PdfOutline Add(string title, PdfPage destinationPage)
{
PdfOutline outline = new PdfOutline(title, destinationPage);
Add(outline);
return outline;
}
/// <summary>
/// Gets the index of the specified item.
/// </summary>
public int IndexOf(PdfOutline item)
{
return _outlines.IndexOf(item);
}
/// <summary>
/// Inserts the item at the specified index.
/// </summary>
public void Insert(int index, PdfOutline outline)
{
if (outline == null)
throw new ArgumentNullException("outline");
if (index < 0 || index >= _outlines.Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.OutlineIndexOutOfRange);
AddToOutlinesTree(outline);
_outlines.Insert(index, outline);
}
/// <summary>
/// Removes the outline item at the specified index.
/// </summary>
public void RemoveAt(int index)
{
PdfOutline outline = _outlines[index];
_outlines.RemoveAt(index);
RemoveFromOutlinesTree(outline);
}
/// <summary>
/// Gets the <see cref="PdfSharp.Pdf.PdfOutline"/> at the specified index.
/// </summary>
public PdfOutline this[int index]
{
get
{
if (index < 0 || index >= _outlines.Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.OutlineIndexOutOfRange);
return _outlines[index];
}
set
{
if (index < 0 || index >= _outlines.Count)
throw new ArgumentOutOfRangeException("index", index, PSSR.OutlineIndexOutOfRange);
if (value == null)
throw new ArgumentOutOfRangeException("value", null, PSSR.SetValueMustNotBeNull);
AddToOutlinesTree(value);
_outlines[index] = value;
}
}
/// <summary>
/// Returns an enumerator that iterates through the outline collection.
/// </summary>
public IEnumerator<PdfOutline> GetEnumerator()
{
return _outlines.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal int CountOpen()
{
int count = 0;
//foreach (PdfOutline outline in _outlines)
// count += outline.CountOpen();
return count;
}
void AddToOutlinesTree(PdfOutline outline)
{
if (outline == null)
throw new ArgumentNullException("outline");
// DestinationPage is optional. PDFsharp does not yet support outlines with action ("/A") instead of destination page ("/DEST")
if (outline.DestinationPage != null && !ReferenceEquals(Owner, outline.DestinationPage.Owner))
throw new ArgumentException("Destination page must belong to this document.");
// TODO check the parent problems...
outline.Document = Owner;
outline.Parent = _parent;
//_outlines.Add(outline);
if (!Owner._irefTable.Contains(outline.ObjectID))
Owner._irefTable.Add(outline);
else
{
outline.GetType();
}
//if (outline.Opened)
//{
// outline = _parent;
// while (outline != null)
// {
// outline.OpenCount++;
// outline = outline.Parent;
// }
//}
}
void RemoveFromOutlinesTree(PdfOutline outline)
{
if (outline == null)
throw new ArgumentNullException("outline");
// TODO check the parent problems...
//outline.Document = Owner;
outline.Parent = null;
Owner._irefTable.Remove(outline.Reference);
}
/// <summary>
/// The parent outine of this collection.
/// </summary>
readonly PdfOutline _parent;
readonly List<PdfOutline> _outlines = new List<PdfOutline>();
}
}
| |
/*
* 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.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public ILSL_Api m_LSL_Functions;
public void ApiTypeLSL(IScriptApi api)
{
if (!(api is ILSL_Api))
return;
m_LSL_Functions = (ILSL_Api)api;
}
public void state(string newState)
{
m_LSL_Functions.state(newState);
}
//
// Script functions
//
public LSL_Integer llAbs(int i)
{
return m_LSL_Functions.llAbs(i);
}
public LSL_Float llAcos(double val)
{
return m_LSL_Functions.llAcos(val);
}
public void llAddToLandBanList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandBanList(avatar, hours);
}
public void llAddToLandPassList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandPassList(avatar, hours);
}
public void llAdjustSoundVolume(double volume)
{
m_LSL_Functions.llAdjustSoundVolume(volume);
}
public void llAllowInventoryDrop(int add)
{
m_LSL_Functions.llAllowInventoryDrop(add);
}
public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b)
{
return m_LSL_Functions.llAngleBetween(a, b);
}
public void llApplyImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyImpulse(force, local);
}
public void llApplyRotationalImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyRotationalImpulse(force, local);
}
public LSL_Float llAsin(double val)
{
return m_LSL_Functions.llAsin(val);
}
public LSL_Float llAtan2(double x, double y)
{
return m_LSL_Functions.llAtan2(x, y);
}
public void llAttachToAvatar(int attachment)
{
m_LSL_Functions.llAttachToAvatar(attachment);
}
public LSL_Key llAvatarOnSitTarget()
{
return m_LSL_Functions.llAvatarOnSitTarget();
}
public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up)
{
return m_LSL_Functions.llAxes2Rot(fwd, left, up);
}
public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle)
{
return m_LSL_Functions.llAxisAngle2Rot(axis, angle);
}
public LSL_Integer llBase64ToInteger(string str)
{
return m_LSL_Functions.llBase64ToInteger(str);
}
public LSL_String llBase64ToString(string str)
{
return m_LSL_Functions.llBase64ToString(str);
}
public void llBreakAllLinks()
{
m_LSL_Functions.llBreakAllLinks();
}
public void llBreakLink(int linknum)
{
m_LSL_Functions.llBreakLink(linknum);
}
public LSL_Integer llCeil(double f)
{
return m_LSL_Functions.llCeil(f);
}
public void llClearCameraParams()
{
m_LSL_Functions.llClearCameraParams();
}
public void llCloseRemoteDataChannel(string channel)
{
m_LSL_Functions.llCloseRemoteDataChannel(channel);
}
public LSL_Float llCloud(LSL_Vector offset)
{
return m_LSL_Functions.llCloud(offset);
}
public void llCollisionFilter(string name, string id, int accept)
{
m_LSL_Functions.llCollisionFilter(name, id, accept);
}
public void llCollisionSound(string impact_sound, double impact_volume)
{
m_LSL_Functions.llCollisionSound(impact_sound, impact_volume);
}
public void llCollisionSprite(string impact_sprite)
{
m_LSL_Functions.llCollisionSprite(impact_sprite);
}
public LSL_Float llCos(double f)
{
return m_LSL_Functions.llCos(f);
}
public void llCreateLink(string target, int parent)
{
m_LSL_Functions.llCreateLink(target, parent);
}
public LSL_List llCSV2List(string src)
{
return m_LSL_Functions.llCSV2List(src);
}
public LSL_List llDeleteSubList(LSL_List src, int start, int end)
{
return m_LSL_Functions.llDeleteSubList(src, start, end);
}
public LSL_String llDeleteSubString(string src, int start, int end)
{
return m_LSL_Functions.llDeleteSubString(src, start, end);
}
public void llDetachFromAvatar()
{
m_LSL_Functions.llDetachFromAvatar();
}
public LSL_Vector llDetectedGrab(int number)
{
return m_LSL_Functions.llDetectedGrab(number);
}
public LSL_Integer llDetectedGroup(int number)
{
return m_LSL_Functions.llDetectedGroup(number);
}
public LSL_Key llDetectedKey(int number)
{
return m_LSL_Functions.llDetectedKey(number);
}
public LSL_Integer llDetectedLinkNumber(int number)
{
return m_LSL_Functions.llDetectedLinkNumber(number);
}
public LSL_String llDetectedName(int number)
{
return m_LSL_Functions.llDetectedName(number);
}
public LSL_Key llDetectedOwner(int number)
{
return m_LSL_Functions.llDetectedOwner(number);
}
public LSL_Vector llDetectedPos(int number)
{
return m_LSL_Functions.llDetectedPos(number);
}
public LSL_Rotation llDetectedRot(int number)
{
return m_LSL_Functions.llDetectedRot(number);
}
public LSL_Integer llDetectedType(int number)
{
return m_LSL_Functions.llDetectedType(number);
}
public LSL_Vector llDetectedTouchBinormal(int index)
{
return m_LSL_Functions.llDetectedTouchBinormal(index);
}
public LSL_Integer llDetectedTouchFace(int index)
{
return m_LSL_Functions.llDetectedTouchFace(index);
}
public LSL_Vector llDetectedTouchNormal(int index)
{
return m_LSL_Functions.llDetectedTouchNormal(index);
}
public LSL_Vector llDetectedTouchPos(int index)
{
return m_LSL_Functions.llDetectedTouchPos(index);
}
public LSL_Vector llDetectedTouchST(int index)
{
return m_LSL_Functions.llDetectedTouchST(index);
}
public LSL_Vector llDetectedTouchUV(int index)
{
return m_LSL_Functions.llDetectedTouchUV(index);
}
public LSL_Vector llDetectedVel(int number)
{
return m_LSL_Functions.llDetectedVel(number);
}
public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel)
{
m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel);
}
public void llDie()
{
m_LSL_Functions.llDie();
}
public LSL_String llDumpList2String(LSL_List src, string seperator)
{
return m_LSL_Functions.llDumpList2String(src, seperator);
}
public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir)
{
return m_LSL_Functions.llEdgeOfWorld(pos, dir);
}
public void llEjectFromLand(string pest)
{
m_LSL_Functions.llEjectFromLand(pest);
}
public void llEmail(string address, string subject, string message)
{
m_LSL_Functions.llEmail(address, subject, message);
}
public LSL_String llEscapeURL(string url)
{
return m_LSL_Functions.llEscapeURL(url);
}
public LSL_Rotation llEuler2Rot(LSL_Vector v)
{
return m_LSL_Functions.llEuler2Rot(v);
}
public LSL_Float llFabs(double f)
{
return m_LSL_Functions.llFabs(f);
}
public LSL_Integer llFloor(double f)
{
return m_LSL_Functions.llFloor(f);
}
public void llForceMouselook(int mouselook)
{
m_LSL_Functions.llForceMouselook(mouselook);
}
public LSL_Float llFrand(double mag)
{
return m_LSL_Functions.llFrand(mag);
}
public LSL_Vector llGetAccel()
{
return m_LSL_Functions.llGetAccel();
}
public LSL_Integer llGetAgentInfo(string id)
{
return m_LSL_Functions.llGetAgentInfo(id);
}
public LSL_String llGetAgentLanguage(string id)
{
return m_LSL_Functions.llGetAgentLanguage(id);
}
public LSL_Vector llGetAgentSize(string id)
{
return m_LSL_Functions.llGetAgentSize(id);
}
public LSL_Float llGetAlpha(int face)
{
return m_LSL_Functions.llGetAlpha(face);
}
public LSL_Float llGetAndResetTime()
{
return m_LSL_Functions.llGetAndResetTime();
}
public LSL_String llGetAnimation(string id)
{
return m_LSL_Functions.llGetAnimation(id);
}
public LSL_List llGetAnimationList(string id)
{
return m_LSL_Functions.llGetAnimationList(id);
}
public LSL_Integer llGetAttached()
{
return m_LSL_Functions.llGetAttached();
}
public LSL_List llGetBoundingBox(string obj)
{
return m_LSL_Functions.llGetBoundingBox(obj);
}
public LSL_Vector llGetCameraPos()
{
return m_LSL_Functions.llGetCameraPos();
}
public LSL_Rotation llGetCameraRot()
{
return m_LSL_Functions.llGetCameraRot();
}
public LSL_Vector llGetCenterOfMass()
{
return m_LSL_Functions.llGetCenterOfMass();
}
public LSL_Vector llGetColor(int face)
{
return m_LSL_Functions.llGetColor(face);
}
public LSL_String llGetCreator()
{
return m_LSL_Functions.llGetCreator();
}
public LSL_String llGetDate()
{
return m_LSL_Functions.llGetDate();
}
public LSL_Float llGetEnergy()
{
return m_LSL_Functions.llGetEnergy();
}
public LSL_Vector llGetForce()
{
return m_LSL_Functions.llGetForce();
}
public LSL_Integer llGetFreeMemory()
{
return m_LSL_Functions.llGetFreeMemory();
}
public LSL_Integer llGetFreeURLs()
{
return m_LSL_Functions.llGetFreeURLs();
}
public LSL_Vector llGetGeometricCenter()
{
return m_LSL_Functions.llGetGeometricCenter();
}
public LSL_Float llGetGMTclock()
{
return m_LSL_Functions.llGetGMTclock();
}
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{
return m_LSL_Functions.llGetHTTPHeader(request_id, header);
}
public LSL_Key llGetInventoryCreator(string item)
{
return m_LSL_Functions.llGetInventoryCreator(item);
}
public LSL_Key llGetInventoryKey(string name)
{
return m_LSL_Functions.llGetInventoryKey(name);
}
public LSL_String llGetInventoryName(int type, int number)
{
return m_LSL_Functions.llGetInventoryName(type, number);
}
public LSL_Integer llGetInventoryNumber(int type)
{
return m_LSL_Functions.llGetInventoryNumber(type);
}
public LSL_Integer llGetInventoryPermMask(string item, int mask)
{
return m_LSL_Functions.llGetInventoryPermMask(item, mask);
}
public LSL_Integer llGetInventoryType(string name)
{
return m_LSL_Functions.llGetInventoryType(name);
}
public LSL_Key llGetKey()
{
return m_LSL_Functions.llGetKey();
}
public LSL_Key llGetLandOwnerAt(LSL_Vector pos)
{
return m_LSL_Functions.llGetLandOwnerAt(pos);
}
public LSL_Key llGetLinkKey(int linknum)
{
return m_LSL_Functions.llGetLinkKey(linknum);
}
public LSL_String llGetLinkName(int linknum)
{
return m_LSL_Functions.llGetLinkName(linknum);
}
public LSL_Integer llGetLinkNumber()
{
return m_LSL_Functions.llGetLinkNumber();
}
public LSL_Integer llGetListEntryType(LSL_List src, int index)
{
return m_LSL_Functions.llGetListEntryType(src, index);
}
public LSL_Integer llGetListLength(LSL_List src)
{
return m_LSL_Functions.llGetListLength(src);
}
public LSL_Vector llGetLocalPos()
{
return m_LSL_Functions.llGetLocalPos();
}
public LSL_Rotation llGetLocalRot()
{
return m_LSL_Functions.llGetLocalRot();
}
public LSL_Float llGetMass()
{
return m_LSL_Functions.llGetMass();
}
public void llGetNextEmail(string address, string subject)
{
m_LSL_Functions.llGetNextEmail(address, subject);
}
public LSL_String llGetNotecardLine(string name, int line)
{
return m_LSL_Functions.llGetNotecardLine(name, line);
}
public LSL_Key llGetNumberOfNotecardLines(string name)
{
return m_LSL_Functions.llGetNumberOfNotecardLines(name);
}
public LSL_Integer llGetNumberOfPrims()
{
return m_LSL_Functions.llGetNumberOfPrims();
}
public LSL_Integer llGetNumberOfSides()
{
return m_LSL_Functions.llGetNumberOfSides();
}
public LSL_String llGetObjectDesc()
{
return m_LSL_Functions.llGetObjectDesc();
}
public LSL_List llGetObjectDetails(string id, LSL_List args)
{
return m_LSL_Functions.llGetObjectDetails(id, args);
}
public LSL_Float llGetObjectMass(string id)
{
return m_LSL_Functions.llGetObjectMass(id);
}
public LSL_String llGetObjectName()
{
return m_LSL_Functions.llGetObjectName();
}
public LSL_Integer llGetObjectPermMask(int mask)
{
return m_LSL_Functions.llGetObjectPermMask(mask);
}
public LSL_Integer llGetObjectPrimCount(string object_id)
{
return m_LSL_Functions.llGetObjectPrimCount(object_id);
}
public LSL_Vector llGetOmega()
{
return m_LSL_Functions.llGetOmega();
}
public LSL_Key llGetOwner()
{
return m_LSL_Functions.llGetOwner();
}
public LSL_Key llGetOwnerKey(string id)
{
return m_LSL_Functions.llGetOwnerKey(id);
}
public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param)
{
return m_LSL_Functions.llGetParcelDetails(pos, param);
}
public LSL_Integer llGetParcelFlags(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelFlags(pos);
}
public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide)
{
return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide);
}
public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide)
{
return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide);
}
public LSL_List llGetParcelPrimOwners(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelPrimOwners(pos);
}
public LSL_Integer llGetPermissions()
{
return m_LSL_Functions.llGetPermissions();
}
public LSL_Key llGetPermissionsKey()
{
return m_LSL_Functions.llGetPermissionsKey();
}
public LSL_Vector llGetPos()
{
return m_LSL_Functions.llGetPos();
}
public LSL_List llGetPrimitiveParams(LSL_List rules)
{
return m_LSL_Functions.llGetPrimitiveParams(rules);
}
public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules)
{
return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules);
}
public LSL_Integer llGetRegionAgentCount()
{
return m_LSL_Functions.llGetRegionAgentCount();
}
public LSL_Vector llGetRegionCorner()
{
return m_LSL_Functions.llGetRegionCorner();
}
public LSL_Integer llGetRegionFlags()
{
return m_LSL_Functions.llGetRegionFlags();
}
public LSL_Float llGetRegionFPS()
{
return m_LSL_Functions.llGetRegionFPS();
}
public LSL_String llGetRegionName()
{
return m_LSL_Functions.llGetRegionName();
}
public LSL_Float llGetRegionTimeDilation()
{
return m_LSL_Functions.llGetRegionTimeDilation();
}
public LSL_Vector llGetRootPosition()
{
return m_LSL_Functions.llGetRootPosition();
}
public LSL_Rotation llGetRootRotation()
{
return m_LSL_Functions.llGetRootRotation();
}
public LSL_Rotation llGetRot()
{
return m_LSL_Functions.llGetRot();
}
public LSL_Vector llGetScale()
{
return m_LSL_Functions.llGetScale();
}
public LSL_String llGetScriptName()
{
return m_LSL_Functions.llGetScriptName();
}
public LSL_Integer llGetScriptState(string name)
{
return m_LSL_Functions.llGetScriptState(name);
}
public LSL_String llGetSimulatorHostname()
{
return m_LSL_Functions.llGetSimulatorHostname();
}
public LSL_Integer llGetStartParameter()
{
return m_LSL_Functions.llGetStartParameter();
}
public LSL_Integer llGetStatus(int status)
{
return m_LSL_Functions.llGetStatus(status);
}
public LSL_String llGetSubString(string src, int start, int end)
{
return m_LSL_Functions.llGetSubString(src, start, end);
}
public LSL_Vector llGetSunDirection()
{
return m_LSL_Functions.llGetSunDirection();
}
public LSL_String llGetTexture(int face)
{
return m_LSL_Functions.llGetTexture(face);
}
public LSL_Vector llGetTextureOffset(int face)
{
return m_LSL_Functions.llGetTextureOffset(face);
}
public LSL_Float llGetTextureRot(int side)
{
return m_LSL_Functions.llGetTextureRot(side);
}
public LSL_Vector llGetTextureScale(int side)
{
return m_LSL_Functions.llGetTextureScale(side);
}
public LSL_Float llGetTime()
{
return m_LSL_Functions.llGetTime();
}
public LSL_Float llGetTimeOfDay()
{
return m_LSL_Functions.llGetTimeOfDay();
}
public LSL_String llGetTimestamp()
{
return m_LSL_Functions.llGetTimestamp();
}
public LSL_Vector llGetTorque()
{
return m_LSL_Functions.llGetTorque();
}
public LSL_Integer llGetUnixTime()
{
return m_LSL_Functions.llGetUnixTime();
}
public LSL_Vector llGetVel()
{
return m_LSL_Functions.llGetVel();
}
public LSL_Float llGetWallclock()
{
return m_LSL_Functions.llGetWallclock();
}
public void llGiveInventory(string destination, string inventory)
{
m_LSL_Functions.llGiveInventory(destination, inventory);
}
public void llGiveInventoryList(string destination, string category, LSL_List inventory)
{
m_LSL_Functions.llGiveInventoryList(destination, category, inventory);
}
public LSL_Integer llGiveMoney(string destination, int amount)
{
return m_LSL_Functions.llGiveMoney(destination, amount);
}
public void llGodLikeRezObject(string inventory, LSL_Vector pos)
{
m_LSL_Functions.llGodLikeRezObject(inventory, pos);
}
public LSL_Float llGround(LSL_Vector offset)
{
return m_LSL_Functions.llGround(offset);
}
public LSL_Vector llGroundContour(LSL_Vector offset)
{
return m_LSL_Functions.llGroundContour(offset);
}
public LSL_Vector llGroundNormal(LSL_Vector offset)
{
return m_LSL_Functions.llGroundNormal(offset);
}
public void llGroundRepel(double height, int water, double tau)
{
m_LSL_Functions.llGroundRepel(height, water, tau);
}
public LSL_Vector llGroundSlope(LSL_Vector offset)
{
return m_LSL_Functions.llGroundSlope(offset);
}
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body)
{
return m_LSL_Functions.llHTTPRequest(url, parameters, body);
}
public void llHTTPResponse(LSL_Key id, int status, string body)
{
m_LSL_Functions.llHTTPResponse(id, status, body);
}
public LSL_String llInsertString(string dst, int position, string src)
{
return m_LSL_Functions.llInsertString(dst, position, src);
}
public void llInstantMessage(string user, string message)
{
m_LSL_Functions.llInstantMessage(user, message);
}
public LSL_String llIntegerToBase64(int number)
{
return m_LSL_Functions.llIntegerToBase64(number);
}
public LSL_String llKey2Name(string id)
{
return m_LSL_Functions.llKey2Name(id);
}
public LSL_String llGetUsername(string id)
{
return m_LSL_Functions.llGetUsername(id);
}
public LSL_String llRequestUsername(string id)
{
return m_LSL_Functions.llRequestUsername(id);
}
public LSL_String llGetDisplayName(string id)
{
return m_LSL_Functions.llGetDisplayName(id);
}
public LSL_String llRequestDisplayName(string id)
{
return m_LSL_Functions.llRequestDisplayName(id);
}
public void llLinkParticleSystem(int linknum, LSL_List rules)
{
m_LSL_Functions.llLinkParticleSystem(linknum, rules);
}
public LSL_String llList2CSV(LSL_List src)
{
return m_LSL_Functions.llList2CSV(src);
}
public LSL_Float llList2Float(LSL_List src, int index)
{
return m_LSL_Functions.llList2Float(src, index);
}
public LSL_Integer llList2Integer(LSL_List src, int index)
{
return m_LSL_Functions.llList2Integer(src, index);
}
public LSL_Key llList2Key(LSL_List src, int index)
{
return m_LSL_Functions.llList2Key(src, index);
}
public LSL_List llList2List(LSL_List src, int start, int end)
{
return m_LSL_Functions.llList2List(src, start, end);
}
public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride)
{
return m_LSL_Functions.llList2ListStrided(src, start, end, stride);
}
public LSL_Rotation llList2Rot(LSL_List src, int index)
{
return m_LSL_Functions.llList2Rot(src, index);
}
public LSL_String llList2String(LSL_List src, int index)
{
return m_LSL_Functions.llList2String(src, index);
}
public LSL_Vector llList2Vector(LSL_List src, int index)
{
return m_LSL_Functions.llList2Vector(src, index);
}
public LSL_Integer llListen(int channelID, string name, string ID, string msg)
{
return m_LSL_Functions.llListen(channelID, name, ID, msg);
}
public void llListenControl(int number, int active)
{
m_LSL_Functions.llListenControl(number, active);
}
public void llListenRemove(int number)
{
m_LSL_Functions.llListenRemove(number);
}
public LSL_Integer llListFindList(LSL_List src, LSL_List test)
{
return m_LSL_Functions.llListFindList(src, test);
}
public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start)
{
return m_LSL_Functions.llListInsertList(dest, src, start);
}
public LSL_List llListRandomize(LSL_List src, int stride)
{
return m_LSL_Functions.llListRandomize(src, stride);
}
public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end)
{
return m_LSL_Functions.llListReplaceList(dest, src, start, end);
}
public LSL_List llListSort(LSL_List src, int stride, int ascending)
{
return m_LSL_Functions.llListSort(src, stride, ascending);
}
public LSL_Float llListStatistics(int operation, LSL_List src)
{
return m_LSL_Functions.llListStatistics(operation, src);
}
public void llLoadURL(string avatar_id, string message, string url)
{
m_LSL_Functions.llLoadURL(avatar_id, message, url);
}
public LSL_Float llLog(double val)
{
return m_LSL_Functions.llLog(val);
}
public LSL_Float llLog10(double val)
{
return m_LSL_Functions.llLog10(val);
}
public void llLookAt(LSL_Vector target, double strength, double damping)
{
m_LSL_Functions.llLookAt(target, strength, damping);
}
public void llLoopSound(string sound, double volume)
{
m_LSL_Functions.llLoopSound(sound, volume);
}
public void llLoopSoundMaster(string sound, double volume)
{
m_LSL_Functions.llLoopSoundMaster(sound, volume);
}
public void llLoopSoundSlave(string sound, double volume)
{
m_LSL_Functions.llLoopSoundSlave(sound, volume);
}
public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset)
{
m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset);
}
public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at)
{
m_LSL_Functions.llMapDestination(simname, pos, look_at);
}
public LSL_String llMD5String(string src, int nonce)
{
return m_LSL_Functions.llMD5String(src, nonce);
}
public LSL_String llSHA1String(string src)
{
return m_LSL_Functions.llSHA1String(src);
}
public void llMessageLinked(int linknum, int num, string str, string id)
{
m_LSL_Functions.llMessageLinked(linknum, num, str, id);
}
public void llMinEventDelay(double delay)
{
m_LSL_Functions.llMinEventDelay(delay);
}
public void llModifyLand(int action, int brush)
{
m_LSL_Functions.llModifyLand(action, brush);
}
public LSL_Integer llModPow(int a, int b, int c)
{
return m_LSL_Functions.llModPow(a, b, c);
}
public void llMoveToTarget(LSL_Vector target, double tau)
{
m_LSL_Functions.llMoveToTarget(target, tau);
}
public void llOffsetTexture(double u, double v, int face)
{
m_LSL_Functions.llOffsetTexture(u, v, face);
}
public void llOpenRemoteDataChannel()
{
m_LSL_Functions.llOpenRemoteDataChannel();
}
public LSL_Integer llOverMyLand(string id)
{
return m_LSL_Functions.llOverMyLand(id);
}
public void llOwnerSay(string msg)
{
m_LSL_Functions.llOwnerSay(msg);
}
public void llParcelMediaCommandList(LSL_List commandList)
{
m_LSL_Functions.llParcelMediaCommandList(commandList);
}
public LSL_List llParcelMediaQuery(LSL_List aList)
{
return m_LSL_Functions.llParcelMediaQuery(aList);
}
public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers)
{
return m_LSL_Functions.llParseString2List(str, separators, spacers);
}
public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers)
{
return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers);
}
public void llParticleSystem(LSL_List rules)
{
m_LSL_Functions.llParticleSystem(rules);
}
public void llPassCollisions(int pass)
{
m_LSL_Functions.llPassCollisions(pass);
}
public void llPassTouches(int pass)
{
m_LSL_Functions.llPassTouches(pass);
}
public void llPlaySound(string sound, double volume)
{
m_LSL_Functions.llPlaySound(sound, volume);
}
public void llPlaySoundSlave(string sound, double volume)
{
m_LSL_Functions.llPlaySoundSlave(sound, volume);
}
public void llPointAt(LSL_Vector pos)
{
m_LSL_Functions.llPointAt(pos);
}
public LSL_Float llPow(double fbase, double fexponent)
{
return m_LSL_Functions.llPow(fbase, fexponent);
}
public void llPreloadSound(string sound)
{
m_LSL_Functions.llPreloadSound(sound);
}
public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local)
{
m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local);
}
public void llRefreshPrimURL()
{
m_LSL_Functions.llRefreshPrimURL();
}
public void llRegionSay(int channelID, string text)
{
m_LSL_Functions.llRegionSay(channelID, text);
}
public void llReleaseCamera(string avatar)
{
m_LSL_Functions.llReleaseCamera(avatar);
}
public void llReleaseURL(string url)
{
m_LSL_Functions.llReleaseURL(url);
}
public void llReleaseControls()
{
m_LSL_Functions.llReleaseControls();
}
public void llRemoteDataReply(string channel, string message_id, string sdata, int idata)
{
m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata);
}
public void llRemoteDataSetRegion()
{
m_LSL_Functions.llRemoteDataSetRegion();
}
public void llRemoteLoadScript(string target, string name, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param);
}
public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param);
}
public void llRemoveFromLandBanList(string avatar)
{
m_LSL_Functions.llRemoveFromLandBanList(avatar);
}
public void llRemoveFromLandPassList(string avatar)
{
m_LSL_Functions.llRemoveFromLandPassList(avatar);
}
public void llRemoveInventory(string item)
{
m_LSL_Functions.llRemoveInventory(item);
}
public void llRemoveVehicleFlags(int flags)
{
m_LSL_Functions.llRemoveVehicleFlags(flags);
}
public LSL_Key llRequestAgentData(string id, int data)
{
return m_LSL_Functions.llRequestAgentData(id, data);
}
public LSL_Key llRequestInventoryData(string name)
{
return m_LSL_Functions.llRequestInventoryData(name);
}
public void llRequestPermissions(string agent, int perm)
{
m_LSL_Functions.llRequestPermissions(agent, perm);
}
public LSL_String llRequestSecureURL()
{
return m_LSL_Functions.llRequestSecureURL();
}
public LSL_Key llRequestSimulatorData(string simulator, int data)
{
return m_LSL_Functions.llRequestSimulatorData(simulator, data);
}
public LSL_Key llRequestURL()
{
return m_LSL_Functions.llRequestURL();
}
public void llResetLandBanList()
{
m_LSL_Functions.llResetLandBanList();
}
public void llResetLandPassList()
{
m_LSL_Functions.llResetLandPassList();
}
public void llResetOtherScript(string name)
{
m_LSL_Functions.llResetOtherScript(name);
}
public void llResetScript()
{
m_LSL_Functions.llResetScript();
}
public void llResetTime()
{
m_LSL_Functions.llResetTime();
}
public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param);
}
public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param);
}
public LSL_Float llRot2Angle(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Angle(rot);
}
public LSL_Vector llRot2Axis(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Axis(rot);
}
public LSL_Vector llRot2Euler(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Euler(r);
}
public LSL_Vector llRot2Fwd(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Fwd(r);
}
public LSL_Vector llRot2Left(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Left(r);
}
public LSL_Vector llRot2Up(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Up(r);
}
public void llRotateTexture(double rotation, int face)
{
m_LSL_Functions.llRotateTexture(rotation, face);
}
public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end)
{
return m_LSL_Functions.llRotBetween(start, end);
}
public void llRotLookAt(LSL_Rotation target, double strength, double damping)
{
m_LSL_Functions.llRotLookAt(target, strength, damping);
}
public LSL_Integer llRotTarget(LSL_Rotation rot, double error)
{
return m_LSL_Functions.llRotTarget(rot, error);
}
public void llRotTargetRemove(int number)
{
m_LSL_Functions.llRotTargetRemove(number);
}
public LSL_Integer llRound(double f)
{
return m_LSL_Functions.llRound(f);
}
public LSL_Integer llSameGroup(string agent)
{
return m_LSL_Functions.llSameGroup(agent);
}
public void llSay(int channelID, string text)
{
m_LSL_Functions.llSay(channelID, text);
}
public void llScaleTexture(double u, double v, int face)
{
m_LSL_Functions.llScaleTexture(u, v, face);
}
public LSL_Integer llScriptDanger(LSL_Vector pos)
{
return m_LSL_Functions.llScriptDanger(pos);
}
public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata)
{
return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata);
}
public void llSensor(string name, string id, int type, double range, double arc)
{
m_LSL_Functions.llSensor(name, id, type, range, arc);
}
public void llSensorRemove()
{
m_LSL_Functions.llSensorRemove();
}
public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate)
{
m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate);
}
public void llSetAlpha(double alpha, int face)
{
m_LSL_Functions.llSetAlpha(alpha, face);
}
public void llSetBuoyancy(double buoyancy)
{
m_LSL_Functions.llSetBuoyancy(buoyancy);
}
public void llSetCameraAtOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraAtOffset(offset);
}
public void llSetCameraEyeOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraEyeOffset(offset);
}
public void llSetCameraParams(LSL_List rules)
{
m_LSL_Functions.llSetCameraParams(rules);
}
public void llSetClickAction(int action)
{
m_LSL_Functions.llSetClickAction(action);
}
public void llSetColor(LSL_Vector color, int face)
{
m_LSL_Functions.llSetColor(color, face);
}
public void llSetDamage(double damage)
{
m_LSL_Functions.llSetDamage(damage);
}
public void llSetForce(LSL_Vector force, int local)
{
m_LSL_Functions.llSetForce(force, local);
}
public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local)
{
m_LSL_Functions.llSetForceAndTorque(force, torque, local);
}
public void llSetHoverHeight(double height, int water, double tau)
{
m_LSL_Functions.llSetHoverHeight(height, water, tau);
}
public void llSetInventoryPermMask(string item, int mask, int value)
{
m_LSL_Functions.llSetInventoryPermMask(item, mask, value);
}
public void llSetLinkAlpha(int linknumber, double alpha, int face)
{
m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face);
}
public void llSetLinkColor(int linknumber, LSL_Vector color, int face)
{
m_LSL_Functions.llSetLinkColor(linknumber, color, face);
}
public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules);
}
public void llSetLinkTexture(int linknumber, string texture, int face)
{
m_LSL_Functions.llSetLinkTexture(linknumber, texture, face);
}
public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate);
}
public void llSetLocalRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetLocalRot(rot);
}
public void llSetObjectDesc(string desc)
{
m_LSL_Functions.llSetObjectDesc(desc);
}
public void llSetObjectName(string name)
{
m_LSL_Functions.llSetObjectName(name);
}
public void llSetObjectPermMask(int mask, int value)
{
m_LSL_Functions.llSetObjectPermMask(mask, value);
}
public void llSetParcelMusicURL(string url)
{
m_LSL_Functions.llSetParcelMusicURL(url);
}
public void llSetPayPrice(int price, LSL_List quick_pay_buttons)
{
m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons);
}
public void llSetPos(LSL_Vector pos)
{
m_LSL_Functions.llSetPos(pos);
}
public void llSetPrimitiveParams(LSL_List rules)
{
m_LSL_Functions.llSetPrimitiveParams(rules);
}
public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules);
}
public void llSetPrimURL(string url)
{
m_LSL_Functions.llSetPrimURL(url);
}
public void llSetRemoteScriptAccessPin(int pin)
{
m_LSL_Functions.llSetRemoteScriptAccessPin(pin);
}
public void llSetRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetRot(rot);
}
public void llSetScale(LSL_Vector scale)
{
m_LSL_Functions.llSetScale(scale);
}
public void llSetScriptState(string name, int run)
{
m_LSL_Functions.llSetScriptState(name, run);
}
public void llSetSitText(string text)
{
m_LSL_Functions.llSetSitText(text);
}
public void llSetSoundQueueing(int queue)
{
m_LSL_Functions.llSetSoundQueueing(queue);
}
public void llSetSoundRadius(double radius)
{
m_LSL_Functions.llSetSoundRadius(radius);
}
public void llSetStatus(int status, int value)
{
m_LSL_Functions.llSetStatus(status, value);
}
public void llSetText(string text, LSL_Vector color, double alpha)
{
m_LSL_Functions.llSetText(text, color, alpha);
}
public void llSetTexture(string texture, int face)
{
m_LSL_Functions.llSetTexture(texture, face);
}
public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate);
}
public void llSetTimerEvent(double sec)
{
m_LSL_Functions.llSetTimerEvent(sec);
}
public void llSetTorque(LSL_Vector torque, int local)
{
m_LSL_Functions.llSetTorque(torque, local);
}
public void llSetTouchText(string text)
{
m_LSL_Functions.llSetTouchText(text);
}
public void llSetVehicleFlags(int flags)
{
m_LSL_Functions.llSetVehicleFlags(flags);
}
public void llSetVehicleFloatParam(int param, LSL_Float value)
{
m_LSL_Functions.llSetVehicleFloatParam(param, value);
}
public void llSetVehicleRotationParam(int param, LSL_Rotation rot)
{
m_LSL_Functions.llSetVehicleRotationParam(param, rot);
}
public void llSetVehicleType(int type)
{
m_LSL_Functions.llSetVehicleType(type);
}
public void llSetVehicleVectorParam(int param, LSL_Vector vec)
{
m_LSL_Functions.llSetVehicleVectorParam(param, vec);
}
public void llShout(int channelID, string text)
{
m_LSL_Functions.llShout(channelID, text);
}
public LSL_Float llSin(double f)
{
return m_LSL_Functions.llSin(f);
}
public void llSitTarget(LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llSitTarget(offset, rot);
}
public void llSleep(double sec)
{
m_LSL_Functions.llSleep(sec);
}
public void llSound(string sound, double volume, int queue, int loop)
{
m_LSL_Functions.llSound(sound, volume, queue, loop);
}
public void llSoundPreload(string sound)
{
m_LSL_Functions.llSoundPreload(sound);
}
public LSL_Float llSqrt(double f)
{
return m_LSL_Functions.llSqrt(f);
}
public void llStartAnimation(string anim)
{
m_LSL_Functions.llStartAnimation(anim);
}
public void llStopAnimation(string anim)
{
m_LSL_Functions.llStopAnimation(anim);
}
public void llStopHover()
{
m_LSL_Functions.llStopHover();
}
public void llStopLookAt()
{
m_LSL_Functions.llStopLookAt();
}
public void llStopMoveToTarget()
{
m_LSL_Functions.llStopMoveToTarget();
}
public void llStopPointAt()
{
m_LSL_Functions.llStopPointAt();
}
public void llStopSound()
{
m_LSL_Functions.llStopSound();
}
public LSL_Integer llStringLength(string str)
{
return m_LSL_Functions.llStringLength(str);
}
public LSL_String llStringToBase64(string str)
{
return m_LSL_Functions.llStringToBase64(str);
}
public LSL_String llStringTrim(string src, int type)
{
return m_LSL_Functions.llStringTrim(src, type);
}
public LSL_Integer llSubStringIndex(string source, string pattern)
{
return m_LSL_Functions.llSubStringIndex(source, pattern);
}
public void llTakeCamera(string avatar)
{
m_LSL_Functions.llTakeCamera(avatar);
}
public void llTakeControls(int controls, int accept, int pass_on)
{
m_LSL_Functions.llTakeControls(controls, accept, pass_on);
}
public LSL_Float llTan(double f)
{
return m_LSL_Functions.llTan(f);
}
public LSL_Integer llTarget(LSL_Vector position, double range)
{
return m_LSL_Functions.llTarget(position, range);
}
public void llTargetOmega(LSL_Vector axis, double spinrate, double gain)
{
m_LSL_Functions.llTargetOmega(axis, spinrate, gain);
}
public void llTargetRemove(int number)
{
m_LSL_Functions.llTargetRemove(number);
}
public void llTeleportAgentHome(string agent)
{
m_LSL_Functions.llTeleportAgentHome(agent);
}
public void llTextBox(string avatar, string message, int chat_channel)
{
m_LSL_Functions.llTextBox(avatar, message, chat_channel);
}
public LSL_String llToLower(string source)
{
return m_LSL_Functions.llToLower(source);
}
public LSL_String llToUpper(string source)
{
return m_LSL_Functions.llToUpper(source);
}
public void llTriggerSound(string sound, double volume)
{
m_LSL_Functions.llTriggerSound(sound, volume);
}
public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west)
{
m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west);
}
public LSL_String llUnescapeURL(string url)
{
return m_LSL_Functions.llUnescapeURL(url);
}
public void llUnSit(string id)
{
m_LSL_Functions.llUnSit(id);
}
public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b)
{
return m_LSL_Functions.llVecDist(a, b);
}
public LSL_Float llVecMag(LSL_Vector v)
{
return m_LSL_Functions.llVecMag(v);
}
public LSL_Vector llVecNorm(LSL_Vector v)
{
return m_LSL_Functions.llVecNorm(v);
}
public void llVolumeDetect(int detect)
{
m_LSL_Functions.llVolumeDetect(detect);
}
public LSL_Float llWater(LSL_Vector offset)
{
return m_LSL_Functions.llWater(offset);
}
public void llWhisper(int channelID, string text)
{
m_LSL_Functions.llWhisper(channelID, text);
}
public LSL_Vector llWind(LSL_Vector offset)
{
return m_LSL_Functions.llWind(offset);
}
public LSL_String llXorBase64Strings(string str1, string str2)
{
return m_LSL_Functions.llXorBase64Strings(str1, str2);
}
public LSL_String llXorBase64StringsCorrect(string str1, string str2)
{
return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2);
}
public LSL_List llGetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llGetPrimMediaParams(face, rules);
}
public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llSetPrimMediaParams(face, rules);
}
public LSL_Integer llClearPrimMedia(LSL_Integer face)
{
return m_LSL_Functions.llClearPrimMedia(face);
}
public void print(string str)
{
m_LSL_Functions.print(str);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmExportProductPerfomace
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmExportProductPerfomace() : base()
{
Load += frmExportProductPerfomace_Load;
KeyPress += frmExportProductPerfomace_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdLoad;
public System.Windows.Forms.Button cmdLoad {
get { return withEventsField_cmdLoad; }
set {
if (withEventsField_cmdLoad != null) {
withEventsField_cmdLoad.Click -= cmdLoad_Click;
}
withEventsField_cmdLoad = value;
if (withEventsField_cmdLoad != null) {
withEventsField_cmdLoad.Click += cmdLoad_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.RadioButton _optType_2;
public System.Windows.Forms.RadioButton _optType_1;
public System.Windows.Forms.RadioButton _optType_0;
public System.Windows.Forms.ComboBox cmbGroup;
public System.Windows.Forms.CheckBox chkPageBreak;
public System.Windows.Forms.Label _lbl_3;
public System.Windows.Forms.GroupBox _Frame1_0;
public System.Windows.Forms.ComboBox cmbSortField;
public System.Windows.Forms.ComboBox cmbSort;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_0;
public System.Windows.Forms.GroupBox _Frame1_1;
private System.Windows.Forms.Button withEventsField_cmdGroup;
public System.Windows.Forms.Button cmdGroup {
get { return withEventsField_cmdGroup; }
set {
if (withEventsField_cmdGroup != null) {
withEventsField_cmdGroup.Click -= cmdGroup_Click;
}
withEventsField_cmdGroup = value;
if (withEventsField_cmdGroup != null) {
withEventsField_cmdGroup.Click += cmdGroup_Click;
}
}
}
public System.Windows.Forms.Label lblGroup;
public System.Windows.Forms.GroupBox _Frame1_2;
//Public WithEvents Frame1 As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents optType As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.cmdLoad = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this._Frame1_0 = new System.Windows.Forms.GroupBox();
this._optType_2 = new System.Windows.Forms.RadioButton();
this._optType_1 = new System.Windows.Forms.RadioButton();
this._optType_0 = new System.Windows.Forms.RadioButton();
this.cmbGroup = new System.Windows.Forms.ComboBox();
this.chkPageBreak = new System.Windows.Forms.CheckBox();
this._lbl_3 = new System.Windows.Forms.Label();
this._Frame1_1 = new System.Windows.Forms.GroupBox();
this.cmbSortField = new System.Windows.Forms.ComboBox();
this.cmbSort = new System.Windows.Forms.ComboBox();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this._Frame1_2 = new System.Windows.Forms.GroupBox();
this.cmdGroup = new System.Windows.Forms.Button();
this.lblGroup = new System.Windows.Forms.Label();
this._Frame1_0.SuspendLayout();
this._Frame1_1.SuspendLayout();
this._Frame1_2.SuspendLayout();
this.SuspendLayout();
//
//cmdLoad
//
this.cmdLoad.BackColor = System.Drawing.SystemColors.Control;
this.cmdLoad.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdLoad.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdLoad.Location = new System.Drawing.Point(160, 356);
this.cmdLoad.Name = "cmdLoad";
this.cmdLoad.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdLoad.Size = new System.Drawing.Size(79, 43);
this.cmdLoad.TabIndex = 16;
this.cmdLoad.Text = "Export Now";
this.cmdLoad.UseVisualStyleBackColor = false;
//
//cmdExit
//
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Location = new System.Drawing.Point(6, 356);
this.cmdExit.Name = "cmdExit";
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Size = new System.Drawing.Size(79, 43);
this.cmdExit.TabIndex = 15;
this.cmdExit.Text = "E&xit";
this.cmdExit.UseVisualStyleBackColor = false;
//
//_Frame1_0
//
this._Frame1_0.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_0.Controls.Add(this._optType_2);
this._Frame1_0.Controls.Add(this._optType_1);
this._Frame1_0.Controls.Add(this._optType_0);
this._Frame1_0.Controls.Add(this.cmbGroup);
this._Frame1_0.Controls.Add(this.chkPageBreak);
this._Frame1_0.Controls.Add(this._lbl_3);
this._Frame1_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_0.Location = new System.Drawing.Point(6, 4);
this._Frame1_0.Name = "_Frame1_0";
this._Frame1_0.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_0.Size = new System.Drawing.Size(232, 105);
this._Frame1_0.TabIndex = 8;
this._Frame1_0.TabStop = false;
this._Frame1_0.Text = "&1. Export Options";
//
//_optType_2
//
this._optType_2.BackColor = System.Drawing.SystemColors.Control;
this._optType_2.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_2.Location = new System.Drawing.Point(12, 57);
this._optType_2.Name = "_optType_2";
this._optType_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_2.Size = new System.Drawing.Size(115, 22);
this._optType_2.TabIndex = 13;
this._optType_2.TabStop = true;
this._optType_2.Text = "Group Totals";
this._optType_2.UseVisualStyleBackColor = false;
//
//_optType_1
//
this._optType_1.BackColor = System.Drawing.SystemColors.Control;
this._optType_1.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_1.Location = new System.Drawing.Point(12, 39);
this._optType_1.Name = "_optType_1";
this._optType_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_1.Size = new System.Drawing.Size(115, 18);
this._optType_1.TabIndex = 12;
this._optType_1.TabStop = true;
this._optType_1.Text = "Items Per Group";
this._optType_1.UseVisualStyleBackColor = false;
//
//_optType_0
//
this._optType_0.BackColor = System.Drawing.SystemColors.Control;
this._optType_0.Checked = true;
this._optType_0.Cursor = System.Windows.Forms.Cursors.Default;
this._optType_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._optType_0.Location = new System.Drawing.Point(12, 21);
this._optType_0.Name = "_optType_0";
this._optType_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._optType_0.Size = new System.Drawing.Size(115, 20);
this._optType_0.TabIndex = 11;
this._optType_0.TabStop = true;
this._optType_0.Text = "Normal Item Listing";
this._optType_0.UseVisualStyleBackColor = false;
//
//cmbGroup
//
this.cmbGroup.BackColor = System.Drawing.SystemColors.Window;
this.cmbGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbGroup.Enabled = false;
this.cmbGroup.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbGroup.Items.AddRange(new object[] {
"Pricing Group",
"Stock Group",
"Supplier"
});
this.cmbGroup.Location = new System.Drawing.Point(110, 78);
this.cmbGroup.Name = "cmbGroup";
this.cmbGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbGroup.Size = new System.Drawing.Size(106, 22);
this.cmbGroup.TabIndex = 10;
//
//chkPageBreak
//
this.chkPageBreak.BackColor = System.Drawing.SystemColors.Control;
this.chkPageBreak.Cursor = System.Windows.Forms.Cursors.Default;
this.chkPageBreak.Enabled = false;
this.chkPageBreak.ForeColor = System.Drawing.SystemColors.ControlText;
this.chkPageBreak.Location = new System.Drawing.Point(30, 130);
this.chkPageBreak.Name = "chkPageBreak";
this.chkPageBreak.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkPageBreak.Size = new System.Drawing.Size(163, 13);
this.chkPageBreak.TabIndex = 9;
this.chkPageBreak.Text = "Page Break after each Group.";
this.chkPageBreak.UseVisualStyleBackColor = false;
this.chkPageBreak.Visible = false;
//
//_lbl_3
//
this._lbl_3.AutoSize = true;
this._lbl_3.BackColor = System.Drawing.Color.Transparent;
this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_3.Location = new System.Drawing.Point(54, 82);
this._lbl_3.Name = "_lbl_3";
this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_3.Size = new System.Drawing.Size(61, 14);
this._lbl_3.TabIndex = 14;
this._lbl_3.Text = "Group on:";
//
//_Frame1_1
//
this._Frame1_1.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_1.Controls.Add(this.cmbSortField);
this._Frame1_1.Controls.Add(this.cmbSort);
this._Frame1_1.Controls.Add(this._lbl_2);
this._Frame1_1.Controls.Add(this._lbl_0);
this._Frame1_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_1.Location = new System.Drawing.Point(6, 114);
this._Frame1_1.Name = "_Frame1_1";
this._Frame1_1.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_1.Size = new System.Drawing.Size(232, 85);
this._Frame1_1.TabIndex = 3;
this._Frame1_1.TabStop = false;
this._Frame1_1.Text = "&2. Export Sort Options";
//
//cmbSortField
//
this.cmbSortField.BackColor = System.Drawing.SystemColors.Window;
this.cmbSortField.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbSortField.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSortField.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbSortField.Items.AddRange(new object[] {
"Item Name",
"Cost",
"Selling",
"Gross Profit",
"Gross Profit %",
"Quantity Sold"
});
this.cmbSortField.Location = new System.Drawing.Point(80, 27);
this.cmbSortField.Name = "cmbSortField";
this.cmbSortField.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbSortField.Size = new System.Drawing.Size(115, 22);
this.cmbSortField.TabIndex = 5;
//
//cmbSort
//
this.cmbSort.BackColor = System.Drawing.SystemColors.Window;
this.cmbSort.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbSort.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSort.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbSort.Items.AddRange(new object[] {
"Ascending",
"Descending"
});
this.cmbSort.Location = new System.Drawing.Point(80, 51);
this.cmbSort.Name = "cmbSort";
this.cmbSort.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbSort.Size = new System.Drawing.Size(115, 22);
this.cmbSort.TabIndex = 4;
//
//_lbl_2
//
this._lbl_2.AutoSize = true;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Location = new System.Drawing.Point(9, 54);
this._lbl_2.Name = "_lbl_2";
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.Size = new System.Drawing.Size(68, 14);
this._lbl_2.TabIndex = 7;
this._lbl_2.Text = "Sort Order:";
//
//_lbl_0
//
this._lbl_0.AutoSize = true;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Location = new System.Drawing.Point(12, 30);
this._lbl_0.Name = "_lbl_0";
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.Size = new System.Drawing.Size(62, 14);
this._lbl_0.TabIndex = 6;
this._lbl_0.Text = "Sort Field:";
//
//_Frame1_2
//
this._Frame1_2.BackColor = System.Drawing.SystemColors.Control;
this._Frame1_2.Controls.Add(this.cmdGroup);
this._Frame1_2.Controls.Add(this.lblGroup);
this._Frame1_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._Frame1_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._Frame1_2.Location = new System.Drawing.Point(6, 204);
this._Frame1_2.Name = "_Frame1_2";
this._Frame1_2.Padding = new System.Windows.Forms.Padding(0);
this._Frame1_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._Frame1_2.Size = new System.Drawing.Size(232, 145);
this._Frame1_2.TabIndex = 0;
this._Frame1_2.TabStop = false;
this._Frame1_2.Text = "&3. Export Filter";
//
//cmdGroup
//
this.cmdGroup.BackColor = System.Drawing.SystemColors.Control;
this.cmdGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdGroup.Location = new System.Drawing.Point(129, 105);
this.cmdGroup.Name = "cmdGroup";
this.cmdGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdGroup.Size = new System.Drawing.Size(97, 31);
this.cmdGroup.TabIndex = 1;
this.cmdGroup.Text = "&Filter";
this.cmdGroup.UseVisualStyleBackColor = false;
//
//lblGroup
//
this.lblGroup.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)));
this.lblGroup.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.lblGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblGroup.Location = new System.Drawing.Point(6, 21);
this.lblGroup.Name = "lblGroup";
this.lblGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblGroup.Size = new System.Drawing.Size(220, 76);
this.lblGroup.TabIndex = 2;
this.lblGroup.Text = "lblGroup";
//
//frmExportProductPerfomace
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(243, 403);
this.ControlBox = false;
this.Controls.Add(this.cmdLoad);
this.Controls.Add(this.cmdExit);
this.Controls.Add(this._Frame1_0);
this.Controls.Add(this._Frame1_1);
this.Controls.Add(this._Frame1_2);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.Location = new System.Drawing.Point(4, 23);
this.Name = "frmExportProductPerfomace";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Export Product Perfomance";
this._Frame1_0.ResumeLayout(false);
this._Frame1_0.PerformLayout();
this._Frame1_1.ResumeLayout(false);
this._Frame1_1.PerformLayout();
this._Frame1_2.ResumeLayout(false);
this.ResumeLayout(false);
}
#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.Runtime.InteropServices;
using System.Text;
internal partial class Interop
{
internal partial class WinHttp
{
public const uint ERROR_SUCCESS = 0;
public const uint ERROR_FILE_NOT_FOUND = 2;
public const uint ERROR_INVALID_HANDLE = 6;
public const uint ERROR_INVALID_PARAMETER = 87;
public const uint ERROR_INSUFFICIENT_BUFFER = 122;
public const uint ERROR_NOT_FOUND = 1168;
public const uint ERROR_WINHTTP_INVALID_OPTION = 12009;
public const uint ERROR_WINHTTP_LOGIN_FAILURE = 12015;
public const uint ERROR_WINHTTP_OPERATION_CANCELLED = 12017;
public const uint ERROR_WINHTTP_INCORRECT_HANDLE_STATE = 12019;
public const uint ERROR_WINHTTP_CONNECTION_ERROR = 12030;
public const uint ERROR_WINHTTP_RESEND_REQUEST = 12032;
public const uint ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED = 12044;
public const uint ERROR_WINHTTP_HEADER_NOT_FOUND = 12150;
public const uint ERROR_WINHTTP_SECURE_FAILURE = 12175;
public const uint ERROR_WINHTTP_AUTODETECTION_FAILED = 12180;
public const uint WINHTTP_OPTION_PROXY = 38;
public const uint WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0;
public const uint WINHTTP_ACCESS_TYPE_NO_PROXY = 1;
public const uint WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3;
public const uint WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = 4;
public const uint WINHTTP_AUTOPROXY_AUTO_DETECT = 0x00000001;
public const uint WINHTTP_AUTOPROXY_CONFIG_URL = 0x00000002;
public const uint WINHTTP_AUTOPROXY_HOST_KEEPCASE = 0x00000004;
public const uint WINHTTP_AUTOPROXY_HOST_LOWERCASE = 0x00000008;
public const uint WINHTTP_AUTOPROXY_RUN_INPROCESS = 0x00010000;
public const uint WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = 0x00020000;
public const uint WINHTTP_AUTOPROXY_NO_DIRECTACCESS = 0x00040000;
public const uint WINHTTP_AUTOPROXY_NO_CACHE_CLIENT = 0x00080000;
public const uint WINHTTP_AUTOPROXY_NO_CACHE_SVC = 0x00100000;
public const uint WINHTTP_AUTOPROXY_SORT_RESULTS = 0x00400000;
public const uint WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001;
public const uint WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002;
public const string WINHTTP_NO_PROXY_NAME = null;
public const string WINHTTP_NO_PROXY_BYPASS = null;
public const uint WINHTTP_ADDREQ_FLAG_ADD = 0x20000000;
public const uint WINHTTP_ADDREQ_FLAG_REPLACE = 0x80000000;
public const string WINHTTP_NO_REFERER = null;
public const string WINHTTP_DEFAULT_ACCEPT_TYPES = null;
public const ushort INTERNET_DEFAULT_PORT = 0;
public const ushort INTERNET_DEFAULT_HTTP_PORT = 80;
public const ushort INTERNET_DEFAULT_HTTPS_PORT = 443;
public const uint WINHTTP_FLAG_SECURE = 0x00800000;
public const StringBuilder WINHTTP_NO_ADDITIONAL_HEADERS = null;
public const uint WINHTTP_QUERY_FLAG_NUMBER = 0x20000000;
public const uint WINHTTP_QUERY_VERSION = 18;
public const uint WINHTTP_QUERY_STATUS_CODE = 19;
public const uint WINHTTP_QUERY_STATUS_TEXT = 20;
public const uint WINHTTP_QUERY_RAW_HEADERS = 21;
public const uint WINHTTP_QUERY_RAW_HEADERS_CRLF = 22;
public const uint WINHTTP_QUERY_CONTENT_ENCODING = 29;
public const uint WINHTTP_QUERY_SET_COOKIE = 43;
public const uint WINHTTP_QUERY_CUSTOM = 65535;
public const string WINHTTP_HEADER_NAME_BY_INDEX = null;
public const byte[] WINHTTP_NO_OUTPUT_BUFFER = null;
public const uint WINHTTP_OPTION_DECOMPRESSION = 118;
public const uint WINHTTP_DECOMPRESSION_FLAG_GZIP = 0x00000001;
public const uint WINHTTP_DECOMPRESSION_FLAG_DEFLATE = 0x00000002;
public const uint WINHTTP_DECOMPRESSION_FLAG_ALL = WINHTTP_DECOMPRESSION_FLAG_GZIP | WINHTTP_DECOMPRESSION_FLAG_DEFLATE;
public const uint WINHTTP_OPTION_REDIRECT_POLICY = 88;
public const uint WINHTTP_OPTION_REDIRECT_POLICY_NEVER = 0;
public const uint WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP = 1;
public const uint WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS = 2;
public const uint WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS = 89;
public const uint WINHTTP_OPTION_MAX_CONNS_PER_SERVER = 73;
public const uint WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER = 74;
public const uint WINHTTP_OPTION_DISABLE_FEATURE = 63;
public const uint WINHTTP_DISABLE_COOKIES = 0x00000001;
public const uint WINHTTP_DISABLE_REDIRECTS = 0x00000002;
public const uint WINHTTP_DISABLE_AUTHENTICATION = 0x00000004;
public const uint WINHTTP_DISABLE_KEEP_ALIVE = 0x00000008;
public const uint WINHTTP_OPTION_ENABLE_FEATURE = 79;
public const uint WINHTTP_ENABLE_SSL_REVOCATION = 0x00000001;
public const uint WINHTTP_OPTION_CLIENT_CERT_CONTEXT = 47;
public const uint WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST = 94;
public const uint WINHTTP_OPTION_SERVER_CERT_CONTEXT = 78;
public const uint WINHTTP_OPTION_SECURITY_FLAGS = 31;
public const uint WINHTTP_OPTION_SECURE_PROTOCOLS = 84;
public const uint WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 = 0x00000008;
public const uint WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 = 0x00000020;
public const uint WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 = 0x00000080;
public const uint WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 = 0x00000200;
public const uint WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 = 0x00000800;
public const uint SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100;
public const uint SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000;
public const uint SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000;
public const uint SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = 0x00000200;
public const uint WINHTTP_OPTION_AUTOLOGON_POLICY = 77;
public const uint WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM = 0; // default creds only sent to intranet servers (default)
public const uint WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW = 1; // default creds set to all servers
public const uint WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH = 2; // default creds never sent
public const uint WINHTTP_AUTH_SCHEME_BASIC = 0x00000001;
public const uint WINHTTP_AUTH_SCHEME_NTLM = 0x00000002;
public const uint WINHTTP_AUTH_SCHEME_PASSPORT = 0x00000004;
public const uint WINHTTP_AUTH_SCHEME_DIGEST = 0x00000008;
public const uint WINHTTP_AUTH_SCHEME_NEGOTIATE = 0x00000010;
public const uint WINHTTP_AUTH_TARGET_SERVER = 0x00000000;
public const uint WINHTTP_AUTH_TARGET_PROXY = 0x00000001;
public const uint WINHTTP_OPTION_USERNAME = 0x1000;
public const uint WINHTTP_OPTION_PASSWORD = 0x1001;
public const uint WINHTTP_OPTION_PROXY_USERNAME = 0x1002;
public const uint WINHTTP_OPTION_PROXY_PASSWORD = 0x1003;
public const uint WINHTTP_OPTION_SERVER_SPN_USED = 106;
public const uint WINHTTP_OPTION_SERVER_CBT = 108;
public const uint WINHTTP_OPTION_CONNECT_TIMEOUT = 3;
public const uint WINHTTP_OPTION_SEND_TIMEOUT = 5;
public const uint WINHTTP_OPTION_RECEIVE_TIMEOUT = 6;
public const uint WINHTTP_OPTION_URL = 34;
public const uint WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE = 91;
public const uint WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE = 92;
public const uint WINHTTP_OPTION_CONNECTION_INFO = 93;
public const uint WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS = 111;
public const uint WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET = 114;
public const uint WINHTTP_OPTION_WEB_SOCKET_CLOSE_TIMEOUT = 115;
public const uint WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL = 116;
public const uint WINHTTP_OPTION_WEB_SOCKET_RECEIVE_BUFFER_SIZE = 122;
public const uint WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE = 123;
public enum WINHTTP_WEB_SOCKET_BUFFER_TYPE
{
WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = 0,
WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = 1,
WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = 2,
WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = 3,
WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = 4
}
public const uint WINHTTP_OPTION_CONTEXT_VALUE = 45;
public const uint WINHTTP_FLAG_ASYNC = 0x10000000;
public const uint WINHTTP_CALLBACK_STATUS_RESOLVING_NAME = 0x00000001;
public const uint WINHTTP_CALLBACK_STATUS_NAME_RESOLVED = 0x00000002;
public const uint WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER = 0x00000004;
public const uint WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER = 0x00000008;
public const uint WINHTTP_CALLBACK_STATUS_SENDING_REQUEST = 0x00000010;
public const uint WINHTTP_CALLBACK_STATUS_REQUEST_SENT = 0x00000020;
public const uint WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE = 0x00000040;
public const uint WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED = 0x00000080;
public const uint WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION = 0x00000100;
public const uint WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED = 0x00000200;
public const uint WINHTTP_CALLBACK_STATUS_HANDLE_CREATED = 0x00000400;
public const uint WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING = 0x00000800;
public const uint WINHTTP_CALLBACK_STATUS_DETECTING_PROXY = 0x00001000;
public const uint WINHTTP_CALLBACK_STATUS_REDIRECT = 0x00004000;
public const uint WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE = 0x00008000;
public const uint WINHTTP_CALLBACK_STATUS_SECURE_FAILURE = 0x00010000;
public const uint WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE = 0x00020000;
public const uint WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE = 0x00040000;
public const uint WINHTTP_CALLBACK_STATUS_READ_COMPLETE = 0x00080000;
public const uint WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE = 0x00100000;
public const uint WINHTTP_CALLBACK_STATUS_REQUEST_ERROR = 0x00200000;
public const uint WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE = 0x00400000;
public const uint WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE = 0x01000000;
public const uint WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE = 0x02000000;
public const uint WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE = 0x04000000;
public const uint WINHTTP_CALLBACK_FLAG_SEND_REQUEST =
WINHTTP_CALLBACK_STATUS_SENDING_REQUEST |
WINHTTP_CALLBACK_STATUS_REQUEST_SENT;
public const uint WINHTTP_CALLBACK_FLAG_HANDLES =
WINHTTP_CALLBACK_STATUS_HANDLE_CREATED |
WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING;
public const uint WINHTTP_CALLBACK_FLAG_REDIRECT = WINHTTP_CALLBACK_STATUS_REDIRECT;
public const uint WINHTTP_CALLBACK_FLAG_SECURE_FAILURE = WINHTTP_CALLBACK_STATUS_SECURE_FAILURE;
public const uint WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE = WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE;
public const uint WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE = WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE;
public const uint WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE = WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE;
public const uint WINHTTP_CALLBACK_FLAG_READ_COMPLETE = WINHTTP_CALLBACK_STATUS_READ_COMPLETE;
public const uint WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE = WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE;
public const uint WINHTTP_CALLBACK_FLAG_REQUEST_ERROR = WINHTTP_CALLBACK_STATUS_REQUEST_ERROR;
public const uint WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE = WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE;
public const uint WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS =
WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE |
WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE |
WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE |
WINHTTP_CALLBACK_STATUS_READ_COMPLETE |
WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE |
WINHTTP_CALLBACK_STATUS_REQUEST_ERROR |
WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE;
public const uint WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS = 0xFFFFFFFF;
public const uint WININET_E_CONNECTION_RESET = 0x80072EFF;
public const int WINHTTP_INVALID_STATUS_CALLBACK = -1;
public delegate void WINHTTP_STATUS_CALLBACK(
IntPtr handle,
IntPtr context,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_AUTOPROXY_OPTIONS
{
public uint Flags;
public uint AutoDetectFlags;
[MarshalAs(UnmanagedType.LPWStr)]
public string AutoConfigUrl;
public IntPtr Reserved1;
public uint Reserved2;
[MarshalAs(UnmanagedType.Bool)]
public bool AutoLoginIfChallenged;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_CURRENT_USER_IE_PROXY_CONFIG
{
[MarshalAs(UnmanagedType.Bool)]
public bool AutoDetect;
public IntPtr AutoConfigUrl;
public IntPtr Proxy;
public IntPtr ProxyBypass;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_PROXY_INFO
{
public uint AccessType;
public IntPtr Proxy;
public IntPtr ProxyBypass;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_CONNECTION_INFO
{
public uint Size;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] LocalAddress; // SOCKADDR_STORAGE
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
public byte[] RemoteAddress; // SOCKADDR_STORAGE
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_ASYNC_RESULT
{
public IntPtr dwResult;
public uint dwError;
}
public const uint API_RECEIVE_RESPONSE = 1;
public const uint API_QUERY_DATA_AVAILABLE = 2;
public const uint API_READ_DATA = 3;
public const uint API_WRITE_DATA = 4;
public const uint API_SEND_REQUEST = 5;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_WEB_SOCKET_ASYNC_RESULT
{
public WINHTTP_ASYNC_RESULT AsyncResult;
public WINHTTP_WEB_SOCKET_OPERATION Operation;
}
public enum WINHTTP_WEB_SOCKET_OPERATION
{
WINHTTP_WEB_SOCKET_SEND_OPERATION = 0,
WINHTTP_WEB_SOCKET_RECEIVE_OPERATION = 1,
WINHTTP_WEB_SOCKET_CLOSE_OPERATION = 2,
WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION = 3
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_WEB_SOCKET_STATUS
{
public uint dwBytesTransferred;
public WINHTTP_WEB_SOCKET_BUFFER_TYPE eBufferType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.DependencyModel.Resolution;
using Orleans.Runtime;
#if NETCOREAPP2_0
using System.Runtime.Loader;
#endif
namespace Orleans.CodeGeneration
{
/// <summary>
/// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve
/// </summary>
internal class AssemblyResolver
{
/// <summary>
/// Needs to be public so can be serialized accross the the app domain.
/// </summary>
public Dictionary<string, string> ReferenceAssemblyPaths { get; } = new Dictionary<string, string>();
private readonly bool installDefaultResolveHandler;
private readonly ICompilationAssemblyResolver assemblyResolver;
private readonly DependencyContext dependencyContext;
private readonly DependencyContext resolverRependencyContext;
#if NETCOREAPP2_0
private readonly AssemblyLoadContext loadContext;
#endif
public AssemblyResolver(string path, List<string> referencedAssemblies, bool installDefaultResolveHandler = true)
{
this.installDefaultResolveHandler = installDefaultResolveHandler;
if (Path.GetFileName(path) == "Orleans.Core.dll")
this.Assembly = typeof(RuntimeVersion).Assembly;
else
this.Assembly = Assembly.LoadFrom(path);
this.dependencyContext = DependencyContext.Load(this.Assembly);
this.resolverRependencyContext = DependencyContext.Load(typeof(AssemblyResolver).Assembly);
var codegenPath = Path.GetDirectoryName(new Uri(typeof(AssemblyResolver).Assembly.CodeBase).LocalPath);
this.assemblyResolver = new CompositeCompilationAssemblyResolver(
new ICompilationAssemblyResolver[]
{
new AppBaseCompilationAssemblyResolver(codegenPath),
new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)),
new ReferenceAssemblyPathResolver(),
new PackageCompilationAssemblyResolver()
});
#if NETCOREAPP2_0
this.loadContext = AssemblyLoadContext.GetLoadContext(this.Assembly);
if (this.loadContext == AssemblyLoadContext.Default)
{
if (this.installDefaultResolveHandler)
{
AssemblyLoadContext.Default.Resolving += this.AssemblyLoadContextResolving;
}
}
else
{
this.loadContext.Resolving += this.AssemblyLoadContextResolving;
}
#else
if (this.installDefaultResolveHandler)
{
AppDomain.CurrentDomain.AssemblyResolve += this.ResolveAssembly;
}
#endif
foreach (var assemblyPath in referencedAssemblies)
{
var libName = Path.GetFileNameWithoutExtension(assemblyPath);
if (!string.IsNullOrWhiteSpace(libName)) this.ReferenceAssemblyPaths[libName] = assemblyPath;
var asmName = AssemblyName.GetAssemblyName(assemblyPath);
this.ReferenceAssemblyPaths[asmName.FullName] = assemblyPath;
}
}
public Assembly Assembly { get; }
public void Dispose()
{
#if NETCOREAPP2_0
if (this.loadContext == AssemblyLoadContext.Default)
{
if (this.installDefaultResolveHandler)
{
AssemblyLoadContext.Default.Resolving -= this.AssemblyLoadContextResolving;
}
}
else
{
this.loadContext.Resolving -= this.AssemblyLoadContextResolving;
}
#else
if (this.installDefaultResolveHandler)
{
AppDomain.CurrentDomain.AssemblyResolve -= this.ResolveAssembly;
}
#endif
}
/// <summary>
/// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="args">The event data.</param>
/// <returns>The assembly that resolves the type, assembly, or resource;
/// or null if theassembly cannot be resolved.
/// </returns>
public Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
var context = default(AssemblyLoadContext);
#if NETCOREAPP2_0
context = AssemblyLoadContext.GetLoadContext(args.RequestingAssembly);
#endif
return this.AssemblyLoadContextResolving(context, new AssemblyName(args.Name));
}
public Assembly AssemblyLoadContextResolving(AssemblyLoadContext context, AssemblyName name)
{
// Attempt to resolve the library from one of the dependency contexts.
var library = this.resolverRependencyContext?.RuntimeLibraries?.FirstOrDefault(NamesMatch)
?? this.dependencyContext?.RuntimeLibraries?.FirstOrDefault(NamesMatch);
if (library != null)
{
var wrapper = new CompilationLibrary(
library.Type,
library.Name,
library.Version,
library.Hash,
library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
library.Dependencies,
library.Serviceable);
var assemblies = new List<string>();
if (this.assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies))
{
foreach (var asm in assemblies)
{
var assembly = TryLoadAssemblyFromPath(asm);
if (assembly != null) return assembly;
}
}
}
if (this.ReferenceAssemblyPaths.TryGetValue(name.FullName, out var pathByFullName))
{
var assembly = TryLoadAssemblyFromPath(pathByFullName);
if (assembly != null) return assembly;
}
if (this.ReferenceAssemblyPaths.TryGetValue(name.Name, out var pathByName))
{
//
// Only try to load it if the resolved path is different than from before
//
if (String.Compare(pathByFullName, pathByName, StringComparison.OrdinalIgnoreCase) != 0)
{
var assembly = TryLoadAssemblyFromPath(pathByName);
if (assembly != null) return assembly;
}
}
return null;
bool NamesMatch(RuntimeLibrary runtime)
{
return string.Equals(runtime.Name, name.Name, StringComparison.OrdinalIgnoreCase);
}
}
private Assembly TryLoadAssemblyFromPath(string path)
{
try
{
#if NETCOREAPP2_0
return this.loadContext.LoadFromAssemblyPath(path);
#else
return Assembly.LoadFrom(path);
#endif
}
catch
{
return null;
}
}
#if !NETCOREAPP2_0
internal class AssemblyLoadContext
{
}
#endif
}
}
| |
using System;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Cosmos.VS.DebugEngine.AD7.Definitions;
using Cosmos.VS.DebugEngine.Engine.Impl;
using IL2CPU.Debug.Symbols;
namespace Cosmos.VS.DebugEngine.AD7.Impl
{
// Represents a logical stack frame on the thread stack.
// Also implements the IDebugExpressionContext interface, which allows expression evaluation and watch windows.
public class AD7StackFrame : IDebugStackFrame2, IDebugExpressionContext2
{
readonly AD7Engine mEngine;
readonly AD7Thread mThread;
//readonly X86ThreadContext m_threadContext;
private string mDocName;
private string mFunctionName;
private uint mLineNum;
private bool mHasSource;
// Must have empty holders, some code looks at length and can run
// before we set them.
internal LOCAL_ARGUMENT_INFO[] mLocalInfos = Array.Empty<LOCAL_ARGUMENT_INFO>();
internal LOCAL_ARGUMENT_INFO[] mArgumentInfos = Array.Empty<LOCAL_ARGUMENT_INFO>();
// An array of this frame's parameters
private DebugLocalInfo[] mParams;
// An array of this frame's locals
private DebugLocalInfo[] mLocals;
private AD7Process mProcess;
public AD7StackFrame(AD7Engine aEngine, AD7Thread aThread, AD7Process aProcess)
{
mEngine = aEngine;
mThread = aThread;
mProcess = aProcess;
var xProcess = mEngine.mProcess;
if (mHasSource = xProcess.mCurrentAddress.HasValue)
{
var xAddress = xProcess.mCurrentAddress.Value;
var xSourceInfos = xProcess.mDebugInfoDb.GetSourceInfos(xAddress);
if (!xSourceInfos.ContainsKey(xAddress))
{
//Attempt to find the ASM address of the first ASM line of the C# line that contains
//the current ASM address line
// Because of Asm breakpoints the address we have might be in the middle of a C# line.
// So we find the closest address to ours that is less or equal to ours.
var xQry = from x in xSourceInfos
where x.Key <= xAddress
orderby x.Key descending
select x.Key;
if (xQry.Count() > 0)
{
xAddress = xQry.First();
}
}
if (mHasSource = xSourceInfos.ContainsKey(xAddress))
{
var xSourceInfo = xSourceInfos[xAddress];
mDocName = xSourceInfo.SourceFile;
mFunctionName = xSourceInfo.MethodName;
mLineNum = (uint)xSourceInfo.LineStart;
// Multiple labels that point to a single address can happen because of exception handling exits etc.
// Because of this given an address, we might find more than one label that matches the address.
// Currently, the label we are looking for will always be the first one so we choose that one.
// In the future this might "break", so be careful about this. In the future we may need to classify
// labels in the output and mark them somehow.
var xLabelsForAddr = xProcess.mDebugInfoDb.GetLabels(xAddress);
if (xLabelsForAddr.Length > 0)
{
MethodIlOp xSymbolInfo;
string xLabel = xLabelsForAddr[0]; // Necessary for LINQ
xSymbolInfo = aProcess.mDebugInfoDb.TryGetFirstMethodIlOpByLabelName(xLabel);
if (xSymbolInfo != null)
{
var xMethod = mProcess.mDebugInfoDb.GetMethod(xSymbolInfo.MethodID.Value);
var xAllInfos = aProcess.mDebugInfoDb.GetAllLocalsAndArgumentsInfosByMethodLabelName(xMethod.LabelCall);
mLocalInfos = xAllInfos.Where(q => !q.IsArgument).ToArray();
mArgumentInfos = xAllInfos.Where(q => q.IsArgument).ToArray();
if (mArgumentInfos.Length > 0)
{
mParams = new DebugLocalInfo[mArgumentInfos.Length];
for (int i = 0; i < mArgumentInfos.Length; i++)
{
mParams[i] = new DebugLocalInfo
{
Name = mArgumentInfos[i].NAME,
Index = i,
IsLocal = false
};
}
mParams = mParams.OrderBy(i => i.Name, StringComparer.OrdinalIgnoreCase).ToArray();
}
if (mLocalInfos.Length > 0)
{
mLocals = new DebugLocalInfo[mLocalInfos.Length];
for (int i = 0; i < mLocalInfos.Length; i++)
{
mLocals[i] = new DebugLocalInfo
{
Name = mLocalInfos[i].NAME,
Index = i,
IsLocal = true
};
}
mLocals = mLocals.OrderBy(i => i.Name, StringComparer.OrdinalIgnoreCase).ToArray();
}
}
}
else
{
AD7Util.MessageBox("No Symbol found for address 0x" + xAddress.ToString("X8").ToUpper());
}
xProcess.DebugMsg(String.Format("StackFrame: Returning: {0}#{1}[{2}]", mDocName, mFunctionName, mLineNum));
}
}
if (!mHasSource)
{
xProcess.DebugMsg("StackFrame: No Source available");
}
// If source information is available, create the collections of locals and parameters and populate them with
// values from the debuggee.
//if (m_hasSource) {
//if (mArgumentInfos.Length > 0) {
//m_parameters = new VariableInformation[m_numParameters];
//m_engine.DebuggedProcess.GetFunctionArgumentsByIP(m_threadContext.eip, m_threadContext.ebp, m_parameters);
//}
//if (mLocalInfos.Length > 0) {
//m_locals = new VariableInformation[m_numLocals];
//m_engine.DebuggedProcess.GetFunctionLocalsByIP(m_threadContext.eip, m_threadContext.ebp, m_locals);
//}
//}
}
#region Non-interface methods
// Construct a FRAMEINFO for this stack frame with the requested information.
public void SetFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, out FRAMEINFO frameInfo)
{
System.Diagnostics.Debug.WriteLine("In AD7StackFrame.SetFrameInfo");
System.Diagnostics.Debug.WriteLine("\tdwFieldSpec = " + dwFieldSpec.ToString());
frameInfo = new FRAMEINFO();
//uint ip = m_threadContext.eip;
//DebuggedModule module = null;// m_engine.DebuggedProcess.ResolveAddress(ip);
// The debugger is asking for the formatted name of the function which is displayed in the callstack window.
// There are several optional parts to this name including the module, argument types and values, and line numbers.
// The optional information is requested by setting flags in the dwFieldSpec parameter.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME))
{
// If there is source information, construct a string that contains the module name, function name, and optionally argument names and values.
if (mHasSource)
{
frameInfo.m_bstrFuncName = "";
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE))
{
// m_
//frameInfo.m_bstrFuncName = System.IO.Path.GetFileName(module.Name) + "!";
frameInfo.m_bstrFuncName = "module!";
}
frameInfo.m_bstrFuncName += mFunctionName;
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS) && mArgumentInfos.Length > 0)
{
frameInfo.m_bstrFuncName += "(";
for (int i = 0; i < mParams.Length; i++)
{
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_TYPES) != 0)
{
//frameInfo.m_bstrFuncName += m_parameters[i]. + " ";
frameInfo.m_bstrFuncName += "ParamType ";
}
if ((dwFieldSpec & enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_NAMES) != 0)
{
frameInfo.m_bstrFuncName += mParams[i].Name;
}
// if ((dwFieldSpec & (uint)enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_ARGS_VALUES) != 0) {
// frameInfo.m_bstrFuncName += "=" + m_parameters[i].m_value;
// }
if (i < mParams.Length - 1)
{
frameInfo.m_bstrFuncName += ", ";
}
}
frameInfo.m_bstrFuncName += ")";
}
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_LINES))
{
frameInfo.m_bstrFuncName += " Line:" + mLineNum.ToString();
}
}
else
{
// No source information, so only return the module name and the instruction pointer.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FUNCNAME_MODULE))
{
//frameInfo.m_bstrFuncName = EngineUtils.GetAddressDescription(module, ip);
}
else
{
//frameInfo.m_bstrFuncName = EngineUtils.GetAddressDescription(null, ip);
}
}
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FUNCNAME;
}
// The debugger is requesting the name of the module for this stack frame.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_MODULE))
{
frameInfo.m_bstrModule = "module";
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_MODULE;
}
// The debugger is requesting the range of memory addresses for this frame.
// For the sample engine, this is the contents of the frame pointer.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_STACKRANGE))
{
//frameInfo.m_addrMin = m_threadContext.ebp;
//frameInfo.m_addrMax = m_threadContext.ebp;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STACKRANGE;
}
// The debugger is requesting the IDebugStackFrame2 value for this frame info.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_FRAME))
{
frameInfo.m_pFrame = this;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_FRAME;
}
// Does this stack frame of symbols loaded?
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO))
{
frameInfo.m_fHasDebugInfo = mHasSource ? 1 : 0;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUGINFO;
}
// Is this frame stale?
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_STALECODE))
{
frameInfo.m_fStaleCode = 0;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_STALECODE;
}
// The debugger would like a pointer to the IDebugModule2 that contains this stack frame.
if (dwFieldSpec.HasFlag(enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP))
{
if (mEngine.mModule != null)
{
frameInfo.m_pModule = mEngine.mModule;
frameInfo.m_dwValidFields |= enum_FRAMEINFO_FLAGS.FIF_DEBUG_MODULEP;
}
}
}
// Construct an instance of IEnumDebugPropertyInfo2 for the combined locals and parameters.
private void CreateLocalsPlusArgsProperties(out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
elementsReturned = 0;
int localsLength = 0;
if (mLocals != null)
{
localsLength = mLocals.Length;
elementsReturned += (uint)localsLength;
}
if (mParams != null)
{
elementsReturned += (uint)mParams.Length;
}
var propInfo = new DEBUG_PROPERTY_INFO[elementsReturned];
if (mLocals != null)
{
for (int i = 0; i < mLocals.Length; i++)
{
var property = new AD7Property(mLocals[i], mProcess, this);
propInfo[i] = property.ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
}
if (mParams != null)
{
for (int i = 0; i < mParams.Length; i++)
{
var property = new AD7Property(mParams[i], mProcess, this);
propInfo[localsLength + i] = property.ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
}
propInfo = propInfo.OrderBy(i => i.bstrName).ToArray();
enumObject = new AD7PropertyInfoEnum(propInfo);
}
// Construct an instance of IEnumDebugPropertyInfo2 for the locals collection only.
private void CreateLocalProperties(out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
elementsReturned = (uint)mLocals.Length;
var propInfo = new DEBUG_PROPERTY_INFO[mLocals.Length];
for (int i = 0; i < propInfo.Length; i++)
{
AD7Property property = new AD7Property(mLocals[i], mProcess, this);
propInfo[i] = property.ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
propInfo = propInfo.OrderBy(i => i.bstrName).ToArray();
enumObject = new AD7PropertyInfoEnum(propInfo);
}
// Construct an instance of IEnumDebugPropertyInfo2 for the parameters collection only.
private void CreateParameterProperties(out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
elementsReturned = (uint)mParams.Length;
var propInfo = new DEBUG_PROPERTY_INFO[mParams.Length];
for (int i = 0; i < propInfo.Length; i++)
{
var property = new AD7Property(mParams[i], mProcess, this);
propInfo[i] = property.ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_STANDARD);
}
propInfo = propInfo.OrderBy(i => i.bstrName).ToArray();
enumObject = new AD7PropertyInfoEnum(propInfo);
}
#endregion
#region IDebugStackFrame2 Members
// Creates an enumerator for properties associated with the stack frame, such as local variables.
// The sample engine only supports returning locals and parameters. Other possible values include
// class fields (this pointer), registers, exceptions...
int IDebugStackFrame2.EnumProperties(enum_DEBUGPROP_INFO_FLAGS dwFields, uint nRadix, ref Guid guidFilter, uint dwTimeout, out uint elementsReturned, out IEnumDebugPropertyInfo2 enumObject)
{
int hr;
elementsReturned = 0;
enumObject = null;
try
{
if (guidFilter == AD7Guids.guidFilterLocalsPlusArgs ||
guidFilter == AD7Guids.guidFilterAllLocalsPlusArgs)
{
CreateLocalsPlusArgsProperties(out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
}
else if (guidFilter == AD7Guids.guidFilterLocals)
{
CreateLocalProperties(out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
}
else if (guidFilter == AD7Guids.guidFilterArgs)
{
CreateParameterProperties(out elementsReturned, out enumObject);
hr = VSConstants.S_OK;
}
else
{
hr = VSConstants.E_NOTIMPL;
}
}
//catch (ComponentException e)
//{
// return e.HResult;
//}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return hr;
}
// Gets the code context for this stack frame. The code context represents the current instruction pointer in this stack frame.
int IDebugStackFrame2.GetCodeContext(out IDebugCodeContext2 memoryAddress)
{
memoryAddress = null;
try
{
//memoryAddress = new AD7MemoryAddress(m_engine, m_threadContext.eip);
return VSConstants.E_NOTIMPL;
}
//catch (ComponentException e)
//{
// return e.HResult;
//}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Gets a description of the properties of a stack frame.
// Calling the IDebugProperty2::EnumChildren method with appropriate filters can retrieve the local variables, method parameters, registers, and "this"
// pointer associated with the stack frame. The debugger calls EnumProperties to obtain these values in the sample.
int IDebugStackFrame2.GetDebugProperty(out IDebugProperty2 property)
{
throw new NotImplementedException();
}
// Gets the document context for this stack frame. The debugger will call this when the current stack frame is changed
// and will use it to open the correct source document for this stack frame.
int IDebugStackFrame2.GetDocumentContext(out IDebugDocumentContext2 docContext)
{
docContext = null;
try
{
if (mHasSource)
{
// Assume all lines begin and end at the beginning of the line.
TEXT_POSITION begTp = new TEXT_POSITION();
begTp.dwColumn = 0;
begTp.dwLine = mLineNum - 1;
TEXT_POSITION endTp = new TEXT_POSITION();
endTp.dwColumn = 0;
endTp.dwLine = mLineNum - 1;
docContext = new AD7DocumentContext(mDocName, begTp, endTp, null);
return VSConstants.S_OK;
}
}
//catch (ComponentException e)
//{
// return e.HResult;
//}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_FALSE;
}
// Gets an evaluation context for expression evaluation within the current context of a stack frame and thread.
// Generally, an expression evaluation context can be thought of as a scope for performing expression evaluation.
// Call the IDebugExpressionContext2::ParseText method to parse an expression and then call the resulting IDebugExpression2::EvaluateSync
// or IDebugExpression2::EvaluateAsync methods to evaluate the parsed expression.
int IDebugStackFrame2.GetExpressionContext(out IDebugExpressionContext2 ppExprCxt)
{
ppExprCxt = this;
return VSConstants.S_OK;
}
// Gets a description of the stack frame.
int IDebugStackFrame2.GetInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, FRAMEINFO[] pFrameInfo)
{
try
{
SetFrameInfo(dwFieldSpec, out pFrameInfo[0]);
return VSConstants.S_OK;
}
//catch (ComponentException e)
//{
// return e.HResult;
//}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Gets the language associated with this stack frame.
// In this sample, all the supported stack frames are C++
int IDebugStackFrame2.GetLanguageInfo(ref string pbstrLanguage, ref Guid pguidLanguage)
{
pbstrLanguage = "CSharp";
pguidLanguage = AD7Guids.guidLanguageCSharp;
return VSConstants.S_OK;
}
// Gets the name of the stack frame.
// The name of a stack frame is typically the name of the method being executed.
int IDebugStackFrame2.GetName(out string name)
{
name = null;
try
{
name = mFunctionName;
return VSConstants.S_OK;
}
//catch (ComponentException e)
//{
// return e.HResult;
//}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
// Gets a machine-dependent representation of the range of physical addresses associated with a stack frame.
int IDebugStackFrame2.GetPhysicalStackRange(out ulong addrMin, out ulong addrMax)
{
addrMin = 0;// m_threadContext.ebp;
addrMax = 0;// m_threadContext.ebp;
return VSConstants.S_OK;
}
// Gets the thread associated with a stack frame.
int IDebugStackFrame2.GetThread(out IDebugThread2 thread)
{
thread = mThread;
return VSConstants.S_OK;
}
#endregion
// Retrieves the name of the evaluation context.
// The name is the description of this evaluation context. It is typically something that can be parsed by an expression evaluator
// that refers to this exact evaluation context. For example, in C++ the name is as follows:
// "{ function-name, source-file-name, module-file-name }"
int IDebugExpressionContext2.GetName(out string pbstrName)
{
throw new NotImplementedException();
}
// Parses a text-based expression for evaluation.
// The engine sample only supports locals and parameters so the only task here is to check the names in those collections.
int IDebugExpressionContext2.ParseText(string pszCode, enum_PARSEFLAGS dwFlags, uint nRadix, out IDebugExpression2 ppExpr,
out string pbstrError,
out uint pichError)
{
//System.Windows.Forms.AD7Util.MessageBox("pszCode: " + pszCode);
pbstrError = "";
pichError = 0;
ppExpr = null;
try
{
if (mParams != null)
{
foreach (DebugLocalInfo currVariable in mParams)
{
if (String.CompareOrdinal(currVariable.Name, pszCode) == 0)
{
ppExpr = new AD7Expression(currVariable, mProcess, this);
return VSConstants.S_OK;
}
}
}
if (mLocals != null)
{
foreach (DebugLocalInfo currVariable in mLocals)
{
if (String.CompareOrdinal(currVariable.Name, pszCode) == 0)
{
ppExpr = new AD7Expression(currVariable, mProcess, this);
return VSConstants.S_OK;
}
}
}
pbstrError = "Invalid Expression";
pichError = (uint)pbstrError.Length;
return VSConstants.S_FALSE;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
}
}
}
| |
#region Copyright (c) 2004 Atif Aziz. All rights reserved.
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah
{
using System.Text;
// Adapted from RazorTemplateBase.cs[1]
// Microsoft Public License (Ms-PL)[2]
//
// [1] http://razorgenerator.codeplex.com/SourceControl/changeset/view/964fcd1393be#RazorGenerator.Templating%2fRazorTemplateBase.cs
// [2] http://razorgenerator.codeplex.com/license
class RazorTemplateBase
{
string _content;
private readonly StringBuilder _generatingEnvironment = new StringBuilder();
public RazorTemplateBase Layout { get; set; }
public virtual void Execute() {}
public void WriteLiteral(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
return;
_generatingEnvironment.Append(textToAppend); ;
}
public virtual void Write(object value)
{
if (value == null)
return;
WriteLiteral(value.ToString());
}
public virtual object RenderBody()
{
return _content;
}
public virtual string TransformText()
{
Execute();
if (Layout != null)
{
Layout._content = _generatingEnvironment.ToString();
return Layout.TransformText();
}
return _generatingEnvironment.ToString();
}
public static HelperResult RenderPartial<T>() where T : RazorTemplateBase, new()
{
return new HelperResult(writer =>
{
var t = new T();
writer.Write(t.TransformText());
});
}
}
}
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
#endregion
/// <summary>
/// Represents the result of a helper action as an HTML-encoded string.
/// </summary>
// See http://msdn.microsoft.com/en-us/library/system.web.webpages.helperresult.aspx
sealed class HelperResult : IHtmlString
{
private readonly Action<TextWriter> _action;
public HelperResult(Action<TextWriter> action)
{
if (action == null) throw new ArgumentNullException("action");
_action = action;
}
public string ToHtmlString()
{
using (var writer = new StringWriter(CultureInfo.InvariantCulture))
{
WriteTo(writer);
return writer.ToString();
}
}
public override string ToString()
{
return ToHtmlString();
}
public void WriteTo(TextWriter writer)
{
_action(writer);
}
}
}
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah
{
using Microsoft.Security.Application;
// http://msdn.microsoft.com/en-us/library/system.web.ihtmlstring.aspx
interface IHtmlString
{
string ToHtmlString();
}
sealed class HtmlString : IHtmlString
{
readonly string _html;
public HtmlString(string html) { _html = html ?? string.Empty; }
public string ToHtmlString() { return _html; }
public override string ToString() { return ToHtmlString(); }
}
static class Html
{
public static readonly IHtmlString Empty = new HtmlString(string.Empty);
public static IHtmlString Raw(string input)
{
return string.IsNullOrEmpty(input) ? Empty : new HtmlString(input);
}
public static IHtmlString Encode(object input)
{
IHtmlString html;
return null != (html = input as IHtmlString)
? html
: input == null
? Empty
: Raw(Encoder.HtmlEncode(input.ToString()));
}
}
}
/*
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah.Fabmail
{
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using Microsoft.Security.Application;
using Encoder = Microsoft.Security.Application.Encoder;
// Adapted from RazorTemplateBase.cs[1]
// Microsoft Public License (Ms-PL)[2]
//
// [1] http://razorgenerator.codeplex.com/SourceControl/changeset/view/964fcd1393be#RazorGenerator.Templating%2fRazorTemplateBase.cs
// [2] http://razorgenerator.codeplex.com/license
class RazorTemplateBase
{
string _content;
private readonly StringBuilder _generatingEnvironment = new StringBuilder();
public RazorTemplateBase Layout { get; set; }
public virtual void Execute() { }
public void WriteLiteral(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
return;
_generatingEnvironment.Append(textToAppend); ;
}
public virtual void Write(object value)
{
if (value == null)
return;
WriteLiteral(value.ToString());
}
public virtual object RenderBody()
{
return _content;
}
public virtual string TransformText()
{
Execute();
if (Layout != null)
{
Layout._content = _generatingEnvironment.ToString();
return Layout.TransformText();
}
return _generatingEnvironment.ToString();
}
public static HelperResult RenderPartial<T>() where T : RazorTemplateBase, new()
{
return new HelperResult(writer =>
{
var t = new T();
writer.Write(t.TransformText());
});
}
}
}
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah.Fabmail
{
/// <summary>
/// Represents the result of a helper action as an HTML-encoded string.
/// </summary>
// See http://msdn.microsoft.com/en-us/library/system.web.webpages.helperresult.aspx
sealed class HelperResult : IHtmlString
{
private readonly Action<TextWriter> _action;
public HelperResult(Action<TextWriter> action)
{
if (action == null) throw new ArgumentNullException("action");
_action = action;
}
public string ToHtmlString()
{
using (var writer = new StringWriter(CultureInfo.InvariantCulture))
{
WriteTo(writer);
return writer.ToString();
}
}
public override string ToString()
{
return ToHtmlString();
}
public void WriteTo(TextWriter writer)
{
_action(writer);
}
}
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// http://msdn.microsoft.com/en-us/library/system.web.ihtmlstring.aspx
interface IHtmlString
{
string ToHtmlString();
}
sealed class HtmlString : IHtmlString
{
readonly string _html;
public HtmlString(string html) { _html = html ?? string.Empty; }
public string ToHtmlString() { return _html; }
public override string ToString() { return ToHtmlString(); }
}
static class Html
{
public static readonly IHtmlString Empty = new HtmlString(string.Empty);
public static IHtmlString Raw(string input)
{
return string.IsNullOrEmpty(input) ? Empty : new HtmlString(input);
}
public static IHtmlString Encode(object input)
{
IHtmlString html;
return null != (html = input as IHtmlString)
? html
: input == null
? Empty
: Raw(Encoder.HtmlEncode(input.ToString()));
}
}
}
*/
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public struct SchedulerTimeSpan : IEquatable< SchedulerTimeSpan >
{
//
// State
//
public static readonly SchedulerTimeSpan MinValue = new SchedulerTimeSpan( long.MinValue );
public static readonly SchedulerTimeSpan MaxValue = new SchedulerTimeSpan( long.MaxValue );
private long m_deltaUnits;
//
// Constructor Methods
//
internal SchedulerTimeSpan( long deltaUnits )
{
m_deltaUnits = deltaUnits;
}
//
// Equality Methods
//
public override bool Equals( Object obj )
{
if(obj is SchedulerTimeSpan)
{
SchedulerTimeSpan other = (SchedulerTimeSpan)obj;
return this.Equals( other );
}
return false;
}
public override int GetHashCode()
{
return m_deltaUnits.GetHashCode();
}
public bool Equals( SchedulerTimeSpan other )
{
return m_deltaUnits == other.m_deltaUnits;
}
public static bool Equals( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.Equals( ts2 );
}
//
// Helper Methods
//
public static int Compare( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits.CompareTo( ts1.m_deltaUnits );
}
public SchedulerTimeSpan Add( SchedulerTimeSpan value )
{
if(value == SchedulerTimeSpan.MaxValue)
{
return MaxValue;
}
else if(value == SchedulerTimeSpan.MinValue)
{
return MinValue;
}
return new SchedulerTimeSpan( m_deltaUnits + value.m_deltaUnits );
}
public SchedulerTimeSpan Add( TimeSpan value )
{
return Add( (SchedulerTimeSpan)value );
}
public SchedulerTimeSpan Subtract( SchedulerTimeSpan value )
{
if(value == SchedulerTimeSpan.MaxValue)
{
return MinValue;
}
else if(value == SchedulerTimeSpan.MinValue)
{
return MaxValue;
}
return new SchedulerTimeSpan( m_deltaUnits - value.m_deltaUnits );
}
public SchedulerTimeSpan Subtract( TimeSpan value )
{
return Subtract( (SchedulerTimeSpan)value );
}
//--//
public static SchedulerTimeSpan FromMilliseconds( long milliSeconds )
{
return new SchedulerTimeSpan( ConvertFromMillisecondsToDeltaUnits( milliSeconds ) );
}
public static explicit operator SchedulerTimeSpan ( TimeSpan ts )
{
return new SchedulerTimeSpan( ConvertFromTimeSpanTicksToDeltaUnits( ts.Ticks ) );
}
public static explicit operator TimeSpan ( SchedulerTimeSpan ts )
{
return new TimeSpan( ConvertFromDeltaUnitsToTimeSpanTicks( ts.m_deltaUnits ) );
}
public static long ToMilliseconds( SchedulerTimeSpan ts )
{
return ConvertFromDeltaUnitsToMilliseconds( ts.m_deltaUnits );
}
//--//
public static SchedulerTimeSpan operator +( SchedulerTimeSpan ts1 ,
TimeSpan ts2 )
{
return ts1.Add( ts2 );
}
public static SchedulerTimeSpan operator -( SchedulerTimeSpan ts1 ,
TimeSpan ts2 )
{
return ts1.Subtract( ts2 );
}
public static SchedulerTimeSpan operator -( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.Subtract( ts2 );
}
[Inline]
public static bool operator ==( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits == ts2.m_deltaUnits;
}
[Inline]
public static bool operator !=( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits != ts2.m_deltaUnits;
}
[Inline]
public static bool operator <( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits < ts2.m_deltaUnits;
}
[Inline]
public static bool operator <=( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits <= ts2.m_deltaUnits;
}
[Inline]
public static bool operator >( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits > ts2.m_deltaUnits;
}
[Inline]
public static bool operator >=( SchedulerTimeSpan ts1 ,
SchedulerTimeSpan ts2 )
{
return ts1.m_deltaUnits >= ts2.m_deltaUnits;
}
//--//
//
// These have to be implemented by the overriding class extension.
//
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern long ConvertFromMillisecondsToDeltaUnits( long milliSeconds );
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern long ConvertFromTimeSpanTicksToDeltaUnits( long ticks );
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern long ConvertFromDeltaUnitsToTimeSpanTicks( long deltaUnits );
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern long ConvertFromDeltaUnitsToMilliseconds( long deltaUnits );
//--//
//
// Access Methods
//
public long DeltaUnits
{
get
{
return m_deltaUnits;
}
}
}
}
| |
using System;
using Fonet.Layout;
using Fonet.Render.Pdf.Fonts;
using Fonet.Pdf;
using Fonet.Pdf.Filter;
namespace Fonet.Pdf
{
/// <summary>
/// Creates all the necessary PDF objects required to represent
/// a font object in a PDF document.
/// </summary>
internal sealed class PdfFontCreator
{
/// <summary>
/// Generates object id's.
/// </summary>
private PdfCreator creator;
/// <summary>
///
/// </summary>
/// <param name="creator"></param>
public PdfFontCreator(PdfCreator creator)
{
this.creator = creator;
}
/// <summary>
/// Returns a subclass of the PdfFont class that may be one of
/// PdfType0Font, PdfType1Font or PdfTrueTypeFont. The type of
/// subclass returned is determined by the type of the <i>font</i>
/// parameter.
/// </summary>
/// <param name="pdfFontID">The PDF font identifier, e.g. F15</param>
/// <param name="font">Underlying font object.</param>
/// <returns></returns>
public PdfFont MakeFont(string pdfFontID, Font font)
{
PdfFont pdfFont = null;
if (font is Base14Font)
{
// One of the standard base 14 fonts
Base14Font base14 = (Base14Font)font;
pdfFont = CreateBase14Font(pdfFontID, base14);
}
else
{
// Will load underlying font if proxy
IFontMetric realMetrics = GetFontMetrics(font);
if (realMetrics is Base14Font)
{
// A non-embeddable font that has been defaulted to a base 14 font
Base14Font base14 = (Base14Font)realMetrics;
pdfFont = CreateBase14Font(pdfFontID, base14);
}
else if (realMetrics is TrueTypeFont)
{
// TrueTypeFont restricted to the WinAnsiEncoding scheme
// that is linked instead of embedded in the PDF.
TrueTypeFont ttf = (TrueTypeFont)realMetrics;
pdfFont = CreateTrueTypeFont(pdfFontID, font, ttf);
}
else
{
// A character indexed font that may be subsetted.
CIDFont cid = (CIDFont)realMetrics;
pdfFont = CreateCIDFont(pdfFontID, font, cid);
}
}
// This should never happen, but it's worth checking
if (pdfFont == null)
{
throw new Exception("Unable to create Pdf font object for " + pdfFontID);
}
creator.AddObject(pdfFont);
return pdfFont;
}
/// <summary>
/// Creates a character indexed font from <i>cidFont</i>
/// </summary>
/// <remarks>
/// The <i>font</i> and <i>cidFont</i> will be different object
/// references since the <i>font</i> parameter will most likely
/// be a <see cref="ProxyFont"/>.
/// </remarks>
/// <param name="pdfFontID">The Pdf font identifier, e.g. F15</param>
/// <param name="font">Required to access the font descriptor.</param>
/// <param name="cidFont">The underlying CID font.</param>
/// <returns></returns>
private PdfFont CreateCIDFont(
string pdfFontID, Font font, CIDFont cidFont)
{
// The font descriptor is required to access licensing details are
// obtain the font program itself as a byte array
IFontDescriptor descriptor = font.Descriptor;
// A compressed stream that stores the font program
PdfFontFile fontFile = new PdfFontFile(
NextObjectId(), descriptor.FontData);
// Add indirect reference to FontFile object to descriptor
PdfFontDescriptor pdfDescriptor = MakeFontDescriptor(pdfFontID, cidFont);
pdfDescriptor.FontFile2 = fontFile;
PdfCIDSystemInfo pdfCidSystemInfo = new PdfCIDSystemInfo(
cidFont.Registry, cidFont.Ordering, cidFont.Supplement);
PdfCIDFont pdfCidFont = new PdfCIDFont(
NextObjectId(), PdfFontSubTypeEnum.CIDFontType2, font.FontName);
pdfCidFont.SystemInfo = pdfCidSystemInfo;
pdfCidFont.Descriptor = pdfDescriptor;
pdfCidFont.DefaultWidth = new PdfNumeric(cidFont.DefaultWidth);
pdfCidFont.Widths = cidFont.WArray;
// Create a ToUnicode CMap that maps characters codes (GIDs) to
// unicode values. Very important to ensure searching and copying
// from a PDF document works correctly.
PdfCMap pdfCMap = new PdfCMap(NextObjectId());
pdfCMap.AddFilter(new FlateFilter());
pdfCMap.SystemInfo = pdfCidSystemInfo;
pdfCMap.AddBfRanges(cidFont.CMapEntries);
// Create a PDF object to represent the CID font
PdfType0Font pdfFont = new PdfType0Font(
NextObjectId(), pdfFontID, font.FontName);
pdfFont.Encoding = new PdfName(cidFont.Encoding);
pdfFont.Descendant = pdfCidFont;
pdfFont.ToUnicode = pdfCMap;
// Add all the Pdf objects to the document. MakeFont will add the actual
// PdfFont object to the document.
creator.AddObject(pdfDescriptor);
creator.AddObject(pdfCidFont);
creator.AddObject(pdfCMap);
creator.AddObject(fontFile);
return pdfFont;
}
/// <summary>
/// Returns the next available Pdf object identifier.
/// </summary>
/// <returns></returns>
private PdfObjectId NextObjectId()
{
return creator.Doc.NextObjectId();
}
/// <summary>
/// Creates an instance of the <see cref="PdfType1Font"/> class
/// </summary>
/// <param name="pdfFontID">The Pdf font identifier, e.g. F15</param>
/// <param name="base14"></param>
/// <returns></returns>
private PdfType1Font CreateBase14Font(string pdfFontID, Base14Font base14)
{
PdfType1Font type1Font = new PdfType1Font(
NextObjectId(), pdfFontID, base14.FontName);
type1Font.Encoding = new PdfName(base14.Encoding);
return type1Font;
}
/// <summary>
/// Creates an instance of the <see cref="PdfTrueTypeFont"/> class
/// that defaults the font encoding to WinAnsiEncoding.
/// </summary>
/// <param name="pdfFontID"></param>
/// <param name="font"></param>
/// <param name="ttf"></param>
/// <returns></returns>
private PdfTrueTypeFont CreateTrueTypeFont(
string pdfFontID, Font font, TrueTypeFont ttf)
{
PdfFontDescriptor pdfDescriptor = MakeFontDescriptor(pdfFontID, ttf);
PdfTrueTypeFont pdfFont = new PdfTrueTypeFont(
NextObjectId(), pdfFontID, font.FontName);
pdfFont.Encoding = new PdfName("WinAnsiEncoding");
pdfFont.Descriptor = pdfDescriptor;
pdfFont.FirstChar = new PdfNumeric(ttf.FirstChar);
pdfFont.LastChar = new PdfNumeric(ttf.LastChar);
pdfFont.Widths = ttf.Array;
creator.AddObject(pdfDescriptor);
return pdfFont;
}
/// <remarks>
/// A ProxyFont must first be resolved before getting the
/// IFontMetircs implementation of the underlying font.
/// </remarks>
/// <param name="font"></param>
private IFontMetric GetFontMetrics(Font font)
{
if (font is ProxyFont)
{
return ((ProxyFont)font).RealFont;
}
else
{
return font;
}
}
private PdfFontDescriptor MakeFontDescriptor(string fontName, IFontMetric metrics)
{
IFontDescriptor descriptor = metrics.Descriptor;
PdfFontDescriptor pdfDescriptor = new PdfFontDescriptor(
fontName, NextObjectId());
pdfDescriptor.Ascent = new PdfNumeric(metrics.Ascender);
pdfDescriptor.CapHeight = new PdfNumeric(metrics.CapHeight);
pdfDescriptor.Descent = new PdfNumeric(metrics.Descender);
pdfDescriptor.Flags = new PdfNumeric(descriptor.Flags);
pdfDescriptor.ItalicAngle = new PdfNumeric(descriptor.ItalicAngle);
pdfDescriptor.StemV = new PdfNumeric(descriptor.StemV);
PdfArray array = new PdfArray();
array.AddArray(descriptor.FontBBox);
pdfDescriptor.FontBBox = array;
return pdfDescriptor;
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: BllCountry.cs
//
// Created: 01-01-2008 SharedCache.com, rschuetz
// Modified: 01-01-2008 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace SharedCache.WinServiceTestClient.BLL
{
/// <summary>
/// Business Logic Layer for Country relevant Data
/// </summary>
public class BllCountry
{
#region Singleton: DAL.DalCountry
private DAL.DalCountry country;
/// <summary>
/// Singleton for <see cref="DAL.DalCountry" />
/// </summary>
private DAL.DalCountry Country
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (this.country == null)
this.country = new DAL.DalCountry();
return this.country;
}
}
#endregion
#region Specific Cache Keys
/// <summary>
/// Defines a shared cache key for getting all data
/// </summary>
private const string cacheKeyAllCountry = @"country_sharedCacheKey_AllData";
/// <summary>
/// Defines a shared cache key for indvidual item based on its id.
/// </summary>
private const string cacheKeyCountryById = @"country_sharedCacheKey_ById_{0}";
/// <summary>
/// Defines a shared cache key for indvidual item received by name
/// </summary>
private const string cacheKeyCountryByName = @"country_sharedCacheKey_ByName_{0}";
#endregion Specific Cache Keys
#region Methods
/// <summary>
/// Get item by name.
/// </summary>
/// <param name="name">The country name.</param>
/// <param name="loadRegion">if set to <c>true</c> [load region].</param>
/// <returns>
/// A list of <see cref="Common.Country"/> objects
/// </returns>
public Common.Country GetByName(string name, bool loadRegion)
{
// create a unique key for this item.
string key = string.Format(cacheKeyCountryByName, name);
Common.Country result = Common.Util.CacheGet<Common.Country>(key);
if (result == null)
{
foreach (Common.Country country in this.GetAll(false, loadRegion))
{
if (name.Equals(country.Name))
{
result = country;
break;
}
}
// now we can add it to the cache
Common.Util.CacheAdd(key, result);
}
return result;
}
/// <summary>
/// Get item by id.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="loadRegion">if set to <c>true</c> [load region].</param>
/// <returns>
/// A list of <see cref="Common.Country"/> objects
/// </returns>
public Common.Country GetById(int id, bool loadRegion)
{
try
{
// create a unique key for this item.
string key = string.Format(cacheKeyCountryById, id.ToString());
Common.Country result = Common.Util.CacheGet<Common.Country>(key);
if (result == null)
{
foreach (Common.Country country in this.GetAll(false, loadRegion))
{
if (id.Equals(country.CountryId))
{
result = country;
break;
}
}
if (result == null)
{
return null;
}
// now we can add it to the cache
Common.Util.CacheAdd(key, result);
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(@"Error: " + ex.Message);
throw ex;
}
}
/// <summary>
/// Get all country items
/// </summary>
/// <param name="withPrint">if set to <c>true</c> [with print].</param>
/// <param name="loadRegion">if set to <c>true</c> [load region].</param>
/// <returns>
/// A list of <see cref="Common.Country"/> objects
/// </returns>
public List<Common.Country> GetAll(bool withPrint, bool loadRegion)
{
string key = cacheKeyAllCountry + loadRegion.ToString();
List<Common.Country> result = Common.Util.CacheGet<List<Common.Country>>(key);
if (result == null)
{
Console.WriteLine(@"country data loaded from XML File!");
result = this.Country.GetAllCountry();
// now we can add it to the cache
Common.Util.CacheAdd(key, result);
}
// loading all regions which are available for the country id
if (loadRegion)
{
foreach (Common.Country country in result)
{
country.Region = new BllRegion().GetByCountryId(country.CountryId);
if (withPrint)
{
Console.WriteLine("\t{0}", country.Name);
foreach (Common.Region region in country.Region)
{
Console.WriteLine("\t\t - {0}", region.Name);
}
}
}
}
return result;
}
#endregion Methods
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.IO;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
/// <summary>
/// An iCalendar representation of the <c>RRULE</c> property.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public partial class RecurrencePattern :
EncodableDataType,
IRecurrencePattern
{
#region Private Fields
#if !SILVERLIGHT
[NonSerialized]
#endif
private FrequencyType _Frequency;
private DateTime _Until = DateTime.MinValue;
private int _Count = int.MinValue;
private int _Interval = int.MinValue;
private IList<int> _BySecond = new List<int>();
private IList<int> _ByMinute = new List<int>();
private IList<int> _ByHour = new List<int>();
private IList<IWeekDay> _ByDay = new List<IWeekDay>();
private IList<int> _ByMonthDay = new List<int>();
private IList<int> _ByYearDay = new List<int>();
private IList<int> _ByWeekNo = new List<int>();
private IList<int> _ByMonth = new List<int>();
private IList<int> _BySetPosition = new List<int>();
private DayOfWeek _FirstDayOfWeek = DayOfWeek.Monday;
private RecurrenceRestrictionType? _RestrictionType = null;
private RecurrenceEvaluationModeType? _EvaluationMode = null;
#endregion
#region IRecurrencePattern Members
public FrequencyType Frequency
{
get { return _Frequency; }
set { _Frequency = value; }
}
public DateTime Until
{
get { return _Until; }
set { _Until = value; }
}
public int Count
{
get { return _Count; }
set { _Count = value; }
}
public int Interval
{
get
{
if (_Interval == int.MinValue)
return 1;
return _Interval;
}
set { _Interval = value; }
}
public IList<int> BySecond
{
get { return _BySecond; }
set { _BySecond = value; }
}
public IList<int> ByMinute
{
get { return _ByMinute; }
set { _ByMinute = value; }
}
public IList<int> ByHour
{
get { return _ByHour; }
set { _ByHour = value; }
}
public IList<IWeekDay> ByDay
{
get { return _ByDay; }
set { _ByDay = value; }
}
public IList<int> ByMonthDay
{
get { return _ByMonthDay; }
set { _ByMonthDay = value; }
}
public IList<int> ByYearDay
{
get { return _ByYearDay; }
set { _ByYearDay = value; }
}
public IList<int> ByWeekNo
{
get { return _ByWeekNo; }
set { _ByWeekNo = value; }
}
public IList<int> ByMonth
{
get { return _ByMonth; }
set { _ByMonth = value; }
}
public IList<int> BySetPosition
{
get { return _BySetPosition; }
set { _BySetPosition = value; }
}
public DayOfWeek FirstDayOfWeek
{
get { return _FirstDayOfWeek; }
set { _FirstDayOfWeek = value; }
}
public RecurrenceRestrictionType RestrictionType
{
get
{
// NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns
if (_RestrictionType != null &&
_RestrictionType.HasValue)
return _RestrictionType.Value;
else if (Calendar != null)
return Calendar.RecurrenceRestriction;
else
return RecurrenceRestrictionType.Default;
}
set { _RestrictionType = value; }
}
public RecurrenceEvaluationModeType EvaluationMode
{
get
{
// NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns
if (_EvaluationMode != null &&
_EvaluationMode.HasValue)
return _EvaluationMode.Value;
else if (Calendar != null)
return Calendar.RecurrenceEvaluationMode;
else
return RecurrenceEvaluationModeType.Default;
}
set { _EvaluationMode = value; }
}
///// <summary>
///// Returns the next occurrence of the pattern,
///// given a valid previous occurrence, <paramref name="lastOccurrence"/>.
///// As long as the recurrence pattern is valid, and
///// <paramref name="lastOccurrence"/> is a valid previous
///// occurrence within the pattern, this will return the
///// next occurrence. NOTE: This will not give accurate results
///// when COUNT or BYSETVAL are used.
///// </summary>
//virtual public IPeriod GetNextOccurrence(IDateTime lastOccurrence)
//{
// RecurrencePatternEvaluator evaluator = GetService<RecurrencePatternEvaluator>();
// if (evaluator != null)
// return evaluator.GetNext(lastOccurrence);
// return null;
//}
#endregion
#region Constructors
public RecurrencePattern()
{
Initialize();
}
public RecurrencePattern(FrequencyType frequency) : this(frequency, 1)
{
}
public RecurrencePattern(FrequencyType frequency, int interval) :
this()
{
Frequency = frequency;
Interval = interval;
}
public RecurrencePattern(string value) :
this()
{
if (value != null)
{
DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer serializer = new DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer();
CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
}
}
void Initialize()
{
SetService(new RecurrencePatternEvaluator(this));
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
public override bool Equals(object obj)
{
if (obj is RecurrencePattern)
{
RecurrencePattern r = (RecurrencePattern)obj;
if (!CollectionEquals(r.ByDay, ByDay) ||
!CollectionEquals(r.ByHour, ByHour) ||
!CollectionEquals(r.ByMinute, ByMinute) ||
!CollectionEquals(r.ByMonth, ByMonth) ||
!CollectionEquals(r.ByMonthDay, ByMonthDay) ||
!CollectionEquals(r.BySecond, BySecond) ||
!CollectionEquals(r.BySetPosition, BySetPosition) ||
!CollectionEquals(r.ByWeekNo, ByWeekNo) ||
!CollectionEquals(r.ByYearDay, ByYearDay))
return false;
if (r.Count != Count) return false;
if (r.Frequency != Frequency) return false;
if (r.Interval != Interval) return false;
if (r.Until != DateTime.MinValue)
{
if (!r.Until.Equals(Until))
return false;
}
else if (Until != DateTime.MinValue)
return false;
if (r.FirstDayOfWeek != FirstDayOfWeek) return false;
return true;
}
return base.Equals(obj);
}
public override string ToString()
{
RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
return serializer.SerializeToString(this);
}
public override int GetHashCode()
{
int hashCode =
ByDay.GetHashCode() ^ ByHour.GetHashCode() ^ ByMinute.GetHashCode() ^
ByMonth.GetHashCode() ^ ByMonthDay.GetHashCode() ^ BySecond.GetHashCode() ^
BySetPosition.GetHashCode() ^ ByWeekNo.GetHashCode() ^ ByYearDay.GetHashCode() ^
Count.GetHashCode() ^ Frequency.GetHashCode();
if (Interval.Equals(1))
hashCode ^= 0x1;
else hashCode ^= Interval.GetHashCode();
hashCode ^= Until.GetHashCode();
hashCode ^= FirstDayOfWeek.GetHashCode();
return hashCode;
}
public override void CopyFrom(ICopyable obj)
{
base.CopyFrom(obj);
if (obj is IRecurrencePattern)
{
IRecurrencePattern r = (IRecurrencePattern)obj;
Frequency = r.Frequency;
Until = r.Until;
Count = r.Count;
Interval = r.Interval;
BySecond = new List<int>(r.BySecond);
ByMinute = new List<int>(r.ByMinute);
ByHour = new List<int>(r.ByHour);
ByDay = new List<IWeekDay>(r.ByDay);
ByMonthDay = new List<int>(r.ByMonthDay);
ByYearDay = new List<int>(r.ByYearDay);
ByWeekNo = new List<int>(r.ByWeekNo);
ByMonth = new List<int>(r.ByMonth);
BySetPosition = new List<int>(r.BySetPosition);
FirstDayOfWeek = r.FirstDayOfWeek;
RestrictionType = r.RestrictionType;
EvaluationMode = r.EvaluationMode;
}
}
private bool CollectionEquals<T>(ICollection<T> c1, ICollection<T> c2)
{
// NOTE: fixes a bug where collections weren't properly compared
if (c1 == null ||
c2 == null)
{
if (c1 == c2)
return true;
else return false;
}
if (!c1.Count.Equals(c2.Count))
return false;
IEnumerator e1 = c1.GetEnumerator();
IEnumerator e2 = c2.GetEnumerator();
while (e1.MoveNext() && e2.MoveNext())
{
if (!object.Equals(e1.Current, e2.Current))
return false;
}
return true;
}
#endregion
#region Protected Methods
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_WOPI
{
using System;
using System.IO;
using System.Net;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// This class is used to support required functions for test class initialization and clean up
/// </summary>
public class TestSuiteHelper : HelperBase
{
#region Variables
/// <summary>
/// A string value represents the protocol short name for the MS-WOPI.
/// </summary>
private const string WopiProtocolShortName = "MS-WOPI";
/// <summary>
/// A string value represents the protocol short name for the shared test cases, it is used in runtime. If plan to run the shared test cases, the WOPI server must implement the MS-FSSHTTP.
/// </summary>
private const string SharedTestCasesProtocolShortName = "MS-FSSHTTP-FSSHTTPB";
/// <summary>
/// Represents a IMS_WOPISUTManageCodeControlAdapter type instance.
/// </summary>
private static IMS_WOPIManagedCodeSUTControlAdapter wopiSutManagedCodeControlAdapter;
/// <summary>
/// Represents the IMS_WOPISUTControlAdapter instance.
/// </summary>
private static IMS_WOPISUTControlAdapter wopiSutControlAdapter;
/// <summary>
/// Represents the IMS_WOPIAdapter instance.
/// </summary>
private static IMS_WOPIAdapter wopiProtocolAdapter;
/// <summary>
/// A string value represents the current test client name which the test suite run on.
/// </summary>
private static string currentTestClientName;
/// <summary>
/// A string value represents the progId which is used in discovery process in order to make the WOPI server enable folder level visit ability when it receive the progId from the discovery response.
/// </summary>
private static string progId = string.Empty;
/// <summary>
/// A string value represents the URL of the relative source file.
/// </summary>
private static string relativeSourceFileUrl = string.Empty;
/// <summary>
/// A bool value represents whether the ShareCaseHelper has been initialized. The value 'true' means it has been initialized.
/// </summary>
private static bool hasInitializedHelperStatus = false;
/// <summary>
/// A bool value represents whether the test suite merge the configuration files.
/// </summary>
private static bool hasMergeWOPIPtfConfigFile = false;
/// <summary>
/// A long type value represents the clean up counter for the discovery process. In each trigger WOPI discovery request purpose process, this counter will increment, and decrement in each discovery clean up purpose process.
/// </summary>
private static long cleanUpDiscoveryStatusCounter = 0;
/// <summary>
/// A string value represents the current WCF endpoint name when running the shared test cases.
/// </summary>
private static string currentSharedTestCasesEndpointName;
/// <summary>
/// A bool value represents whether the current SUT support the MS-WOPI protocol.
/// </summary>
private static bool isCurrentSUTSupportWOPI = false;
/// <summary>
/// A bool value represents whether the test suite has checked that the current SUT support the MS-WOPI protocol.
/// </summary>
private static bool hasCheckSupportWOPI = false;
#endregion
/// <summary>
/// Prevents a default instance of the TestSuiteHelper class from being created
/// </summary>
private TestSuiteHelper()
{
}
/// <summary>
/// Gets a value indicating whether the ShareCaseHelper has been initialized. The value 'true' means it has been initialized.
/// </summary>
public static bool HasInitialized
{
get
{
return hasInitializedHelperStatus;
}
}
/// <summary>
/// Gets the IMS_WOPISUTControlAdapter instance.
/// </summary>
public static IMS_WOPISUTControlAdapter WOPISutControladapter
{
get
{
if (null == wopiSutControlAdapter)
{
throw new InvalidOperationException("Should call the [InitializeHelper] method to initial this helper.");
}
return wopiSutControlAdapter;
}
}
/// <summary>
/// Gets the IMS_WOPIManagedCodeSUTControlAdapter instance.
/// </summary>
public static IMS_WOPIManagedCodeSUTControlAdapter WOPIManagedCodeSUTControlAdapter
{
get
{
if (null == wopiSutManagedCodeControlAdapter)
{
throw new InvalidOperationException("Should call the [InitializeHelper] method to initial this helper.");
}
return wopiSutManagedCodeControlAdapter;
}
}
/// <summary>
/// Gets the IMS_WOPIAdapter instance.
/// </summary>
public static IMS_WOPIAdapter WOPIProtocolAdapter
{
get
{
if (null == wopiProtocolAdapter)
{
throw new InvalidOperationException("Should call the [InitializeHelper] method to initial this helper.");
}
return wopiProtocolAdapter;
}
}
/// <summary>
/// Gets the name of current test client.
/// </summary>
public static string CurrentTestClientName
{
get
{
if (string.IsNullOrEmpty(currentTestClientName))
{
throw new InvalidOperationException("Should call the [InitializeHelper] method to initial this helper.");
}
return currentTestClientName;
}
}
/// <summary>
/// This method is used to initialize the share test case helper. This method will also initialize all helpers which are required to initialize during test suite running.
/// </summary>
/// <param name="siteInstance">A parameter represents the ITestSite instance.</param>
public static void InitializeHelper(ITestSite siteInstance)
{
TestSuiteHelper.CheckInputParameterNullOrEmpty<ITestSite>(siteInstance, "siteInstance", "InitializeHelper");
if (string.IsNullOrEmpty(currentTestClientName))
{
currentTestClientName = Common.GetConfigurationPropertyValue("TestClientName", siteInstance);
}
if (null == wopiSutControlAdapter)
{
wopiSutControlAdapter = siteInstance.GetAdapter<IMS_WOPISUTControlAdapter>();
}
if (null == wopiSutManagedCodeControlAdapter)
{
wopiSutManagedCodeControlAdapter = siteInstance.GetAdapter<IMS_WOPIManagedCodeSUTControlAdapter>();
}
if (null == wopiProtocolAdapter)
{
wopiProtocolAdapter = siteInstance.GetAdapter<IMS_WOPIAdapter>();
}
InitializeRequiredHelpers(wopiSutManagedCodeControlAdapter, siteInstance);
if (string.IsNullOrEmpty(relativeSourceFileUrl))
{
relativeSourceFileUrl = Common.GetConfigurationPropertyValue("NormalFile", siteInstance);
}
progId = Common.GetConfigurationPropertyValue("ProgIdForDiscoveryProcess", siteInstance);
// Setting the endpoint name according to the current http transport.
if (string.IsNullOrEmpty(currentSharedTestCasesEndpointName))
{
TransportProtocol currentTransport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", siteInstance);
switch (currentTransport)
{
case TransportProtocol.HTTP:
{
currentSharedTestCasesEndpointName = Common.GetConfigurationPropertyValue("SharedTestCaseEndPointNameForHTTP", siteInstance);
break;
}
case TransportProtocol.HTTPS:
{
currentSharedTestCasesEndpointName = Common.GetConfigurationPropertyValue("SharedTestCaseEndPointNameForHTTPS", siteInstance);
break;
}
default:
{
throw new InvalidOperationException(string.Format("The test suite only support HTTP or HTTPS transport. Current:[{0}]", currentTransport));
}
}
}
// Set the protocol name of current test suite
siteInstance.DefaultProtocolDocShortName = WopiProtocolShortName;
hasInitializedHelperStatus = true;
}
/// <summary>
/// This method is used to initialize the shared test cases' context.
/// </summary>
/// <param name="requestFileUrl">A parameter represents the file URL.</param>
/// <param name="userName">A parameter represents the user name we used.</param>
/// <param name="password">A parameter represents the password of the user.</param>
/// <param name="domain">A parameter represents the domain.</param>
/// <param name="celloperationType">A parameter represents the type of CellStore operation which is used to determine different initialize logic.</param>
/// <param name="site">A parameter represents the site.</param>
public static void InitializeContextForShare(string requestFileUrl, string userName, string password, string domain, CellStoreOperationType celloperationType, ITestSite site)
{
SharedContext context = SharedContext.Current;
string normalTargetUrl = string.Empty;
switch (celloperationType)
{
case CellStoreOperationType.NormalCellStore:
{
normalTargetUrl = requestFileUrl;
context.OperationType = OperationType.WOPICellStorageRequest;
break;
}
case CellStoreOperationType.RelativeAdd:
{
// For relative adding a file, the WOPI resource file URL should be an existed file, and the file should be added in a location where the relative source file is located.
normalTargetUrl = relativeSourceFileUrl;
context.OperationType = OperationType.WOPICellStorageRelativeRequest;
break;
}
case CellStoreOperationType.RealativeModified:
{
normalTargetUrl = requestFileUrl;
context.OperationType = OperationType.WOPICellStorageRelativeRequest;
break;
}
}
// Convert the request file url to WOPI format URL so that the MS-FSSHTTP test cases will use WOPI format URL to send request.
string wopiTargetUrl = wopiSutManagedCodeControlAdapter.GetWOPIRootResourceUrl(normalTargetUrl, WOPIRootResourceUrlType.FileLevel, userName, password, domain);
context.TargetUrl = wopiTargetUrl;
context.IsMsFsshttpRequirementsCaptured = false;
context.Site = site;
// Only set the X-WOPI-RelativeTarget header value in relative CellStorage operation.
if (CellStoreOperationType.NormalCellStore != celloperationType)
{
// Read the file name from the target resource URL.
context.XWOPIRelativeTarget = GetFileNameFromFullUrl(requestFileUrl);
}
// Generate common headers
WebHeaderCollection commonHeaders = HeadersHelper.GetCommonHeaders(wopiTargetUrl);
context.XWOPIProof = commonHeaders["X-WOPI-Proof"];
context.XWOPIProofOld = commonHeaders["X-WOPI-ProofOld"];
context.XWOPITimeStamp = commonHeaders["X-WOPI-TimeStamp"];
context.XWOPIAuthorization = commonHeaders["Authorization"];
context.EndpointConfigurationName = currentSharedTestCasesEndpointName;
context.UserName = userName;
context.Password = password;
context.Domain = domain;
}
/// <summary>
/// This method is used to merge the configurations which are used by shared test cases.
/// </summary>
/// <param name="siteInstance">A parameter represents the site.</param>
public static void MergeConfigurationFileForShare(ITestSite siteInstance)
{
siteInstance.DefaultProtocolDocShortName = SharedTestCasesProtocolShortName;
// Get the name of common configuration file.
string commonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", siteInstance);
// Merge the common configuration.
Common.MergeGlobalConfig(commonConfigFileName, siteInstance);
// Merge the should may configuration file.
Common.MergeSHOULDMAYConfig(siteInstance);
// Roll back the short name in the ITestSite instance.
siteInstance.DefaultProtocolDocShortName = WopiProtocolShortName;
}
/// <summary>
/// A method is used to perform the discovery process
/// </summary>
/// <param name="currentTestClient">A parameter represents the current test client which is listening the discovery request.</param>
/// <param name="sutControllerAdapterInstance">A parameter represents the IMS_WOPISUTControlAdapter instance which is used to make the WOPI server perform sending discovery request to the discovery listener.</param>
/// <param name="siteInstance">A parameter represents the ITestSite instance which is used to get the test context.</param>
public static void PerformDiscoveryProcess(string currentTestClient, IMS_WOPISUTControlAdapter sutControllerAdapterInstance, ITestSite siteInstance)
{
DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<string>(currentTestClient, "currentTestClient", "PerformDiscoveryProcess");
DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<IMS_WOPISUTControlAdapter>(sutControllerAdapterInstance, "sutControllerAdapterInstance", "PerformDiscoveryProcess");
DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<ITestSite>(siteInstance, "siteInstance", "PerformDiscoveryProcess");
// If the test class invoke this, means the test class will uses the WOPI discovery binding. The test suite will count all WOPI discovery usage of test classes
System.Threading.Interlocked.Increment(ref cleanUpDiscoveryStatusCounter);
// Start the listener, if the listen thread has been start, the DiscoverProcessHelper will not start any new listen thread.
DiscoveryProcessHelper.StartDiscoveryListen(currentTestClient, progId);
// Initialize the WOPI Discovery process so that the WOPI server will use the test suite as WOPI client.
if (!DiscoveryProcessHelper.HasPerformDiscoveryProcessSucceed)
{
DiscoveryProcessHelper.PerformDiscoveryProcess(currentTestClient, sutControllerAdapterInstance);
}
}
/// <summary>
/// A method is used to clean the WOPI discovery process for the WOPI server.
/// </summary>
/// <param name="currentTestClient">A parameter represents the test client name which is running the test suite. This test client act as WOPI client and response discovery request from the WOPI server successfully.</param>
/// <param name="sutControllerAdapterInstance">A parameter represents the IMS_WOPISUTControlAdapter instance which is used to make the WOPI server perform sending discovery request to the discovery listener.</param>
public static void CleanUpDiscoveryProcess(string currentTestClient, IMS_WOPISUTControlAdapter sutControllerAdapterInstance)
{
// If the current SUT does not support MS-WOPI, the test suite will not perform any discovery process logics.
if (!isCurrentSUTSupportWOPI)
{
return;
}
// If the test class invoke this, means the test class will uses the binding.
long currentCleanUpStatusCounter = System.Threading.Interlocked.Decrement(ref cleanUpDiscoveryStatusCounter);
if (currentCleanUpStatusCounter > 0)
{
return;
}
else if (0 == currentCleanUpStatusCounter)
{
// Clean up the WOPI discovery process record from so the WOPI server. The test suite act as WOPI client.
if (DiscoveryProcessHelper.NeedToCleanUpDiscoveryRecord)
{
DiscoveryProcessHelper.CleanUpDiscoveryRecord(currentTestClient, sutControllerAdapterInstance);
}
// Dispose the discovery request listener.
DiscoveryProcessHelper.DisposeDiscoveryListener();
}
else
{
throw new InvalidOperationException(string.Format("The discovery clean up counter should not be less than zero. current value[{0}]", currentCleanUpStatusCounter));
}
}
/// <summary>
/// This method is used to get the file name from the URL.
/// </summary>
/// <param name="fullUrlOfFile">A parameter represents the full URL of the file.</param>
/// <returns>A parameter represents the file name.</returns>
public static string GetFileNameFromFullUrl(string fullUrlOfFile)
{
// Ensure the file name exists.
if (string.IsNullOrEmpty(fullUrlOfFile))
{
throw new ArgumentNullException("fullUrlOfFile");
}
// Get the file name.
Uri currentFilePath;
if (!Uri.TryCreate(fullUrlOfFile, UriKind.Absolute, out currentFilePath))
{
throw new UriFormatException("The [fullUrlOfFile] parameter must be a valid absolute URL.");
}
string fileName = Path.GetFileName(currentFilePath.LocalPath);
if (string.IsNullOrEmpty(fileName))
{
throw new InvalidOperationException(string.Format("Could not get the file name from the file path:[{0}].", currentFilePath.OriginalString));
}
return fileName;
}
/// <summary>
/// This method is used to merge the configuration of the WOPI PTF configuration files.
/// </summary>
/// <param name="siteInstance">A parameter represents the site.</param>
public static void MergeWOPIPtfConfigFiles(ITestSite siteInstance)
{
if (!hasMergeWOPIPtfConfigFile)
{
// Set the default short name for WOPI.
siteInstance.DefaultProtocolDocShortName = WopiProtocolShortName;
// Merge the common configuration.
string conmmonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", siteInstance);
Common.MergeGlobalConfig(conmmonConfigFileName, siteInstance);
// Merge the SHOULDMAY configuration
Common.MergeSHOULDMAYConfig(siteInstance);
hasMergeWOPIPtfConfigFile = true;
}
}
/// <summary>
/// A method is used to check whether the SUT product supports the MS-WOPI protocol. If the SUT does not support, this method will raise an inconclusive assertion.
/// </summary>
/// <param name="site">A parameter represents the site.</param>
public static void PerformSupportProductsCheck(ITestSite site)
{
TestSuiteHelper.CheckInputParameterNullOrEmpty<ITestSite>(site, "siteInstance", "PerformSupportProductsCheck");
if (!hasCheckSupportWOPI)
{
isCurrentSUTSupportWOPI = Common.GetConfigurationPropertyValue<bool>("MS-WOPI_Supported", site);
hasCheckSupportWOPI = true;
}
if (!isCurrentSUTSupportWOPI)
{
SutVersion currentSutVersion = Common.GetConfigurationPropertyValue<SutVersion>("SutVersion", site);
site.Assume.Inconclusive(@"The server does not support this specification [MS-WOPI]. It is determined by ""MS-WOPI_Supported"" SHOULDMAY property of the [{0}_{1}_SHOULDMAY.deployment.ptfconfig] configuration file.", WopiProtocolShortName, currentSutVersion);
}
}
/// <summary>
/// A method is used to check whether the WOPI server Cobalt feature, this feature depends on that the WOPI server whether implements MS-FSSHTTP. If current WOPI server does support Cobalt feature, this method will capture related requirement R961, otherwise this method will raise an inconclusive assertion.
/// </summary>
/// <param name="siteInstance">A parameter represents the site instance.</param>
public static void PerformSupportCobaltCheck(ITestSite siteInstance)
{
DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<ITestSite>(siteInstance, "siteInstance", "PerformSupportCobaltCheck");
if (!Common.IsRequirementEnabled("MS-WOPI", 961, siteInstance))
{
siteInstance.Assert.Inconclusive(@"The WOPI server does not support the Cobalt feature. To supporting this feature, the WOPI server must implement the MS-FSSHTTP protocol.It is determined by ""R961Enabled_MS-WOPI"" SHOULDMAY property.");
}
}
/// <summary>
/// A method used to initialize the test suite. It is used in test class level initialization.
/// </summary>
/// <param name="testSite">A parameter represents the ITestSite instance which contain the test context information.</param>
public static void InitializeTestSuite(ITestSite testSite)
{
if (null == testSite)
{
throw new ArgumentNullException("testSite");
}
try
{
if (!TestSuiteHelper.HasInitialized)
{
TestSuiteHelper.InitializeHelper(testSite);
}
TestSuiteHelper.PerformDiscoveryProcess(
currentTestClientName,
wopiSutControlAdapter,
testSite);
}
catch (Exception)
{
TestSuiteHelper.CleanUpDiscoveryProcess(currentTestClientName, wopiSutControlAdapter);
throw;
}
}
/// <summary>
/// A method is used to verify whether test suite run in support products. If the value of "SutVersion" property in common configuration file is not included in "SupportProducts" property in "MS-WOPI_TestSuite.deployment.ptfconfig", the "MS-WOPI_Supported" SHOULDMAY property will always equal to false. And the unsupported initialization logic will not be executed in unsupported products.
/// </summary>
/// <param name="siteInstance">A parameter represents the site instance.</param>
/// <returns>Return 'true' indicating the test suite is running in support products. The initialization logics should be performed.</returns>
public static bool VerifyRunInSupportProducts(ITestSite siteInstance)
{
if (null == siteInstance)
{
throw new ArgumentNullException("siteInstance");
}
TestSuiteHelper.MergeWOPIPtfConfigFiles(siteInstance);
return Common.GetConfigurationPropertyValue<bool>("MS-WOPI_Supported", siteInstance);
}
/// <summary>
/// A method is used to initialize all required helpers when calling the SharedCase helper. Normally, all this method will try to initial all helpers which are required to initialize.
/// </summary>
/// <param name="sutManagedCodeControlAdpater">A parameter represents the IMS_WOPISUTManageCodeControlAdapter instance which is used to convert the normal resource URL to WOPI format URL.</param>
/// <param name="siteInstance">A parameter represents the ITestSite instance.</param>
private static void InitializeRequiredHelpers(IMS_WOPIManagedCodeSUTControlAdapter sutManagedCodeControlAdpater, ITestSite siteInstance)
{
if (!TokenAndRequestUrlHelper.HasInitialized)
{
TokenAndRequestUrlHelper.InitializeHelper(sutManagedCodeControlAdpater, siteInstance);
}
}
}
}
| |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace TiltBrush {
// Rough equivalent of C# 4.0 HasFlag (actually more efficient since types must match).
public static class EnumExtensions {
public static bool HasFlag<T>(this T flags, T flag) where T : struct, IConvertible
{
var iFlags = Convert.ToUInt64(flags);
var iFlag = Convert.ToUInt64(flag);
return ((iFlags & iFlag) == iFlag);
}
}
public class SketchMemoryScript : MonoBehaviour {
public static SketchMemoryScript m_Instance;
public event Action OperationStackChanged;
public GameObject m_UndoBatchMeshPrefab;
public GameObject m_UndoBatchMesh;
public bool m_SanityCheckStrokes = false;
private int m_LastCheckedVertCount;
private int m_MemoryWarningVertCount;
[Flags]
public enum StrokeFlags {
None = 0,
Deprecated1 = 1 << 0,
/// This stroke continues a group that is considered a single entity with respect to undo and
/// redo. To support timestamp ordering, only strokes having identical timestamps on the initial
/// control point may be grouped (e.g. mirrored strokes). Currently, these strokes must also be
/// added to SketchMemoryScript at the same time.
///
/// This is distinct from Stroke.Group, which is a collection of strokes (of possibly differing
/// timestamps) that are selected together.
IsGroupContinue = 1 << 1,
}
// NOTE: making this generic is way more trouble than it's worth
public static void SetFlag(ref SketchMemoryScript.StrokeFlags flags,
SketchMemoryScript.StrokeFlags flag, bool flagValue) {
if (flagValue) {
flags |= flag;
} else {
flags &= ~flag;
}
}
// stack of sketch operations this session
private Stack<BaseCommand> m_OperationStack;
// stack of undone operations available for redo
private Stack<BaseCommand> m_RedoStack;
// Memory list by timestamp of initial control point. The nodes of this list are
// embedded in MemoryObject. Notable properties:
// * only MemoryObjects to be serialized (i.e. strokes) are kept in the list
// * objects remain in this list despite being in "undone" state (i.e. on redo stack)
// * edit-ordering is preserved among strokes having the same timestamp-- implying that
// by-time order matches edit order for sketches with no timestamps, and moreover that
// stroke grouping is preserved
//
// Why we can get away with linked list performance for sequence time ordering:
// * load case: sort once at init to populate sequence-time list. Since we save in
// timestamp order, this should be O(N).
// * playback case: simply walk sequence-time list for normal case. For timeline scrub,
// hopefully skip interval is small (say 10 seconds) so the number of items to traverse
// is reasonable.
// * edit case: update current position in sequence-time list every frame (same as playback)
// so we're always ready to insert new strokes
private LinkedList<Stroke> m_MemoryList = new LinkedList<Stroke>();
// Used as a starting point for any search by time. Either null or a node contained in
// m_MemoryList.
// TODO: Have Update() advance this position to match current sketch time so that we
// amortize list traversal in timeline edit mode.
private LinkedListNode<Stroke> m_CurrentNodeByTime;
//for loading .sketches
public enum PlaybackMode {
Distance,
Timestamps,
}
private IScenePlayback m_ScenePlayback;
/// discern between initial and edit-time playback in timeline edit mode
private bool m_IsInitialPlay;
private PlaybackMode m_PlaybackMode;
private float m_DistancePerSecond; // in units. for PlaybackMode.Distance
// operation stack size as of last load (always 0) or save
private int m_LastOperationStackCount;
private bool m_HasVisibleObjects;
private bool m_MemoryExceeded;
private bool m_MemoryWarningAccepted;
// Strokes that should be deleted; processed and cleared each frame.
private HashSet<Stroke> m_DeleteStrokes = new HashSet<Stroke>(new ReferenceComparer<Stroke>());
// Non-null if there are strokes that should be repainted this frame.
// TODO: give this the same treatment as m_DeleteStrokes?
private BaseCommand m_RepaintStrokeParent;
private TrTransform m_xfSketchInitial_RS;
private Coroutine m_RepaintCoroutine;
private float m_RepaintProgress;
public float RepaintProgress {
get { return m_RepaintCoroutine == null ? 1f : m_RepaintProgress; }
}
public TrTransform InitialSketchTransform {
get { return m_xfSketchInitial_RS; }
set { m_xfSketchInitial_RS = value; }
}
public bool IsPlayingBack { get { return m_ScenePlayback != null; } }
public float PlaybackMetersPerSecond {
get {
return m_DistancePerSecond * App.UNITS_TO_METERS;
}
}
public float GetDrawnPercent() {
return (float) m_ScenePlayback.MemoryObjectsDrawn / (m_MemoryList.Count - 1);
}
// Note this value is cached and only updated once per frame.
public bool HasVisibleObjects() { return m_HasVisibleObjects; }
public bool MemoryExceeded {
get { return m_MemoryExceeded; }
}
public bool MemoryWarningAccepted {
get { return m_MemoryWarningAccepted; }
set {
m_MemoryWarningAccepted = value;
App.Switchboard.TriggerMemoryWarningAcceptedChanged();
}
}
public float MemoryExceededRatio {
get { return (float)m_LastCheckedVertCount / (float)m_MemoryWarningVertCount; }
}
public void SetLastOperationStackCount() {
m_LastOperationStackCount = m_OperationStack.Count;
}
public bool WillVertCountPutUsOverTheMemoryLimit(int numVerts) {
if (!m_MemoryExceeded && !m_MemoryWarningAccepted) {
int vertCount = numVerts +
App.Scene.MainCanvas.BatchManager.CountAllBatchVertices() +
App.Scene.SelectionCanvas.BatchManager.CountAllBatchVertices() +
WidgetManager.m_Instance.WidgetsVertCount;
return vertCount > m_MemoryWarningVertCount;
}
return false;
}
void CheckSketchForOverMemoryLimit() {
if (!m_MemoryExceeded) {
// Only do the memory check in the AppState.Standard. The AppState.MemoryWarning exits to
// AppState.Standard, so interrupting any other state would have bad consequences.
if (App.CurrentState == App.AppState.Standard) {
m_LastCheckedVertCount =
App.Scene.MainCanvas.BatchManager.CountAllBatchVertices() +
App.Scene.SelectionCanvas.BatchManager.CountAllBatchVertices() +
WidgetManager.m_Instance.WidgetsVertCount;
if (m_LastCheckedVertCount > m_MemoryWarningVertCount) {
if (!m_MemoryWarningAccepted) {
App.Instance.SetDesiredState(App.AppState.MemoryExceeded);
}
m_MemoryExceeded = true;
App.Switchboard.TriggerMemoryExceededChanged();
}
}
}
}
// True if strokes have been modified since last load or save (approximately)
public bool IsMemoryDirty() {
if (m_OperationStack.Count != m_LastOperationStackCount) {
IEnumerable<BaseCommand> newCommands = null;
if (m_OperationStack.Count > m_LastOperationStackCount) {
newCommands = m_OperationStack.Take(m_OperationStack.Count - m_LastOperationStackCount);
} else {
newCommands = m_RedoStack.Take(m_LastOperationStackCount - m_OperationStack.Count);
}
return newCommands.Any(e => e.NeedsSave);
}
return false;
}
public bool CanUndo() { return m_OperationStack.Count > 0; }
public bool CanRedo() { return m_RedoStack.Count > 0; }
void Awake() {
m_OperationStack = new Stack<BaseCommand>();
m_LastOperationStackCount = 0;
m_RedoStack = new Stack<BaseCommand>();
m_HasVisibleObjects = false;
m_MemoryExceeded = false;
m_MemoryWarningAccepted = false;
m_LastCheckedVertCount = 0;
m_UndoBatchMesh = GameObject.Instantiate(m_UndoBatchMeshPrefab);
m_Instance = this;
m_xfSketchInitial_RS = TrTransform.identity;
m_MemoryWarningVertCount = App.PlatformConfig.MemoryWarningVertCount;
}
void Update() {
// Brute force, but this should short circuit early.
m_HasVisibleObjects = m_MemoryList.Any(obj => obj.IsGeometryEnabled);
// This may be unnecessary to do every frame. We may, instead, want to do it after
// specific operations.
CheckSketchForOverMemoryLimit();
if (m_DeleteStrokes.Count > 0 || m_RepaintStrokeParent != null) {
ClearRedo();
if (m_DeleteStrokes.Count > 0) {
var parent = new BaseCommand();
// TODO: should this be done in deterministic order?
foreach (Stroke stroke in m_DeleteStrokes) {
new DeleteStrokeCommand(stroke, parent);
switch (stroke.m_Type) {
case Stroke.Type.BrushStroke:
InitUndoObject(stroke.m_Object.GetComponent<BaseBrushScript>());
break;
case Stroke.Type.BatchedBrushStroke:
InitUndoObject(stroke.m_BatchSubset);
break;
case Stroke.Type.NotCreated:
Debug.LogError("Unexpected: MemorizeDeleteSelection NotCreated stroke");
break;
}
}
PerformAndRecordCommand(parent);
m_DeleteStrokes.Clear();
}
if (m_RepaintStrokeParent != null) {
PerformAndRecordCommand(m_RepaintStrokeParent);
m_RepaintStrokeParent = null;
}
OperationStackChanged();
}
}
/// Duplicates a stroke. Duplicated strokes have a timestamp that corresponds to the current time.
public Stroke DuplicateStroke(Stroke srcStroke, CanvasScript canvas, TrTransform? transform) {
Stroke duplicate = new Stroke(srcStroke);
if (srcStroke.m_Type == Stroke.Type.BatchedBrushStroke) {
if (transform == null) {
duplicate.CopyGeometry(canvas, srcStroke);
} else {
// If this fires, consider adding transform support to CreateGeometryByCopying
Debug.LogWarning("Unexpected: Taking slow DuplicateStroke path");
duplicate.Recreate(transform, canvas);
}
} else {
duplicate.Recreate(transform, canvas);
}
UpdateTimestampsToCurrentSketchTime(duplicate);
MemoryListAdd(duplicate);
return duplicate;
}
public void PerformAndRecordCommand(BaseCommand command, bool discardIfNotMerged = false) {
bool discardCommand = discardIfNotMerged;
BaseCommand delta = command;
ClearRedo();
while (m_OperationStack.Any()) {
BaseCommand top = m_OperationStack.Pop();
if (!top.Merge(command)) {
m_OperationStack.Push(top);
break;
}
discardCommand = false;
command = top;
}
if (discardCommand) {
command.Dispose();
return;
}
delta.Redo();
m_OperationStack.Push(command);
OperationStackChanged();
}
// TODO: deprecate in favor of PerformAndRecordCommand
// Used by BrushStrokeCommand and ModifyLightCommmand while in Disco mode
public void RecordCommand(BaseCommand command) {
ClearRedo();
while (m_OperationStack.Any()) {
BaseCommand top = m_OperationStack.Pop();
if (!top.Merge(command)) {
m_OperationStack.Push(top);
break;
}
command = top;
}
m_OperationStack.Push(command);
OperationStackChanged();
}
/// Returns approximate latest timestamp from the stroke list (including deleted strokes).
/// If there are no strokes, raise System.InvalidOperationException
public double GetApproximateLatestTimestamp() {
if (m_MemoryList.Count > 0) {
var obj = m_MemoryList.Last.Value;
return obj.TailTimestampMs / 1000f;
}
throw new InvalidOperationException();
}
/// Returns the earliest timestamp from the stroke list (including deleted strokes).
/// If there are no strokes, raise System.InvalidOperationException
public double GetEarliestTimestamp() {
if (m_MemoryList.Count > 0) {
var obj = m_MemoryList.First.Value;
return obj.HeadTimestampMs / 1000f;
}
throw new InvalidOperationException();
}
private static bool StrokeTimeLT(Stroke a, Stroke b) {
return (a.HeadTimestampMs < b.HeadTimestampMs);
}
private static bool StrokeTimeLTE(Stroke a, Stroke b) {
return !StrokeTimeLT(b, a);
}
// The memory list by time is updated-- control points are expected to be initialized
// and immutable. This includes the timestamps on the control points.
public void MemoryListAdd(Stroke stroke) {
Debug.Assert(stroke.m_Type == Stroke.Type.NotCreated ||
stroke.m_Type == Stroke.Type.BrushStroke ||
stroke.m_Type == Stroke.Type.BatchedBrushStroke);
if (stroke.m_ControlPoints.Length == 0) {
Debug.LogWarning("Unexpected zero-length stroke");
return;
}
// add to sequence-time list
// We add to furthest position possible in the list (i.e. following all strokes
// with lead control point timestamp LTE the new one). This ensures that grouped
// strokes are not divided, given that such strokes must have identical timestamps.
// NOTE: O(1) given expected timestamp order of strokes in the .tilt file.
var node = stroke.m_NodeByTime;
if (m_MemoryList.Count == 0 || StrokeTimeLT(stroke, m_MemoryList.First.Value)) {
m_MemoryList.AddFirst(node);
} else {
// find insert position-- most efficient for "not too far ahead of current position" case
var addAfter = m_CurrentNodeByTime;
if (addAfter == null || StrokeTimeLT(stroke, addAfter.Value)) {
addAfter = m_MemoryList.First;
}
while (addAfter.Next != null && StrokeTimeLTE(addAfter.Next.Value, stroke)) {
addAfter = addAfter.Next;
}
m_MemoryList.AddAfter(addAfter, node);
}
m_CurrentNodeByTime = node;
// add to scene playback
if (m_ScenePlayback != null) {
m_ScenePlayback.AddStroke(stroke);
}
}
public void MemorizeBatchedBrushStroke(
BatchSubset subset, Color rColor, Guid brushGuid,
float fBrushSize, float brushScale,
List<PointerManager.ControlPoint> rControlPoints, StrokeFlags strokeFlags,
StencilWidget stencil, float lineLength, int seed) {
// NOTE: PointerScript calls ClearRedo() in batch case
Stroke rNewStroke = new Stroke();
rNewStroke.m_Type = Stroke.Type.BatchedBrushStroke;
rNewStroke.m_BatchSubset = subset;
rNewStroke.m_ControlPoints = rControlPoints.ToArray();
rNewStroke.m_ControlPointsToDrop = new bool[rNewStroke.m_ControlPoints.Length];
rNewStroke.m_Color = rColor;
rNewStroke.m_BrushGuid = brushGuid;
rNewStroke.m_BrushSize = fBrushSize;
rNewStroke.m_BrushScale = brushScale;
rNewStroke.m_Flags = strokeFlags;
rNewStroke.m_Seed = seed;
subset.m_Stroke = rNewStroke;
SketchMemoryScript.m_Instance.RecordCommand(
new BrushStrokeCommand(rNewStroke, stencil, lineLength));
if (m_SanityCheckStrokes) {
SanityCheckGeometryGeneration(rNewStroke);
//SanityCheckVersusReplacementBrush(rNewObject);
}
MemoryListAdd(rNewStroke);
TiltMeterScript.m_Instance.AdjustMeter(rNewStroke, up: true);
}
public void MemorizeBrushStroke(
BaseBrushScript brushScript, Color rColor, Guid brushGuid,
float fBrushSize, float brushScale,
List<PointerManager.ControlPoint> rControlPoints,
StrokeFlags strokeFlags,
StencilWidget stencil, float lineLength) {
ClearRedo();
Stroke rNewStroke = new Stroke();
rNewStroke.m_Type = Stroke.Type.BrushStroke;
rNewStroke.m_Object = brushScript.gameObject;
rNewStroke.m_ControlPoints = rControlPoints.ToArray();
rNewStroke.m_ControlPointsToDrop = new bool[rNewStroke.m_ControlPoints.Length];
rNewStroke.m_Color = rColor;
rNewStroke.m_BrushGuid = brushGuid;
rNewStroke.m_BrushSize = fBrushSize;
rNewStroke.m_BrushScale = brushScale;
rNewStroke.m_Flags = strokeFlags;
brushScript.Stroke = rNewStroke;
SketchMemoryScript.m_Instance.RecordCommand(
new BrushStrokeCommand(rNewStroke, stencil, lineLength));
MemoryListAdd(rNewStroke);
TiltMeterScript.m_Instance.AdjustMeter(rNewStroke, up: true);
}
/// Queues a stroke for deletion later in the frame. Because deletion is deferred,
/// the stroke will _not_ look deleted when this function returns.
///
/// It's an error to pass an already deleted stroke. Calling this
/// multiple times on the same stroke is otherwise allowed.
public void MemorizeDeleteSelection(Stroke strokeObj) {
// Note for edit-during-playback: erase selection only works on fully rendered
// strokes so a guard against deletion of in-progress strokes isn't needed here.
// It's only possible to detect double-delete if the stroke is batched, but
// thankfully that's the common case.
Debug.Assert(
strokeObj.m_BatchSubset == null || strokeObj.m_BatchSubset.m_Active,
"Deleting deleted stroke");
if (!m_DeleteStrokes.Add(strokeObj)) {
// The API says this is ok; but it (currently) should never happen either.
Debug.LogWarningFormat(
"Unexpected: enqueuing same stroke twice @ {0}",
Time.frameCount);
}
}
public void MemorizeDeleteSelection(GameObject rObject) {
var brush = rObject.GetComponent<BaseBrushScript>();
if (brush) {
MemorizeDeleteSelection(brush.Stroke);
}
}
public bool MemorizeStrokeRepaint(Stroke stroke, bool recolor, bool rebrush) {
Guid brushGuid = PointerManager.m_Instance
.GetPointer(InputManager.ControllerName.Brush).CurrentBrush.m_Guid;
if ((recolor && stroke.m_Color != PointerManager.m_Instance.PointerColor) ||
(rebrush && stroke.m_BrushGuid != brushGuid)) {
if (m_RepaintStrokeParent == null) {
m_RepaintStrokeParent = new BaseCommand();
}
Color newColor = recolor ? PointerManager.m_Instance.PointerColor : stroke.m_Color;
Guid newGuid = rebrush ? brushGuid : stroke.m_BrushGuid;
new RepaintStrokeCommand(stroke, newColor, newGuid, m_RepaintStrokeParent);
return true;
}
return false;
}
public bool MemorizeStrokeRepaint(GameObject rObject, bool recolor, bool rebrush) {
var brush = rObject.GetComponent<BaseBrushScript>();
if (brush) {
MemorizeStrokeRepaint(brush.Stroke, recolor, rebrush);
return true;
}
return false;
}
/// Removes stroke from our list only.
/// It's the caller's responsibility to destroy if (if desired).
public void RemoveMemoryObject(Stroke stroke) {
var nodeByTime = stroke.m_NodeByTime;
if (nodeByTime.List != null) { // implies stroke object
if (m_CurrentNodeByTime == nodeByTime) {
m_CurrentNodeByTime = nodeByTime.Previous;
}
m_MemoryList.Remove(nodeByTime); // O(1)
if (m_ScenePlayback != null) {
m_ScenePlayback.RemoveStroke(stroke);
}
}
}
// This function is a patch fix for bad data making its way in to save files. Bad strokes
// can't be detected until the geometry generation has run over the control points, so we
// need to parse the memory list after load. PointerScript.DetachLine() has an early discard
// for strokes with bad data, so the empty geometry won't be added to the scene, but we'll
// still have the entry in the memory list. This function clears those out.
public void SanitizeMemoryList() {
LinkedListNode<Stroke> node = m_MemoryList.First;
while (node != null) {
LinkedListNode<Stroke> nextNode = node.Next;
if (node.Value.m_Type == Stroke.Type.BatchedBrushStroke &&
node.Value.m_BatchSubset.m_VertLength == 0) {
m_MemoryList.Remove(node);
}
node = nextNode;
}
}
public List<Stroke> GetAllUnselectedActiveStrokes() {
return m_MemoryList.Where(
s => s.IsGeometryEnabled && s.Canvas == App.Scene.MainCanvas &&
(s.m_Type != Stroke.Type.BatchedBrushStroke ||
s.m_BatchSubset.m_VertLength > 0)).ToList();
}
public void ClearRedo() {
foreach (var command in m_RedoStack) {
command.Dispose();
}
m_RedoStack.Clear();
}
public void ClearMemory() {
if (m_ScenePlayback != null) {
// Ensure scene playback completes so that geometry is in state expected by rest of system.
// TODO: Lift this restriction. Artifact observed is a ghost stroke from previously deleted
// scene appearing briefly.
App.Instance.CurrentSketchTime = float.MaxValue;
m_ScenePlayback.Update();
m_ScenePlayback = null;
}
SelectionManager.m_Instance.ForgetStrokesInSelectionCanvas();
ClearRedo();
foreach (var item in m_MemoryList) {
//skip batched strokes here because they'll all get dumped in ResetPools()
if (item.m_Type != Stroke.Type.BatchedBrushStroke) {
item.DestroyStroke();
}
}
m_OperationStack.Clear();
if (OperationStackChanged != null) { OperationStackChanged(); }
m_LastOperationStackCount = 0;
m_MemoryList.Clear();
App.GroupManager.ResetGroups();
SelectionManager.m_Instance.OnFinishReset();
m_CurrentNodeByTime = null;
foreach (var canvas in App.Scene.AllCanvases) {
canvas.BatchManager.ResetPools();
}
TiltMeterScript.m_Instance.ResetMeter();
App.Instance.CurrentSketchTime = 0;
App.Instance.AutosaveRestoreFileExists = false;
m_HasVisibleObjects = false;
m_MemoryExceeded = false;
m_LastCheckedVertCount = 0;
MemoryWarningAccepted = false;
App.Switchboard.TriggerMemoryExceededChanged();
SaveLoadScript.m_Instance.MarkAsAutosaveDone();
SaveLoadScript.m_Instance.NewAutosaveFile();
m_xfSketchInitial_RS = TrTransform.identity;
Resources.UnloadUnusedAssets();
}
public IEnumerator<float> RepaintCoroutine() {
int numStrokes = m_MemoryList.Count;
int strokesRepainted = 0;
int remainingStrokesPerSlice = 0;
int totalPrevVerts = 0;
int totalVerts = 0;
// First, gather a bunch of info about our strokes.
bool [] batchEnabled = new bool[m_MemoryList.Count];
int batchEnabledIndex = 0;
for (var node = m_MemoryList.First; node != null; node = node.Next) {
// TODO: Should we skip this stroke if it's particles?
var stroke = node.Value;
if (stroke.m_Type == Stroke.Type.BatchedBrushStroke) {
totalPrevVerts += stroke.m_BatchSubset.m_VertLength;
batchEnabled[batchEnabledIndex] = stroke.IsGeometryEnabled;
}
Array.Clear(stroke.m_ControlPointsToDrop, 0, stroke.m_ControlPointsToDrop.Length);
stroke.Uncreate();
++batchEnabledIndex;
}
// Clear pools.
foreach (var canvas in App.Scene.AllCanvases) {
canvas.BatchManager.ResetPools();
}
// Recreate strokes.
batchEnabledIndex = 0;
for (var node = m_MemoryList.First; node != null; node = node.Next) {
// TODO: Should we skip this stroke if it's particles?
var stroke = node.Value;
stroke.Recreate();
if (stroke.m_Type == Stroke.Type.BatchedBrushStroke) {
totalVerts += stroke.m_BatchSubset.m_VertLength;
if (!batchEnabled[batchEnabledIndex]) {
stroke.m_BatchSubset.m_ParentBatch.DisableSubset(stroke.m_BatchSubset);
}
}
strokesRepainted++;
remainingStrokesPerSlice--;
if (remainingStrokesPerSlice < 0) {
m_RepaintProgress = Mathf.Clamp01(strokesRepainted / (float)numStrokes);
yield return m_RepaintProgress;
remainingStrokesPerSlice = numStrokes / 100;
}
++batchEnabledIndex;
}
// Report change to user.
if (totalPrevVerts < totalVerts) {
float vertChange = (float)totalVerts / (float)totalPrevVerts;
float increasePercent = (vertChange - 1.0f) * 100.0f;
int increaseReadable = (int)Mathf.Max(1.0f, Mathf.Floor(increasePercent));
string report = "Sketch is " + increaseReadable.ToString() + "% larger.";
OutputWindowScript.m_Instance.CreateInfoCardAtController(
InputManager.ControllerName.Wand,
report);
} else if (totalPrevVerts > totalVerts) {
float vertChange = (float)totalVerts / (float)totalPrevVerts;
float decreasePercent = 100.0f - (vertChange * 100.0f);
int decreaseReadable = (int)Mathf.Max(1.0f, Mathf.Floor(decreasePercent));
string report = "Sketch is " + decreaseReadable.ToString() + "% smaller.";
OutputWindowScript.m_Instance.CreateInfoCardAtController(
InputManager.ControllerName.Wand,
report);
} else {
OutputWindowScript.m_Instance.CreateInfoCardAtController(
InputManager.ControllerName.Wand,
"No change in sketch size.");
}
ControllerConsoleScript.m_Instance.AddNewLine("Sketch rebuilt! Vertex count: " +
totalPrevVerts.ToString() + " -> " + totalVerts.ToString());
m_RepaintCoroutine = null;
}
public void StepBack() {
var comm = m_OperationStack.Pop();
comm.Undo();
m_RedoStack.Push(comm);
OperationStackChanged();
}
public void StepForward() {
var comm = m_RedoStack.Pop();
comm.Redo();
m_OperationStack.Push(comm);
OperationStackChanged();
}
public static IEnumerable<Stroke> AllStrokes() {
return m_Instance.m_MemoryList;
}
public static int AllStrokesCount() {
return m_Instance.m_MemoryList.Count();
}
public static void InitUndoObject(BaseBrushScript rBrushScript) {
rBrushScript.CloneAsUndoObject();
}
public static void InitUndoObject(BatchSubset subset) {
// TODO: Finish moving control of prefab into BatchManager
subset.Canvas.BatchManager.CloneAsUndoObject(
subset, m_Instance.m_UndoBatchMesh);
}
/// Restore stroke to its unrendered state, deleting underlying geometry.
/// This is used by rewind functionality of ScenePlayback.
/// TODO: Rather than destroying geometry for rewind, we should employ the hiding
/// mechanism of the stroke erase / undo operations.
public void UnrenderStrokeMemoryObject(Stroke stroke) {
TiltMeterScript.m_Instance.AdjustMeter(stroke, up: false);
stroke.Uncreate();
}
public void SetPlaybackMode(PlaybackMode mode, float distancePerSecond) {
m_PlaybackMode = mode;
m_DistancePerSecond = distancePerSecond;
}
public void SpeedUpMemoryDrawingSpeed() {
m_DistancePerSecond *= 1.25f;
}
public void QuickLoadDrawingMemory() {
if (m_ScenePlayback != null) {
m_ScenePlayback.QuickLoadRemaining();
}
}
/// timeline edit mode: if forEdit is true, play audio countdown and keep user pointers enabled
public void BeginDrawingFromMemory(bool bDrawFromStart, bool forEdit = false) {
if (bDrawFromStart) {
switch (m_PlaybackMode) {
case PlaybackMode.Distance:
default:
m_ScenePlayback = new ScenePlaybackByStrokeDistance(m_MemoryList);
PointerManager.m_Instance.SetPointersAudioForPlayback();
break;
case PlaybackMode.Timestamps:
App.Instance.CurrentSketchTime = GetEarliestTimestamp();
m_ScenePlayback = new ScenePlaybackByTimeLayered(m_MemoryList);
break;
}
m_IsInitialPlay = true;
}
if (!forEdit) {
PointerManager.m_Instance.SetInPlaybackMode(true);
PointerManager.m_Instance.RequestPointerRendering(false);
}
}
/// returns true if there is more to draw
public bool ContinueDrawingFromMemory() {
if (m_ScenePlayback != null && !m_ScenePlayback.Update()) {
if (m_IsInitialPlay) {
m_IsInitialPlay = false;
if (m_ScenePlayback.MaxPointerUnderrun > 0) {
Debug.LogFormat("Parallel pointer underrun during playback: deficient {0} pointers",
m_ScenePlayback.MaxPointerUnderrun);
}
// we're done-- however in timeline edit mode we keep playback alive to allow scrubbing
PointerManager.m_Instance.SetInPlaybackMode(false);
PointerManager.m_Instance.RequestPointerRendering(true);
m_ScenePlayback = null;
}
return false;
}
return true;
}
private void SortMemoryList() {
var sorted = m_MemoryList.OrderBy(obj => obj.HeadTimestampMs).ToArray();
m_MemoryList.Clear();
foreach (var obj in sorted) {
m_MemoryList.AddLast(obj.m_NodeByTime);
}
}
// Redraw scene instantly and optionally re-sort by timestamp-- will drop frames and thrash mem.
// For use by internal tools which mutate MemoryObjects.
public void Redraw(bool doSort) {
ClearRedo();
if (m_ScenePlayback == null) {
foreach (var obj in m_MemoryList) {
SketchMemoryScript.m_Instance.UnrenderStrokeMemoryObject(obj);
}
if (doSort) { SortMemoryList(); }
m_ScenePlayback = new ScenePlaybackByStrokeDistance(m_MemoryList);
m_ScenePlayback.QuickLoadRemaining();
m_ScenePlayback.Update();
m_ScenePlayback = null;
} else { // timeline edit mode
var savedSketchTime = App.Instance.CurrentSketchTime;
App.Instance.CurrentSketchTime = 0;
m_ScenePlayback.Update();
if (doSort) { SortMemoryList(); }
m_ScenePlayback = new ScenePlaybackByTimeLayered(m_MemoryList);
App.Instance.CurrentSketchTime = savedSketchTime;
m_ScenePlayback.Update();
}
}
//
// Sanity-checking geometry generation
//
// Return a non-null error message if the mesh data is not identical
private static string Compare(
Vector3[] oldVerts, int iOldVert0, int iOldVert1,
int[] oldTris, int iOldTri0, int iOldTri1,
Vector2[] oldUv0s,
BaseBrushScript newBrush) {
Vector3[] newVerts; int nNewVerts;
Vector2[] newUv0s;
int[] newTris; int nNewTris;
newBrush.DebugGetGeometry(out newVerts, out nNewVerts, out newUv0s, out newTris, out nNewTris);
if (nNewVerts != iOldVert1 - iOldVert0) {
return "vert count mismatch";
}
for (int i = 0; i < nNewVerts; ++i) {
Vector3 vo = oldVerts[iOldVert0 + i];
Vector3 vn = newVerts[i];
if (vo != vn) {
return string.Format("vert mismatch @ {0}/{1}", i, nNewVerts);
}
}
// Before enabling, we need a way of skipping this for brushes that
// legitimately want randomized UVs. There is also a known nondeterminism
// for QuadStripBrushStretchUV, though.
#if false
if (oldUv0s != null) {
if (newUv0s == null) {
return "uv0 mismatch (loaded mesh has no UVs)";
}
for (int i = 0; i < nNewVerts; ++i) {
Vector2 uvo = oldUv0s[iOldVert0 + i];
Vector2 uvn = newUv0s[i];
if (uvo != uvn) {
return string.Format("uv mismatch @ {0}/{1}", i, nNewVerts);
}
}
}
#endif
if (nNewTris != iOldTri1 - iOldTri0) {
return "tri count mismatch";
}
// Try to account for vert numbering
{
int triOffset = newTris[0] - oldTris[iOldTri0];
for (int i = 0; i < nNewTris; ++i) {
int to = oldTris[iOldTri0 + i];
int tn = newTris[i];
if (to + triOffset != tn) {
return string.Format("tri mismatch @ {0}/{1}", i, nNewTris);
}
}
}
return null;
}
private static void SanityCheckVersusReplacementBrush(Stroke oldStroke) {
BrushDescriptor desc = BrushCatalog.m_Instance.GetBrush(oldStroke.m_BrushGuid);
BrushDescriptor replacementDesc = desc.m_Supersedes;
if (replacementDesc == null) {
return;
}
// Make a copy, since Begin/EndLineFromMemory mutate little bits of MemoryBrushStroke
Stroke newStroke = new Stroke {
m_BrushGuid = replacementDesc.m_Guid,
m_IntendedCanvas = oldStroke.Canvas,
m_ControlPoints = oldStroke.m_ControlPoints,
m_BrushScale = oldStroke.m_BrushScale,
m_BrushSize = oldStroke.m_BrushSize,
m_Color = oldStroke.m_Color,
m_Seed = oldStroke.m_Seed
};
Array.Copy(oldStroke.m_ControlPointsToDrop, newStroke.m_ControlPointsToDrop,
oldStroke.m_ControlPointsToDrop.Length);
newStroke.Recreate(TrTransform.T(new Vector3(0.5f, 0, 0)));
}
private static string Compare(Mesh oldMesh, BaseBrushScript newBrush) {
Vector3[] verts = oldMesh.vertices;
int[] tris = oldMesh.triangles;
// There is no way of querying Unity what the format of uv0 is, so don't check it
return Compare(verts, 0, verts.Length, tris, 0, tris.Length, null, newBrush);
}
// Generate geometry from stroke as if it were being played back.
// If played-back geometry is different, complain and make the new stroke visible.
// TODO: do more kinds of brushes
private static void SanityCheckGeometryGeneration(Stroke oldStroke) {
if (oldStroke.m_Type == Stroke.Type.BrushStroke) {
if (oldStroke.m_Object.GetComponent<MeshFilter>() == null) {
// Stroke can't be checked
return;
}
}
{
BrushDescriptor desc = BrushCatalog.m_Instance.GetBrush(oldStroke.m_BrushGuid);
if (desc == null || desc.m_Nondeterministic) {
// Stroke doesn't want to be checked
return;
}
}
// Re-create geometry. PointerManager's pointer management is a complete mess.
// "5" is the most-likely to be unused.
var pointer = PointerManager.m_Instance.GetTransientPointer(5);
// Make a copy, since Begin/EndLineFromMemory mutate little bits of MemoryBrushStroke
Stroke newStroke = new Stroke();
newStroke.m_BrushGuid = oldStroke.m_BrushGuid;
newStroke.m_ControlPoints = oldStroke.m_ControlPoints;
newStroke.m_BrushScale = oldStroke.m_BrushScale;
newStroke.m_BrushSize = oldStroke.m_BrushSize;
newStroke.m_Color = oldStroke.m_Color;
newStroke.m_Seed = oldStroke.m_Seed;
// Now swap r and b
newStroke.m_Color.r = oldStroke.m_Color.b;
newStroke.m_Color.b = oldStroke.m_Color.r;
Array.Copy(oldStroke.m_ControlPointsToDrop, newStroke.m_ControlPointsToDrop,
oldStroke.m_ControlPointsToDrop.Length);
newStroke.m_Object = pointer.BeginLineFromMemory(newStroke, oldStroke.Canvas);
pointer.UpdateLineFromStroke(newStroke);
// Compare geometry
string err;
var newBrush = pointer.CurrentBrushScript;
if (oldStroke.m_Type == Stroke.Type.BrushStroke) {
Mesh oldMesh = oldStroke.m_Object.GetComponent<MeshFilter>().sharedMesh;
err = Compare(oldMesh, newBrush);
} else {
BatchSubset oldMesh = oldStroke.m_BatchSubset;
GeometryPool allGeom = oldMesh.m_ParentBatch.Geometry;
Vector3[] verts = allGeom.m_Vertices.GetBackingArray();
int[] tris = allGeom.m_Tris.GetBackingArray();
// To avoid super complications, only check in the common case of
// uv0 == Vector2[]
Vector2[] uv0;
if (allGeom.Layout.texcoord0.size == 2) {
uv0 = allGeom.m_Texcoord0.v2.GetBackingArray();
} else {
uv0 = null;
}
err = Compare(
verts, oldMesh.m_StartVertIndex, oldMesh.m_StartVertIndex + oldMesh.m_VertLength,
tris, oldMesh.m_iTriIndex, oldMesh.m_iTriIndex + oldMesh.m_nTriIndex,
uv0, newBrush);
}
if (err != null) {
// Use assert so it shows up in ExceptionRenderScript
UnityEngine.Debug.Assert(false, string.Format("Sanity check stroke: {0}", err));
newBrush.ApplyChangesToVisuals();
// Turn off batching for this stroke because our batching system currently
// can't handle strokes that aren't on the undo stack, in sketch memory, etc
bool prevValue = App.Config.m_UseBatchedBrushes;
App.Config.m_UseBatchedBrushes = false;
pointer.EndLineFromMemory(newStroke, discard: false);
App.Config.m_UseBatchedBrushes = prevValue;
} else {
pointer.EndLineFromMemory(newStroke, discard: true);
}
}
// Modify a stroke in a way that tries to satisfy:
// - No control points should be before CurrentSketchTime.
// (because they might overlap with previous points)
// - Few control points should be after CurrentSketchTime
// (because they might overlap with to-be-drawn strokes)
private static void UpdateTimestampsToCurrentSketchTime(Stroke stroke) {
uint nowMs = (uint)(App.Instance.CurrentSketchTime * 1000);
uint offsetMs = 0;
uint nCp = (uint)stroke.m_ControlPoints.Length;
for (uint iCp = 0; iCp < nCp; ++iCp) {
stroke.m_ControlPoints[iCp].m_TimestampMs = nowMs + offsetMs++;
}
}
}
} // namespace TiltBrush
| |
using Lucene.Net.Support;
using Lucene.Net.Support.IO;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
namespace Lucene.Net.Store
{
/*
* 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 Constants = Lucene.Net.Util.Constants;
/// <summary>
/// File-based <see cref="Directory"/> implementation that uses
/// <see cref="MemoryMappedFile"/> for reading, and
/// <see cref="FSDirectory.FSIndexOutput"/> for writing.
///
/// <para/><b>NOTE</b>: memory mapping uses up a portion of the
/// virtual memory address space in your process equal to the
/// size of the file being mapped. Before using this class,
/// be sure your have plenty of virtual address space, e.g. by
/// using a 64 bit runtime, or a 32 bit runtime with indexes that are
/// guaranteed to fit within the address space.
/// On 32 bit platforms also consult <see cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
/// if you have problems with mmap failing because of fragmented
/// address space. If you get an <see cref="OutOfMemoryException"/>, it is recommended
/// to reduce the chunk size, until it works.
/// <para>
/// <b>NOTE:</b> Accessing this class either directly or
/// indirectly from a thread while it's interrupted can close the
/// underlying channel immediately if at the same time the thread is
/// blocked on IO. The channel will remain closed and subsequent access
/// to <see cref="MMapDirectory"/> will throw a <see cref="ObjectDisposedException"/>.
/// </para>
/// </summary>
public class MMapDirectory : FSDirectory
{
// LUCENENET specific - unmap hack not needed
/// <summary>
/// Default max chunk size. </summary>
/// <seealso cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
public static readonly int DEFAULT_MAX_BUFF = Constants.RUNTIME_IS_64BIT ? (1 << 30) : (1 << 28);
private readonly int chunkSizePower;
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or null for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path, LockFactory lockFactory)
: this(path, lockFactory, DEFAULT_MAX_BUFF)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path)
: this(path, null)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location, specifying the
/// maximum chunk size used for memory mapping.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or <c>null</c> for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <param name="maxChunkSize"> maximum chunk size (default is 1 GiBytes for
/// 64 bit runtimes and 256 MiBytes for 32 bit runtimes) used for memory mapping.
/// <para/>
/// Especially on 32 bit platform, the address space can be very fragmented,
/// so large index files cannot be mapped. Using a lower chunk size makes
/// the directory implementation a little bit slower (as the correct chunk
/// may be resolved on lots of seeks) but the chance is higher that mmap
/// does not fail. On 64 bit platforms, this parameter should always
/// be <c>1 << 30</c>, as the address space is big enough.
/// <para/>
/// <b>Please note:</b> The chunk size is always rounded down to a power of 2.
/// </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(DirectoryInfo path, LockFactory lockFactory, int maxChunkSize)
: base(path, lockFactory)
{
if (maxChunkSize <= 0)
{
throw new System.ArgumentException("Maximum chunk size for mmap must be >0");
}
this.chunkSizePower = 31 - Number.NumberOfLeadingZeros(maxChunkSize);
Debug.Assert(this.chunkSizePower >= 0 && this.chunkSizePower <= 30);
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or null for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path, LockFactory lockFactory)
: this(path, lockFactory, DEFAULT_MAX_BUFF)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location and <see cref="NativeFSLockFactory"/>.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path)
: this(path, null)
{
}
/// <summary>
/// Create a new <see cref="MMapDirectory"/> for the named location, specifying the
/// maximum chunk size used for memory mapping.
/// <para/>
/// LUCENENET specific overload for convenience using string instead of <see cref="DirectoryInfo"/>.
/// </summary>
/// <param name="path"> the path of the directory </param>
/// <param name="lockFactory"> the lock factory to use, or <c>null</c> for the default
/// (<see cref="NativeFSLockFactory"/>); </param>
/// <param name="maxChunkSize"> maximum chunk size (default is 1 GiBytes for
/// 64 bit runtimes and 256 MiBytes for 32 bit runtimes) used for memory mapping.
/// <para/>
/// Especially on 32 bit platform, the address space can be very fragmented,
/// so large index files cannot be mapped. Using a lower chunk size makes
/// the directory implementation a little bit slower (as the correct chunk
/// may be resolved on lots of seeks) but the chance is higher that mmap
/// does not fail. On 64 bit platforms, this parameter should always
/// be <c>1 << 30</c>, as the address space is big enough.
/// <para/>
/// <b>Please note:</b> The chunk size is always rounded down to a power of 2.
/// </param>
/// <exception cref="IOException"> if there is a low-level I/O error </exception>
public MMapDirectory(string path, LockFactory lockFactory, int maxChunkSize)
: this(new DirectoryInfo(path), lockFactory, maxChunkSize)
{
}
// LUCENENET specific - Some JREs had a bug that didn't allow them to unmap.
// But according to MSDN, the MemoryMappedFile.Dispose() method will
// indeed "release all resources". Therefore unmap hack is not needed in .NET.
/// <summary>
/// Returns the current mmap chunk size. </summary>
/// <seealso cref="MMapDirectory(DirectoryInfo, LockFactory, int)"/>
public int MaxChunkSize
{
get
{
return 1 << chunkSizePower;
}
}
/// <summary>
/// Creates an <see cref="IndexInput"/> for the file with the given name. </summary>
public override IndexInput OpenInput(string name, IOContext context)
{
EnsureOpen();
var file = new FileInfo(Path.Combine(Directory.FullName, name));
var fc = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return new MMapIndexInput(this, "MMapIndexInput(path=\"" + file + "\")", fc);
}
public override IndexInputSlicer CreateSlicer(string name, IOContext context)
{
var full = (MMapIndexInput)OpenInput(name, context);
return new IndexInputSlicerAnonymousInnerClassHelper(this, full);
}
private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer
{
private readonly MMapDirectory outerInstance;
private MMapIndexInput full;
public IndexInputSlicerAnonymousInnerClassHelper(MMapDirectory outerInstance, MMapIndexInput full)
{
this.outerInstance = outerInstance;
this.full = full;
}
public override IndexInput OpenSlice(string sliceDescription, long offset, long length)
{
outerInstance.EnsureOpen();
return full.Slice(sliceDescription, offset, length);
}
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public override IndexInput OpenFullSlice()
{
outerInstance.EnsureOpen();
return (IndexInput)full.Clone();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
full.Dispose();
}
}
}
public sealed class MMapIndexInput : ByteBufferIndexInput
{
internal MemoryMappedFile memoryMappedFile; // .NET port: this is equivalent to FileChannel.map
private readonly FileStream fc;
private readonly MMapDirectory outerInstance;
internal MMapIndexInput(MMapDirectory outerInstance, string resourceDescription, FileStream fc)
: base(resourceDescription, null, fc.Length, outerInstance.chunkSizePower, true)
{
this.outerInstance = outerInstance;
if (fc == null)
throw new ArgumentNullException("fc");
this.fc = fc;
this.SetBuffers(outerInstance.Map(this, fc, 0, fc.Length));
}
protected override sealed void Dispose(bool disposing)
{
try
{
if (disposing)
{
try
{
if (this.memoryMappedFile != null)
{
this.memoryMappedFile.Dispose();
this.memoryMappedFile = null;
}
}
finally
{
// LUCENENET: If the file is 0 length we will not create a memoryMappedFile above
// so we must always ensure the FileStream is explicitly disposed.
this.fc.Dispose();
}
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Try to unmap the buffer, this method silently fails if no support
/// for that in the runtime. On Windows, this leads to the fact,
/// that mmapped files cannot be modified or deleted.
/// </summary>
protected override void FreeBuffer(ByteBuffer buffer)
{
// LUCENENET specific: this should free the memory mapped view accessor
var mmfbb = buffer as MemoryMappedFileByteBuffer;
if (mmfbb != null)
mmfbb.Dispose();
// LUCENENET specific: no need for UnmapHack
}
}
/// <summary>
/// Maps a file into a set of buffers </summary>
internal virtual ByteBuffer[] Map(MMapIndexInput input, FileStream fc, long offset, long length)
{
if (Number.URShift(length, chunkSizePower) >= int.MaxValue)
throw new ArgumentException("RandomAccessFile too big for chunk size: " + fc.ToString());
// LUCENENET specific: Return empty buffer if length is 0, rather than attempting to create a MemoryMappedFile.
// Part of a solution provided by Vincent Van Den Berghe: http://apache.markmail.org/message/hafnuhq2ydhfjmi2
if (length == 0)
{
return new[] { ByteBuffer.Allocate(0).AsReadOnlyBuffer() };
}
long chunkSize = 1L << chunkSizePower;
// we always allocate one more buffer, the last one may be a 0 byte one
int nrBuffers = (int)((long)((ulong)length >> chunkSizePower)) + 1;
ByteBuffer[] buffers = new ByteBuffer[nrBuffers];
if (input.memoryMappedFile == null)
{
input.memoryMappedFile = MemoryMappedFile.CreateFromFile(
fileStream: fc,
mapName: null,
capacity: length,
access: MemoryMappedFileAccess.Read,
#if !NETSTANDARD
memoryMappedFileSecurity: null,
#endif
inheritability: HandleInheritability.Inheritable,
leaveOpen: true); // LUCENENET: We explicitly dispose the FileStream separately.
}
long bufferStart = 0L;
for (int bufNr = 0; bufNr < nrBuffers; bufNr++)
{
int bufSize = (int)((length > (bufferStart + chunkSize)) ? chunkSize : (length - bufferStart));
// LUCENENET: We get an UnauthorizedAccessException if we create a 0 byte file at the end of the range.
// See: https://stackoverflow.com/a/5501331
// We can fix this by moving back 1 byte on the offset if the bufSize is 0.
int adjust = 0;
if (bufSize == 0 && bufNr == (nrBuffers - 1) && (offset + bufferStart) > 0)
{
adjust = 1;
}
buffers[bufNr] = new MemoryMappedFileByteBuffer(
input.memoryMappedFile.CreateViewAccessor(
offset: (offset + bufferStart) - adjust,
size: bufSize,
access: MemoryMappedFileAccess.Read),
bufSize);
bufferStart += bufSize;
}
return buffers;
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.Dnx.Runtime.Common.CommandLine;
namespace dotnet_new2
{
public class Program
{
public static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "--debug")
{
args = args.Skip(1).ToArray();
Console.WriteLine($"Waiting for debugger to attach. Process ID {Process.GetCurrentProcess().Id}");
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
}
try
{
return new Program(new TemplateManager(), new ProjectCreator()).Run(args);
}
catch (Exception ex)
{
Console.Error.WriteLine("FAIL: {0}", ex);
return 1;
}
}
private readonly TemplateManager _templateManager;
private readonly ProjectCreator _projectCreator;
public Program(TemplateManager templateManager, ProjectCreator projectCreator)
{
_templateManager = templateManager;
_projectCreator = projectCreator;
}
public int Run(string [] args)
{
var app = new CommandLineApplication();
app.Name = "dotnet-new2";
app.Description = $"The {app.Name} command is used to create .NET Core projects using templates installed via NuGet packages.";
app.HelpOption("-?|-h|--help");
app.Command("list", command =>
{
command.Description = "Lists installed templates";
command.OnExecute(() =>
{
var packages = _templateManager.GetInstalledTemplatePackages();
if (!packages.Any())
{
Console.WriteLine($"No templates installed. Type '{app.Name} install --help' for help on installing templates.");
return 0;
}
foreach (var package in packages)
{
Console.WriteLine($"{package.Id} {package.Version}");
var templates = package.GetTemplatesList();
if (templates.Any())
{
var maxNameLength = templates.Max(t => t.Title.Length);
foreach (var template in templates)
{
var padding = new string(' ', maxNameLength - template.Title.Length);
Console.WriteLine($" - {template.Title} {padding} [{template.Path}]");
}
}
}
return 0;
});
});
app.Command("install", command =>
{
command.Description = "Installs templates from a package with optional version";
var idArg = command.Argument("[PackageId]", "The ID of the template package");
var versionArg = command.Argument("[PackageVersion]", "The version of the template package");
command.HelpOption("-?|-h|--help");
command.OnExecute(() =>
{
if (idArg.Value == null || versionArg.Value == null)
{
// TODO: Support not having to pass the version in (likely requires NuGet API support)
command.ShowHelp();
return 2;
}
if (!_templateManager.InstallTemplatePackage(idArg.Value, versionArg.Value))
{
return 1;
}
return 0;
});
});
app.Command("uninstall", command =>
{
command.Description = "Uninstalls a template package";
var idArg = command.Argument("[PackageId]", "The ID of the template package");
command.HelpOption("-?|-h|--help");
command.OnExecute(() =>
{
if (idArg.Value == null)
{
command.ShowHelp();
return 2;
}
if (!_templateManager.UninstallTemplatePackage(idArg.Value))
{
return 1;
}
return 0;
});
});
app.Command("restore", command =>
{
command.Description = "Restores installed template packages";
command.OnExecute(() =>
{
if (!_templateManager.RestoreTemplatePackages())
{
Console.WriteLine("Error restoring templates.");
return 1;
}
Console.WriteLine($"Templates restored. Type '{app.Name} list' to list installed templates.");
return 0;
});
});
var templateOption = app.Option("-t|--template <template/path>", "The path of the template to use", CommandOptionType.SingleValue);
var nameOption = app.Option("-n|--name <name>", "The name of the new project", CommandOptionType.SingleValue);
app.OnExecute(() =>
{
var templatePath = templateOption.Value();
Template template;
if (templatePath == null)
{
template = PromptForTemplate();
if (template == null)
{
Console.WriteLine($"No templates installed. Type '{app.Name} install --help' for help on installing templates.");
return 1;
}
}
else
{
template = _templateManager.GetTemplate(templatePath);
if (template == null)
{
Console.WriteLine($"The template {templatePath} wasn't found. Type '{app.Name} list' to list installed templates, or '{app.Name}' to select from installed templates.");
return 1;
}
}
string newProjectName;
string newProjectPath;
if (nameOption.Value() == null)
{
if (templateOption.Value() == null)
{
// User passed no args so we're in interactive mode
newProjectName = PromptForName();
newProjectPath = Path.Combine(Directory.GetCurrentDirectory(), newProjectName);
}
else
{
// User passed the template arg but no name arg so create project in current dir
newProjectPath = Directory.GetCurrentDirectory();
newProjectName = newProjectPath.Split(Path.DirectorySeparatorChar).Last();
}
}
else
{
newProjectName = nameOption.Value();
newProjectPath = Path.Combine(Directory.GetCurrentDirectory(), newProjectName);
}
if (!_projectCreator.CreateProject(newProjectName, newProjectPath, template))
{
Console.WriteLine("Error creating project");
return 1;
}
return 0;
});
return app.Execute(args);
}
private Template PromptForTemplate()
{
var templatePackages = _templateManager.GetInstalledTemplatePackages();
if (templatePackages.Count == 0)
{
return null;
}
var menuEntries = _templateManager.MergeManifestEntries(templatePackages);
if (menuEntries.Count == 0)
{
return null;
}
ManifestEntry currentEntry = null;
Template selectedTemplate = null;
while (selectedTemplate == null)
{
var title = currentEntry == null ? "Templates" : currentEntry.Title + " Templates";
Console.WriteLine();
Console.WriteLine(title);
Console.WriteLine("-----------------------------------------");
var maxTitleLength = menuEntries.Max(e => e.Title.Length);
for (var i = 0; i < menuEntries.Count; i++)
{
var entry = menuEntries[i];
var padding = new string(' ', maxTitleLength - entry.Title.Length);
Console.WriteLine($"{i + 1}. {entry.Title} {padding}[{entry.Path}]");
}
Console.WriteLine();
Console.Write($"Select a template [1]: ");
var selectedNumber = ConsoleUtils.ReadInt(menuEntries.Count);
currentEntry = menuEntries[selectedNumber - 1];
var category = currentEntry as TemplateCategory;
if (category != null)
{
if (category.Children.Count == 1)
{
var firstTemplate = category.Children.FirstOrDefault() as Template;
if (firstTemplate != null)
{
// Only one template in this category so just pick it without prompting any further
selectedTemplate = firstTemplate;
}
}
menuEntries = category.Children;
}
else
{
selectedTemplate = currentEntry as Template;
}
}
return selectedTemplate;
}
private string PromptForName()
{
var defaultName = "Project1";
Console.Write($"Enter a project name [{defaultName}]: ");
var name = Console.ReadLine();
if (string.IsNullOrWhiteSpace(name))
{
name = defaultName;
}
return name;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/services.proto
// Original file comments:
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// An integration test service that covers all the method signature permutations
// of unary/streaming requests/responses.
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Grpc.Testing {
public static partial class BenchmarkService
{
static readonly string __ServiceName = "grpc.testing.BenchmarkService";
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.Unary,
__ServiceName,
"UnaryCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
static readonly grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_StreamingCall = new grpc::Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"StreamingCall",
__Marshaller_SimpleRequest,
__Marshaller_SimpleResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of BenchmarkService</summary>
public abstract partial class BenchmarkServiceBase
{
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task StreamingCall(grpc::IAsyncStreamReader<global::Grpc.Testing.SimpleRequest> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.SimpleResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for BenchmarkService</summary>
public partial class BenchmarkServiceClient : grpc::ClientBase<BenchmarkServiceClient>
{
/// <summary>Creates a new client for BenchmarkService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public BenchmarkServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for BenchmarkService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public BenchmarkServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected BenchmarkServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected BenchmarkServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCall(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UnaryCallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_UnaryCall, null, options, request);
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingCall(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// One request followed by one response.
/// The server returns the client payload as-is.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingCall, null, options);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override BenchmarkServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new BenchmarkServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(BenchmarkServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall)
.AddMethod(__Method_StreamingCall, serviceImpl.StreamingCall).Build();
}
}
public static partial class WorkerService
{
static readonly string __ServiceName = "grpc.testing.WorkerService";
static readonly grpc::Marshaller<global::Grpc.Testing.ServerArgs> __Marshaller_ServerArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerArgs.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ServerStatus> __Marshaller_ServerStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerStatus.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ClientArgs> __Marshaller_ClientArgs = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientArgs.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.ClientStatus> __Marshaller_ClientStatus = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientStatus.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.CoreRequest> __Marshaller_CoreRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.CoreResponse> __Marshaller_CoreResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Grpc.Testing.Void> __Marshaller_Void = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Void.Parser.ParseFrom);
static readonly grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> __Method_RunServer = new grpc::Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"RunServer",
__Marshaller_ServerArgs,
__Marshaller_ServerStatus);
static readonly grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> __Method_RunClient = new grpc::Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"RunClient",
__Marshaller_ClientArgs,
__Marshaller_ClientStatus);
static readonly grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse> __Method_CoreCount = new grpc::Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CoreCount",
__Marshaller_CoreRequest,
__Marshaller_CoreResponse);
static readonly grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void> __Method_QuitWorker = new grpc::Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void>(
grpc::MethodType.Unary,
__ServiceName,
"QuitWorker",
__Marshaller_Void,
__Marshaller_Void);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[1]; }
}
/// <summary>Base class for server-side implementations of WorkerService</summary>
public abstract partial class WorkerServiceBase
{
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task RunServer(grpc::IAsyncStreamReader<global::Grpc.Testing.ServerArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ServerStatus> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task RunClient(grpc::IAsyncStreamReader<global::Grpc.Testing.ClientArgs> requestStream, grpc::IServerStreamWriter<global::Grpc.Testing.ClientStatus> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.CoreResponse> CoreCount(global::Grpc.Testing.CoreRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Grpc.Testing.Void> QuitWorker(global::Grpc.Testing.Void request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for WorkerService</summary>
public partial class WorkerServiceClient : grpc::ClientBase<WorkerServiceClient>
{
/// <summary>Creates a new client for WorkerService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public WorkerServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for WorkerService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public WorkerServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected WorkerServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected WorkerServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunServer(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Start server with specified workload.
/// First request sent specifies the ServerConfig followed by ServerStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test server
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_RunServer, null, options);
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RunClient(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Start client with specified workload.
/// First request sent specifies the ClientConfig followed by ClientStatus
/// response. After that, a "Mark" can be sent anytime to request the latest
/// stats. Closing the stream will initiate shutdown of the test client
/// and once the shutdown has finished, the OK status is sent to terminate
/// this RPC.
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_RunClient, null, options);
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CoreCount(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CoreCount, null, options, request);
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CoreCountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Just return the core count - unary call
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CoreCount, null, options, request);
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return QuitWorker(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_QuitWorker, null, options, request);
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return QuitWorkerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Quit this worker
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_QuitWorker, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override WorkerServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new WorkerServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(WorkerServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_RunServer, serviceImpl.RunServer)
.AddMethod(__Method_RunClient, serviceImpl.RunClient)
.AddMethod(__Method_CoreCount, serviceImpl.CoreCount)
.AddMethod(__Method_QuitWorker, serviceImpl.QuitWorker).Build();
}
}
}
#endregion
| |
// ----------------------------------------------------------------------------
// <copyright file="AccountService.cs" company="Exit Games GmbH">
// Photon Cloud Account Service - Copyright (C) 2012 Exit Games GmbH
// </copyright>
// <summary>
// Provides methods to register a new user-account for the Photon Cloud and
// get the resulting appId.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
#if UNITY_EDITOR
//#define PHOTON_VOICE
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
public class AccountService
{
private const string ServiceUrl = "https://service.exitgames.com/AccountExt/AccountServiceExt.aspx";
private Action<AccountService> registrationCallback; // optional (when using async reg)
public string Message { get; private set; } // msg from server (in case of success, this is the appid)
protected internal Exception Exception { get; set; } // exceptions in account-server communication
public string AppId { get; private set; }
public string AppId2 { get; private set; }
public int ReturnCode { get; private set; } // 0 = OK. anything else is a error with Message
public enum Origin : byte { ServerWeb = 1, CloudWeb = 2, Pun = 3, Playmaker = 4 };
/// <summary>
/// Creates a instance of the Account Service to register Photon Cloud accounts.
/// </summary>
public AccountService()
{
WebRequest.DefaultWebProxy = null;
ServicePointManager.ServerCertificateValidationCallback = Validator;
}
public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true; // any certificate is ok in this case
}
/// <summary>
/// Attempts to create a Photon Cloud Account.
/// Check ReturnCode, Message and AppId to get the result of this attempt.
/// </summary>
/// <param name="email">Email of the account.</param>
/// <param name="origin">Marks which channel created the new account (if it's new).</param>
/// <param name="serviceType">Defines which type of Photon-service is being requested.</param>
public void RegisterByEmail(string email, Origin origin, string serviceType = null)
{
this.registrationCallback = null;
this.AppId = string.Empty;
this.AppId2 = string.Empty;
this.Message = string.Empty;
this.ReturnCode = -1;
string result;
try
{
WebRequest req = HttpWebRequest.Create(this.RegistrationUri(email, (byte)origin, serviceType));
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
// now read result
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
catch (Exception ex)
{
this.Message = "Failed to connect to Cloud Account Service. Please register via account website.";
this.Exception = ex;
return;
}
this.ParseResult(result);
}
/// <summary>
/// Attempts to create a Photon Cloud Account asynchronously.
/// Once your callback is called, check ReturnCode, Message and AppId to get the result of this attempt.
/// </summary>
/// <param name="email">Email of the account.</param>
/// <param name="origin">Marks which channel created the new account (if it's new).</param>
/// <param name="serviceType">Defines which type of Photon-service is being requested.</param>
/// <param name="callback">Called when the result is available.</param>
public void RegisterByEmailAsync(string email, Origin origin, string serviceType, Action<AccountService> callback = null)
{
this.registrationCallback = callback;
this.AppId = string.Empty;
this.AppId2 = string.Empty;
this.Message = string.Empty;
this.ReturnCode = -1;
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(this.RegistrationUri(email, (byte)origin, serviceType));
req.Timeout = 5000;
req.BeginGetResponse(this.OnRegisterByEmailCompleted, req);
}
catch (Exception ex)
{
this.Message = "Failed to connect to Cloud Account Service. Please register via account website.";
this.Exception = ex;
if (this.registrationCallback != null)
{
this.registrationCallback(this);
}
}
}
/// <summary>
/// Internal callback with result of async HttpWebRequest (in RegisterByEmailAsync).
/// </summary>
/// <param name="ar"></param>
private void OnRegisterByEmailCompleted(IAsyncResult ar)
{
try
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
// no error. use the result
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
this.ParseResult(result);
}
else
{
// a response but some error on server. show message
this.Message = "Failed to connect to Cloud Account Service. Please register via account website.";
}
}
catch (Exception ex)
{
// not even a response. show message
this.Message = "Failed to connect to Cloud Account Service. Please register via account website.";
this.Exception = ex;
}
if (this.registrationCallback != null)
{
this.registrationCallback(this);
}
}
/// <summary>
/// Creates the service-call Uri, escaping the email for security reasons.
/// </summary>
/// <param name="email">Email of the account.</param>
/// <param name="origin">1 = server-web, 2 = cloud-web, 3 = PUN, 4 = playmaker</param>
/// <param name="serviceType">Defines which type of Photon-service is being requested. Options: "", "voice", "chat"</param>
/// <returns>Uri to call.</returns>
private Uri RegistrationUri(string email, byte origin, string serviceType)
{
if (serviceType == null)
{
serviceType = string.Empty;
}
string emailEncoded = Uri.EscapeDataString(email);
string uriString = string.Format("{0}?email={1}&origin={2}&serviceType={3}", ServiceUrl, emailEncoded, origin, serviceType);
return new Uri(uriString);
}
/// <summary>
/// Reads the Json response and applies it to local properties.
/// </summary>
/// <param name="result"></param>
private void ParseResult(string result)
{
if (string.IsNullOrEmpty(result))
{
this.Message = "Server's response was empty. Please register through account website during this service interruption.";
return;
}
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
if (values == null)
{
this.Message = "Service temporarily unavailable. Please register through account website.";
return;
}
int returnCodeInt = -1;
string returnCodeString = string.Empty;
string message;
string messageDetailed;
values.TryGetValue("ReturnCode", out returnCodeString);
values.TryGetValue("Message", out message);
values.TryGetValue("MessageDetailed", out messageDetailed);
int.TryParse(returnCodeString, out returnCodeInt);
this.ReturnCode = returnCodeInt;
if (returnCodeInt == 0)
{
// returnCode == 0 means: all ok. message is new AppId
this.AppId = message;
#if PHOTON_VOICE
this.AppId2 = messageDetailed;
#endif
}
else
{
// any error gives returnCode != 0
this.AppId = string.Empty;
#if PHOTON_VOICE
this.AppId2 = string.Empty;
#endif
this.Message = message;
}
}
}
#endif
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCON
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestSuites.Common.DataStructures;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
/// <summary>
/// The base class of scenario class.
/// </summary>
[TestClass]
public class TestSuiteBase : TestClassBase
{
#region Variables
/// <summary>
/// Gets or sets the information of User1.
/// </summary>
protected UserInformation User1Information { get; set; }
/// <summary>
/// Gets or sets the information of User2.
/// </summary>
protected UserInformation User2Information { get; set; }
/// <summary>
/// Gets or sets the information of User3.
/// </summary>
protected UserInformation User3Information { get; set; }
/// <summary>
/// Gets MS-ASCON protocol adapter.
/// </summary>
protected IMS_ASCONAdapter CONAdapter { get; private set; }
/// <summary>
/// Gets the latest SyncKey.
/// </summary>
protected string LatestSyncKey { get; private set; }
#endregion
/// <summary>
/// Record the user name, folder collectionId and subjects the current test case impacts.
/// </summary>
/// <param name="userInformation">The information of the user.</param>
/// <param name="folderCollectionId">The collectionId of folders that the current test case impacts.</param>
/// <param name="itemSubject">The subject of items that the current test case impacts.</param>
/// <param name="isDeleted">Whether the item has been deleted and should be removed from the record.</param>
protected static void RecordCaseRelativeItems(UserInformation userInformation, string folderCollectionId, string itemSubject, bool isDeleted)
{
// Record the item in the specified folder.
CreatedItems items = new CreatedItems { CollectionId = folderCollectionId };
items.ItemSubject.Add(itemSubject);
bool isSame = false;
if (!isDeleted)
{
if (userInformation.UserCreatedItems.Count > 0)
{
foreach (CreatedItems createdItems in userInformation.UserCreatedItems)
{
if (createdItems.CollectionId == folderCollectionId && createdItems.ItemSubject[0] == itemSubject)
{
isSame = true;
}
}
if (!isSame)
{
userInformation.UserCreatedItems.Add(items);
}
}
else
{
userInformation.UserCreatedItems.Add(items);
}
}
else
{
if (userInformation.UserCreatedItems.Count > 0)
{
foreach (CreatedItems existItem in userInformation.UserCreatedItems)
{
if (existItem.CollectionId == folderCollectionId && existItem.ItemSubject[0] == itemSubject)
{
userInformation.UserCreatedItems.Remove(existItem);
break;
}
}
}
}
}
#region Test case initialize and cleanup
/// <summary>
/// Initialize the Test suite.
/// </summary>
protected override void TestInitialize()
{
base.TestInitialize();
this.CONAdapter = Site.GetAdapter<IMS_ASCONAdapter>();
// If implementation doesn't support this specification [MS-ASCON], the case will not start.
if (!bool.Parse(Common.GetConfigurationPropertyValue("MS-ASCON_Supported", this.Site)))
{
this.Site.Assert.Inconclusive("This test suite is not supported under current SUT, because MS-ASCON_Supported value is set to false in MS-ASCON_{0}_SHOULDMAY.deployment.ptfconfig file.", Common.GetSutVersion(this.Site));
}
Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The airsyncbase:BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
this.User1Information = new UserInformation
{
UserName = Common.GetConfigurationPropertyValue("User1Name", Site),
UserPassword = Common.GetConfigurationPropertyValue("User1Password", Site),
UserDomain = Common.GetConfigurationPropertyValue("Domain", Site)
};
this.User2Information = new UserInformation
{
UserName = Common.GetConfigurationPropertyValue("User2Name", Site),
UserPassword = Common.GetConfigurationPropertyValue("User2Password", Site),
UserDomain = Common.GetConfigurationPropertyValue("Domain", Site)
};
this.User3Information = new UserInformation
{
UserName = Common.GetConfigurationPropertyValue("User3Name", Site),
UserPassword = Common.GetConfigurationPropertyValue("User3Password", Site),
UserDomain = Common.GetConfigurationPropertyValue("Domain", Site)
};
if (Common.GetSutVersion(this.Site) != SutVersion.ExchangeServer2007 || string.Equals(Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "12.1"))
{
// Switch the current user to User1 and synchronize the folder hierarchy of User1.
this.SwitchUser(this.User1Information, true);
}
}
/// <summary>
/// Clean up the environment.
/// </summary>
protected override void TestCleanup()
{
// If implementation doesn't support this specification [MS-ASCON], the case will not start.
if (bool.Parse(Common.GetConfigurationPropertyValue("MS-ASCON_Supported", this.Site)))
{
if (this.User1Information.UserCreatedItems.Count != 0)
{
// Switch to User1
this.SwitchUser(this.User1Information, false);
this.DeleteItemsInFolder(this.User1Information.UserCreatedItems);
}
if (this.User2Information.UserCreatedItems.Count != 0)
{
// Switch to User2
this.SwitchUser(this.User2Information, false);
this.DeleteItemsInFolder(this.User2Information.UserCreatedItems);
}
if (this.User3Information.UserCreatedItems.Count != 0)
{
// Switch to User3
this.SwitchUser(this.User3Information, false);
this.DeleteItemsInFolder(this.User3Information.UserCreatedItems);
}
}
base.TestCleanup();
}
#endregion
#region Test case base methods
/// <summary>
/// Change user to call active sync operations and resynchronize the collection hierarchy.
/// </summary>
/// <param name="userInformation">The information of the user.</param>
/// <param name="isFolderSyncNeeded">A boolean value that indicates whether needs to synchronize the folder hierarchy.</param>
protected void SwitchUser(UserInformation userInformation, bool isFolderSyncNeeded)
{
this.CONAdapter.SwitchUser(userInformation.UserName, userInformation.UserPassword, userInformation.UserDomain);
if (isFolderSyncNeeded)
{
// Call FolderSync command to synchronize the collection hierarchy.
FolderSyncRequest folderSyncRequest = Common.CreateFolderSyncRequest("0");
FolderSyncResponse folderSyncResponse = this.CONAdapter.FolderSync(folderSyncRequest);
// Verify FolderSync command response.
Site.Assert.AreEqual<int>(
1,
int.Parse(folderSyncResponse.ResponseData.Status),
"If the FolderSync command executes successfully, the Status in response should be 1.");
// Get the folder collectionId of User1
if (userInformation.UserName == this.User1Information.UserName)
{
if (string.IsNullOrEmpty(this.User1Information.InboxCollectionId))
{
this.User1Information.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site);
}
if (string.IsNullOrEmpty(this.User1Information.DeletedItemsCollectionId))
{
this.User1Information.DeletedItemsCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.DeletedItems, this.Site);
}
if (string.IsNullOrEmpty(this.User1Information.CalendarCollectionId))
{
this.User1Information.CalendarCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Calendar, this.Site);
}
if (string.IsNullOrEmpty(this.User1Information.SentItemsCollectionId))
{
this.User1Information.SentItemsCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.SentItems, this.Site);
}
if (string.IsNullOrEmpty(this.User1Information.RecipientInformationCacheCollectionId))
{
this.User1Information.RecipientInformationCacheCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.RecipientInformationCache, this.Site);
}
}
// Get the folder collectionId of User2
if (userInformation.UserName == this.User2Information.UserName)
{
if (string.IsNullOrEmpty(this.User2Information.InboxCollectionId))
{
this.User2Information.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site);
}
}
// Get the folder collectionId of User3
if (userInformation.UserName == this.User3Information.UserName)
{
if (string.IsNullOrEmpty(this.User3Information.InboxCollectionId))
{
this.User3Information.InboxCollectionId = Common.GetDefaultFolderServerId(folderSyncResponse, FolderType.Inbox, this.Site);
}
}
}
}
/// <summary>
/// Create a conversation.
/// </summary>
/// <param name="subject">The subject of the emails in the conversation.</param>
/// <returns>The created conversation item.</returns>
protected ConversationItem CreateConversation(string subject)
{
#region Send email from User2 to User1
this.SwitchUser(this.User2Information, true);
string user1MailboxAddress = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain);
string user2MailboxAddress = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain);
this.CallSendMailCommand(user2MailboxAddress, user1MailboxAddress, subject, null);
RecordCaseRelativeItems(this.User1Information, this.User1Information.InboxCollectionId, subject, false);
#endregion
#region SmartReply the received email from User1 to User2.
this.SwitchUser(this.User1Information, false);
Sync syncResult = this.SyncEmail(subject, this.User1Information.InboxCollectionId, true, null, null);
this.CallSmartReplyCommand(syncResult.ServerId, this.User1Information.InboxCollectionId, user1MailboxAddress, user2MailboxAddress, subject);
RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, subject, false);
#endregion
#region SmartReply the received email from User2 to User1.
this.SwitchUser(this.User2Information, false);
syncResult = this.SyncEmail(subject, this.User2Information.InboxCollectionId, true, null, null);
this.CallSmartReplyCommand(syncResult.ServerId, this.User2Information.InboxCollectionId, user2MailboxAddress, user1MailboxAddress, subject);
#endregion
#region Switch current user to User1 and get the conversation item.
this.SwitchUser(this.User1Information, false);
int counter = 0;
int itemsCount;
int retryLimit = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", Site));
int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", Site));
do
{
System.Threading.Thread.Sleep(waitTime);
SyncStore syncStore = this.CallSyncCommand(this.User1Information.InboxCollectionId, false);
// Reset the item count.
itemsCount = 0;
foreach (Sync item in syncStore.AddElements)
{
if (item.Email.Subject.Contains(subject))
{
syncResult = item;
itemsCount++;
}
}
counter++;
}
while (itemsCount < 2 && counter < retryLimit);
Site.Assert.AreEqual<int>(2, itemsCount, "There should be 2 emails with subject {0} in the Inbox folder, actual {1}.", subject, itemsCount);
return this.GetConversationItem(this.User1Information.InboxCollectionId, syncResult.Email.ConversationId);
#endregion
}
/// <summary>
/// Call Search command to find a specified conversation.
/// </summary>
/// <param name="conversationId">The ConversationId of the items to search.</param>
/// <param name="itemsCount">The count of the items expected to be found.</param>
/// <param name="bodyPartPreference">The BodyPartPreference element.</param>
/// <param name="bodyPreference">The BodyPreference element.</param>
/// <returns>The SearchStore instance that contains the search result.</returns>
protected SearchStore CallSearchCommand(string conversationId, int itemsCount, Request.BodyPartPreference bodyPartPreference, Request.BodyPreference bodyPreference)
{
// Create Search command request.
SearchRequest searchRequest = TestSuiteHelper.GetSearchRequest(conversationId, bodyPartPreference, bodyPreference);
SearchStore searchStore = this.CONAdapter.Search(searchRequest, true, itemsCount);
Site.Assert.AreEqual("1", searchStore.Status, "The Search operation should be success.");
return searchStore;
}
/// <summary>
/// Call SendMail command to send mail.
/// </summary>
/// <param name="from">The mailbox address of sender.</param>
/// <param name="to">The mailbox address of recipient.</param>
/// <param name="subject">The subject of the email.</param>
/// <param name="body">The body content of the email.</param>
protected void CallSendMailCommand(string from, string to, string subject, string body)
{
if (string.IsNullOrEmpty(body))
{
body = Common.GenerateResourceName(this.Site, "body");
}
// Create the SendMail command request.
string template =
@"From: {0}
To: {1}
Subject: {2}
Content-Type: text/html; charset=""us-ascii""
MIME-Version: 1.0
<html>
<body>
<font color=""blue"">{3}</font>
</body>
</html>
";
string mime = Common.FormatString(template, from, to, subject, body);
SendMailRequest sendMailRequest = Common.CreateSendMailRequest(null, System.Guid.NewGuid().ToString(), mime);
// Call SendMail command.
SendMailResponse sendMailResponse = this.CONAdapter.SendMail(sendMailRequest);
Site.Assert.AreEqual(string.Empty, sendMailResponse.ResponseDataXML, "The SendMail command should be executed successfully.");
}
/// <summary>
/// Call SmartReply command to reply an email.
/// </summary>
/// <param name="itemServerId">The ServerId of the email to reply.</param>
/// <param name="collectionId">The folder collectionId of the source email.</param>
/// <param name="from">The mailbox address of sender.</param>
/// <param name="replyTo">The mailbox address of recipient.</param>
/// <param name="subject">The subject of the email to reply.</param>
protected void CallSmartReplyCommand(string itemServerId, string collectionId, string from, string replyTo, string subject)
{
// Create SmartReply command request.
Request.Source source = new Request.Source();
string mime = Common.CreatePlainTextMime(from, replyTo, string.Empty, string.Empty, subject, "SmartReply content");
SmartReplyRequest smartReplyRequest = Common.CreateSmartReplyRequest(null, System.Guid.NewGuid().ToString(), mime, source);
// Set the command parameters.
smartReplyRequest.SetCommandParameters(new Dictionary<CmdParameterName, object>());
source.FolderId = collectionId;
source.ItemId = itemServerId;
smartReplyRequest.CommandParameters.Add(CmdParameterName.CollectionId, collectionId);
smartReplyRequest.CommandParameters.Add(CmdParameterName.ItemId, itemServerId);
smartReplyRequest.RequestData.ReplaceMime = string.Empty;
// Call SmartReply command.
SmartReplyResponse smartReplyResponse = this.CONAdapter.SmartReply(smartReplyRequest);
Site.Assert.AreEqual(string.Empty, smartReplyResponse.ResponseDataXML, "The SmartReply command should be executed successfully.");
}
/// <summary>
/// Call SmartForward command to forward an email.
/// </summary>
/// <param name="itemServerId">The ServerId of the email to reply.</param>
/// <param name="collectionId">The folder collectionId of the source email.</param>
/// <param name="from">The mailbox address of sender.</param>
/// <param name="forwardTo">The mailbox address of recipient.</param>
/// <param name="subject">The subject of the email to reply.</param>
protected void CallSmartForwardCommand(string itemServerId, string collectionId, string from, string forwardTo, string subject)
{
// Create SmartForward command request.
Request.Source source = new Request.Source();
string mime = Common.CreatePlainTextMime(from, forwardTo, string.Empty, string.Empty, subject, "SmartForward content");
SmartForwardRequest smartForwardRequest = Common.CreateSmartForwardRequest(null, System.Guid.NewGuid().ToString(), mime, source);
// Set the command parameters.
smartForwardRequest.SetCommandParameters(new Dictionary<CmdParameterName, object>());
source.FolderId = collectionId;
source.ItemId = itemServerId;
smartForwardRequest.CommandParameters.Add(CmdParameterName.CollectionId, collectionId);
smartForwardRequest.CommandParameters.Add(CmdParameterName.ItemId, itemServerId);
smartForwardRequest.RequestData.ReplaceMime = string.Empty;
// Call SmartForward command.
SmartForwardResponse smartForwardResponse = this.CONAdapter.SmartForward(smartForwardRequest);
Site.Assert.AreEqual(string.Empty, smartForwardResponse.ResponseDataXML, "The SmartForward command should be executed successfully.");
}
/// <summary>
/// Call ItemOperations command to fetch an email in the specific folder.
/// </summary>
/// <param name="collectionId">The folder collection id to be fetched.</param>
/// <param name="serverId">The ServerId of the item</param>
/// <param name="bodyPartPreference">The BodyPartPreference element.</param>
/// <param name="bodyPreference">The bodyPreference element.</param>
/// <returns>An Email instance that includes the fetch result.</returns>
protected Email ItemOperationsFetch(string collectionId, string serverId, Request.BodyPartPreference bodyPartPreference, Request.BodyPreference bodyPreference)
{
ItemOperationsRequest itemOperationsRequest = TestSuiteHelper.GetItemOperationsRequest(collectionId, serverId, bodyPartPreference, bodyPreference);
ItemOperationsResponse itemOperationsResponse = this.CONAdapter.ItemOperations(itemOperationsRequest);
Site.Assert.AreEqual("1", itemOperationsResponse.ResponseData.Status, "The ItemOperations operation should be success.");
ItemOperationsStore itemOperationsStore = Common.LoadItemOperationsResponse(itemOperationsResponse);
Site.Assert.AreEqual(1, itemOperationsStore.Items.Count, "Only one email is supposed to be fetched.");
Site.Assert.AreEqual("1", itemOperationsStore.Items[0].Status, "The fetch result should be success.");
Site.Assert.IsNotNull(itemOperationsStore.Items[0].Email, "The fetched email should not be null.");
return itemOperationsStore.Items[0].Email;
}
/// <summary>
/// Call ItemOperations command to move a conversation to a folder.
/// </summary>
/// <param name="conversationId">The Id of conversation to be moved.</param>
/// <param name="destinationFolder">The destination folder id.</param>
/// <param name="moveAlways">Should future messages always be moved.</param>
/// <returns>An instance of the ItemOperationsResponse.</returns>
protected ItemOperationsResponse ItemOperationsMove(string conversationId, string destinationFolder, bool moveAlways)
{
Request.ItemOperationsMove move = new Request.ItemOperationsMove
{
DstFldId = destinationFolder,
ConversationId = conversationId
};
if (moveAlways)
{
move.Options = new Request.ItemOperationsMoveOptions { MoveAlways = string.Empty };
}
ItemOperationsRequest itemOperationRequest = Common.CreateItemOperationsRequest(new object[] { move });
ItemOperationsResponse itemOperationResponse = this.CONAdapter.ItemOperations(itemOperationRequest);
Site.Assert.AreEqual("1", itemOperationResponse.ResponseData.Status, "The ItemOperations operation should be success.");
Site.Assert.AreEqual(1, itemOperationResponse.ResponseData.Response.Move.Length, "The server should return one Move element in ItemOperationsResponse.");
return itemOperationResponse;
}
/// <summary>
/// Call Sync command to add items to the specified folder.
/// </summary>
/// <param name="collectionId">The CollectionId of the specified folder.</param>
/// <param name="subject">Subject of the item to add.</param>
/// <param name="syncKey">The latest SyncKey.</param>
protected void SyncAdd(string collectionId, string subject, string syncKey)
{
// Create Sync request.
Request.SyncCollectionAdd add = new Request.SyncCollectionAdd
{
ClientId = Guid.NewGuid().ToString(),
ApplicationData = new Request.SyncCollectionAddApplicationData
{
Items = new object[] { subject },
ItemsElementName = new Request.ItemsChoiceType8[] { Request.ItemsChoiceType8.Subject2 }
}
};
Request.SyncCollection collection = new Request.SyncCollection
{
Commands = new object[] { add },
CollectionId = collectionId,
SyncKey = syncKey
};
SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { collection });
// Call Sync command to add the item.
SyncStore syncStore = this.CONAdapter.Sync(syncRequest);
// Verify Sync command response.
Site.Assert.AreEqual<byte>(
1,
syncStore.CollectionStatus,
"If the Sync command executes successfully, the Status in response should be 1.");
this.LatestSyncKey = syncStore.SyncKey;
}
/// <summary>
/// Call Sync command to change the status of the emails in Inbox folder.
/// </summary>
/// <param name="syncKey">The latest SyncKey.</param>
/// <param name="serverIds">The collection of ServerIds.</param>
/// <param name="collectionId">The folder collectionId which needs to be sychronized.</param>
/// <param name="read">Read element of the item.</param>
/// <param name="status">Flag status of the item.</param>
/// <returns>The SyncStore instance returned from Sync command.</returns>
protected SyncStore SyncChange(string syncKey, Collection<string> serverIds, string collectionId, bool? read, string status)
{
List<Request.SyncCollectionChange> changes = new List<Request.SyncCollectionChange>();
foreach (string serverId in serverIds)
{
Request.SyncCollectionChange change = new Request.SyncCollectionChange
{
ServerId = serverId,
ApplicationData = new Request.SyncCollectionChangeApplicationData()
};
List<object> changeItems = new List<object>();
List<Request.ItemsChoiceType7> changeItemsElementName = new List<Request.ItemsChoiceType7>();
if (read != null)
{
changeItems.Add(read);
changeItemsElementName.Add(Request.ItemsChoiceType7.Read);
}
if (!string.IsNullOrEmpty(status))
{
Request.Flag flag = new Request.Flag();
if (status == "1")
{
// The Complete Time format is yyyy-MM-ddThh:mm:ss.fffZ.
flag.CompleteTime = System.DateTime.Now.ToUniversalTime();
flag.CompleteTimeSpecified = true;
flag.DateCompleted = System.DateTime.Now.ToUniversalTime();
flag.DateCompletedSpecified = true;
}
flag.Status = status;
flag.FlagType = "Flag for follow up";
changeItems.Add(flag);
changeItemsElementName.Add(Request.ItemsChoiceType7.Flag);
}
change.ApplicationData.Items = changeItems.ToArray();
change.ApplicationData.ItemsElementName = changeItemsElementName.ToArray();
changes.Add(change);
}
Request.SyncCollection collection = new Request.SyncCollection
{
CollectionId = collectionId,
SyncKey = syncKey,
Commands = changes.ToArray()
};
SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { collection });
SyncStore syncStore = this.CONAdapter.Sync(syncRequest);
// Verify Sync command response.
Site.Assert.AreEqual<byte>(
1,
syncStore.CollectionStatus,
"If the Sync command executes successfully, the Status in response should be 1.");
this.LatestSyncKey = syncStore.SyncKey;
return syncStore;
}
/// <summary>
/// Call Sync command to delete items.
/// </summary>
/// <param name="collectionId">The CollectionId of the folder.</param>
/// <param name="syncKey">The latest SyncKey.</param>
/// <param name="serverIds">The ServerId of the items to delete.</param>
/// <returns>The SyncStore instance returned from Sync command.</returns>
protected SyncStore SyncDelete(string collectionId, string syncKey, string[] serverIds)
{
List<Request.SyncCollectionDelete> deleteCollection = new List<Request.SyncCollectionDelete>();
foreach (string itemId in serverIds)
{
Request.SyncCollectionDelete delete = new Request.SyncCollectionDelete { ServerId = itemId };
deleteCollection.Add(delete);
}
Request.SyncCollection collection = new Request.SyncCollection
{
Commands = deleteCollection.ToArray(),
DeletesAsMoves = true,
DeletesAsMovesSpecified = true,
CollectionId = collectionId,
SyncKey = syncKey
};
SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { collection });
SyncStore syncStore = this.CONAdapter.Sync(syncRequest);
// Verify Sync command response.
Site.Assert.AreEqual<byte>(
1,
syncStore.CollectionStatus,
"If the Sync command executes successfully, the Status in response should be 1.");
return syncStore;
}
/// <summary>
/// Find the specified email.
/// </summary>
/// <param name="subject">The subject of the email to find.</param>
/// <param name="collectionId">The folder collectionId which needs to be synchronized.</param>
/// <param name="isRetryNeeded">A Boolean value indicates whether need retry.</param>
/// <param name="bodyPartPreference">The bodyPartPreference in the options element.</param>
/// <param name="bodyPreference">The bodyPreference in the options element.</param>
/// <returns>The found email object.</returns>
protected Sync SyncEmail(string subject, string collectionId, bool isRetryNeeded, Request.BodyPartPreference bodyPartPreference, Request.BodyPreference bodyPreference)
{
// Call initial Sync command.
SyncRequest syncRequest = Common.CreateInitialSyncRequest(collectionId);
SyncStore syncStore = this.CONAdapter.Sync(syncRequest);
// Find the specific email.
syncRequest = TestSuiteHelper.GetSyncRequest(collectionId, syncStore.SyncKey, bodyPartPreference, bodyPreference, false);
Sync syncResult = this.CONAdapter.SyncEmail(syncRequest, subject, isRetryNeeded);
this.LatestSyncKey = syncStore.SyncKey;
return syncResult;
}
/// <summary>
/// Sync items in the specified folder.
/// </summary>
/// <param name="collectionId">The CollectionId of the folder.</param>
/// <param name="conversationMode">The value of ConversationMode element.</param>
/// <returns>A SyncStore instance that contains the result.</returns>
protected SyncStore CallSyncCommand(string collectionId, bool conversationMode)
{
// Call initial Sync command.
SyncRequest syncRequest = Common.CreateInitialSyncRequest(collectionId);
SyncStore syncStore = this.CONAdapter.Sync(syncRequest);
// Verify Sync command response.
Site.Assert.AreEqual<byte>(
1,
syncStore.CollectionStatus,
"If the Sync command executes successfully, the Status in response should be 1.");
if (conversationMode && Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site) != "12.1")
{
syncRequest = TestSuiteHelper.GetSyncRequest(collectionId, syncStore.SyncKey, null, null, true);
}
else
{
syncRequest = TestSuiteHelper.GetSyncRequest(collectionId, syncStore.SyncKey, null, null, false);
}
syncStore = this.CONAdapter.Sync(syncRequest);
// Verify Sync command response.
Site.Assert.AreEqual<byte>(
1,
syncStore.CollectionStatus,
"If the Sync command executes successfully, the Status in response should be 1.");
bool checkSyncStore = syncStore.AddElements != null && syncStore.AddElements.Count != 0;
Site.Assert.IsTrue(checkSyncStore, "The items should be gotten from the Sync command response.");
this.LatestSyncKey = syncStore.SyncKey;
return syncStore;
}
/// <summary>
/// Gets an estimate of the number of items in the specific folder.
/// </summary>
/// <param name="syncKey">The latest SyncKey.</param>
/// <param name="collectionId">The CollectionId of the folder.</param>
/// <returns>The response of GetItemEstimate command.</returns>
protected GetItemEstimateResponse CallGetItemEstimateCommand(string syncKey, string collectionId)
{
List<Request.ItemsChoiceType10> itemsElementName = new List<Request.ItemsChoiceType10>()
{
Request.ItemsChoiceType10.SyncKey,
Request.ItemsChoiceType10.CollectionId,
};
List<object> items = new List<object>()
{
syncKey,
collectionId,
};
if (Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site) != "12.1")
{
itemsElementName.Add(Request.ItemsChoiceType10.ConversationMode);
items.Add(true);
}
// Create GetItemEstimate command request.
Request.GetItemEstimateCollection collection = new Request.GetItemEstimateCollection
{
ItemsElementName = itemsElementName.ToArray(),
Items = items.ToArray()
};
GetItemEstimateRequest getItemEstimateRequest = Common.CreateGetItemEstimateRequest(new Request.GetItemEstimateCollection[] { collection });
GetItemEstimateResponse getItemEstimateResponse = this.CONAdapter.GetItemEstimate(getItemEstimateRequest);
return getItemEstimateResponse;
}
/// <summary>
/// Move items to the specific folder.
/// </summary>
/// <param name="serverIds">The ServerId of the items to move.</param>
/// <param name="sourceFolder">The CollectionId of the source folder.</param>
/// <param name="destinationFolder">The CollectionId of the destination folder.</param>
/// <returns>The response of MoveItems command.</returns>
protected MoveItemsResponse CallMoveItemsCommand(Collection<string> serverIds, string sourceFolder, string destinationFolder)
{
// Move the items from sourceFolder to destinationFolder.
List<Request.MoveItemsMove> moveItems = new List<Request.MoveItemsMove>();
foreach (string serverId in serverIds)
{
Request.MoveItemsMove move = new Request.MoveItemsMove
{
SrcFldId = sourceFolder,
DstFldId = destinationFolder,
SrcMsgId = serverId
};
moveItems.Add(move);
}
MoveItemsRequest moveItemsRequest = Common.CreateMoveItemsRequest(moveItems.ToArray());
// Call MoveItems command to move the items.
MoveItemsResponse moveItemsResponse = this.CONAdapter.MoveItems(moveItemsRequest);
Site.Assert.AreEqual<int>(serverIds.Count, moveItemsResponse.ResponseData.Response.Length, "The count of Response element should be {0}, actual {1}.", serverIds.Count, moveItemsResponse.ResponseData.Response.Length);
foreach (Response.MoveItemsResponse response in moveItemsResponse.ResponseData.Response)
{
Site.Assert.AreEqual<int>(3, int.Parse(response.Status), "If the MoveItems command executes successfully, the Status should be 3, actual {0}.", response.Status);
}
return moveItemsResponse;
}
/// <summary>
/// Gets the created ConversationItem.
/// </summary>
/// <param name="collectionId">The CollectionId of the parent folder which has the conversation.</param>
/// <param name="conversationId">The ConversationId of the conversation.</param>
/// <returns>A ConversationItem object.</returns>
protected ConversationItem GetConversationItem(string collectionId, string conversationId)
{
// Call Sync command to get the emails in Inbox folder.
SyncStore syncStore = this.CallSyncCommand(collectionId, false);
// Get the emails from Sync response according to the ConversationId.
ConversationItem conversationItem = new ConversationItem { ConversationId = conversationId };
foreach (Sync addElement in syncStore.AddElements)
{
if (addElement.Email.ConversationId == conversationId)
{
conversationItem.ServerId.Add(addElement.ServerId);
}
}
Site.Assert.AreNotEqual<int>(0, conversationItem.ServerId.Count, "The conversation should have at least one email.");
return conversationItem;
}
/// <summary>
/// Gets the conversation with the expected emails count.
/// </summary>
/// <param name="collectionId">The CollectionId of the parent folder which has the conversation.</param>
/// <param name="conversationId">The ConversationId of the conversation.</param>
/// <param name="expectEmailCount">The expect count of the conversation emails.</param>
/// <returns>A ConversationItem object.</returns>
protected ConversationItem GetConversationItem(string collectionId, string conversationId, int expectEmailCount)
{
ConversationItem coversationItem;
int counter = 0;
int retryLimit = int.Parse(Common.GetConfigurationPropertyValue("RetryCount", Site));
int waitTime = int.Parse(Common.GetConfigurationPropertyValue("WaitTime", Site));
do
{
System.Threading.Thread.Sleep(waitTime);
coversationItem = this.GetConversationItem(collectionId, conversationId);
counter++;
}
while (coversationItem.ServerId.Count != expectEmailCount && counter < retryLimit);
return coversationItem;
}
/// <summary>
/// Checks if ActiveSync Protocol Version is not "14.0".
/// </summary>
protected void CheckActiveSyncVersionIsNot140()
{
Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The airsyncbase:BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion.");
}
#endregion
#region Capture code
/// <summary>
/// Verify the message part when the request contains neither BodyPreference nor BodyPartPreference elements.
/// </summary>
/// <param name="email">The email item server returned.</param>
protected void VerifyMessagePartWithoutPreference(Email email)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R245");
// Verify MS-ASCON requirement: MS-ASCON_R245
bool isVerifiedR245 = email.Body != null && email.BodyPart == null;
Site.CaptureRequirementIfIsTrue(
isVerifiedR245,
245,
@"[In Sending a Message Part] If request contains neither airsyncbase:BodyPreference nor airsyncbase:BodyPartPreference elements, then the response contains only airsyncbase:Body element.");
}
/// <summary>
/// Verify the message part when the request contains only BodyPreference element.
/// </summary>
/// <param name="email">The email item server returned.</param>
protected void VerifyMessagePartWithBodyPreference(Email email)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R246");
// Verify MS-ASCON requirement: MS-ASCON_R246
bool isVerifiedR246 = email.Body != null && email.BodyPart == null;
Site.CaptureRequirementIfIsTrue(
isVerifiedR246,
246,
@"[In Sending a Message Part] If request contains only airsyncbase:BodyPreference element, then the response contains only airsyncbase:Body element.");
}
/// <summary>
/// Verify the message part when the request contains only BodyPartPreference element.
/// </summary>
/// <param name="email">The email item server returned.</param>
/// <param name="truncatedData">The truncated email data returned in BodyPart.</param>
/// <param name="allData">All email data without being truncated.</param>
/// <param name="truncationSize">The TruncationSize element specified in BodyPartPreference.</param>
protected void VerifyMessagePartWithBodyPartPreference(Email email, string truncatedData, string allData, int truncationSize)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R239");
// Verify MS-ASCON requirement: MS-ASCON_R239
bool isVerifiedR239 = email.BodyPart.TruncatedSpecified && email.BodyPart.Truncated
&& truncatedData == TestSuiteHelper.TruncateData(allData, truncationSize);
Site.CaptureRequirementIfIsTrue(
isVerifiedR239,
239,
@"[In Sending a Message Part] The client's preferences affect the server response as follows: If the size of the message part exceeds the value specified in the airsyncbase:TruncationSize element ([MS-ASAIRS] section 2.2.2.40.1) of the request, then the server truncates the message part.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R240");
// Verify MS-ASCON requirement: MS-ASCON_R240
bool isVerifiedR240 = email.BodyPart.TruncatedSpecified && email.BodyPart.Truncated && email.BodyPart.EstimatedDataSize > 0;
Site.CaptureRequirementIfIsTrue(
isVerifiedR240,
240,
@"[In Sending a Message Part] The server includes the airsyncbase:Truncated element ([MS-ASAIRS] section 2.2.2.39.1) and the airsyncbase:EstimatedDataSize element ([MS-ASAIRS] section 2.2.2.23.2) in the response when it truncates the message part.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R247");
// Verify MS-ASCON requirement: MS-ASCON_R247
bool isVerifiedR247 = email.Body == null && email.BodyPart != null;
Site.CaptureRequirementIfIsTrue(
isVerifiedR247,
247,
@"[In Sending a Message Part] If request contains only airsyncbase:BodyPartPreference element, then the response contains only airsyncbase:BodyPart element.");
}
/// <summary>
/// Verify the message part when the request contains both BodyPreference and BodyPartPreference elements.
/// </summary>
/// <param name="email">The email item server returned.</param>
protected void VerifyMessagePartWithBothPreference(Email email)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R248");
// Verify MS-ASCON requirement: MS-ASCON_R248
bool isVerifiedR248 = email.Body != null && email.BodyPart != null;
Site.CaptureRequirementIfIsTrue(
isVerifiedR248,
248,
@"[In Sending a Message Part] If request contains both airsyncbase:BodyPreference and airsyncbase:BodyPartPreference element, then the response contains both airsyncbase:Body and airsyncbase:BodyPart element.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R243");
// Verify MS-ASCON requirement: MS-ASCON_R243
// If R248 is captured, then BodyPart element and Body element do co-exist in the server response.
Site.CaptureRequirement(
243,
@"[In Sending a Message Part] The airsyncbase:BodyPart element and the airsyncbase:Body element ([MS-ASAIRS] section 2.2.2.9) can co-exist in the server response.");
}
/// <summary>
/// Verify status 164 is returned when the Type element in the BodyPartPreference is other than 2.
/// </summary>
/// <param name="status">The status that server returned.</param>
protected void VerifyMessagePartStatus164(int status)
{
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCON_R241");
// Verify MS-ASCON requirement: MS-ASCON_R241
Site.CaptureRequirementIfAreEqual<int>(
164,
status,
241,
@"[In Sending a Message Part] [The client's preferences affect the server response as follows:] If a value other than 2 is specified in the airsyncbase:Type element ([MS-ASAIRS] section 2.2.2.41.3) of the request, then the server returns a status value of 164.");
}
#endregion
#region Private methods
/// <summary>
/// Delete all the items in a folder.
/// </summary>
/// <param name="createdItems">The created items which should be deleted.</param>
private void DeleteItemsInFolder(Collection<CreatedItems> createdItems)
{
foreach (CreatedItems createdItem in createdItems)
{
SyncStore syncResult = this.CallSyncCommand(createdItem.CollectionId, false);
List<Request.SyncCollectionDelete> deleteData = new List<Request.SyncCollectionDelete>();
List<string> serverIds = new List<string>();
foreach (string subject in createdItem.ItemSubject)
{
if (syncResult != null)
{
foreach (Sync item in syncResult.AddElements)
{
if (item.Email.Subject != null && item.Email.Subject.Equals(subject, StringComparison.CurrentCulture))
{
serverIds.Add(item.ServerId);
}
if (item.Calendar.Subject != null && item.Calendar.Subject.Equals(subject, StringComparison.CurrentCulture))
{
serverIds.Add(item.ServerId);
}
}
}
Site.Assert.AreNotEqual<int>(0, serverIds.Count, "The items with subject '{0}' should be found!", subject);
foreach (string serverId in serverIds)
{
deleteData.Add(new Request.SyncCollectionDelete() { ServerId = serverId });
}
Request.SyncCollection syncCollection = new Request.SyncCollection
{
Commands = deleteData.ToArray(),
DeletesAsMoves = false,
DeletesAsMovesSpecified = true,
CollectionId = createdItem.CollectionId,
SyncKey = syncResult.SyncKey
};
SyncRequest syncRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
SyncStore deleteResult = this.CONAdapter.Sync(syncRequest);
Site.Assert.AreEqual<byte>(
1,
deleteResult.CollectionStatus,
"The value of Status should be 1 to indicate the Sync command executed successfully.");
}
}
}
#endregion
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.Platform.Internal.ARMv6
{
public unsafe static class Runtime
{
private const uint nativeIntSize = 4;
// This method will be plugged by "Mosa.Kernel.AVR32.KernelMemory.AllocateMemory"
private static uint AllocateMemory(uint size)
{
return 0;
}
public static void* AllocateObject(void* methodTable, uint classSize)
{
// An object has the following memory layout:
// - IntPtr MTable
// - IntPtr SyncBlock
// - 0 .. n object data fields
uint allocationSize = (2 * nativeIntSize) + classSize;
void* memory = (void*)AllocateMemory(allocationSize);
uint* destination = (uint*)memory;
destination[0] = (uint)methodTable;
destination[1] = 0; // No sync block initially
return memory;
}
public static void* AllocateArray(void* methodTable, uint elementSize, uint elements)
{
// An array has the following memory layout:
// - IntPtr MTable
// - IntPtr SyncBlock
// - int length
// - ElementType[length] elements
uint allocationSize = (nativeIntSize * 3) + (uint)(elements * elementSize);
void* memory = (void*)AllocateMemory(allocationSize);
uint* destination = (uint*)memory;
destination[0] = (uint)methodTable;
destination[1] = 0; // No sync block initially
destination[2] = elements;
return memory;
}
public static void* AllocateString(void* methodTable, uint length)
{
return AllocateArray(methodTable, 2, length);
}
public static void* GetTypeHandle(uint** obj)
{
// Method table is located at the beginning of object (i.e. *obj )
// Type metadata (TypeDefinition) located at the second of the method table (i.e. *(*obj + 1) )
return (void*)*(*obj + 1);
}
public static uint IsInstanceOfType(uint methodTable, uint obj)
{
if (obj == 0)
return 0;
uint objMethodTable = ((uint*)obj)[0];
while (objMethodTable != 0)
{
if (objMethodTable == methodTable)
return obj;
objMethodTable = ((uint*)objMethodTable)[3];
}
return 0;
}
public static uint IsInstanceOfInterfaceType(int interfaceSlot, uint obj)
{
uint objMethodTable = ((uint*)obj)[0];
if (objMethodTable == 0)
return 0;
uint bitmap = ((uint*)(objMethodTable))[2];
if (bitmap == 0)
return 0;
int index = interfaceSlot / 32;
int bit = interfaceSlot % 32;
uint value = ((uint*)bitmap)[index];
uint result = value & (uint)(1 << bit);
if (result == 0)
return 0;
return obj;
}
public static uint Castclass(uint methodTable, uint obj)
{
//TODO: Fake result
return obj;
}
public static void* BoxChar(void* methodTable, uint classSize, char value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
char* destination = (char*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxBoolean(void* methodTable, uint classSize, bool value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
bool* destination = (bool*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxInt8(void* methodTable, uint classSize, sbyte value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
sbyte* destination = (sbyte*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxUInt8(void* methodTable, uint classSize, uint value)
{
byte* memory = (byte*)AllocateObject(methodTable, 4);
uint* destination = (uint*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxInt16(void* methodTable, uint classSize, short value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
short* destination = (short*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxUInt16(void* methodTable, uint classSize, ushort value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
ushort* destination = (ushort*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxInt32(void* methodTable, uint classSize, int value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
int* destination = (int*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxUInt32(void* methodTable, uint classSize, uint value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
uint* destination = (uint*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxInt64(void* methodTable, uint classSize, long value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
long* destination = (long*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxUInt64(void* methodTable, uint classSize, ulong value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
ulong* destination = (ulong*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxSingle(void* methodTable, uint classSize, float value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
float* destination = (float*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static void* BoxDouble(void* methodTable, uint classSize, double value)
{
byte* memory = (byte*)AllocateObject(methodTable, classSize);
double* destination = (double*)(memory + (nativeIntSize * 2));
destination[0] = value;
return memory;
}
public static char UnboxChar(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((char*)memory)[0];
}
public static bool UnboxBoolean(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((bool*)memory)[0];
}
public static sbyte UnboxInt8(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((sbyte*)memory)[0];
}
public static byte UnboxUInt8(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((byte*)memory)[0];
}
public static short UnboxInt16(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((short*)memory)[0];
}
public static ushort UnboxUInt16(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((ushort*)memory)[0];
}
public static int UnboxInt32(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((int*)memory)[0];
}
public static uint UnboxUInt32(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((uint*)memory)[0];
}
public static long UnboxInt64(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((long*)memory)[0];
}
public static ulong UnboxUInt64(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((ulong*)memory)[0];
}
public static float UnboxSingle(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((float*)memory)[0];
}
public static double UnboxDouble(void* obj)
{
byte* memory = (byte*)obj + (nativeIntSize * 2);
return ((double*)memory)[0];
}
public static void Throw(uint something)
{
}
public static uint GetSizeOfObject(void* obj)
{
void* methodTable = (void*)((uint*)obj)[0];
return GetSizeOfType((void*)methodTable);
}
public static uint GetSizeOfType(void* methodTable)
{
uint definitionTable = ((uint*)methodTable)[4];
if (definitionTable == 0)
return 0; // Not good
uint sizeOf = ((uint*)definitionTable)[0];
return sizeOf;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite
{
[TestClass]
public class FileLevelTrim : SMB2TestBase
{
#region Variables
private Smb2FunctionalClient client;
private uint status;
private string fileName;
private string uncSharePath;
private string contentWrite;
#endregion
#region Test Initialize and Cleanup
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
#region Test Case Initialize and Clean up
protected override void TestInitialize()
{
base.TestInitialize();
client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
fileName = "FileLevelTrim_" + Guid.NewGuid() + ".txt";
uncSharePath = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare);
contentWrite = Smb2Utility.CreateRandomString(TestConfig.WriteBufferLengthInKb);
}
protected override void TestCleanup()
{
if (client != null)
{
try
{
client.Disconnect();
}
catch (Exception ex)
{
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"Unexpected exception when disconnect client: {0}", ex.ToString());
}
}
base.TestCleanup();
}
#endregion
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.FsctlFileLevelTrim)]
[Description("This test case is designed to test basic functionality of FSCTL_FILE_LEVEL_TRIM.")]
public void BVT_FileLevelTrim()
{
uint treeId;
FILEID fileId;
PrepareFileForTrimming(out treeId, out fileId);
FSCTL_FILE_LEVEL_TRIM_RANGE fileLevelTrimRange;
Random random = new Random();
uint offset = (uint)random.Next(0, TestConfig.WriteBufferLengthInKb * 1024);
uint length = (uint)random.Next(0, (int)(TestConfig.WriteBufferLengthInKb * 1024 - offset));
fileLevelTrimRange.Offset = offset;
fileLevelTrimRange.Length = length;
FSCTL_FILE_LEVEL_TRIM_INPUT fileLevelTrimInput;
fileLevelTrimInput.Key = 0;
fileLevelTrimInput.NumRanges = 1;
fileLevelTrimInput.Ranges = new FSCTL_FILE_LEVEL_TRIM_RANGE[] { fileLevelTrimRange };
byte[] buffer = TypeMarshal.ToBytes<FSCTL_FILE_LEVEL_TRIM_INPUT>(fileLevelTrimInput);
byte[] respOutput;
status = client.FileLevelTrim(
treeId,
fileId,
buffer,
out respOutput,
(header, response) => BaseTestSite.Assert.AreEqual(
true,
header.Status == Smb2Status.STATUS_SUCCESS || header.Status == Smb2Status.STATUS_NO_RANGES_PROCESSED,
// The operation was successful, but no range was processed.
"{0} should complete with STATUS_SUCCESS or STATUS_NO_RANGES_PROCESSED, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status)));
if (status != Smb2Status.STATUS_NO_RANGES_PROCESSED // Skip parsing the response when server returns STATUS_NO_RANGES_PROCESSED
&& respOutput != null) // Skip parsing the response if no output buffer is returned
{
FSCTL_FILE_LEVEL_TRIM_OUTPUT fileLevelTrimOutput = TypeMarshal.ToStruct<FSCTL_FILE_LEVEL_TRIM_OUTPUT>(respOutput);
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"Number of ranges that were processed: {0}", fileLevelTrimOutput.NumRangesProcessed);
}
else
{
BaseTestSite.Log.Add(LogEntryKind.Debug, "No range was processed during this operation.");
}
status = client.Close(treeId, fileId);
status = client.TreeDisconnect(treeId);
status = client.LogOff();
}
[TestMethod]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.FsctlFileLevelTrim)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Test the server response when non-zero value is set to the Key field of FSCTL_FILE_LEVEL_TRIM request.")]
public void FileLevelTrim_Negative_NonZeroKeyInRequest()
{
uint treeId;
FILEID fileId;
PrepareFileForTrimming(out treeId, out fileId);
FSCTL_FILE_LEVEL_TRIM_RANGE fileLevelTrimRange;
Random random = new Random();
uint offset = (uint)random.Next(0, TestConfig.WriteBufferLengthInKb * 1024);
uint length = (uint)random.Next(0, (int)(TestConfig.WriteBufferLengthInKb * 1024 - offset));
fileLevelTrimRange.Offset = offset;
fileLevelTrimRange.Length = length;
FSCTL_FILE_LEVEL_TRIM_INPUT fileLevelTrimInput;
fileLevelTrimInput.Key = (uint)random.Next(1, int.MaxValue); // Set the Key field a non-zero value
fileLevelTrimInput.NumRanges = 1;
fileLevelTrimInput.Ranges = new FSCTL_FILE_LEVEL_TRIM_RANGE[] { fileLevelTrimRange };
byte[] buffer = TypeMarshal.ToBytes<FSCTL_FILE_LEVEL_TRIM_INPUT>(fileLevelTrimInput);
byte[] respOutput;
status = client.FileLevelTrim(
treeId,
fileId,
buffer,
out respOutput,
(header, response) => Assert.AreEqual(
Smb2Status.STATUS_INVALID_PARAMETER,
header.Status,
"If the Key field in FSCTL_FILE_LEVEL_TRIM, as specified in [MS-FSCC] section 2.3.73, is not zero," +
" the server MUST fail the request with an error code of STATUS_INVALID_PARAMETER. " +
"Actually server returns {0}.", Smb2Status.GetStatusCode(header.Status)));
}
private void PrepareFileForTrimming(out uint treeId, out FILEID fileId)
{
#region Check Applicability
TestConfig.CheckDialect(DialectRevision.Smb30);
TestConfig.CheckIOCTL(CtlCode_Values.FSCTL_FILE_LEVEL_TRIM);
#endregion
client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
status = client.Negotiate(
TestConfig.RequestDialects,
TestConfig.IsSMB1NegotiateEnabled,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"CREATE should succeed, actually server returns {0}.", Smb2Status.GetStatusCode(header.Status));
TestConfig.CheckNegotiateDialect(DialectRevision.Smb30, response);
});
status = client.SessionSetup(
TestConfig.DefaultSecurityPackage,
TestConfig.SutComputerName,
TestConfig.AccountCredential,
TestConfig.UseServerGssToken);
status = client.TreeConnect(uncSharePath, out treeId);
Smb2CreateContextResponse[] serverCreateContexts;
status = client.Create(
treeId,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileId,
out serverCreateContexts);
status = client.Write(treeId, fileId, contentWrite);
status = client.Close(treeId, fileId);
status = client.Create(
treeId,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileId,
out serverCreateContexts);
}
}
}
| |
namespace Humidifier.IoTAnalytics
{
using System.Collections.Generic;
using PipelineTypes;
public class Pipeline : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::IoTAnalytics::Pipeline";
}
}
/// <summary>
/// PipelineName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iotanalytics-pipeline.html#cfn-iotanalytics-pipeline-pipelinename
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic PipelineName
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iotanalytics-pipeline.html#cfn-iotanalytics-pipeline-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
/// <summary>
/// PipelineActivities
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iotanalytics-pipeline.html#cfn-iotanalytics-pipeline-pipelineactivities
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// ItemType: Activity
/// </summary>
public List<Activity> PipelineActivities
{
get;
set;
}
}
namespace PipelineTypes
{
public class DeviceShadowEnrich
{
/// <summary>
/// Attribute
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-attribute
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Attribute
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// ThingName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-thingname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ThingName
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-rolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class Lambda
{
/// <summary>
/// BatchSize
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-lambda.html#cfn-iotanalytics-pipeline-lambda-batchsize
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic BatchSize
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-lambda.html#cfn-iotanalytics-pipeline-lambda-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// LambdaName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-lambda.html#cfn-iotanalytics-pipeline-lambda-lambdaname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LambdaName
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-lambda.html#cfn-iotanalytics-pipeline-lambda-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class SelectAttributes
{
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-selectattributes.html#cfn-iotanalytics-pipeline-selectattributes-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Attributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-selectattributes.html#cfn-iotanalytics-pipeline-selectattributes-attributes
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Attributes_
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-selectattributes.html#cfn-iotanalytics-pipeline-selectattributes-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class Channel
{
/// <summary>
/// ChannelName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-channel.html#cfn-iotanalytics-pipeline-channel-channelname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ChannelName
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-channel.html#cfn-iotanalytics-pipeline-channel-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-channel.html#cfn-iotanalytics-pipeline-channel-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class Filter
{
/// <summary>
/// Filter
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-filter.html#cfn-iotanalytics-pipeline-filter-filter
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Filter_
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-filter.html#cfn-iotanalytics-pipeline-filter-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-filter.html#cfn-iotanalytics-pipeline-filter-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class Activity
{
/// <summary>
/// SelectAttributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-selectattributes
/// Required: False
/// UpdateType: Mutable
/// Type: SelectAttributes
/// </summary>
public SelectAttributes SelectAttributes
{
get;
set;
}
/// <summary>
/// Datastore
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-datastore
/// Required: False
/// UpdateType: Mutable
/// Type: Datastore
/// </summary>
public Datastore Datastore
{
get;
set;
}
/// <summary>
/// Filter
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-filter
/// Required: False
/// UpdateType: Mutable
/// Type: Filter
/// </summary>
public Filter Filter
{
get;
set;
}
/// <summary>
/// AddAttributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-addattributes
/// Required: False
/// UpdateType: Mutable
/// Type: AddAttributes
/// </summary>
public AddAttributes AddAttributes
{
get;
set;
}
/// <summary>
/// Channel
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-channel
/// Required: False
/// UpdateType: Mutable
/// Type: Channel
/// </summary>
public Channel Channel
{
get;
set;
}
/// <summary>
/// DeviceShadowEnrich
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-deviceshadowenrich
/// Required: False
/// UpdateType: Mutable
/// Type: DeviceShadowEnrich
/// </summary>
public DeviceShadowEnrich DeviceShadowEnrich
{
get;
set;
}
/// <summary>
/// Math
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-math
/// Required: False
/// UpdateType: Mutable
/// Type: Math
/// </summary>
public Math Math
{
get;
set;
}
/// <summary>
/// Lambda
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-lambda
/// Required: False
/// UpdateType: Mutable
/// Type: Lambda
/// </summary>
public Lambda Lambda
{
get;
set;
}
/// <summary>
/// DeviceRegistryEnrich
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-deviceregistryenrich
/// Required: False
/// UpdateType: Mutable
/// Type: DeviceRegistryEnrich
/// </summary>
public DeviceRegistryEnrich DeviceRegistryEnrich
{
get;
set;
}
/// <summary>
/// RemoveAttributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-activity.html#cfn-iotanalytics-pipeline-activity-removeattributes
/// Required: False
/// UpdateType: Mutable
/// Type: RemoveAttributes
/// </summary>
public RemoveAttributes RemoveAttributes
{
get;
set;
}
}
public class Math
{
/// <summary>
/// Attribute
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-math.html#cfn-iotanalytics-pipeline-math-attribute
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Attribute
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-math.html#cfn-iotanalytics-pipeline-math-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Math
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-math.html#cfn-iotanalytics-pipeline-math-math
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Math_
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-math.html#cfn-iotanalytics-pipeline-math-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class RemoveAttributes
{
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-removeattributes.html#cfn-iotanalytics-pipeline-removeattributes-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Attributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-removeattributes.html#cfn-iotanalytics-pipeline-removeattributes-attributes
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Attributes_
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-removeattributes.html#cfn-iotanalytics-pipeline-removeattributes-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class Datastore
{
/// <summary>
/// DatastoreName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-datastore.html#cfn-iotanalytics-pipeline-datastore-datastorename
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DatastoreName
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-datastore.html#cfn-iotanalytics-pipeline-datastore-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class AddAttributes
{
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// Attributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-attributes
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Json
/// </summary>
public dynamic Attributes_
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-addattributes.html#cfn-iotanalytics-pipeline-addattributes-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class DeviceRegistryEnrich
{
/// <summary>
/// Attribute
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceregistryenrich.html#cfn-iotanalytics-pipeline-deviceregistryenrich-attribute
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Attribute
{
get;
set;
}
/// <summary>
/// Next
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceregistryenrich.html#cfn-iotanalytics-pipeline-deviceregistryenrich-next
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Next
{
get;
set;
}
/// <summary>
/// ThingName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceregistryenrich.html#cfn-iotanalytics-pipeline-deviceregistryenrich-thingname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ThingName
{
get;
set;
}
/// <summary>
/// RoleArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceregistryenrich.html#cfn-iotanalytics-pipeline-deviceregistryenrich-rolearn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RoleArn
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceregistryenrich.html#cfn-iotanalytics-pipeline-deviceregistryenrich-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
}
}
| |
using System;
using SharpVectors.Dom.Events;
namespace SharpVectors.Dom.Events
{
/// <summary>
/// Summary description for EventListenerMap.
/// </summary>
public class EventListenerMap
{
#region Private Fields
private const int GrowthBuffer = 8;
private const int GrowthFactor = 2;
private EventListenerMapEntry[] entries;
private int count;
private bool locked;
#endregion
#region Private Helpers
private EventListenerMapEntry[] GrowBy(
int growth)
{
if (entries == null)
{
entries = new EventListenerMapEntry[
growth * GrowthFactor + GrowthBuffer];
this.count = 0;
this.locked = false;
return entries;
}
int newCount = count + growth;
if (newCount > entries.Length)
{
newCount = newCount * GrowthFactor + GrowthBuffer;
EventListenerMapEntry[] newEntries =
new EventListenerMapEntry[newCount];
Array.Copy(entries, 0, newEntries, 0, entries.Length);
entries = newEntries;
}
return entries;
}
#endregion
#region Public Methods
public void AddEventListener(
string namespaceUri,
string eventType,
object eventGroup,
EventListener listener)
{
EventListenerMapEntry[] entries = GrowBy(1);
for (int i = 0; i < count; i++)
{
if (namespaceUri != entries[i].NamespaceUri)
{
continue;
}
if (eventType != entries[i].Type)
{
continue;
}
if (listener == entries[i].Listener)
{
return;
}
}
entries[count] = new EventListenerMapEntry(
namespaceUri, eventType, eventGroup, listener, locked);
count++;
}
public void RemoveEventListener(
string namespaceUri,
string eventType,
EventListener listener)
{
if (entries == null)
{
return;
}
for (int i = 0; i < count; i++)
{
if (namespaceUri != entries[i].NamespaceUri)
{
continue;
}
if (eventType != entries[i].Type)
{
continue;
}
if (listener == entries[i].Listener)
{
count--;
entries[i] = entries[count];
entries[count] = new EventListenerMapEntry();
return;
}
}
}
public void FireEvent(
IEvent @event)
{
string namespaceUri = @event.NamespaceUri;
string eventType = @event.Type;
for (int i = 0; i < count; i++)
{
// Check if the entry was added during this phase
if (entries[i].Locked)
continue;
string entryNamespaceUri = entries[i].NamespaceUri;
string entryEventType = entries[i].Type;
if (entryNamespaceUri != null && namespaceUri != null)
{
if (entryNamespaceUri != namespaceUri)
{
continue;
}
}
if (entryEventType != eventType)
{
continue;
}
entries[i].Listener(@event);
}
}
public bool HasEventListenerNs(
string namespaceUri,
string eventType)
{
if (entries == null)
{
return false;
}
for (int i = 0; i < count; i++)
{
if (namespaceUri != entries[i].NamespaceUri)
{
continue;
}
if (eventType != entries[i].Type)
{
continue;
}
return true;
}
return false;
}
public void Lock()
{
locked = true;
}
public void Unlock()
{
// Unlock the map
locked = false;
// Unlock pending entries
for (int i = 0; i < count; i++)
{
entries[i].Locked = false;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Compute.Tests
{
public class VMOperationalTests : VMTestBase
{
class Image
{
[JsonProperty("uri")]
public string Uri { get; set; }
}
class OSDisk
{
[JsonProperty("image")]
public Image Image { get; set; }
}
class StorageProfile
{
[JsonProperty("osDisk")]
public OSDisk OSDisk { get; set; }
}
class Properties
{
[JsonProperty("storageProfile")]
public StorageProfile StorageProfile { get; set; }
}
class Resource
{
[JsonProperty("properties")]
public Properties Properties { get; set; }
}
class Template
{
[JsonProperty("resources")]
public List<Resource> Resources { get; set; }
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// GET VM Model View
/// Start VM
/// Stop VM
/// Restart VM
/// RunCommand VM
/// Deallocate VM
/// Generalize VM
/// Capture VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true, sku: "2019-Datacenter-smalldisk");
// Create resource group
string rg1Name = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1;
string as1Name = ComputeManagementTestUtilities.GenerateName("as");
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, as1Name, storageAccountOutput, imageRef, out inputVM1);
m_CrpClient.VirtualMachines.Start(rg1Name, vm1.Name);
m_CrpClient.VirtualMachines.Redeploy(rg1Name, vm1.Name);
m_CrpClient.VirtualMachines.Restart(rg1Name, vm1.Name);
m_CrpClient.VirtualMachines.PowerOff(rg1Name, vm1.Name);
m_CrpClient.VirtualMachines.Deallocate(rg1Name, vm1.Name);
m_CrpClient.VirtualMachines.Generalize(rg1Name, vm1.Name);
VirtualMachine ephemeralVM;
string as2Name = as1Name + "_ephemeral";
CreateVM(rg1Name, as2Name, storageAccountName, imageRef, out ephemeralVM, hasManagedDisks: true, hasDiffDisks: true, vmSize: VirtualMachineSizeTypes.StandardDS5V2,
osDiskStorageAccountType: StorageAccountTypes.StandardLRS, dataDiskStorageAccountType: StorageAccountTypes.StandardLRS);
m_CrpClient.VirtualMachines.Reimage(rg1Name, ephemeralVM.Name, tempDisk: true);
var captureParams = new VirtualMachineCaptureParameters
{
DestinationContainerName = ComputeManagementTestUtilities.GenerateName(TestPrefix),
VhdPrefix = ComputeManagementTestUtilities.GenerateName(TestPrefix),
OverwriteVhds = true
};
var captureResponse = m_CrpClient.VirtualMachines.Capture(rg1Name, vm1.Name, captureParams);
Assert.NotNull(captureResponse);
Assert.True(captureResponse.Resources.Count > 0);
string resource = captureResponse.Resources[0].ToString();
Assert.Contains(captureParams.DestinationContainerName.ToLowerInvariant(), resource.ToLowerInvariant());
Assert.Contains(captureParams.VhdPrefix.ToLowerInvariant(), resource.ToLowerInvariant());
Resource template = JsonConvert.DeserializeObject<Resource>(resource);
string imageUri = template.Properties.StorageProfile.OSDisk.Image.Uri;
Assert.False(string.IsNullOrEmpty(imageUri));
// Create 3rd VM from the captured image
// TODO : Provisioning Time-out Issues
VirtualMachine inputVM2;
string as3Name = as1Name + "b";
VirtualMachine vm3 = CreateVM(rg1Name, as3Name, storageAccountOutput, imageRef, out inputVM2,
vm =>
{
vm.StorageProfile.ImageReference = null;
vm.StorageProfile.OsDisk.Image = new VirtualHardDisk { Uri = imageUri };
vm.StorageProfile.OsDisk.Vhd.Uri = vm.StorageProfile.OsDisk.Vhd.Uri.Replace(".vhd", "copy.vhd");
vm.StorageProfile.OsDisk.OsType = OperatingSystemTypes.Windows;
}, false, false);
Assert.True(vm3.StorageProfile.OsDisk.Image.Uri == imageUri);
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rg1Name);
}
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// GET VM Model View
/// Redeploy VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_Redeploy()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1;
string asName = TestUtilities.GenerateName("as");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
bool passed = false;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef,
out inputVM1);
var redeployOperationResponse = m_CrpClient.VirtualMachines.BeginRedeployWithHttpMessagesAsync(rg1Name, vm1.Name);
//Assert.Equal(HttpStatusCode.Accepted, redeployOperationResponse.Result.Response.StatusCode);
var lroResponse = m_CrpClient.VirtualMachines.RedeployWithHttpMessagesAsync(rg1Name,
vm1.Name).GetAwaiter().GetResult();
//Assert.Equal(ComputeOperationStatus.Succeeded, lroResponse.Status);
passed = true;
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name);
//Assert.True(deleteRg1Response.StatusCode == HttpStatusCode.Accepted,
// "BeginDeleting status was not Accepted.");
}
Assert.True(passed);
}
}
[Fact]
public void TestVMOperations_Reapply()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1;
string asName = TestUtilities.GenerateName("as");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
bool passed = false;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef,
out inputVM1);
var reapplyperationResponse = m_CrpClient.VirtualMachines.BeginReapplyWithHttpMessagesAsync(rg1Name, vm1.Name);
var lroResponse = m_CrpClient.VirtualMachines.ReapplyWithHttpMessagesAsync(rg1Name,
vm1.Name).GetAwaiter().GetResult();
passed = true;
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name);
}
Assert.True(passed);
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create VM
/// Start VM
/// Shutdown VM with skipShutdown = true
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_PowerOffWithSkipShutdown()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1;
string asName = TestUtilities.GenerateName("as");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
bool passed = false;
try
{
// Create Storage Account for this VM
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef,
out inputVM1);
m_CrpClient.VirtualMachines.Start(rg1Name, vm1.Name);
// Shutdown VM with SkipShutdown = true
m_CrpClient.VirtualMachines.PowerOff(rg1Name, vm1.Name, true);
passed = true;
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name);
}
Assert.True(passed);
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// GET VM Model View
/// PerformMaintenance VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_PerformMaintenance()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1;
string asName = TestUtilities.GenerateName("as");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1 = null;
bool passed = false;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, asName, storageAccountOutput, imageRef,
out inputVM1);
m_CrpClient.VirtualMachines.PerformMaintenance(rg1Name, vm1.Name);
passed = true;
}
catch (CloudException cex)
{
passed = true;
string expectedMessage = $"Operation 'performMaintenance' is not allowed on VM '{inputVM1.Name}' since the Subscription of this VM" +
" is not eligible.";
Assert.Equal(expectedMessage, cex.Message);
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name);
}
Assert.True(passed);
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// Call SimulateEviction on that VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_SimulateEviction()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = TestUtilities.GenerateName(TestPrefix) + 1;
string asName = TestUtilities.GenerateName("as");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
bool passed = false;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name,
asName,
storageAccountOutput.Name,
imageRef,
out inputVM1,
(virtualMachine) =>
{
virtualMachine.Priority = VirtualMachinePriorityTypes.Spot;
virtualMachine.AvailabilitySet = null;
virtualMachine.BillingProfile = new BillingProfile { MaxPrice = -1 };
},
vmSize: VirtualMachineSizeTypes.StandardA1V2);
m_CrpClient.VirtualMachines.SimulateEviction(rg1Name, vm1.Name);
passed = true;
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
var deleteRg1Response = m_ResourcesClient.ResourceGroups.BeginDeleteWithHttpMessagesAsync(rg1Name);
}
Assert.True(passed);
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// Call RunCommand on that VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_RunCommand()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
// Create resource group
string rg1Name = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1;
string as1Name = ComputeManagementTestUtilities.GenerateName("as");
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
VirtualMachine inputVM1;
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rg1Name, storageAccountName);
VirtualMachine vm1 = CreateVM(rg1Name, as1Name, storageAccountOutput, imageRef, out inputVM1);
var runCommandImput = new RunCommandInput()
{
CommandId = "RunPowerShellScript",
Script = new List<string>() {
"param(",
" [string]$arg1,",
" [string]$arg2",
")",
"echo This is a sample script with parameters $arg1 $arg2"
},
Parameters = new List<RunCommandInputParameter>()
{
new RunCommandInputParameter("arg1","value1"),
new RunCommandInputParameter("arg2","value2"),
}
};
RunCommandResult result = m_CrpClient.VirtualMachines.RunCommand(rg1Name, vm1.Name, runCommandImput);
Assert.NotNull(result);
Assert.NotNull(result.Value);
Assert.True(result.Value.Count > 0);
}
finally
{
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rg1Name);
}
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources
/// Create VM
/// Hibernate VM
/// Start VM
/// Delete RG
/// </summary>
[Fact]
public void TestVMOperations_HibernateResume()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
// Hard code the location to "eastus2euap".
// This is because Hibernate support is in canary currently and is not available worldwide.
// Before changing the default location, we have to save it to be reset it at the end of the test.
// Since ComputeManagementTestUtilities.DefaultLocation is a static variable and can affect other tests if it is not reset.
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2euap");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true, sku: "2019-Datacenter");
// Create resource group
string rgName = ComputeManagementTestUtilities.GenerateName(TestPrefix) + 1;
string asName = ComputeManagementTestUtilities.GenerateName("as");
string storageAccountName = ComputeManagementTestUtilities.GenerateName(TestPrefix);
try
{
// Create Storage Account, so that both the VMs can share it
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
Action<VirtualMachine> vmCustomizer = customizedVM =>
{
customizedVM.AvailabilitySet = null;
customizedVM.AdditionalCapabilities = new AdditionalCapabilities
{
HibernationEnabled = true
};
};
VirtualMachine vm = CreateVM(rgName, asName, storageAccountName, imageRef, out VirtualMachine inputVM, vmCustomizer: vmCustomizer,
hasManagedDisks: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3);
Assert.NotNull(vm.AdditionalCapabilities);
Assert.True(vm.AdditionalCapabilities.HibernationEnabled, "VM should have hibernation enabled");
// Hibernating the VM and validating instance view status
m_CrpClient.VirtualMachines.Deallocate(rgName, vm.Name, hibernate: true);
var instanceViewResponse = m_CrpClient.VirtualMachines.InstanceView(rgName, inputVM.Name);
Assert.NotNull(instanceViewResponse);
List<InstanceViewStatus> actualInstanceViewStatuses = instanceViewResponse.Statuses.ToList();
Assert.True(actualInstanceViewStatuses[1].Code == "PowerState/deallocated",
"Powerstates doesn't match after hibernate operation");
Assert.True(actualInstanceViewStatuses[1].DisplayStatus == "VM deallocated",
"Powerstates doesn't match after hibernate operation");
Assert.True(instanceViewResponse.Statuses[2].Code == "HibernationState/Hibernated",
"Hibernation status doesn't match after hibernate operation");
Assert.True(instanceViewResponse.Statuses[2].DisplayStatus == "VM hibernated",
"Hibernation status doesn't match after hibernate operation");
// Resuming the VM and validating instance view status
m_CrpClient.VirtualMachines.Start(rgName, vm.Name);
instanceViewResponse = m_CrpClient.VirtualMachines.InstanceView(rgName, inputVM.Name);
Assert.NotNull(instanceViewResponse);
actualInstanceViewStatuses = instanceViewResponse.Statuses.ToList();
Assert.True(actualInstanceViewStatuses[1].Code == "PowerState/running",
"Powerstates doesn't match after resume operation");
Assert.True(actualInstanceViewStatuses[1].DisplayStatus == "VM running",
"Powerstates doesn't match after resume operation");
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
// Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
// of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.BeginDelete(rgName);
}
}
}
}
}
| |
using System;
using System.IO;
namespace Org.BouncyCastle.Asn1
{
public class Asn1StreamParser
{
private readonly Stream _in;
private readonly int _limit;
public Asn1StreamParser(
Stream inStream)
: this(inStream, Asn1InputStream.FindLimit(inStream))
{
}
public Asn1StreamParser(
Stream inStream,
int limit)
{
if (!inStream.CanRead)
throw new ArgumentException(@"Expected stream to be readable", "inStream");
this._in = inStream;
this._limit = limit;
}
public Asn1StreamParser(
byte[] encoding)
: this(new MemoryStream(encoding, false), encoding.Length)
{
}
internal IAsn1Convertible ReadIndef(int tagValue)
{
// Note: INDEF => CONSTRUCTED
// TODO There are other tags that may be constructed (e.g. BIT_STRING)
switch (tagValue)
{
case Asn1Tags.External:
return new DerExternalParser(this);
case Asn1Tags.OctetString:
return new BerOctetStringParser(this);
case Asn1Tags.Sequence:
return new BerSequenceParser(this);
case Asn1Tags.Set:
return new BerSetParser(this);
default:
throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X"));
}
}
internal IAsn1Convertible ReadImplicit(bool constructed, int tag)
{
if (_in is IndefiniteLengthInputStream)
{
if (!constructed)
throw new IOException("indefinite length primitive encoding encountered");
return ReadIndef(tag);
}
if (constructed)
{
switch (tag)
{
case Asn1Tags.Set:
return new DerSetParser(this);
case Asn1Tags.Sequence:
return new DerSequenceParser(this);
case Asn1Tags.OctetString:
return new BerOctetStringParser(this);
}
}
else
{
switch (tag)
{
case Asn1Tags.Set:
throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)");
case Asn1Tags.Sequence:
throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)");
case Asn1Tags.OctetString:
return new DerOctetStringParser((DefiniteLengthInputStream)_in);
}
}
throw new Asn1Exception("implicit tagging not implemented");
}
internal Asn1Object ReadTaggedObject(bool constructed, int tag)
{
if (!constructed)
{
// Note: !CONSTRUCTED => IMPLICIT
DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in;
return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray()));
}
Asn1EncodableVector v = ReadVector();
if (_in is IndefiniteLengthInputStream)
{
return v.Count == 1
? new BerTaggedObject(true, tag, v[0])
: new BerTaggedObject(false, tag, BerSequence.FromVector(v));
}
return v.Count == 1
? new DerTaggedObject(true, tag, v[0])
: new DerTaggedObject(false, tag, DerSequence.FromVector(v));
}
public virtual IAsn1Convertible ReadObject()
{
int tag = _in.ReadByte();
if (tag == -1)
return null;
// turn of looking for "00" while we resolve the tag
Set00Check(false);
//
// calculate tag number
//
int tagNo = Asn1InputStream.ReadTagNumber(_in, tag);
bool isConstructed = (tag & Asn1Tags.Constructed) != 0;
//
// calculate length
//
int length = Asn1InputStream.ReadLength(_in, _limit);
if (length < 0) // indefinite length method
{
if (!isConstructed)
throw new IOException("indefinite length primitive encoding encountered");
IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit);
Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit);
if ((tag & Asn1Tags.Application) != 0)
{
return new BerApplicationSpecificParser(tagNo, sp);
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(true, tagNo, sp);
}
return sp.ReadIndef(tagNo);
}
else
{
DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length);
if ((tag & Asn1Tags.Application) != 0)
{
return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray());
}
if ((tag & Asn1Tags.Tagged) != 0)
{
return new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn));
}
if (isConstructed)
{
// TODO There are other tags that may be constructed (e.g. BitString)
switch (tagNo)
{
case Asn1Tags.OctetString:
//
// yes, people actually do this...
//
return new BerOctetStringParser(new Asn1StreamParser(defIn));
case Asn1Tags.Sequence:
return new DerSequenceParser(new Asn1StreamParser(defIn));
case Asn1Tags.Set:
return new DerSetParser(new Asn1StreamParser(defIn));
case Asn1Tags.External:
return new DerExternalParser(new Asn1StreamParser(defIn));
default:
// TODO Add DerUnknownTagParser class?
return new DerUnknownTag(true, tagNo, defIn.ToArray());
}
}
// Some primitive encodings can be handled by parsers too...
switch (tagNo)
{
case Asn1Tags.OctetString:
return new DerOctetStringParser(defIn);
}
try
{
return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn.ToArray());
}
catch (ArgumentException e)
{
throw new Asn1Exception("corrupted stream detected", e);
}
}
}
private void Set00Check(
bool enabled)
{
if (_in is IndefiniteLengthInputStream)
{
((IndefiniteLengthInputStream) _in).SetEofOn00(enabled);
}
}
internal Asn1EncodableVector ReadVector()
{
Asn1EncodableVector v = new Asn1EncodableVector();
IAsn1Convertible obj;
while ((obj = ReadObject()) != null)
{
v.Add(obj.ToAsn1Object());
}
return v;
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.Rfc2251.RfcLdapMessage.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
using System.IO;
using Novell.Directory.Ldap.Asn1;
namespace Novell.Directory.Ldap.Rfc2251
{
/// <summary>
/// Represents an Ldap Message.
/// <pre>
/// LdapMessage ::= SEQUENCE {
/// messageID MessageID,
/// protocolOp CHOICE {
/// bindRequest BindRequest,
/// bindResponse BindResponse,
/// unbindRequest UnbindRequest,
/// searchRequest SearchRequest,
/// searchResEntry SearchResultEntry,
/// searchResDone SearchResultDone,
/// searchResRef SearchResultReference,
/// modifyRequest ModifyRequest,
/// modifyResponse ModifyResponse,
/// addRequest AddRequest,
/// addResponse AddResponse,
/// delRequest DelRequest,
/// delResponse DelResponse,
/// modDNRequest ModifyDNRequest,
/// modDNResponse ModifyDNResponse,
/// compareRequest CompareRequest,
/// compareResponse CompareResponse,
/// abandonRequest AbandonRequest,
/// extendedReq ExtendedRequest,
/// extendedResp ExtendedResponse },
/// controls [0] Controls OPTIONAL }
/// </pre>
/// Note: The creation of a MessageID should be hidden within the creation of
/// an RfcLdapMessage. The MessageID needs to be in sequence, and has an
/// upper and lower limit. There is never a case when a user should be
/// able to specify the MessageID for an RfcLdapMessage. The MessageID()
/// constructor should be package protected. (So the MessageID value
/// isn't arbitrarily run up.)
/// </summary>
public class RfcLdapMessage : Asn1Sequence
{
/// <summary> Returns this RfcLdapMessage's messageID as an int.</summary>
public virtual int MessageID
{
get { return ((Asn1Integer) get_Renamed(0)).intValue(); }
}
/// <summary> Returns this RfcLdapMessage's message type</summary>
public virtual int Type
{
get { return get_Renamed(1).getIdentifier().Tag; }
}
/// <summary>
/// Returns the response associated with this RfcLdapMessage.
/// Can be one of RfcLdapResult, RfcBindResponse, RfcExtendedResponse
/// all which extend RfcResponse. It can also be
/// RfcSearchResultEntry, or RfcSearchResultReference
/// </summary>
public virtual Asn1Object Response
{
get { return get_Renamed(1); }
}
/// <summary> Returns the optional Controls for this RfcLdapMessage.</summary>
public virtual RfcControls Controls
{
get
{
if (size() > 2)
return (RfcControls) get_Renamed(2);
return null;
}
}
/// <summary> Returns the dn of the request, may be null</summary>
public virtual string RequestDN
{
get { return ((RfcRequest) op).getRequestDN(); }
}
/// <summary>
/// returns the original request in this message
/// </summary>
/// <returns>
/// the original msg request for this response
/// </returns>
/// <summary>
/// sets the original request in this message
/// </summary>
/// <param name="msg">
/// the original request for this response
/// </param>
public virtual LdapMessage RequestingMessage
{
get { return requestMessage; }
set { requestMessage = value; }
}
private readonly Asn1Object op;
private RfcControls controls;
private LdapMessage requestMessage;
/// <summary>
/// Create an RfcLdapMessage by copying the content array
/// </summary>
/// <param name="origContent">
/// the array list to copy
/// </param>
internal RfcLdapMessage(Asn1Object[] origContent, RfcRequest origRequest, string dn, string filter,
bool reference) : base(origContent, origContent.Length)
{
set_Renamed(0, new RfcMessageID()); // MessageID has static counter
var req = (RfcRequest) origContent[1];
var newreq = req.dupRequest(dn, filter, reference);
op = (Asn1Object) newreq;
set_Renamed(1, (Asn1Object) newreq);
}
/// <summary> Create an RfcLdapMessage using the specified Ldap Request.</summary>
public RfcLdapMessage(RfcRequest op) : this(op, null)
{
}
/// <summary> Create an RfcLdapMessage request from input parameters.</summary>
public RfcLdapMessage(RfcRequest op, RfcControls controls) : base(3)
{
this.op = (Asn1Object) op;
this.controls = controls;
add(new RfcMessageID()); // MessageID has static counter
add((Asn1Object) op);
if (controls != null)
{
add(controls);
}
}
/// <summary> Create an RfcLdapMessage using the specified Ldap Response.</summary>
public RfcLdapMessage(Asn1Sequence op) : this(op, null)
{
}
/// <summary> Create an RfcLdapMessage response from input parameters.</summary>
public RfcLdapMessage(Asn1Sequence op, RfcControls controls) : base(3)
{
this.op = op;
this.controls = controls;
add(new RfcMessageID()); // MessageID has static counter
add(op);
if (controls != null)
{
add(controls);
}
}
/// <summary> Will decode an RfcLdapMessage directly from an InputStream.</summary>
[CLSCompliant(false)]
public RfcLdapMessage(Asn1Decoder dec, Stream in_Renamed, int len) : base(dec, in_Renamed, len)
{
sbyte[] content;
MemoryStream bais;
// Decode implicitly tagged protocol operation from an Asn1Tagged type
// to its appropriate application type.
var protocolOp = (Asn1Tagged) get_Renamed(1);
var protocolOpId = protocolOp.getIdentifier();
content = ((Asn1OctetString) protocolOp.taggedValue()).byteValue();
bais = new MemoryStream(SupportClass.ToByteArray(content));
switch (protocolOpId.Tag)
{
case LdapMessage.SEARCH_RESPONSE:
set_Renamed(1, new RfcSearchResultEntry(dec, bais, content.Length));
break;
case LdapMessage.SEARCH_RESULT:
set_Renamed(1, new RfcSearchResultDone(dec, bais, content.Length));
break;
case LdapMessage.SEARCH_RESULT_REFERENCE:
set_Renamed(1, new RfcSearchResultReference(dec, bais, content.Length));
break;
case LdapMessage.ADD_RESPONSE:
set_Renamed(1, new RfcAddResponse(dec, bais, content.Length));
break;
case LdapMessage.BIND_RESPONSE:
set_Renamed(1, new RfcBindResponse(dec, bais, content.Length));
break;
case LdapMessage.COMPARE_RESPONSE:
set_Renamed(1, new RfcCompareResponse(dec, bais, content.Length));
break;
case LdapMessage.DEL_RESPONSE:
set_Renamed(1, new RfcDelResponse(dec, bais, content.Length));
break;
case LdapMessage.EXTENDED_RESPONSE:
set_Renamed(1, new RfcExtendedResponse(dec, bais, content.Length));
break;
case LdapMessage.INTERMEDIATE_RESPONSE:
set_Renamed(1, new RfcIntermediateResponse(dec, bais, content.Length));
break;
case LdapMessage.MODIFY_RESPONSE:
set_Renamed(1, new RfcModifyResponse(dec, bais, content.Length));
break;
case LdapMessage.MODIFY_RDN_RESPONSE:
set_Renamed(1, new RfcModifyDNResponse(dec, bais, content.Length));
break;
default:
throw new Exception("RfcLdapMessage: Invalid tag: " + protocolOpId.Tag);
}
// decode optional implicitly tagged controls from Asn1Tagged type to
// to RFC 2251 types.
if (size() > 2)
{
var controls = (Asn1Tagged) get_Renamed(2);
// Asn1Identifier controlsId = protocolOp.getIdentifier();
// we could check to make sure we have controls here....
content = ((Asn1OctetString) controls.taggedValue()).byteValue();
bais = new MemoryStream(SupportClass.ToByteArray(content));
set_Renamed(2, new RfcControls(dec, bais, content.Length));
}
}
//*************************************************************************
// Accessors
//*************************************************************************
/// <summary>
/// Returns the request associated with this RfcLdapMessage.
/// Throws a class cast exception if the RfcLdapMessage is not a request.
/// </summary>
public RfcRequest getRequest()
{
return (RfcRequest) get_Renamed(1);
}
public virtual bool isRequest()
{
return get_Renamed(1) is RfcRequest;
}
/// <summary>
/// Duplicate this message, replacing base dn, filter, and scope if supplied
/// </summary>
/// <param name="dn">
/// the base dn
/// </param>
/// <param name="filter">
/// the filter
/// </param>
/// <param name="reference">
/// true if a search reference
/// </param>
/// <returns>
/// the object representing the new message
/// </returns>
public object dupMessage(string dn, string filter, bool reference)
{
if (op == null)
{
throw new LdapException("DUP_ERROR", LdapException.LOCAL_ERROR, null);
}
var newMsg = new RfcLdapMessage(toArray(), (RfcRequest) get_Renamed(1), dn, filter, reference);
return newMsg;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 Outercurve Foundation 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 System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.CRM;
using WebsitePanel.Providers.DNS;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
using System.Text.RegularExpressions;
namespace WebsitePanel.EnterpriseServer
{
public class CRMController
{
private static CRM GetCRMProxy(int packageId)
{
int crmServiceId = GetCRMServiceId(packageId);
CRM ws = new CRM();
ServiceProviderProxy.Init(ws, crmServiceId);
return ws;
}
private static int GetCRMServiceId(int packageId)
{
int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM2013);
if (serviceId == 0)
serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.HostedCRM);
return serviceId;
}
private static int GetCRMServiceId(int packageId, ResultObject res)
{
int serviceId = GetCRMServiceId(packageId);
if (serviceId == 0)
CompleteTask(res, CrmErrorCodes.CRM_IS_NOT_SELECTED_IN_HOSTING_PLAN, null,
"CRM is not selected in hosting plan.");
return serviceId;
}
private static ResultObject CreateDnsZoneRecord(int domainId, string recordName, string ip)
{
ResultObject ret = StartTask<ResultObject>("CRM", "CREATE_DNS_ZONE");
try
{
//check for existing empty A record
DnsRecord[] records = ServerController.GetDnsZoneRecords(domainId);
foreach (DnsRecord record in records)
{
if ((record.RecordType == DnsRecordType.A || record.RecordType == DnsRecordType.AAAA) && (String.Compare(recordName, record.RecordName, true) == 0))
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_DNS_ZONE, null,
string.Format("DNS record already exists. DomainId={0}, RecordName={1}", domainId, recordName));
return ret;
}
}
var type = ip.Contains(":") ? DnsRecordType.AAAA : DnsRecordType.A;
int res = ServerController.AddDnsZoneRecord(domainId, recordName, type, ip, 0, 0, 0, 0);
if (res != 0)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_DNS_ZONE, null,
string.Format("Cannot create dns record. DomainId={0}, IP={1}, ErrorCode={2}, RecordName={3}", domainId, ip, res, recordName));
return ret;
}
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_DNS_ZONE, ex);
return ret;
}
CompleteTask();
return ret;
}
private static ValueResultObject<DomainInfo> CreateOrganizationDomain(Organization org)
{
ValueResultObject<DomainInfo> ret = StartTask<ValueResultObject<DomainInfo>>("CRM", "CREATE_ORGANIZATIO_DOMAIN");
try
{
int dnsServiceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.Dns);
if (dnsServiceId <= 0)
{
CompleteTask(ret, CrmErrorCodes.DNS_SERVER_IS_NOT_SELECTED_IN_HOSTIN_PLAN, null,
string.Format("DNS Server is not selected in hosting plan."));
return ret;
}
int crmServiceId = GetCRMServiceId(org.PackageId);
StringDictionary serviceSettings = ServerController.GetServiceSettings(crmServiceId);
string strDomainName = string.Format("{0}.{1}", org.OrganizationId,
serviceSettings[Constants.IFDWebApplicationRootDomain]);
DomainInfo domain = ServerController.GetDomain(strDomainName);
if (domain == null)
{
domain = new DomainInfo();
domain.PackageId = org.PackageId;
domain.DomainName = strDomainName;
domain.IsInstantAlias = false;
domain.IsSubDomain = false;
domain.DomainId = ServerController.AddDomain(domain);
}
ret.Value = domain;
if (domain.DomainId <= 0)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_CRM_ORGANIZATION_DOMAIN, null,
string.Format("Crm organization domain cannot be created. DomainId {0}", domain.DomainId));
return ret;
}
ResultObject resAddDnsZoneRecord = CreateDnsZoneRecord(domain.DomainId, string.Empty, serviceSettings[Constants.CRMWebsiteIP]);
ret.ErrorCodes.AddRange(resAddDnsZoneRecord.ErrorCodes);
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CREATE_CRM_ORGANIZATION_DOMAIN_GENERAL_ERROR, ex);
return ret;
}
CompleteTask();
return ret;
}
private static void CompleteTask(ResultObject res, string errorCode, Exception ex, string errorMessage)
{
if (res != null)
{
res.IsSuccess = false;
if (!string.IsNullOrEmpty(errorCode))
res.ErrorCodes.Add(errorCode);
}
if (ex != null)
TaskManager.WriteError(ex);
if (!string.IsNullOrEmpty(errorMessage))
TaskManager.WriteError(errorMessage);
//LogRecord.
TaskManager.CompleteTask();
}
private static void CompleteTask(ResultObject res, string errorCode, Exception ex)
{
CompleteTask(res, errorCode, ex, null);
}
private static void CompleteTask(ResultObject res, string errorCode)
{
CompleteTask(res, errorCode, null, null);
}
private static void CompleteTask(ResultObject res)
{
CompleteTask(res, null);
}
private static void CompleteTask()
{
CompleteTask(null);
}
private static T StartTask<T>(string source, string taskName) where T : ResultObject, new()
{
TaskManager.StartTask(source, taskName);
T res = new T();
res.IsSuccess = true;
return res;
}
private static string GetProviderProperty(int organizationServiceId, string property)
{
Organizations orgProxy = new Organizations();
ServiceProviderProxy.Init(orgProxy, organizationServiceId);
string[] organizationSettings = orgProxy.ServiceProviderSettingsSoapHeaderValue.Settings;
string value = string.Empty;
foreach (string str in organizationSettings)
{
string[] props = str.Split('=');
if (props.Length == 2)
{
if (props[0].ToLower() == property)
{
value = props[1];
break;
}
}
}
return value;
}
public static string GetOrganizationCRMUniqueName(string orgName)
{
return Regex.Replace(orgName, @"[^\dA-Za-z]", "-", RegexOptions.Compiled);
}
public static OrganizationResult CreateOrganization(int organizationId, string baseCurrencyCode, string baseCurrencyName, string baseCurrencySymbol, string regionName, int userId, string collation, int baseLanguageCode)
{
OrganizationResult res = StartTask<OrganizationResult>("CRM", "CREATE_ORGANIZATION");
try
{
Organization org = OrganizationController.GetOrganization(organizationId);
try
{
if (!CheckQuota(org.PackageId))
{
CompleteTask(res, CrmErrorCodes.QUOTA_HAS_BEEN_REACHED);
return res;
}
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CHECK_QUOTAS, ex);
return res;
}
CRM crm = GetCRMProxy(org.PackageId);
Guid orgId = Guid.NewGuid();
OrganizationUser user = OrganizationController.GetUserGeneralSettings(organizationId, userId);
if (string.IsNullOrEmpty(user.FirstName))
{
CompleteTask(res, CrmErrorCodes.FIRST_NAME_IS_NOT_SPECIFIED);
return res;
}
if (string.IsNullOrEmpty(user.LastName))
{
CompleteTask(res, CrmErrorCodes.LAST_NAME_IS_NOT_SPECIFIED);
return res;
}
int serviceid = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.HostedOrganizations);
string rootOU = GetProviderProperty(serviceid, "rootou");
PackageContext cntx = PackageController.GetPackageContext(org.PackageId);
string maxDBSizeQuotaName = "";
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) maxDBSizeQuotaName = Quotas.CRM2013_MAXDATABASESIZE;
else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) maxDBSizeQuotaName = Quotas.CRM_MAXDATABASESIZE;
long maxDBSize = cntx.Quotas[maxDBSizeQuotaName].QuotaAllocatedValue;
if (maxDBSize != -1) maxDBSize = maxDBSize * 1024 * 1024;
org.CrmAdministratorId = user.AccountId;
org.CrmCurrency =
string.Join("|", new[] {baseCurrencyCode, baseCurrencyName, baseCurrencySymbol, regionName});
org.CrmCollation = collation;
org.CrmOrgState = (int) CrmOrganizationState.Enabled;
org.CrmLanguadgeCode = baseLanguageCode.ToString();
org.CrmOrganizationId = orgId;
OrganizationResult serverRes =
crm.CreateOrganization(orgId, org.OrganizationId, org.Name,
baseLanguageCode,
org.OrganizationId + "." + rootOU,
baseCurrencyCode, baseCurrencyName,
baseCurrencySymbol, user.SamAccountName, user.FirstName, user.LastName, user.PrimaryEmailAddress,
collation, maxDBSize);
if (!serverRes.IsSuccess)
{
res.ErrorCodes.AddRange(serverRes.ErrorCodes);
CompleteTask(res);
return res;
}
ValueResultObject<DomainInfo> resDomain = CreateOrganizationDomain(org);
res.ErrorCodes.AddRange(resDomain.ErrorCodes);
int crmServiceId = GetCRMServiceId(org.PackageId);
StringDictionary serviceSettings = ServerController.GetServiceSettings(crmServiceId);
string port = serviceSettings[Constants.Port];
string schema = serviceSettings[Constants.UrlSchema];
if (port == "80" && schema == "http")
port = string.Empty;
if (port == "443" && schema == "https")
port = string.Empty;
if (port != string.Empty)
port = ":" + port;
string strDomainName = string.Format("{0}.{1}", GetOrganizationCRMUniqueName(org.OrganizationId),
serviceSettings[Constants.IFDWebApplicationRootDomain]);
org.CrmUrl = string.Format("{0}://{1}{2}", schema, strDomainName, port);
PackageController.UpdatePackageItem(org);
CrmUserResult crmUser = crm.GetCrmUserByDomainName(user.DomainUserName, org.OrganizationId);
res.ErrorCodes.AddRange(crmUser.ErrorCodes);
if (crmUser.IsSuccess)
{
try
{
DataProvider.CreateCRMUser(userId, crmUser.Value.CRMUserId, crmUser.Value.BusinessUnitId, 0);
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_ADD_ORGANIZATION_OWNER_TO_ORGANIZATIO_USER, ex, "Cannot add organization owner to organization users");
}
}
res.Value = org;
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CREATE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static StringArrayResultObject GetCollationByServiceId(int serviceId)
{
StringArrayResultObject ret = StartTask<StringArrayResultObject>("CRM", "GET_COLLATION_NAMES");
ret.IsSuccess = true;
try
{
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret.Value = crm.GetSupportedCollationNames();
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_GET_COLLATION_NAMES, ex);
return ret;
}
CompleteTask();
return ret;
}
public static StringArrayResultObject GetCollation(int packageId)
{
StringArrayResultObject ret = StartTask<StringArrayResultObject>("CRM", "GET_COLLATION_NAMES");
ret.IsSuccess = true;
try
{
int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
return ret;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret.Value = crm.GetSupportedCollationNames();
}
catch(Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_GET_COLLATION_NAMES, ex);
return ret;
}
CompleteTask();
return ret;
}
public static CurrencyArrayResultObject GetCurrencyByServiceId(int serviceId)
{
CurrencyArrayResultObject ret = StartTask<CurrencyArrayResultObject>("CRM", "GET_CURRENCY");
ret.IsSuccess = true;
try
{
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret.Value = crm.GetCurrencyList();
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_GET_CURRENCY_LIST, ex);
return ret;
}
CompleteTask();
return ret;
}
public static CurrencyArrayResultObject GetCurrency(int packageId)
{
CurrencyArrayResultObject ret = StartTask<CurrencyArrayResultObject>("CRM", "GET_CURRENCY");
ret.IsSuccess = true;
try
{
int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
return ret;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret.Value = crm.GetCurrencyList();
}
catch(Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_GET_CURRENCY_LIST, ex);
return ret;
}
CompleteTask();
return ret;
}
private static ResultObject DeleteDnsRecord(int domainId, string recordName, string ip)
{
ResultObject ret = StartTask<ResultObject>("CRM", "DELETE_DNS_RECORD");
try
{
var type = ip.Contains(":") ? DnsRecordType.AAAA : DnsRecordType.A;
int res = ServerController.DeleteDnsZoneRecord(domainId, recordName, type, ip);
if (res != 0)
{
CompleteTask(ret, CrmErrorCodes.DELETE_DNS_RECORD_ERROR, null,
string.Format("Cannot delete dns record. DomainId={0}, DnsRecord={1}, ErrorCode={2}", domainId, DnsRecordType.A, res));
return ret;
}
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_DELETE_DNS_RECORD, ex);
return ret;
}
CompleteTask();
return ret;
}
private static ResultObject DeleteOrganizationDomain(Organization org)
{
ResultObject ret = StartTask<ResultObject>("CRM", "DELETE_ORGANIZATION_DOMAIN");
try
{
int dnsServiceId = PackageController.GetPackageServiceId(org.PackageId, ResourceGroups.Dns);
int crmServiceId = GetCRMServiceId(org.PackageId);
if (dnsServiceId <= 0)
{
TaskManager.WriteError("DNS Server is not selected in hosting plan.");
CompleteTask(ret, CrmErrorCodes.DNS_SERVER_IS_NOT_SELECTED_IN_HOSTIN_PLAN);
return ret;
}
StringDictionary serviceSettings = ServerController.GetServiceSettings(crmServiceId);
string domainName =
string.Format("{0}.{1}", org.OrganizationId, serviceSettings[Constants.IFDWebApplicationRootDomain]);
DomainInfo domainInfo = ServerController.GetDomain(domainName);
if (domainInfo == null)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_GET_CRM_ORGANIZATION_DOMAIN, null,
string.Format("Cannot get crm organization domain {0}", domainName));
return ret;
}
ResultObject resultDeleteDnsRecord = DeleteDnsRecord(domainInfo.DomainId, string.Empty, serviceSettings[Constants.CRMWebsiteIP]);
ret.ErrorCodes.AddRange(resultDeleteDnsRecord.ErrorCodes);
if (!resultDeleteDnsRecord.IsSuccess)
{
CompleteTask(ret);
return ret;
}
/*try
{
ServerController.DeleteDomain(domainInfo.DomainId);
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_DELETE_CRM_ORGANIZATIO_DOMAIN, ex);
return ret;
}*/
}
catch(Exception ex)
{
CompleteTask(ret, CrmErrorCodes.DELETE_CRM_ORGANIZATION_DOMAIN_GENERAL_ERROR, ex);
return ret;
}
CompleteTask();
return ret;
}
public static ResultObject DeleteOrganization(int organizationId)
{
ResultObject res = StartTask<ResultObject>("CRM", "DELETE_ORGANIZATION");
try
{
Organization org = OrganizationController.GetOrganization(organizationId);
CRM crm = GetCRMProxy(org.PackageId);
try
{
DataProvider.DeleteCrmOrganization(organizationId);
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_DELETE_CRM_ORGANIZATION_METADATA, ex);
return res;
}
ResultObject resDeleteDomain = DeleteOrganizationDomain(org);
res.ErrorCodes.AddRange(resDeleteDomain.ErrorCodes);
ResultObject resDeleteOrganization = crm.DeleteOrganization(org.CrmOrganizationId);
res.ErrorCodes.AddRange(resDeleteOrganization.ErrorCodes);
if (!resDeleteOrganization.IsSuccess)
{
CompleteTask(res);
return res;
}
org.CrmAdministratorId = 0;
org.CrmCollation = string.Empty;
org.CrmCurrency = string.Empty;
org.CrmOrganizationId = Guid.Empty;
org.CrmOrgState = (int) CrmOrganizationState.Disabled;
org.CrmUrl = string.Empty;
PackageController.UpdatePackageItem(org);
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.DELETE_CRM_ORGANIZATION_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
private static bool CheckQuota(int packageId)
{
TaskManager.StartTask("CRM", "CHECK_QUOTA");
bool res = false;
try
{
// check account
int errorCode = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (errorCode < 0) return false;
PackageContext cntx = PackageController.GetPackageContext(packageId);
string quotaName = "";
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) quotaName = Quotas.CRM2013_ORGANIZATION;
else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) quotaName = Quotas.CRM_ORGANIZATION;
return (cntx.Quotas[quotaName] != null && !cntx.Quotas[quotaName].QuotaExhausted);
}
catch(Exception ex)
{
TaskManager.WriteError(ex);
res = false;
}
finally
{
TaskManager.CompleteTask();
}
return res;
}
public static IntResult GetCRMUsersCount(int itemId, string name, string email, int CALType)
{
IntResult res = StartTask<IntResult>("CRM", "GET_CRM_USERS_COUNT");
try
{
res.Value = DataProvider.GetCRMUsersCount(itemId, name, email, CALType);
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.GET_CRM_USER_COUNT, ex);
return res;
}
CompleteTask();
return res;
}
public static List<OrganizationUser> GetCRMOrganizationUsers(int itemId)
{
IDataReader reader =
DataProvider.GetCRMOrganizationUsers(itemId);
List<OrganizationUser> accounts = new List<OrganizationUser>();
ObjectUtils.FillCollectionFromDataReader(accounts, reader);
return accounts;
}
public static OrganizationUsersPagedResult GetCRMUsers(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int count)
{
OrganizationUsersPagedResult res = StartTask<OrganizationUsersPagedResult>("CRM", "GET_CRM_USERS");
try
{
IDataReader reader =
DataProvider.GetCrmUsers(itemId, sortColumn, sortDirection, name, email, startRow, count);
List<OrganizationUser> accounts = new List<OrganizationUser>();
ObjectUtils.FillCollectionFromDataReader(accounts, reader);
res.Value = new OrganizationUsersPaged();
res.Value.PageUsers = accounts.ToArray();
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.GET_CRM_USERS, ex);
return res;
}
IntResult intRes = GetCRMUsersCount(itemId, name, email, -1);
res.ErrorCodes.AddRange(intRes.ErrorCodes);
if (!intRes.IsSuccess)
{
CompleteTask(res);
return res;
}
res.Value.RecordsCount = intRes.Value;
CompleteTask();
return res;
}
public static UserResult CreateCRMUser(OrganizationUser user, int packageId, int itemId, Guid businessUnitId, int CALType)
{
UserResult ret = StartTask<UserResult>("CRM", "CREATE_CRM_USER");
try
{
if (user == null)
throw new ArgumentNullException("user");
if (businessUnitId == Guid.Empty)
throw new ArgumentNullException("businessUnitId");
if (string.IsNullOrEmpty(user.FirstName))
{
CompleteTask(ret, CrmErrorCodes.FIRST_NAME_IS_NOT_SPECIFIED, null, "First name is not specified.");
return ret;
}
if (string.IsNullOrEmpty(user.LastName))
{
CompleteTask(ret, CrmErrorCodes.LAST_NAME_IS_NOT_SPECIFIED, null, "Last name is not specified.");
return ret;
}
Guid crmUserId = GetCrmUserId(user.AccountId);
if (crmUserId != Guid.Empty)
{
CompleteTask(ret, CrmErrorCodes.CRM_USER_ALREADY_EXISTS, null, "CRM user already exists.");
return ret;
}
BoolResult quotaRes = CheckQuota(packageId, itemId, CALType);
ret.ErrorCodes.AddRange(quotaRes.ErrorCodes);
if (!quotaRes.IsSuccess)
{
CompleteTask(ret);
return ret;
}
if (!quotaRes.Value)
{
string errorCode = CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED;
PackageContext cntx = PackageController.GetPackageContext(packageId);
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
errorCode += "2013_";
errorCode += CALType.ToString();
CompleteTask(ret, errorCode , null, "CRM user quota has been reached.");
return ret;
}
Guid crmId;
try
{
int serviceId = GetCRMServiceId(packageId, ret);
if (serviceId == 0)
return ret;
Organization org = OrganizationController.GetOrganization(itemId);
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
UserResult res = crm.CreateCRMUser(user, org.OrganizationId, org.CrmOrganizationId, businessUnitId, CALType);
ret.ErrorCodes.AddRange(res.ErrorCodes);
if (!res.IsSuccess)
{
CompleteTask(res);
return ret;
}
crmId = res.Value.CrmUserId;
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_CRM_USER_GENERAL_ERROR, ex);
return ret;
}
try
{
DataProvider.CreateCRMUser(user.AccountId, crmId, businessUnitId, CALType);
}
catch (Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CANNOT_CREATE_CRM_USER_IN_DATABASE, ex);
return ret;
}
}
catch(Exception ex)
{
CompleteTask(ret, CrmErrorCodes.CREATE_CRM_USER_GENERAL_ERROR, ex);
return ret;
}
CompleteTask();
return ret;
}
public static CRMBusinessUnitsResult GetCRMBusinessUnits(int itemId, int packageId)
{
CRMBusinessUnitsResult res = StartTask<CRMBusinessUnitsResult>("CRM", "GET_CRM_BUSINESS_UNITS");
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return res;
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org.CrmOrganizationId == Guid.Empty)
throw new ApplicationException("Current organization is not CRM organization.");
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_GET_CRM_ORGANIZATION, ex);
return res;
}
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
CRMBusinessUnitsResult providerRes = crm.GetOrganizationBusinessUnits(org.CrmOrganizationId, org.OrganizationId);
res.ErrorCodes.AddRange(providerRes.ErrorCodes);
if (!providerRes.IsSuccess)
{
CompleteTask(res);
return res;
}
res.Value = providerRes.Value;
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_GET_BUSINESS_UNITS_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static CrmRolesResult GetCRMRoles(int itemId, int accountId, int packageId)
{
CrmRolesResult res = StartTask<CrmRolesResult>("CRM", "GET_CRM_ROLES");
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return res;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org = OrganizationController.GetOrganization(itemId);
CrmUserResult crmUserResult = GetCrmUser(itemId, accountId);
res.ErrorCodes.AddRange(crmUserResult.ErrorCodes);
if (!crmUserResult.IsSuccess)
{
CompleteTask(res);
return res;
}
CrmUser crmUser = crmUserResult.Value;
CrmRolesResult crmRoles = crm.GetAllCrmRoles(org.OrganizationId, crmUser.BusinessUnitId);
res.ErrorCodes.AddRange(crmRoles.ErrorCodes);
if (!crmRoles.IsSuccess)
{
CompleteTask(res);
return res;
}
Guid userId = crmUser.CRMUserId;
CrmRolesResult crmUserRoles = crm.GetCrmUserRoles(org.OrganizationId, userId);
res.ErrorCodes.AddRange(crmUserRoles.ErrorCodes);
if (!crmUserRoles.IsSuccess)
{
CompleteTask(res);
return res;
}
foreach (CrmRole role in crmUserRoles.Value)
{
CrmRole retRole = crmRoles.Value.Find(delegate(CrmRole currentRole)
{
return currentRole.RoleId == role.RoleId;
});
if (retRole != null)
retRole.IsCurrentUserRole = true;
}
res.Value = crmRoles.Value;
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_GET_CRM_ROLES_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static Guid GetCrmUserId(int accountId)
{
IDataReader reader = DataProvider.GetCrmUser(accountId);
CrmUser user = ObjectUtils.FillObjectFromDataReader<CrmUser>(reader);
return user == null ? Guid.Empty :user.CRMUserId;
}
public static CrmUserResult GetCrmUser(int itemId, int accountId)
{
CrmUserResult res = StartTask<CrmUserResult>("CRM", "GET_CRM_USER");
try
{
Guid crmUserId = GetCrmUserId(accountId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return res;
}
int serviceId = GetCRMServiceId(org.PackageId, res);
if (serviceId == 0)
return res;
try
{
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
CrmUserResult user = crm.GetCrmUserById(crmUserId, org.OrganizationId);
res.ErrorCodes.AddRange(user.ErrorCodes);
if (!user.IsSuccess)
{
CompleteTask(res);
return res;
}
res.Value = user.Value;
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANONT_GET_CRM_USER_BY_ID, ex);
return res;
}
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANONT_GET_CRM_USER_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static ResultObject SetUserRoles(int itemId, int accountId, int packageId, Guid[] roles)
{
CrmRolesResult res = StartTask<CrmRolesResult>("CRM", "GET_CRM_ROLES");
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return res;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return res;
}
Guid crmUserId = GetCrmUserId(accountId);
ResultObject rolesRes = crm.SetUserRoles(org.OrganizationId, crmUserId, roles);
res.ErrorCodes.AddRange(rolesRes.ErrorCodes);
if (!rolesRes.IsSuccess)
{
CompleteTask(res);
return res;
}
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_SET_CRM_USER_ROLES_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static ResultObject SetUserCALType(int itemId, int accountId, int packageId, int CALType)
{
ResultObject res = StartTask<CrmRolesResult>("CRM", "SET_CRM_CALTYPE");
try
{
CrmUserResult user = GetCrmUser(itemId, accountId);
if (user.Value.CALType + ((int)user.Value.ClientAccessMode)*10 == CALType)
{
res.IsSuccess = true;
CompleteTask();
return res;
}
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return res;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return res;
}
BoolResult quotaRes = CheckQuota(packageId, itemId, CALType);
res.ErrorCodes.AddRange(quotaRes.ErrorCodes);
if (!quotaRes.IsSuccess)
{
CompleteTask(res);
return res;
}
if (!quotaRes.Value)
{
string errorCode = CrmErrorCodes.USER_QUOTA_HAS_BEEN_REACHED;
PackageContext cntx = PackageController.GetPackageContext(packageId);
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
errorCode += "2013_";
errorCode += CALType.ToString();
CompleteTask(res, errorCode, null, "CRM user quota has been reached.");
return res;
}
Guid crmUserId = GetCrmUserId(accountId);
ResultObject rolesRes = crm.SetUserCALType(org.Name, crmUserId, CALType);
DataProvider.UpdateCRMUser(accountId, CALType);
res.ErrorCodes.AddRange(rolesRes.ErrorCodes);
if (!rolesRes.IsSuccess)
{
CompleteTask(res);
return res;
}
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_SET_CRM_USER_ROLES_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
public static ResultObject ChangeUserState(int itemId, int accountId, bool disable)
{
CrmRolesResult res = StartTask<CrmRolesResult>("CRM", "CHANGER_USER_STATE");
Organization org;
try
{
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return res;
}
int serviceId = GetCRMServiceId(org.PackageId, res);
if (serviceId == 0)
return res;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Guid crmUserId = GetCrmUserId(accountId);
ResultObject changeStateRes = crm.ChangeUserState(disable, org.OrganizationId, crmUserId);
if (!changeStateRes.IsSuccess)
res.IsSuccess = false;
res.ErrorCodes.AddRange(changeStateRes.ErrorCodes);
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CHANGE_USER_STATE_GENERAL_ERROR, ex);
return res;
}
CompleteTask();
return res;
}
private static BoolResult CheckQuota(int packageId, int itemId, int CALType)
{
BoolResult res = StartTask<BoolResult>("CRM", "CHECK_QUOTA");
try
{
PackageContext cntx = PackageController.GetPackageContext(packageId);
IntResult tmp = GetCRMUsersCount(itemId, string.Empty, string.Empty, CALType);
res.ErrorCodes.AddRange(tmp.ErrorCodes);
if (!tmp.IsSuccess)
{
CompleteTask(res);
return res;
}
string quotaName = "";
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013))
{
switch (CALType)
{
case CRMUserLycenseTypes.PROFESSIONAL:
quotaName = Quotas.CRM2013_PROFESSIONALUSERS;
break;
case CRMUserLycenseTypes.BASIC:
quotaName = Quotas.CRM2013_BASICUSERS;
break;
case CRMUserLycenseTypes.ESSENTIAL:
quotaName = Quotas.CRM2013_ESSENTIALUSERS;
break;
}
}
else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM))
{
switch (CALType)
{
case CRMUserLycenseTypes.FULL:
quotaName = Quotas.CRM_USERS;
break;
case CRMUserLycenseTypes.LIMITED:
quotaName = Quotas.CRM_LIMITEDUSERS;
break;
case CRMUserLycenseTypes.ESS:
quotaName = Quotas.CRM_ESSUSERS;
break;
}
}
int allocatedCrmUsers = cntx.Quotas[quotaName].QuotaAllocatedValuePerOrganization;
res.Value = allocatedCrmUsers == -1 || allocatedCrmUsers > tmp.Value;
}
catch(Exception ex)
{
CompleteTask(res, CrmErrorCodes.CHECK_QUOTA, ex);
return res;
}
CompleteTask();
return res;
}
public static ResultObject SetMaxDBSize(int itemId, int packageId, long maxSize)
{
ResultObject res = StartTask<ResultObject>("CRM", "SET_CRM_MAXDBSIZE");
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return res;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return res;
}
PackageContext cntx = PackageController.GetPackageContext(packageId);
string quotaName = "";
if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) quotaName = Quotas.CRM2013_MAXDATABASESIZE;
else if (cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) quotaName = Quotas.CRM_MAXDATABASESIZE;
long limitSize = cntx.Quotas[quotaName].QuotaAllocatedValue;
if (limitSize != -1)
{
limitSize = limitSize * 1024 * 1024;
if (maxSize == -1) maxSize = limitSize;
if (maxSize > limitSize) maxSize = limitSize;
}
res = crm.SetMaxDBSize(org.CrmOrganizationId, maxSize);
res.ErrorCodes.AddRange(res.ErrorCodes);
if (!res.IsSuccess)
{
CompleteTask(res);
return res;
}
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
return res;
}
CompleteTask();
return res;
}
public static long GetDBSize(int itemId, int packageId)
{
ResultObject res = StartTask<ResultObject>("CRM", "GET_CRM_DBSIZE");
long size = -1;
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return -1;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return -1;
}
size = crm.GetDBSize(org.CrmOrganizationId);
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
return -1;
}
CompleteTask();
return size;
}
public static long GetMaxDBSize(int itemId, int packageId)
{
ResultObject res = StartTask<ResultObject>("CRM", "GET_CRM_MAXDBSIZE");
long size = -1;
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return -1;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
Organization org;
try
{
org = OrganizationController.GetOrganization(itemId);
if (org == null)
throw new ApplicationException("Org is null.");
}
catch (Exception ex)
{
CompleteTask(res, ErrorCodes.CANNOT_GET_ORGANIZATION_BY_ITEM_ID, ex);
return -1;
}
size = crm.GetMaxDBSize(org.CrmOrganizationId);
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
return -1;
}
CompleteTask();
return size;
}
public static int[] GetInstalledLanguagePacks(int packageId)
{
ResultObject res = StartTask<ResultObject>("CRM", "GET_CRM_MAXDBSIZE");
int[] ret = null;
try
{
int serviceId = GetCRMServiceId(packageId, res);
if (serviceId == 0)
return null;
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret = crm.GetInstalledLanguagePacks();
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
return null;
}
CompleteTask();
return ret;
}
public static int[] GetInstalledLanguagePacksByServiceId(int serviceId)
{
ResultObject res = StartTask<ResultObject>("CRM", "GET_CRM_MAXDBSIZE");
int[] ret = null;
try
{
CRM crm = new CRM();
ServiceProviderProxy.Init(crm, serviceId);
ret = crm.GetInstalledLanguagePacks();
}
catch (Exception ex)
{
CompleteTask(res, CrmErrorCodes.CANNOT_CONFIGURE_CRM_ORGANIZATION, ex);
return null;
}
CompleteTask();
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class CastTests : EnumerableTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
Assert.Empty(source.Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IEnumerable<double> cast = source.Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IEnumerable<T> cast = source.Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
[Fact]
public void NullSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<object>)null).Cast<string>());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = new object[0].Where(i => i != null).Cast<string>();
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<string>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An asset storage interface for the SQLite database system
/// </summary>
public class SQLiteAssetData : AssetDataBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string SelectAssetSQL = "select * from assets where UUID=:UUID";
private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count";
private const string DeleteAssetSQL = "delete from assets where UUID=:UUID AND asset_flags <> 0";
private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)";
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID AND asset_flags<>0";
private const string assetSelect = "select * from assets";
private SqliteConnection m_conn;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
override public void Dispose()
{
if (m_conn != null)
{
m_conn.Close();
m_conn = null;
}
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises AssetData interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
override public void Initialise(string dbconnect)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:Asset.db,version=3";
}
m_conn = new SqliteConnection(dbconnect);
m_conn.Open();
Migration m = new Migration(m_conn, Assembly, "AssetStore");
m.Update();
return;
}
/// <summary>
/// Fetch Asset
/// </summary>
/// <param name="uuid">UUID of ... ?</param>
/// <returns>Asset base</returns>
override public AssetBase GetAsset(UUID uuid)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
}
}
/// <summary>
/// Create an asset
/// </summary>
/// <param name="asset">Asset Base</param>
override public void StoreAsset(AssetBase asset)
{
string assetName = asset.Name;
if (asset.Name.Length > AssetBase.MAX_ASSET_NAME)
{
assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > AssetBase.MAX_ASSET_DESC)
{
assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
//m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString());
if (AssetsExist(new[] { asset.FullID })[0])
{
//LogAssetLoad(asset);
using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
else
{
using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
}
// /// <summary>
// /// Some... logging functionnality
// /// </summary>
// /// <param name="asset"></param>
// private static void LogAssetLoad(AssetBase asset)
// {
// string temporary = asset.Temporary ? "Temporary" : "Stored";
// string local = asset.Local ? "Local" : "Remote";
//
// int assetLength = (asset.Data != null) ? asset.Data.Length : 0;
//
// m_log.Debug("[ASSET DB]: " +
// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)",
// asset.FullID, asset.Name, asset.Description, asset.Type,
// temporary, local, assetLength));
// }
/// <summary>
/// Check if the assets exist in the database.
/// </summary>
/// <param name="uuids">The assets' IDs</param>
/// <returns>For each asset: true if it exists, false otherwise</returns>
public override bool[] AssetsExist(UUID[] uuids)
{
if (uuids.Length == 0)
return new bool[0];
HashSet<UUID> exist = new HashSet<UUID>();
string ids = "'" + string.Join("','", uuids) + "'";
string sql = string.Format("select UUID from assets where UUID in ({0})", ids);
using (SqliteCommand cmd = new SqliteCommand(sql, m_conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID id = new UUID((string)reader["UUID"]);
exist.Add(id);
}
}
}
bool[] results = new bool[uuids.Length];
for (int i = 0; i < uuids.Length; i++)
results[i] = exist.Contains(uuids[i]);
return results;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static AssetBase buildAsset(IDataReader row)
{
// TODO: this doesn't work yet because something more
// interesting has to be done to actually get these values
// back out. Not enough time to figure it out yet.
AssetBase asset = new AssetBase(
new UUID((String)row["UUID"]),
(String)row["Name"],
Convert.ToSByte(row["Type"]),
(String)row["CreatorID"]
);
asset.Description = (String) row["Description"];
asset.Local = Convert.ToBoolean(row["Local"]);
asset.Temporary = Convert.ToBoolean(row["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
asset.Data = (byte[])row["Data"];
return asset;
}
private static AssetMetadata buildAssetMetadata(IDataReader row)
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = new UUID((string) row["UUID"]);
metadata.Name = (string) row["Name"];
metadata.Description = (string) row["Description"];
metadata.Type = Convert.ToSByte(row["Type"]);
metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
metadata.CreatorID = row["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] {};
return metadata;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":start", start));
cmd.Parameters.Add(new SqliteParameter(":count", count));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = buildAssetMetadata(reader);
retList.Add(metadata);
}
}
}
return retList;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
#region IPlugin interface
/// <summary>
///
/// </summary>
override public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Initialise the AssetData interface using default URI
/// </summary>
override public void Initialise()
{
Initialise("URI=file:Asset.db,version=3");
}
/// <summary>
/// Name of this DB provider
/// </summary>
override public string Name
{
get { return "SQLite Asset storage engine"; }
}
// TODO: (AlexRa): one of these is to be removed eventually (?)
/// <summary>
/// Delete an asset from database
/// </summary>
/// <param name="uuid"></param>
public bool DeleteAsset(UUID uuid)
{
using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
cmd.ExecuteNonQuery();
}
return true;
}
public override bool Delete(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return DeleteAsset(assetID);
}
#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 Xunit;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Threading.Tasks.Tests
{
public class TaskAwaiterTests
{
// awaiting tasks
[Fact]
[OuterLoop]
public static void RunAsyncTaskAwaiterTests()
{
var completed = new TaskCompletionSource<string>();
Task task = completed.Task;
Task<string> taskOfString = completed.Task;
completed.SetResult("42");
{
// IsCompleted/OnCompleted on a non-completed Task with SyncContext and completes the task in another context
var vccsc = new ValidateCorrectContextSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(vccsc);
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = ((Task)tcs.Task).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Awaiter on non-completed task should not be IsCompleted");
awaiter.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Continuation should be running in captured sync context.");
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not run until task completes.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should have completed.");
Assert.True(vccsc.PostCount == 1, " > FAILURE. Await continuation should have posted to the target context.");
SynchronizationContext.SetSynchronizationContext(null);
}
{
// IsCompleted/OnCompleted on a non-completed Task with TaskScheduler and completes the task in another context
var quwi = new QUWITaskScheduler();
RunWithSchedulerAsCurrent(quwi, delegate
{
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = ((Task)tcs.Task).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Awaiter on non-completed task should not be IsCompleted");
awaiter.OnCompleted(() =>
{
Assert.True(TaskScheduler.Current == quwi, " > FAILURE. Continuation should be running in task scheduler.");
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not run until task completes.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should have completed.");
});
}
{
// Configured IsCompleted/OnCompleted on a non-completed Task with SyncContext
for (int iter = 0; iter < 2; iter++)
{
Task.Factory.StartNew(() =>
{
bool continueOnCapturedContext = iter == 0;
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Configured awaiter on non-completed task should not be IsCompleted");
awaiter.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext == continueOnCapturedContext,
" > FAILURE. Continuation should have been posted to context iff continueOnCapturedContext == true.");
//
// Assert.True(Environment.StackTrace.Contains("SetResult") != continueOnCapturedContext,
// " > FAILURE. Continuation should have been executed synchronously iff continueOnCapturedContext == false.");
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not have run before task completed.");
Task.Factory.StartNew(() => tcs.SetResult(null));
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should now have completed.");
SynchronizationContext.SetSynchronizationContext(null);
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Wait();
}
}
{
// IsCompleted/OnCompleted on a non-completed Task<TResult> with SyncContext and completes the task in another context
var vccsc = new ValidateCorrectContextSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(vccsc);
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = ((Task<object>)tcs.Task).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Awaiter on non-completed Task<TResult> should not be IsCompleted");
awaiter.OnCompleted(() =>
{
Assert.True(ValidateCorrectContextSynchronizationContext.IsPostedInContext, " > FAILURE. Await continuation should have posted to target context");
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not have run before task completed.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should now have completed.");
Assert.True(vccsc.PostCount == 1, " > FAILURE. Await continuation should have posted to the target context");
SynchronizationContext.SetSynchronizationContext(null);
}
{
// Configured IsCompleted/OnCompleted on a non-completed Task<TResult> with SyncContext
for (int iter = 0; iter < 2; iter++)
{
Task.Factory.StartNew(() =>
{
bool continueOnCapturedContext = iter == 0;
SynchronizationContext.SetSynchronizationContext(new ValidateCorrectContextSynchronizationContext());
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = tcs.Task.ConfigureAwait(continueOnCapturedContext).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Configured awaiter on non-completed Task<TResult> should not be IsCompleted");
awaiter.OnCompleted(() =>
{
Assert.True(
ValidateCorrectContextSynchronizationContext.IsPostedInContext == continueOnCapturedContext,
" > FAILURE. Await continuation should have posted to target context iff continueOnCapturedContext == true");
// Assert.True(
// Environment.StackTrace.Contains("SetResult") != continueOnCapturedContext,
// " > FAILURE. Await continuation should have executed inline iff continueOnCapturedContext == false");
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not have run before task completed.");
Task.Factory.StartNew(() => tcs.SetResult(null));
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should now have completed.");
SynchronizationContext.SetSynchronizationContext(null);
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Wait();
}
}
{
// Validate successful GetResult
task.GetAwaiter().GetResult();
task.ConfigureAwait(false).GetAwaiter().GetResult();
task.ConfigureAwait(true).GetAwaiter().GetResult();
Assert.Equal(taskOfString.GetAwaiter().GetResult(), "42");
Assert.Equal(taskOfString.ConfigureAwait(false).GetAwaiter().GetResult(), "42");
Assert.Equal(taskOfString.ConfigureAwait(true).GetAwaiter().GetResult(), "42");
}
{
// Validate GetResult blocks until completion
var tcs = new TaskCompletionSource<bool>();
// Kick off tasks that should all block
var t1 = Task.Factory.StartNew(() => tcs.Task.GetAwaiter().GetResult());
var t2 = Task.Factory.StartNew(() => ((Task)tcs.Task).GetAwaiter().GetResult());
var t3 = Task.Factory.StartNew(() => tcs.Task.ConfigureAwait(false).GetAwaiter().GetResult());
var t4 = Task.Factory.StartNew(() => ((Task)tcs.Task).ConfigureAwait(false).GetAwaiter().GetResult());
var allTasks = new Task[] { t1, t2, t3, t4 };
// Wait with timeout should return false
bool waitCompleted;
try
{
waitCompleted = Task.WaitAll(allTasks, 4000);
Assert.False(waitCompleted, " > Expected tasks to not be completed");
}
catch (Exception exc)
{
Assert.True(false, string.Format(" > Did not expect an exception: " + exc));
}
// Now complete the tasks
tcs.SetResult(true);
// All tasks should complete successfully
waitCompleted = Task.WaitAll(allTasks, 4000);
Assert.True(waitCompleted,
"After completion, excepted all GetResult calls to completed successfully");
foreach (var taskToCheck in allTasks)
{
Assert.True(taskToCheck.Status == TaskStatus.RanToCompletion, "Task was not run to completion. Excepted all GetResult calls to completed successfully");
}
}
}
[Fact]
public static void RunAsyncTaskAwaiterTests_Exceptions()
{
// Validate cancellation
var canceled = new TaskCompletionSource<string>();
canceled.SetCanceled();
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<TaskCanceledException>(() => { ((Task)canceled.Task).GetAwaiter().GetResult(); });
Assert.Throws<TaskCanceledException>(() => { ((Task<string>)canceled.Task).GetAwaiter().GetResult(); });
// w/ ConfigureAwait false and true
Assert.Throws<TaskCanceledException>(() => { ((Task)canceled.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<TaskCanceledException>(() => { ((Task)canceled.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
Assert.Throws<TaskCanceledException>(() => { ((Task<string>)canceled.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<TaskCanceledException>(() => { ((Task<string>)canceled.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
}
[Fact]
public static void AsyncTaskAwaiterTests_EqualityTests()
{
var completed = new TaskCompletionSource<string>();
Task task = completed.Task;
// Validate awaiter and awaitable equality
// TaskAwaiter
task.GetAwaiter().Equals(task.GetAwaiter());
// ConfiguredTaskAwaitable
Assert.Equal(((Task)task).ConfigureAwait(false), ((Task)task).ConfigureAwait(false));
Assert.NotEqual(((Task)task).ConfigureAwait(false), ((Task)task).ConfigureAwait(true));
Assert.NotEqual(((Task)task).ConfigureAwait(true), ((Task)task).ConfigureAwait(false));
// ConfiguredTaskAwaitable<T>
Assert.Equal(task.ConfigureAwait(false), ((Task)task).ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), ((Task)task).ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), ((Task)task).ConfigureAwait(false));
// ConfiguredTaskAwaitable.ConfiguredTaskAwaiter
Assert.Equal(((Task)task).ConfigureAwait(false).GetAwaiter(), ((Task)task).ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(((Task)task).ConfigureAwait(false).GetAwaiter(), ((Task)task).ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(((Task)task).ConfigureAwait(true).GetAwaiter(), ((Task)task).ConfigureAwait(false).GetAwaiter());
// ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), ((Task)task).ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), ((Task)task).ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), ((Task)task).ConfigureAwait(false).GetAwaiter());
}
[Fact]
public static void AsyncTaskAwaiterTests_NegativeTests()
{
{
// Validate GetResult on a single exception
var oneException = new TaskCompletionSource<string>();
oneException.SetException(new ArgumentException("uh oh"));
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<ArgumentException>(() => { ((Task)oneException.Task).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)oneException.Task).GetAwaiter().GetResult(); });
// w/ ConfigureAwait false and true
Assert.Throws<ArgumentException>(() => { ((Task)oneException.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task)oneException.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)oneException.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)oneException.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
}
{
// Validate GetResult on multiple exceptions
var multiException = new TaskCompletionSource<string>();
multiException.SetException(new Exception[] { new ArgumentException("uh oh"), new InvalidOperationException("uh oh") });
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<ArgumentException>(() => { ((Task)multiException.Task).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)multiException.Task).GetAwaiter().GetResult(); });
// w/ ConfigureAwait false and true
Assert.Throws<ArgumentException>(() => { ((Task)multiException.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task)multiException.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)multiException.Task).ConfigureAwait(false).GetAwaiter().GetResult(); });
Assert.Throws<ArgumentException>(() => { ((Task<string>)multiException.Task).ConfigureAwait(true).GetAwaiter().GetResult(); });
}
}
[Fact]
public static void RunAsyncTaskAwaiterAdditionalBehaviorsTests()
{
// Test that base SynchronizationContext is treated the same as no SynchronizationContext for awaits
{
var quwi = new QUWITaskScheduler();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
RunWithSchedulerAsCurrent(quwi, delegate
{
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
int result = 1;
var awaiter = ((Task)tcs.Task).GetAwaiter();
Assert.False(awaiter.IsCompleted, " > FAILURE. Awaiter on non-completed task should not be IsCompleted");
Assert.True(SynchronizationContext.Current != null, " > FAILURE. Expected a current SyncCtx but found null");
awaiter.OnCompleted(() =>
{
Assert.True(TaskScheduler.Current == quwi, " > FAILURE. Continuation should be running in task scheduler.");
Assert.True(SynchronizationContext.Current == null, " > FAILURE. Expected no current SyncCtx but found " + SynchronizationContext.Current);
result = 2;
mres.Set();
});
Assert.True(result == 1, " > FAILURE. Await continuation should not run until task completes.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
awaiter.GetResult();
Assert.True(result == 2, " > FAILURE. Await continuation should have completed.");
});
SynchronizationContext.SetSynchronizationContext(null);
}
}
[Fact]
public static void AsyncTaskAwaiterTests_CTandOCE()
{
// Test that CancellationToken is correctly flowed through await
{
var amb = AsyncTaskMethodBuilder.Create();
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
amb.SetException(oce);
try
{
amb.Task.GetAwaiter().GetResult();
Assert.True(false, string.Format(" > FAILURE. Faulted task's GetResult should have thrown."));
}
catch (OperationCanceledException oceToCheck)
{
Assert.True(oceToCheck.CancellationToken == cts.Token, " > FAILURE. The tasks token should have equaled the provided token.");
}
catch (Exception exc)
{
Assert.True(false, string.Format(" > FAILURE. Exception an OCE rather than a " + exc.GetType()));
}
}
// Test that original OCE is propagated through await
{
var tasks = new List<Task>();
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// A Task that throws an exception to cancel
var b = new Barrier(2);
Task<int> t2 = Task<int>.Factory.StartNew(() =>
{
b.SignalAndWait();
b.SignalAndWait();
throw oce;
}, cts.Token);
Task t1 = t2;
b.SignalAndWait(); // make sure task is started before we cancel
cts.Cancel();
b.SignalAndWait(); // release task to complete
tasks.Add(t2);
// A WhenAll Task
tasks.Add(Task.WhenAll(t1));
tasks.Add(Task.WhenAll(t1, Task.FromResult(42)));
tasks.Add(Task.WhenAll(Task.FromResult(42), t1));
tasks.Add(Task.WhenAll(t1, t1, t1));
// A WhenAll Task<int[]>
tasks.Add(Task.WhenAll(t2));
tasks.Add(Task.WhenAll(t2, Task.FromResult(42)));
tasks.Add(Task.WhenAll(Task.FromResult(42), t2));
tasks.Add(Task.WhenAll(t2, t2, t2));
// A Task.Run Task and Task<int>
tasks.Add(Task.Run(() => t1));
tasks.Add(Task.Run(() => t2));
// A FromAsync Task and Task<int>
tasks.Add(Task.Factory.FromAsync(t1, new Action<IAsyncResult>(ar => { throw oce; })));
tasks.Add(Task<int>.Factory.FromAsync(t2, new Func<IAsyncResult, int>(ar => { throw oce; })));
// Test each kind of task
foreach (var task in tasks)
{
((IAsyncResult)task).AsyncWaitHandle.WaitOne();
try
{
if (task is Task<int>)
{
((Task<int>)task).GetAwaiter().GetResult();
}
else if (task is Task<int[]>)
{
((Task<int[]>)task).GetAwaiter().GetResult();
}
else
{
task.GetAwaiter().GetResult();
}
Assert.True(false, " > FAILURE. Expected an OCE to be thrown.");
}
catch (Exception exc)
{
Assert.True(
Object.ReferenceEquals(oce, exc),
" > FAILURE. The thrown exception was not the original instance.");
}
}
}
}
#region Helper Methods / Classes
private class ValidateCorrectContextSynchronizationContext : SynchronizationContext
{
[ThreadStatic]
internal static bool IsPostedInContext;
internal int PostCount;
internal int SendCount;
public override void Post(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref PostCount);
Task.Run(() =>
{
IsPostedInContext = true;
d(state);
IsPostedInContext = false;
});
}
public override void Send(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref SendCount);
d(state);
}
}
/// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary>
private class QUWITaskScheduler : TaskScheduler
{
private int _queueTaskCount;
private int _tryExecuteTaskInlineCount;
public int QueueTaskCount { get { return _queueTaskCount; } }
public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref _queueTaskCount);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Interlocked.Increment(ref _tryExecuteTaskInlineCount);
return TryExecuteTask(task);
}
}
/// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
{
var t = new Task(action);
t.RunSynchronously(scheduler);
t.Wait();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReorderParameters
{
public partial class ReorderParametersTests
{
#region Methods
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeBeforeMethodName()
{
var markup = @"
using System;
class MyClass
{
public void $$Foo(int x, string y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeInParameterList()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, $$string y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeAfterParameterList()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)$$
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeBeforeMethodDeclaration()
{
var markup = @"
using System;
class MyClass
{
$$public void Foo(int x, string y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail()
{
var markup = @"
class C
{
static void Main(string[] args)
{
((System.IFormattable)null).ToSt$$ring(""test"", null);
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail()
{
var markup = @"
class C
{
static void Main(string[] args)
{
$$((System.IFormattable)null).ToString(""test"", null);
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail()
{
var markup = @"
class C
{
static void Main(string[] args)
{
((System.IFormattable)null).ToString(""test"",$$ null);
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail()
{
var markup = @"
class C
{
string s = ((System.IFormattable)null).ToString(""test"", null)$$;
}";
TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeInMethodBody()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
$$
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
$$Bar(x, y);
}
public void Bar(int x, string y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(y, x);
}
public void Bar(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_ArgumentList()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
$$Bar(x, y);
}
public void Bar(int x, string y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(y, x);
}
public void Bar(string y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_NestedCalls1()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar($$Baz(x, y), y);
}
public void Bar(int x, string y)
{
}
public int Baz(int x, string y)
{
return 1;
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(Baz(y, x), y);
}
public void Bar(int x, string y)
{
}
public int Baz(string y, int x)
{
return 1;
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_NestedCalls2()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar$$(Baz(x, y), y);
}
public void Bar(int x, string y)
{
}
public int Baz(int x, string y)
{
return 1;
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(y, Baz(x, y));
}
public void Bar(string y, int x)
{
}
public int Baz(int x, string y)
{
return 1;
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_NestedCalls3()
{
var markup = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(Baz(x, y), $$y);
}
public void Bar(int x, string y)
{
}
public int Baz(int x, string y)
{
return 1;
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
class MyClass
{
public void Foo(int x, string y)
{
Bar(y, Baz(x, y));
}
public void Bar(string y, int x)
{
}
public int Baz(int x, string y)
{
return 1;
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_Attribute()
{
var markup = @"
using System;
[$$My(1, 2)]
class MyAttribute : Attribute
{
public MyAttribute(int x, int y)
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
using System;
[My(2, 1)]
class MyAttribute : Attribute
{
public MyAttribute(int y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols()
{
var markup = @"
class Test
{
void M(int x, string y) { }
void M(int x, double y) { }
void M2() { $$M(""s"", 1); }
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Test
{
void M(string y, int x) { }
void M(int x, double y) { }
void M2() { M(1, ""s""); }
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor()
{
var markup = @"
class Program
{
public Program(int x, int y) : this(1, 2, 3)$$
{
}
public Program(int x, int y, int z)
{
}
}";
var permutation = new[] { 2, 1, 0 };
var updatedCode = @"
class Program
{
public Program(int x, int y) : this(3, 2, 1)
{
}
public Program(int z, int y, int x)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor()
{
var markup = @"
class B
{
public B(int a, int b)
{
}
}
class D : B
{
public D(int x, int y) : base(1, 2)$$
{
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class B
{
public B(int b, int a)
{
}
}
class D : B
{
public D(int x, int y) : base(2, 1)
{
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
#endregion
#region Indexers
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InvokeAtBeginningOfDeclaration()
{
var markup = @"
class Program
{
$$int this[int x, string y]
{
get { return 5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InParameters()
{
var markup = @"
class Program
{
int this[int x, $$string y]
{
get { return 5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InvokeAtEndOfDeclaration()
{
var markup = @"
class Program
{
int this[int x, string y]$$
{
get { return 5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InvokeInAccessor()
{
var markup = @"
class Program
{
int this[int x, string y]
{
get { return $$5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InvokeOnReference_BeforeTarget()
{
var markup = @"
class Program
{
void M(Program p)
{
var t = $$p[5, ""test""];
}
int this[int x, string y]
{
get { return 5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
void M(Program p)
{
var t = p[""test"", 5];
}
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)]
public void ReorderIndexerParameters_InvokeOnReference_InArgumentList()
{
var markup = @"
class Program
{
void M(Program p)
{
var t = p[5, ""test""$$];
}
int this[int x, string y]
{
get { return 5; }
set { }
}
}";
var permutation = new[] { 1, 0 };
var updatedCode = @"
class Program
{
void M(Program p)
{
var t = p[""test"", 5];
}
int this[string y, int x]
{
get { return 5; }
set { }
}
}";
TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode);
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using TestParameterizedProperties;
using TestPSSnapIn;
namespace ReferenceTests.API
{
// prevents the compiler from complaining about unused fields, etc
#pragma warning disable 169, 414, 0649
interface IDummyBase
{
int DummyBaseProperty { get; }
}
interface IDummy : IDummyBase
{
}
class DummyAncestor : IDummyBase
{
private int AncFieldPrivated;
protected int AncFieldProtected;
static public int AncFieldPublic;
public string AncProperty { get; set; }
public int DummyBaseProperty { get { return 0; } }
private void AncMethodPrivate() { }
protected void AncMethodProtected() { }
public void AncMethodPublic() { }
public virtual void VirtualMethod() { }
}
class DummyDescendant : DummyAncestor
{
private int DescFieldPrivated;
protected int DescFieldProtected;
internal int DescFieldInternal;
public int DescFieldPublic;
public string DescProperty { get; set; }
private void DescMethodPrivate() { }
protected void DescMethodProtected() { }
static public void DescMethodPublic() { }
public override void VirtualMethod() { }
}
#pragma warning restore 169, 414, 0649
[TestFixture]
public class PSObjectTests : ReferenceTestBase
{
private Collection<string> _dummyDescendantTypeNames = new Collection<string>() {
typeof(DummyDescendant).FullName,
typeof(DummyAncestor).FullName,
typeof(Object).FullName
};
private IEnumerable<string> GetPublicInstanceMembers(Type type)
{
var members = (from member in
type.GetMembers(BindingFlags.Instance | BindingFlags.Public)
where (member.MemberType & (MemberTypes.Field | MemberTypes.Property)) != 0
select member.Name).ToList();
type.GetInterfaces().ToList().ForEach(
i => members.AddRange(
from prop
in i.GetProperties(BindingFlags.Instance | BindingFlags.Public)
select prop.Name
)
);
return members.Distinct();
}
private IEnumerable<string> GetPublicInstanceMethods(Type type)
{
return from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
select method.Name;
}
[Test]
public void PSObjectWrapsInstance()
{
var instace = new DummyDescendant();
var psobj = PSObject.AsPSObject(instace);
Assert.AreSame(instace, psobj.BaseObject);
Assert.AreSame(instace, psobj.ImmediateBaseObject);
}
[Test]
public void PSObjectReflectsTypeNames()
{
var psobj = PSObject.AsPSObject(new DummyDescendant());
var names = psobj.TypeNames;
Assert.AreEqual(_dummyDescendantTypeNames, names);
}
[Test]
public void PSObjectReflectsProperties()
{
var psobj = PSObject.AsPSObject(new DummyDescendant());
var propertyNames = from prop in psobj.Properties select prop.Name;
var realProperyNames = GetPublicInstanceMembers(typeof(DummyDescendant));
Assert.That(propertyNames, Is.EquivalentTo(realProperyNames));
}
[Test]
public void PSObjectReflectsMethods()
{
var psobj = PSObject.AsPSObject(new DummyDescendant());
var methodNames = from method in psobj.Methods select method.Name;
var realMethodNames = GetPublicInstanceMethods(typeof(DummyDescendant));
Assert.That(methodNames, Is.EquivalentTo(realMethodNames));
}
[Test]
public void PSObjectReflectsMembers()
{
var psobj = PSObject.AsPSObject(new DummyDescendant());
var memberNames = from member in psobj.Members select member.Name;
var type = typeof(DummyDescendant);
var realMemberNames = GetPublicInstanceMembers(type).Concat(GetPublicInstanceMethods(type));
Assert.That(memberNames, Is.EquivalentTo(realMemberNames));
}
[Test]
public void AsPSObjectCannotWrapNull()
{
// TODO: check for exception type
Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate
{
PSObject.AsPSObject(null);
});
}
[Test]
public void PSObjectCannotConstructNull()
{
// TODO: check for exception type
Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate
{
new PSObject(null);
});
}
[Test]
[TestCase(new int[] { 1, 2 }, "1 2")]
[TestCase(new object[] { 1, "foo" }, "1 foo")]
[TestCase(new object[] { 1, new object[] { 1, 2 } }, "1 System.Object[]")]
public void PSObjectToStringConvertsArrayCorrectly(object input, string expected)
{
Assert.AreEqual(expected, new PSObject(input).ToString());
}
[Test, SetCulture("de-DE")]
public void PSObjectToStringUsesCurrentCulture()
{
Assert.AreEqual("1 2,5", new PSObject(new object[] { 1, 2.5 }).ToString());
}
[Test]
public void ObjectWithReadOnlyParameterizedProperty()
{
var obj = new TestReadOnlyParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsFalse(propertyInfo.IsSettable);
Assert.IsTrue(propertyInfo.IsInstance);
Assert.AreEqual(PSMemberTypes.ParameterizedProperty, propertyInfo.MemberType);
Assert.AreEqual("FileNames", propertyInfo.Name);
Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string FileNames(int index) {get;}", propertyInfo.OverloadDefinitions[0]);
}
[Test]
public void ObjectWithWriteOnlyParameterizedProperty()
{
var obj = new TestWriteOnlyParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsFalse(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("void FileNames(int index) {set;}", propertyInfo.OverloadDefinitions[0]);
}
[Test]
public void ObjectWithReadWriteOnlyParameterizedProperty()
{
var obj = new TestParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]);
}
[Test]
public void ParameterizedPropertyCopy()
{
var obj = new TestReadOnlyParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
propertyInfo = propertyInfo.Copy() as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsFalse(propertyInfo.IsSettable);
Assert.IsTrue(propertyInfo.IsInstance);
Assert.AreEqual(PSMemberTypes.ParameterizedProperty, propertyInfo.MemberType);
Assert.AreEqual("FileNames", propertyInfo.Name);
Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string FileNames(int index) {get;}", propertyInfo.OverloadDefinitions[0]);
}
[Test]
public void InvokeParameterizedPropertyGetter()
{
var obj = new TestParameterizedProperty(new string[] {"a.txt"});
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
object result = propertyInfo.Invoke(0);
Assert.AreEqual("a.txt", result);
}
[Test]
public void InvokeParameterizedPropertySetter()
{
var obj = new TestParameterizedProperty(new string[] { "a.txt" });
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
propertyInfo.InvokeSet("b.txt", 0);
Assert.AreEqual("b.txt", obj[0]);
}
[Test]
public void CannotInvokeParameterizedPropertySetterWithInvokeMethod()
{
var obj = new TestParameterizedProperty(new string[] { "a.txt" });
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
GetValueInvocationException ex = Assert.Throws<GetValueInvocationException>(() => propertyInfo.Invoke(0, "b.txt"));
var innerEx = ex.InnerException as MethodException;
StringAssert.StartsWith("Exception getting \"FileNames\": ", ex.Message);
Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"2\".", innerEx.Message);
StringAssert.StartsWith("Exception getting \"FileNames\": ", ex.ErrorRecord.Exception.Message);
Assert.AreEqual("CatchFromBaseParameterizedPropertyAdapterGetValue", ex.ErrorRecord.FullyQualifiedErrorId);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity);
Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category);
Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType);
Assert.IsNull(ex.ErrorRecord.TargetObject);
Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), ex.ErrorRecord.Exception);
StringAssert.StartsWith("Cannot find an overload for \"FileNames\"", innerEx.ErrorRecord.Exception.Message);
Assert.AreEqual("MethodCountCouldNotFindBest", innerEx.ErrorRecord.FullyQualifiedErrorId);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.Activity);
Assert.AreEqual(ErrorCategory.NotSpecified, innerEx.ErrorRecord.CategoryInfo.Category);
Assert.AreEqual("ParentContainsErrorRecordException", innerEx.ErrorRecord.CategoryInfo.Reason);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetName);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetType);
Assert.IsNull(innerEx.ErrorRecord.TargetObject);
Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), innerEx.ErrorRecord.Exception);
}
[Test]
public void CannotInvokeParameterizedPropertyGetterWithInvokeSet()
{
var obj = new TestParameterizedProperty(new string[] { "a.txt" });
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
SetValueInvocationException ex = Assert.Throws<SetValueInvocationException>(() => propertyInfo.InvokeSet(0));
var innerEx = ex.InnerException as MethodException;
StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.Message);
Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"0\".", innerEx.Message);
StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.ErrorRecord.Exception.Message);
Assert.AreEqual("CatchFromBaseAdapterParameterizedPropertySetValue", ex.ErrorRecord.FullyQualifiedErrorId);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity);
Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category);
Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType);
Assert.IsNull(ex.ErrorRecord.TargetObject);
Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), ex.ErrorRecord.Exception);
StringAssert.StartsWith("Cannot find an overload for \"FileNames\"", innerEx.ErrorRecord.Exception.Message);
Assert.AreEqual("MethodCountCouldNotFindBest", innerEx.ErrorRecord.FullyQualifiedErrorId);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.Activity);
Assert.AreEqual(ErrorCategory.NotSpecified, innerEx.ErrorRecord.CategoryInfo.Category);
Assert.AreEqual("ParentContainsErrorRecordException", innerEx.ErrorRecord.CategoryInfo.Reason);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetName);
Assert.AreEqual("", innerEx.ErrorRecord.CategoryInfo.TargetType);
Assert.IsNull(innerEx.ErrorRecord.TargetObject);
Assert.IsInstanceOf(typeof(ParentContainsErrorRecordException), innerEx.ErrorRecord.Exception);
}
[Test]
public void TooManyArgumentsForParameterizedPropertyInvokeSet()
{
var obj = new TestParameterizedProperty(new string[] { "a.txt" });
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
SetValueInvocationException ex = Assert.Throws<SetValueInvocationException>(() => propertyInfo.InvokeSet(0, 1, 2, 3));
var innerEx = ex.InnerException as MethodException;
StringAssert.StartsWith("Exception setting \"FileNames\": ", ex.Message);
Assert.AreEqual("Cannot find an overload for \"FileNames\" and the argument count: \"3\".", innerEx.Message);
}
[Test]
public void TooManyArgumentsForPSMethodInvoke()
{
var obj = new Object();
var psObject = new PSObject(obj);
PSMethodInfo method = psObject.Methods.First(m => m.Name == "ToString");
MethodException ex = Assert.Throws<MethodException>(() => method.Invoke(1, 2, 3, 4, 5));
Assert.AreEqual("Cannot find an overload for \"ToString\" and the argument count: \"5\".", ex.Message);
}
[Test]
public void ObjectWithOverloadedByTypeParameterizedProperty()
{
var obj = new TestOverloadedByTypeParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("FileNames", propertyInfo.Name);
Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]);
Assert.AreEqual("string FileNames(string fileName) {get;set;}", propertyInfo.OverloadDefinitions[1]);
}
[Test]
public void ObjectWithOverloadedByArgumentNumberParameterizedProperty()
{
var obj = new TestOverloadedByArgumentNumbersParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("Grid", propertyInfo.Name);
Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string Grid(int x) {get;set;}", propertyInfo.OverloadDefinitions[0]);
Assert.AreEqual("string Grid(int x, int y) {get;set;}", propertyInfo.OverloadDefinitions[1]);
}
[Test]
public void InvokeOverloadedByTypeParameterizedPropertySetter()
{
var obj = new TestOverloadedByTypeParameterizedProperty(new [] {"a.txt"});
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty;
propertyInfo.InvokeSet("b.txt", "a.txt");
Assert.AreEqual("b.txt", obj[1]);
}
[Test]
public void InvokeOverloadedByArgumentNumberParameterizedPropertyGetter()
{
var obj = new TestOverloadedByArgumentNumbersParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty;
object result = propertyInfo.Invoke(1, 2);
Assert.AreEqual("1, 2", result);
}
[Test]
public void InvokeOverloadedByArgumentNumbersParameterizedPropertySetter()
{
var obj = new TestOverloadedByArgumentNumbersParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "Grid") as PSParameterizedProperty;
propertyInfo.InvokeSet("b.txt", 1, 2);
Assert.AreEqual("b.txt", obj.get_Grid(1, 2));
}
[Test]
public void ObjectWithTwoInterfacesOneWithParameterizedProperty()
{
var obj = new TestInterfaceParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("FileNames", propertyInfo.Name);
Assert.AreEqual("System.String", propertyInfo.TypeNameOfValue);
Assert.AreEqual(1, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string ITestParameterizedProperty.FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]);
}
[Test]
public void ObjectWithOverloadedParameterizedPropertiesWithDifferentReturnTypes()
{
var obj = new TestDifferentReturnTypesParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "FileNames") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("FileNames", propertyInfo.Name);
Assert.AreEqual("System.Object", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("string FileNames(int index) {get;set;}", propertyInfo.OverloadDefinitions[0]);
Assert.AreEqual("int FileNames(string fileName) {get;set;}", propertyInfo.OverloadDefinitions[1]);
}
[Test]
public void DictionaryObjectInterfaceHasItemParameterizedProperty()
{
var obj = new Dictionary<string, int>();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.Single(m => m.Name == "Item") as PSParameterizedProperty;
Assert.IsTrue(propertyInfo.IsGettable);
Assert.IsTrue(propertyInfo.IsSettable);
Assert.AreEqual("Item", propertyInfo.Name);
Assert.AreEqual("System.Object", propertyInfo.TypeNameOfValue);
Assert.AreEqual(propertyInfo, propertyInfo.Value);
Assert.AreEqual(2, propertyInfo.OverloadDefinitions.Count);
Assert.AreEqual("int Item(string key) {get;set;}", propertyInfo.OverloadDefinitions[0]);
Assert.AreEqual("System.Object IDictionary.Item(System.Object key) {get;set;}", propertyInfo.OverloadDefinitions[1]);
}
[Test]
public void SetParameterizedPropertyValue()
{
const string expectedErrorMessage = "Cannot set the Value property for PSMemberInfo object of type \"System.Management.Automation.PSParameterizedProperty\".";
var obj = new TestParameterizedProperty();
var psObject = new PSObject(obj);
var propertyInfo = psObject.Members.FirstOrDefault(m => m.Name == "FileNames") as PSParameterizedProperty;
var ex = Assert.Throws<ExtendedTypeSystemException>(() => propertyInfo.Value = "a");
var errorRecordException = ex.ErrorRecord.Exception as ParentContainsErrorRecordException;
Assert.AreEqual(expectedErrorMessage, ex.Message);
Assert.IsNull(ex.InnerException);
Assert.AreEqual("CannotChangePSMethodInfoValue", ex.ErrorRecord.FullyQualifiedErrorId);
Assert.AreEqual(expectedErrorMessage, errorRecordException.Message);
Assert.IsNull(errorRecordException.InnerException);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.Activity);
Assert.AreEqual(ErrorCategory.NotSpecified, ex.ErrorRecord.CategoryInfo.Category);
Assert.AreEqual("ParentContainsErrorRecordException", ex.ErrorRecord.CategoryInfo.Reason);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetName);
Assert.AreEqual("", ex.ErrorRecord.CategoryInfo.TargetType);
Assert.IsNull(ex.ErrorRecord.TargetObject);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using NUnit.Framework;
using HostMe.Sdk.Client;
using HostMe.Sdk.Api;
using HostMe.Sdk.Model;
namespace HostMe.Sdk.Test
{
/// <summary>
/// Class for testing AdminLoyaltyApi
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the API endpoint.
/// </remarks>
[TestFixture]
public class AdminLoyaltyApiTests
{
private AdminLoyaltyApi instance;
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
instance = new AdminLoyaltyApi();
}
/// <summary>
/// Clean up after each unit test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of AdminLoyaltyApi
/// </summary>
[Test]
public void InstanceTest()
{
Assert.IsInstanceOf<AdminLoyaltyApi> (instance, "instance is a AdminLoyaltyApi");
}
/// <summary>
/// Test AddMember
/// </summary>
[Test]
public void AddMemberTest()
{
// TODO: add unit test for the method 'AddMember'
int? restaurantId = null; // TODO: replace null with proper value
MembershipCreate contract = null; // TODO: replace null with proper value
var response = instance.AddMember(restaurantId, contract);
Assert.IsInstanceOf<Object> (response, "response is Object");
}
/// <summary>
/// Test AddNewReward
/// </summary>
[Test]
public void AddNewRewardTest()
{
// TODO: add unit test for the method 'AddNewReward'
int? restaurantId = null; // TODO: replace null with proper value
Reward reward = null; // TODO: replace null with proper value
var response = instance.AddNewReward(restaurantId, reward);
Assert.IsInstanceOf<Reward> (response, "response is Reward");
}
/// <summary>
/// Test ApproveRedeemRequest
/// </summary>
[Test]
public void ApproveRedeemRequestTest()
{
// TODO: add unit test for the method 'ApproveRedeemRequest'
int? restaurantId = null; // TODO: replace null with proper value
string redeemId = null; // TODO: replace null with proper value
var response = instance.ApproveRedeemRequest(restaurantId, redeemId);
Assert.IsInstanceOf<RedeemRequest> (response, "response is RedeemRequest");
}
/// <summary>
/// Test CloseMembership
/// </summary>
[Test]
public void CloseMembershipTest()
{
// TODO: add unit test for the method 'CloseMembership'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
var response = instance.CloseMembership(restaurantId, memberId);
Assert.IsInstanceOf<Member> (response, "response is Member");
}
/// <summary>
/// Test DeleteReward
/// </summary>
[Test]
public void DeleteRewardTest()
{
// TODO: add unit test for the method 'DeleteReward'
int? restaurantId = null; // TODO: replace null with proper value
string rewardId = null; // TODO: replace null with proper value
instance.DeleteReward(restaurantId, rewardId);
}
/// <summary>
/// Test ExportMembers
/// </summary>
[Test]
public void ExportMembersTest()
{
// TODO: add unit test for the method 'ExportMembers'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.ExportMembers(restaurantId);
Assert.IsInstanceOf<Object> (response, "response is Object");
}
/// <summary>
/// Test Filter
/// </summary>
[Test]
public void FilterTest()
{
// TODO: add unit test for the method 'Filter'
int? restaurantId = null; // TODO: replace null with proper value
int? take = null; // TODO: replace null with proper value
string token = null; // TODO: replace null with proper value
var response = instance.Filter(restaurantId, take, token);
Assert.IsInstanceOf<List<CustomerProfile>> (response, "response is List<CustomerProfile>");
}
/// <summary>
/// Test FindMemberByPhoneNumber
/// </summary>
[Test]
public void FindMemberByPhoneNumberTest()
{
// TODO: add unit test for the method 'FindMemberByPhoneNumber'
int? restaurantId = null; // TODO: replace null with proper value
string phoneNumber = null; // TODO: replace null with proper value
var response = instance.FindMemberByPhoneNumber(restaurantId, phoneNumber);
Assert.IsInstanceOf<Member> (response, "response is Member");
}
/// <summary>
/// Test GetAlRewards
/// </summary>
[Test]
public void GetAlRewardsTest()
{
// TODO: add unit test for the method 'GetAlRewards'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetAlRewards(restaurantId);
Assert.IsInstanceOf<List<Reward>> (response, "response is List<Reward>");
}
/// <summary>
/// Test GetAllMembers
/// </summary>
[Test]
public void GetAllMembersTest()
{
// TODO: add unit test for the method 'GetAllMembers'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetAllMembers(restaurantId);
Assert.IsInstanceOf<ODataPagedResult1MemberContract> (response, "response is ODataPagedResult1MemberContract");
}
/// <summary>
/// Test GetAllRedeemRequests
/// </summary>
[Test]
public void GetAllRedeemRequestsTest()
{
// TODO: add unit test for the method 'GetAllRedeemRequests'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetAllRedeemRequests(restaurantId);
Assert.IsInstanceOf<List<RedeemRequest>> (response, "response is List<RedeemRequest>");
}
/// <summary>
/// Test GetDefaultLoyaltySettings
/// </summary>
[Test]
public void GetDefaultLoyaltySettingsTest()
{
// TODO: add unit test for the method 'GetDefaultLoyaltySettings'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetDefaultLoyaltySettings(restaurantId);
Assert.IsInstanceOf<LoyaltySettings> (response, "response is LoyaltySettings");
}
/// <summary>
/// Test GetLoyaltySettings
/// </summary>
[Test]
public void GetLoyaltySettingsTest()
{
// TODO: add unit test for the method 'GetLoyaltySettings'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetLoyaltySettings(restaurantId);
Assert.IsInstanceOf<LoyaltySettings> (response, "response is LoyaltySettings");
}
/// <summary>
/// Test GetMemberAvatar
/// </summary>
[Test]
public void GetMemberAvatarTest()
{
// TODO: add unit test for the method 'GetMemberAvatar'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
var response = instance.GetMemberAvatar(restaurantId, memberId);
Assert.IsInstanceOf<byte[]> (response, "response is byte[]");
}
/// <summary>
/// Test GetMemberTransactions
/// </summary>
[Test]
public void GetMemberTransactionsTest()
{
// TODO: add unit test for the method 'GetMemberTransactions'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
var response = instance.GetMemberTransactions(restaurantId, memberId);
Assert.IsInstanceOf<ODataPagedResult1TransactionContract> (response, "response is ODataPagedResult1TransactionContract");
}
/// <summary>
/// Test GetMemberVisits
/// </summary>
[Test]
public void GetMemberVisitsTest()
{
// TODO: add unit test for the method 'GetMemberVisits'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
var response = instance.GetMemberVisits(restaurantId, memberId);
Assert.IsInstanceOf<ODataPagedResult1MembershipVisitItemContract> (response, "response is ODataPagedResult1MembershipVisitItemContract");
}
/// <summary>
/// Test GetMembershipInfo
/// </summary>
[Test]
public void GetMembershipInfoTest()
{
// TODO: add unit test for the method 'GetMembershipInfo'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
var response = instance.GetMembershipInfo(restaurantId, memberId);
Assert.IsInstanceOf<Member> (response, "response is Member");
}
/// <summary>
/// Test GetRewardById
/// </summary>
[Test]
public void GetRewardByIdTest()
{
// TODO: add unit test for the method 'GetRewardById'
int? restaurantId = null; // TODO: replace null with proper value
string rewardId = null; // TODO: replace null with proper value
var response = instance.GetRewardById(restaurantId, rewardId);
Assert.IsInstanceOf<Reward> (response, "response is Reward");
}
/// <summary>
/// Test PublishReward
/// </summary>
[Test]
public void PublishRewardTest()
{
// TODO: add unit test for the method 'PublishReward'
int? restaurantId = null; // TODO: replace null with proper value
string rewardId = null; // TODO: replace null with proper value
var response = instance.PublishReward(restaurantId, rewardId);
Assert.IsInstanceOf<Reward> (response, "response is Reward");
}
/// <summary>
/// Test RejectRedeemRequest
/// </summary>
[Test]
public void RejectRedeemRequestTest()
{
// TODO: add unit test for the method 'RejectRedeemRequest'
int? restaurantId = null; // TODO: replace null with proper value
string redeemId = null; // TODO: replace null with proper value
RedeemRequestReject reject = null; // TODO: replace null with proper value
var response = instance.RejectRedeemRequest(restaurantId, redeemId, reject);
Assert.IsInstanceOf<RedeemRequest> (response, "response is RedeemRequest");
}
/// <summary>
/// Test SetLoyaltySettings
/// </summary>
[Test]
public void SetLoyaltySettingsTest()
{
// TODO: add unit test for the method 'SetLoyaltySettings'
int? restaurantId = null; // TODO: replace null with proper value
LoyaltySettings settings = null; // TODO: replace null with proper value
instance.SetLoyaltySettings(restaurantId, settings);
}
/// <summary>
/// Test UnpublishReward
/// </summary>
[Test]
public void UnpublishRewardTest()
{
// TODO: add unit test for the method 'UnpublishReward'
int? restaurantId = null; // TODO: replace null with proper value
string rewardId = null; // TODO: replace null with proper value
var response = instance.UnpublishReward(restaurantId, rewardId);
Assert.IsInstanceOf<Reward> (response, "response is Reward");
}
/// <summary>
/// Test UpdateMember
/// </summary>
[Test]
public void UpdateMemberTest()
{
// TODO: add unit test for the method 'UpdateMember'
int? restaurantId = null; // TODO: replace null with proper value
int? memberId = null; // TODO: replace null with proper value
MembershipUpdate contract = null; // TODO: replace null with proper value
var response = instance.UpdateMember(restaurantId, memberId, contract);
Assert.IsInstanceOf<Object> (response, "response is Object");
}
/// <summary>
/// Test UpdateReward
/// </summary>
[Test]
public void UpdateRewardTest()
{
// TODO: add unit test for the method 'UpdateReward'
int? restaurantId = null; // TODO: replace null with proper value
string rewardId = null; // TODO: replace null with proper value
Reward reward = null; // TODO: replace null with proper value
var response = instance.UpdateReward(restaurantId, rewardId, reward);
Assert.IsInstanceOf<Reward> (response, "response is Reward");
}
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for high precision colors has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
#define USE_UNSAFE_CODE
using MatterHackers.Agg.Image;
using MatterHackers.VectorMath;
using System;
using image_filter_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_filter_scale_e;
using image_subpixel_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_subpixel_scale_e;
namespace MatterHackers.Agg
{
// it should be easy to write a 90 rotating or mirroring filter too. LBB 2012/01/14
public class span_image_filter_rgba_nn_stepXby1 : span_image_filter
{
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
public span_image_filter_rgba_nn_stepXby1(IImageBufferAccessor sourceAccessor, ISpanInterpolator spanInterpolator)
: base(sourceAccessor, spanInterpolator, null)
{
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage;
if (SourceRenderingBuffer.BitDepth != 32)
{
throw new NotSupportedException("The source is expected to be 32 bit.");
}
ISpanInterpolator spanInterpolator = interpolator();
spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len);
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int bufferIndex;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer();
#if USE_UNSAFE_CODE
unsafe
{
fixed (byte* pSource = fg_ptr)
{
do
{
span[spanIndex++] = *(Color*)&(pSource[bufferIndex]);
bufferIndex += 4;
} while (--len != 0);
}
}
#else
RGBA_Bytes color = new RGBA_Bytes();
do
{
color.blue = fg_ptr[bufferIndex++];
color.green = fg_ptr[bufferIndex++];
color.red = fg_ptr[bufferIndex++];
color.alpha = fg_ptr[bufferIndex++];
span[spanIndex++] = color;
} while (--len != 0);
#endif
}
}
//==============================================span_image_filter_rgba_nn
public class span_image_filter_rgba_nn : span_image_filter
{
private const int baseShift = 8;
private const int baseScale = (int)(1 << baseShift);
private const int baseMask = baseScale - 1;
public span_image_filter_rgba_nn(IImageBufferAccessor sourceAccessor, ISpanInterpolator spanInterpolator)
: base(sourceAccessor, spanInterpolator, null)
{
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage;
if (SourceRenderingBuffer.BitDepth != 32)
{
throw new NotSupportedException("The source is expected to be 32 bit.");
}
ISpanInterpolator spanInterpolator = interpolator();
spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len);
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer();
do
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int bufferIndex;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
Color color;
color.blue = fg_ptr[bufferIndex++];
color.green = fg_ptr[bufferIndex++];
color.red = fg_ptr[bufferIndex++];
color.alpha = fg_ptr[bufferIndex++];
span[spanIndex] = color;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
};
public class span_image_filter_rgba_bilinear : span_image_filter
{
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
public span_image_filter_rgba_bilinear(IImageBufferAccessor src, ISpanInterpolator inter)
: base(src, inter, null)
{
}
#if false
public void generate(out RGBA_Bytes destPixel, int x, int y)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), 1);
int* fg = stackalloc int[4];
byte* fg_ptr;
IImage imageSource = base.source().DestImage;
int maxx = (int)imageSource.Width() - 1;
int maxy = (int)imageSource.Height() - 1;
ISpanInterpolator spanInterpolator = base.interpolator();
unchecked
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
fg[0] = fg[1] = fg[2] = fg[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
fg_ptr = imageSource.GetPixelPointerY(y_lr) + (x_lr * 4);
weight = (int)(((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
fg[0] += weight * fg_ptr[0];
fg[1] += weight * fg_ptr[1];
fg[2] += weight * fg_ptr[2];
fg[3] += weight * fg_ptr[3];
weight = (int)(x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
fg[0] += weight * fg_ptr[4];
fg[1] += weight * fg_ptr[5];
fg[2] += weight * fg_ptr[6];
fg[3] += weight * fg_ptr[7];
++y_lr;
fg_ptr = imageSource.GetPixelPointerY(y_lr) + (x_lr * 4);
weight = (int)(((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
fg[0] += weight * fg_ptr[0];
fg[1] += weight * fg_ptr[1];
fg[2] += weight * fg_ptr[2];
fg[3] += weight * fg_ptr[3];
weight = (int)(x_hr * y_hr);
fg[0] += weight * fg_ptr[4];
fg[1] += weight * fg_ptr[5];
fg[2] += weight * fg_ptr[6];
fg[3] += weight * fg_ptr[7];
fg[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
fg[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
fg[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
fg[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
destPixel.m_R = (byte)fg[OrderR];
destPixel.m_G = (byte)fg[OrderG];
destPixel.m_B = (byte)fg[ImageBuffer.OrderB];
destPixel.m_A = (byte)fg[OrderA];
}
}
#endif
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage;
ISpanInterpolator spanInterpolator = base.interpolator();
int bufferIndex;
byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(out bufferIndex);
unchecked
{
do
{
int tempR;
int tempG;
int tempB;
int tempA;
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
tempR =
tempG =
tempB =
tempA = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
bufferIndex += 4;
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
y_lr++;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
bufferIndex += 4;
weight = (x_hr * y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
tempR >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
tempG >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
tempB >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
tempA >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
Color color;
color.red = (byte)tempR;
color.green = (byte)tempG;
color.blue = (byte)tempB;
color.alpha = (byte)255;// tempA;
span[spanIndex] = color;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
}
}
public class span_image_filter_rgba_bilinear_float : span_image_filter_float
{
public span_image_filter_rgba_bilinear_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat inter)
: base(src, inter, null)
{
}
public override void generate(ColorF[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
ImageBufferFloat SourceRenderingBuffer = (ImageBufferFloat)base.source().SourceImage;
ISpanInterpolatorFloat spanInterpolator = base.interpolator();
int bufferIndex;
float[] fg_ptr = SourceRenderingBuffer.GetBuffer(out bufferIndex);
unchecked
{
do
{
float tempR;
float tempG;
float tempB;
float tempA;
float x_hr;
float y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_dbl();
y_hr -= base.filter_dy_dbl();
int x_lr = (int)x_hr;
int y_lr = (int)y_hr;
float weight;
tempR = tempG = tempB = tempA = 0;
x_hr -= x_lr;
y_hr -= y_lr;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
#if false
unsafe
{
fixed (float* pSource = fg_ptr)
{
Vector4f tempFinal = new Vector4f(0.0f, 0.0f, 0.0f, 0.0f);
Vector4f color0 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 0]);
weight = (1.0f - x_hr) * (1.0f - y_hr);
Vector4f weight4f = new Vector4f(weight, weight, weight, weight);
tempFinal = tempFinal + weight4f * color0;
Vector4f color1 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 4]);
weight = (x_hr) * (1.0f - y_hr);
weight4f = new Vector4f(weight, weight, weight, weight);
tempFinal = tempFinal + weight4f * color1;
y_lr++;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
Vector4f color2 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 0]);
weight = (1.0f - x_hr) * (y_hr);
weight4f = new Vector4f(weight, weight, weight, weight);
tempFinal = tempFinal + weight4f * color2;
Vector4f color3 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 4]);
weight = (x_hr) * (y_hr);
weight4f = new Vector4f(weight, weight, weight, weight);
tempFinal = tempFinal + weight4f * color3;
RGBA_Floats color;
color.m_B = tempFinal.X;
color.m_G = tempFinal.Y;
color.m_R = tempFinal.Z;
color.m_A = tempFinal.W;
span[spanIndex] = color;
}
}
#else
weight = (1.0f - x_hr) * (1.0f - y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
bufferIndex += 4;
weight = (x_hr) * (1.0f - y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
y_lr++;
bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
weight = (1.0f - x_hr) * (y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
bufferIndex += 4;
weight = (x_hr) * (y_hr);
tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
ColorF color;
color.red = tempR;
color.green = tempG;
color.blue = tempB;
color.alpha = tempA;
span[spanIndex] = color;
#endif
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
}
};
//====================================span_image_filter_rgba_bilinear_clip
public class span_image_filter_rgba_bilinear_clip : span_image_filter
{
private Color m_OutsideSourceColor;
private const int base_shift = 8;
private const int base_scale = (int)(1 << base_shift);
private const int base_mask = base_scale - 1;
public span_image_filter_rgba_bilinear_clip(IImageBufferAccessor src,
IColorType back_color, ISpanInterpolator inter)
: base(src, inter, null)
{
m_OutsideSourceColor = back_color.ToColor();
}
public IColorType background_color()
{
return m_OutsideSourceColor;
}
public void background_color(IColorType v)
{
m_OutsideSourceColor = v.ToColor();
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage;
int bufferIndex;
byte[] fg_ptr;
if (base.m_interpolator.GetType() == typeof(MatterHackers.Agg.span_interpolator_linear)
&& ((MatterHackers.Agg.span_interpolator_linear)base.m_interpolator).transformer().GetType() == typeof(MatterHackers.Agg.Transform.Affine)
&& ((MatterHackers.Agg.Transform.Affine)((MatterHackers.Agg.span_interpolator_linear)base.m_interpolator).transformer()).is_identity())
{
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x, y, out bufferIndex);
//unsafe
{
#if true
do
{
span[spanIndex].blue = (byte)fg_ptr[bufferIndex++];
span[spanIndex].green = (byte)fg_ptr[bufferIndex++];
span[spanIndex].red = (byte)fg_ptr[bufferIndex++];
span[spanIndex].alpha = (byte)fg_ptr[bufferIndex++];
++spanIndex;
} while (--len != 0);
#else
fixed (byte* pSource = &fg_ptr[bufferIndex])
{
int* pSourceInt = (int*)pSource;
fixed (RGBA_Bytes* pDest = &span[spanIndex])
{
int* pDestInt = (int*)pDest;
do
{
*pDestInt++ = *pSourceInt++;
} while (--len != 0);
}
}
#endif
}
return;
}
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int[] accumulatedColor = new int[4];
int back_r = m_OutsideSourceColor.red;
int back_g = m_OutsideSourceColor.green;
int back_b = m_OutsideSourceColor.blue;
int back_a = m_OutsideSourceColor.alpha;
int distanceBetweenPixelsInclusive = base.GetImageBufferAccessor().SourceImage.GetBytesBetweenPixelsInclusive();
int maxx = (int)SourceRenderingBuffer.Width - 1;
int maxy = (int)SourceRenderingBuffer.Height - 1;
ISpanInterpolator spanInterpolator = base.interpolator();
unchecked
{
do
{
int x_hr;
int y_hr;
spanInterpolator.coordinates(out x_hr, out y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int weight;
if (x_lr >= 0 && y_lr >= 0 &&
x_lr < maxx && y_lr < maxy)
{
accumulatedColor[0] =
accumulatedColor[1] =
accumulatedColor[2] =
accumulatedColor[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
if (weight > base_mask)
{
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
}
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
if (weight > base_mask)
{
bufferIndex += distanceBetweenPixelsInclusive;
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
}
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
if (weight > base_mask)
{
++y_lr;
fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex);
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
}
weight = (x_hr * y_hr);
if (weight > base_mask)
{
bufferIndex += distanceBetweenPixelsInclusive;
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
}
accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
}
else
{
if (x_lr < -1 || y_lr < -1 ||
x_lr > maxx || y_lr > maxy)
{
accumulatedColor[0] = back_r;
accumulatedColor[1] = back_g;
accumulatedColor[2] = back_b;
accumulatedColor[3] = back_a;
}
else
{
accumulatedColor[0] =
accumulatedColor[1] =
accumulatedColor[2] =
accumulatedColor[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2;
x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask;
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) *
((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
if (weight > base_mask)
{
BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
}
x_lr++;
weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr));
if (weight > base_mask)
{
BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
}
x_lr--;
y_lr++;
weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr);
if (weight > base_mask)
{
BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
}
x_lr++;
weight = (x_hr * y_hr);
if (weight > base_mask)
{
BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight);
}
accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
accumulatedColor[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2;
}
}
span[spanIndex].red = (byte)accumulatedColor[0];
span[spanIndex].green = (byte)accumulatedColor[1];
span[spanIndex].blue = (byte)accumulatedColor[2];
span[spanIndex].alpha = (byte)accumulatedColor[3];
++spanIndex;
spanInterpolator.Next();
} while (--len != 0);
}
}
private void BlendInFilterPixel(int[] accumulatedColor, int back_r, int back_g, int back_b, int back_a, IImageByte SourceRenderingBuffer, int maxx, int maxy, int x_lr, int y_lr, int weight)
{
byte[] fg_ptr;
unchecked
{
if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy)
{
int bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr);
fg_ptr = SourceRenderingBuffer.GetBuffer();
accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
}
else
{
accumulatedColor[0] += back_r * weight;
accumulatedColor[1] += back_g * weight;
accumulatedColor[2] += back_b * weight;
accumulatedColor[3] += back_a * weight;
}
}
}
};
/*
//==============================================span_image_filter_rgba_2x2
//template<class Source, class Interpolator>
public class span_image_filter_rgba_2x2 : span_image_filter//<Source, Interpolator>
{
//typedef Source source_type;
//typedef typename source_type::color_type color_type;
//typedef typename source_type::order_type order_type;
//typedef Interpolator interpolator_type;
//typedef span_image_filter<source_type, interpolator_type> base_type;
//typedef typename color_type::value_type value_type;
//typedef typename color_type::calc_type calc_type;
enum base_scale_e
{
base_shift = 8, //color_type::base_shift,
base_mask = 255,//color_type::base_mask
};
//--------------------------------------------------------------------
public span_image_filter_rgba_2x2() {}
public span_image_filter_rgba_2x2(pixfmt_alpha_blend_bgra32 src,
interpolator_type inter,
ImageFilterLookUpTable filter) :
base(src, inter, filter)
{}
//--------------------------------------------------------------------
public void generate(color_type* span, int x, int y, unsigned len)
{
base.interpolator().begin(x + base.filter_dx_dbl(),
y + base.filter_dy_dbl(), len);
calc_type fg[4];
byte *fg_ptr;
int16* weight_array = base.filter().weight_array() +
((base.filter().diameter()/2 - 1) <<
image_subpixel_shift);
do
{
int x_hr;
int y_hr;
base.interpolator().coordinates(&x_hr, &y_hr);
x_hr -= base.filter_dx_int();
y_hr -= base.filter_dy_int();
int x_lr = x_hr >> image_subpixel_shift;
int y_lr = y_hr >> image_subpixel_shift;
unsigned weight;
fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2;
x_hr &= image_subpixel_mask;
y_hr &= image_subpixel_mask;
fg_ptr = base.source().span(x_lr, y_lr, 2);
weight = (weight_array[x_hr + image_subpixel_scale] *
weight_array[y_hr + image_subpixel_scale] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
image_filter_shift;
fg[0] += weight * *fg_ptr++;
fg[1] += weight * *fg_ptr++;
fg[2] += weight * *fg_ptr++;
fg[3] += weight * *fg_ptr;
fg_ptr = base.source().next_x();
weight = (weight_array[x_hr] *
weight_array[y_hr + image_subpixel_scale] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
image_filter_shift;
fg[0] += weight * *fg_ptr++;
fg[1] += weight * *fg_ptr++;
fg[2] += weight * *fg_ptr++;
fg[3] += weight * *fg_ptr;
fg_ptr = base.source().next_y();
weight = (weight_array[x_hr + image_subpixel_scale] *
weight_array[y_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
image_filter_shift;
fg[0] += weight * *fg_ptr++;
fg[1] += weight * *fg_ptr++;
fg[2] += weight * *fg_ptr++;
fg[3] += weight * *fg_ptr;
fg_ptr = base.source().next_x();
weight = (weight_array[x_hr] *
weight_array[y_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
image_filter_shift;
fg[0] += weight * *fg_ptr++;
fg[1] += weight * *fg_ptr++;
fg[2] += weight * *fg_ptr++;
fg[3] += weight * *fg_ptr;
fg[0] >>= image_filter_shift;
fg[1] >>= image_filter_shift;
fg[2] >>= image_filter_shift;
fg[3] >>= image_filter_shift;
if(fg[ImageBuffer.OrderA] > base_mask) fg[ImageBuffer.OrderA] = base_mask;
if(fg[ImageBuffer.OrderR] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderR] = fg[ImageBuffer.OrderA];
if(fg[ImageBuffer.OrderG] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderG] = fg[ImageBuffer.OrderA];
if(fg[ImageBuffer.OrderB] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderB] = fg[ImageBuffer.OrderA];
span->r = (byte)fg[ImageBuffer.OrderR];
span->g = (byte)fg[ImageBuffer.OrderG];
span->b = (byte)fg[ImageBuffer.OrderB];
span->a = (byte)fg[ImageBuffer.OrderA];
++span;
++base.interpolator();
} while(--len);
}
};
*/
public class span_image_filter_rgba : span_image_filter
{
private const int base_mask = 255;
//--------------------------------------------------------------------
public span_image_filter_rgba(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter)
: base(src, inter, filter)
{
if (src.SourceImage.GetBytesBetweenPixelsInclusive() != 4)
{
throw new System.NotSupportedException("span_image_filter_rgba must have a 32 bit DestImage");
}
}
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int f_r, f_g, f_b, f_a;
byte[] fg_ptr;
int diameter = m_filter.diameter();
int start = m_filter.start();
int[] weight_array = m_filter.weight_array();
int x_count;
int weight_y;
ISpanInterpolator spanInterpolator = base.interpolator();
IImageBufferAccessor sourceAccessor = GetImageBufferAccessor();
do
{
spanInterpolator.coordinates(out x, out y);
x -= base.filter_dx_int();
y -= base.filter_dy_int();
int x_hr = x;
int y_hr = y;
int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift;
f_b = f_g = f_r = f_a = (int)image_filter_scale_e.image_filter_scale / 2;
int x_fract = x_hr & (int)image_subpixel_scale_e.image_subpixel_mask;
int y_count = diameter;
y_hr = (int)image_subpixel_scale_e.image_subpixel_mask - (y_hr & (int)image_subpixel_scale_e.image_subpixel_mask);
int bufferIndex;
fg_ptr = sourceAccessor.span(x_lr + start, y_lr + start, diameter, out bufferIndex);
for (; ; )
{
x_count = (int)diameter;
weight_y = weight_array[y_hr];
x_hr = (int)image_subpixel_scale_e.image_subpixel_mask - x_fract;
for (; ; )
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
(int)image_filter_scale_e.image_filter_shift;
f_b += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
f_g += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
f_r += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
f_a += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
if (--x_count == 0) break;
x_hr += (int)image_subpixel_scale_e.image_subpixel_scale;
sourceAccessor.next_x(out bufferIndex);
}
if (--y_count == 0) break;
y_hr += (int)image_subpixel_scale_e.image_subpixel_scale;
fg_ptr = sourceAccessor.next_y(out bufferIndex);
}
f_b >>= (int)image_filter_scale_e.image_filter_shift;
f_g >>= (int)image_filter_scale_e.image_filter_shift;
f_r >>= (int)image_filter_scale_e.image_filter_shift;
f_a >>= (int)image_filter_scale_e.image_filter_shift;
unchecked
{
if ((uint)f_b > base_mask)
{
if (f_b < 0) f_b = 0;
if (f_b > base_mask) f_b = (int)base_mask;
}
if ((uint)f_g > base_mask)
{
if (f_g < 0) f_g = 0;
if (f_g > base_mask) f_g = (int)base_mask;
}
if ((uint)f_r > base_mask)
{
if (f_r < 0) f_r = 0;
if (f_r > base_mask) f_r = (int)base_mask;
}
if ((uint)f_a > base_mask)
{
if (f_a < 0) f_a = 0;
if (f_a > base_mask) f_a = (int)base_mask;
}
}
span[spanIndex].red = (byte)f_b;
span[spanIndex].green = (byte)f_g;
span[spanIndex].blue = (byte)f_r;
span[spanIndex].alpha = (byte)f_a;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
};
public class span_image_filter_rgba_float : span_image_filter_float
{
public span_image_filter_rgba_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat inter, IImageFilterFunction filterFunction)
: base(src, inter, filterFunction)
{
if (src.SourceImage.GetFloatsBetweenPixelsInclusive() != 4)
{
throw new System.NotSupportedException("span_image_filter_rgba must have a 32 bit DestImage");
}
}
public override void generate(ColorF[] span, int spanIndex, int xInt, int yInt, int len)
{
base.interpolator().begin(xInt + base.filter_dx_dbl(), yInt + base.filter_dy_dbl(), len);
float f_r, f_g, f_b, f_a;
float[] fg_ptr;
int radius = (int)m_filterFunction.radius();
int diameter = radius * 2;
int start = -(int)(diameter / 2 - 1);
int x_count;
ISpanInterpolatorFloat spanInterpolator = base.interpolator();
IImageBufferAccessorFloat sourceAccessor = source();
do
{
float x = xInt;
float y = yInt;
spanInterpolator.coordinates(out x, out y);
//x -= (float)base.filter_dx_dbl();
//y -= (float)base.filter_dy_dbl();
int sourceXInt = (int)x;
int sourceYInt = (int)y;
Vector2 sourceOrigin = new Vector2(x, y);
Vector2 sourceSample = new Vector2(sourceXInt + start, sourceYInt + start);
f_b = f_g = f_r = f_a = 0;
int y_count = diameter;
int bufferIndex;
fg_ptr = sourceAccessor.span(sourceXInt + start, sourceYInt + start, diameter, out bufferIndex);
float totalWeight = 0.0f;
for (; ; )
{
float yweight = (float)m_filterFunction.calc_weight(System.Math.Sqrt((sourceSample.Y - sourceOrigin.Y) * (sourceSample.Y - sourceOrigin.Y)));
x_count = (int)diameter;
for (; ; )
{
float xweight = (float)m_filterFunction.calc_weight(System.Math.Sqrt((sourceSample.X - sourceOrigin.X) * (sourceSample.X - sourceOrigin.X)));
float weight = xweight * yweight;
f_r += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR];
f_g += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG];
f_b += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB];
f_a += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA];
totalWeight += weight;
sourceSample.X += 1;
if (--x_count == 0) break;
sourceAccessor.next_x(out bufferIndex);
}
sourceSample.X -= diameter;
if (--y_count == 0) break;
sourceSample.Y += 1;
fg_ptr = sourceAccessor.next_y(out bufferIndex);
}
if (f_b < 0) f_b = 0; if (f_b > 1) f_b = 1;
if (f_r < 0) f_r = 0; if (f_r > 1) f_r = 1;
if (f_g < 0) f_g = 0; if (f_g > 1) f_g = 1;
span[spanIndex].red = f_r;
span[spanIndex].green = f_g;
span[spanIndex].blue = f_b;
span[spanIndex].alpha = 1;// f_a;
spanIndex++;
spanInterpolator.Next();
} while (--len != 0);
}
};
/*
//========================================span_image_resample_rgba_affine
public class span_image_resample_rgba_affine : span_image_resample_affine
{
//typedef Source source_type;
//typedef typename source_type::color_type color_type;
//typedef typename source_type::order_type order_type;
//typedef span_image_resample_affine<source_type> base_type;
//typedef typename base.interpolator_type interpolator_type;
//typedef typename color_type::value_type value_type;
//typedef typename color_type::long_type long_type;
enum base_scale_e
{
base_shift = 8, //color_type::base_shift,
base_mask = 255,//color_type::base_mask,
downscale_shift = image_filter_shift
};
//--------------------------------------------------------------------
public span_image_resample_rgba_affine() {}
public span_image_resample_rgba_affine(pixfmt_alpha_blend_bgra32 src,
interpolator_type inter,
ImageFilterLookUpTable filter) :
base(src, inter, filter)
{}
//--------------------------------------------------------------------
public void generate(color_type* span, int x, int y, unsigned len)
{
base.interpolator().begin(x + base.filter_dx_dbl(),
y + base.filter_dy_dbl(), len);
long_type fg[4];
int diameter = base.filter().diameter();
int filter_scale = diameter << image_subpixel_shift;
int radius_x = (diameter * base.m_rx) >> 1;
int radius_y = (diameter * base.m_ry) >> 1;
int len_x_lr =
(diameter * base.m_rx + image_subpixel_mask) >>
image_subpixel_shift;
int16* weight_array = base.filter().weight_array();
do
{
base.interpolator().coordinates(&x, &y);
x += base.filter_dx_int() - radius_x;
y += base.filter_dy_int() - radius_y;
fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2;
int y_lr = y >> image_subpixel_shift;
int y_hr = ((image_subpixel_mask - (y & image_subpixel_mask)) *
base.m_ry_inv) >>
image_subpixel_shift;
int total_weight = 0;
int x_lr = x >> image_subpixel_shift;
int x_hr = ((image_subpixel_mask - (x & image_subpixel_mask)) *
base.m_rx_inv) >>
image_subpixel_shift;
int x_hr2 = x_hr;
byte* fg_ptr = base.source().span(x_lr, y_lr, len_x_lr);
for(;;)
{
int weight_y = weight_array[y_hr];
x_hr = x_hr2;
for(;;)
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
downscale_shift;
fg[0] += *fg_ptr++ * weight;
fg[1] += *fg_ptr++ * weight;
fg[2] += *fg_ptr++ * weight;
fg[3] += *fg_ptr++ * weight;
total_weight += weight;
x_hr += base.m_rx_inv;
if(x_hr >= filter_scale) break;
fg_ptr = base.source().next_x();
}
y_hr += base.m_ry_inv;
if(y_hr >= filter_scale) break;
fg_ptr = base.source().next_y();
}
fg[0] /= total_weight;
fg[1] /= total_weight;
fg[2] /= total_weight;
fg[3] /= total_weight;
if(fg[0] < 0) fg[0] = 0;
if(fg[1] < 0) fg[1] = 0;
if(fg[2] < 0) fg[2] = 0;
if(fg[3] < 0) fg[3] = 0;
if(fg[ImageBuffer.OrderA] > base_mask) fg[ImageBuffer.OrderA] = base_mask;
if(fg[ImageBuffer.OrderR] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderR] = fg[ImageBuffer.OrderA];
if(fg[ImageBuffer.OrderG] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderG] = fg[ImageBuffer.OrderA];
if(fg[ImageBuffer.OrderB] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderB] = fg[ImageBuffer.OrderA];
span->r = (byte)fg[ImageBuffer.OrderR];
span->g = (byte)fg[ImageBuffer.OrderG];
span->b = (byte)fg[ImageBuffer.OrderB];
span->a = (byte)fg[ImageBuffer.OrderA];
++span;
++base.interpolator();
} while(--len);
}
};
*/
//==============================================span_image_resample_rgba
public class span_image_resample_rgba
: span_image_resample
{
private const int base_mask = 255;
private const int downscale_shift = (int)ImageFilterLookUpTable.image_filter_scale_e.image_filter_shift;
//--------------------------------------------------------------------
public span_image_resample_rgba(IImageBufferAccessor src,
ISpanInterpolator inter,
ImageFilterLookUpTable filter) :
base(src, inter, filter)
{
if (src.SourceImage.GetRecieveBlender().NumPixelBits != 32)
{
throw new System.FormatException("You have to use a rgba blender with span_image_resample_rgba");
}
}
//--------------------------------------------------------------------
public override void generate(Color[] span, int spanIndex, int x, int y, int len)
{
ISpanInterpolator spanInterpolator = base.interpolator();
spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int[] fg = new int[4];
byte[] fg_ptr;
int[] weightArray = filter().weight_array();
int diameter = (int)base.filter().diameter();
int filter_scale = diameter << (int)image_subpixel_scale_e.image_subpixel_shift;
int[] weight_array = weightArray;
do
{
int rx;
int ry;
int rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
int ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
spanInterpolator.coordinates(out x, out y);
spanInterpolator.local_scale(out rx, out ry);
base.adjust_scale(ref rx, ref ry);
rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / rx;
ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / ry;
int radius_x = (diameter * rx) >> 1;
int radius_y = (diameter * ry) >> 1;
int len_x_lr =
(diameter * rx + (int)image_subpixel_scale_e.image_subpixel_mask) >>
(int)(int)image_subpixel_scale_e.image_subpixel_shift;
x += base.filter_dx_int() - radius_x;
y += base.filter_dy_int() - radius_y;
fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2;
int y_lr = y >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int y_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (y & (int)image_subpixel_scale_e.image_subpixel_mask)) *
ry_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int total_weight = 0;
int x_lr = x >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (x & (int)image_subpixel_scale_e.image_subpixel_mask)) *
rx_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr2 = x_hr;
int sourceIndex;
fg_ptr = base.GetImageBufferAccessor().span(x_lr, y_lr, len_x_lr, out sourceIndex);
for (; ; )
{
int weight_y = weight_array[y_hr];
x_hr = x_hr2;
for (; ; )
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
downscale_shift;
fg[0] += fg_ptr[sourceIndex + ImageBuffer.OrderR] * weight;
fg[1] += fg_ptr[sourceIndex + ImageBuffer.OrderG] * weight;
fg[2] += fg_ptr[sourceIndex + ImageBuffer.OrderB] * weight;
fg[3] += fg_ptr[sourceIndex + ImageBuffer.OrderA] * weight;
total_weight += weight;
x_hr += rx_inv;
if (x_hr >= filter_scale) break;
fg_ptr = base.GetImageBufferAccessor().next_x(out sourceIndex);
}
y_hr += ry_inv;
if (y_hr >= filter_scale)
{
break;
}
fg_ptr = base.GetImageBufferAccessor().next_y(out sourceIndex);
}
fg[0] /= total_weight;
fg[1] /= total_weight;
fg[2] /= total_weight;
fg[3] /= total_weight;
if (fg[0] < 0) fg[0] = 0;
if (fg[1] < 0) fg[1] = 0;
if (fg[2] < 0) fg[2] = 0;
if (fg[3] < 0) fg[3] = 0;
if (fg[0] > base_mask) fg[0] = base_mask;
if (fg[1] > base_mask) fg[1] = base_mask;
if (fg[2] > base_mask) fg[2] = base_mask;
if (fg[3] > base_mask) fg[3] = base_mask;
span[spanIndex].red = (byte)fg[0];
span[spanIndex].green = (byte)fg[1];
span[spanIndex].blue = (byte)fg[2];
span[spanIndex].alpha = (byte)fg[3];
spanIndex++;
interpolator().Next();
} while (--len != 0);
}
/*
ISpanInterpolator spanInterpolator = base.interpolator();
spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len);
int* fg = stackalloc int[4];
byte* fg_ptr;
fixed (int* pWeightArray = filter().weight_array())
{
int diameter = (int)base.filter().diameter();
int filter_scale = diameter << (int)image_subpixel_scale_e.image_subpixel_shift;
int* weight_array = pWeightArray;
do
{
int rx;
int ry;
int rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
int ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale;
spanInterpolator.coordinates(out x, out y);
spanInterpolator.local_scale(out rx, out ry);
base.adjust_scale(ref rx, ref ry);
rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / rx;
ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / ry;
int radius_x = (diameter * rx) >> 1;
int radius_y = (diameter * ry) >> 1;
int len_x_lr =
(diameter * rx + (int)image_subpixel_scale_e.image_subpixel_mask) >>
(int)(int)image_subpixel_scale_e.image_subpixel_shift;
x += base.filter_dx_int() - radius_x;
y += base.filter_dy_int() - radius_y;
fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2;
int y_lr = y >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int y_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (y & (int)image_subpixel_scale_e.image_subpixel_mask)) *
ry_inv) >>
(int)(int)image_subpixel_scale_e.image_subpixel_shift;
int total_weight = 0;
int x_lr = x >> (int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (x & (int)image_subpixel_scale_e.image_subpixel_mask)) *
rx_inv) >>
(int)(int)image_subpixel_scale_e.image_subpixel_shift;
int x_hr2 = x_hr;
fg_ptr = base.source().span(x_lr, y_lr, (int)len_x_lr);
for(;;)
{
int weight_y = weight_array[y_hr];
x_hr = x_hr2;
for(;;)
{
int weight = (weight_y * weight_array[x_hr] +
(int)image_filter_scale_e.image_filter_scale / 2) >>
downscale_shift;
fg[0] += *fg_ptr++ * weight;
fg[1] += *fg_ptr++ * weight;
fg[2] += *fg_ptr++ * weight;
fg[3] += *fg_ptr++ * weight;
total_weight += weight;
x_hr += rx_inv;
if(x_hr >= filter_scale) break;
fg_ptr = base.source().next_x();
}
y_hr += ry_inv;
if (y_hr >= filter_scale)
{
break;
}
fg_ptr = base.source().next_y();
}
fg[0] /= total_weight;
fg[1] /= total_weight;
fg[2] /= total_weight;
fg[3] /= total_weight;
if(fg[0] < 0) fg[0] = 0;
if(fg[1] < 0) fg[1] = 0;
if(fg[2] < 0) fg[2] = 0;
if(fg[3] < 0) fg[3] = 0;
if(fg[0] > fg[0]) fg[0] = fg[0];
if(fg[1] > fg[1]) fg[1] = fg[1];
if(fg[2] > fg[2]) fg[2] = fg[2];
if (fg[3] > base_mask) fg[3] = base_mask;
span->R_Byte = (byte)fg[ImageBuffer.OrderR];
span->G_Byte = (byte)fg[ImageBuffer.OrderG];
span->B_Byte = (byte)fg[ImageBuffer.OrderB];
span->A_Byte = (byte)fg[ImageBuffer.OrderA];
++span;
interpolator().Next();
} while(--len != 0);
}
*/
};
}
//#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServerManagement
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// NodeOperations operations.
/// </summary>
internal partial class NodeOperations : IServiceOperations<ServerManagementClient>, INodeOperations
{
/// <summary>
/// Initializes a new instance of the NodeOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal NodeOperations(ServerManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ServerManagementClient
/// </summary>
public ServerManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<NodeResource>> CreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<NodeResource> _response = await BeginCreateWithHttpMessagesAsync(
resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Creates or updates a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NodeResource>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new ValidationException(ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
NodeParameters gatewayParameters = new NodeParameters();
if (location != null || tags != null || gatewayId != null || connectionName != null || userName != null || password != null)
{
gatewayParameters.Location = location;
gatewayParameters.Tags = tags;
gatewayParameters.GatewayId = gatewayId;
gatewayParameters.ConnectionName = connectionName;
gatewayParameters.UserName = userName;
gatewayParameters.Password = password;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("gatewayParameters", gatewayParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", Uri.EscapeDataString(nodeName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(gatewayParameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(gatewayParameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NodeResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<NodeResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<NodeResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<NodeResource>> UpdateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<NodeResource> _response = await BeginUpdateWithHttpMessagesAsync(
resourceGroupName, nodeName, location, tags, gatewayId, connectionName, userName, password, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Updates a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='location'>
/// location of the resource?
/// </param>
/// <param name='tags'>
/// resource tags
/// </param>
/// <param name='gatewayId'>
/// Gateway id which will manage this node
/// </param>
/// <param name='connectionName'>
/// myhost.domain.com
/// </param>
/// <param name='userName'>
/// User name to be used to connect to node
/// </param>
/// <param name='password'>
/// Password associated with user name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NodeResource>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string location = default(string), object tags = default(object), string gatewayId = default(string), string connectionName = default(string), string userName = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new ValidationException(ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
NodeParameters nodeParameters = new NodeParameters();
if (location != null || tags != null || gatewayId != null || connectionName != null || userName != null || password != null)
{
nodeParameters.Location = location;
nodeParameters.Tags = tags;
nodeParameters.GatewayId = gatewayId;
nodeParameters.ConnectionName = connectionName;
nodeParameters.UserName = userName;
nodeParameters.Password = password;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("nodeParameters", nodeParameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", Uri.EscapeDataString(nodeName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(nodeParameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(nodeParameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NodeResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<NodeResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// deletes a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string nodeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new ValidationException(ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", Uri.EscapeDataString(nodeName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// gets a management node
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='nodeName'>
/// The node name (256 characters maximum).
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<NodeResource>> GetWithHttpMessagesAsync(string resourceGroupName, string nodeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
if (nodeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nodeName");
}
if (nodeName != null)
{
if (nodeName.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "nodeName", 256);
}
if (nodeName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "nodeName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"))
{
throw new ValidationException(ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("nodeName", nodeName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{nodeName}", Uri.EscapeDataString(nodeName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<NodeResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<NodeResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns nodes in a subscription
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeResource>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.ServerManagement/nodes").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns nodes in a resource group
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name uniquely identifies the resource group within the
/// user subscriptionId.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeResource>>> ListForResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+");
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListForResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns nodes in a subscription
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Returns nodes in a resource group
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeResource>>> ListForResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListForResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeResource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using IL2CPU.API.Attribs;
namespace TheRingMaster
{
public class Program
{
enum Ring
{
External = 0,
CPU = 10,
Platform = 20,
HAL = 30,
System = 40,
Application = 50,
Plug = 91,
CpuPlug = 92,
Debug
}
static Dictionary<Assembly, Ring> RingCache = new Dictionary<Assembly, Ring>();
static string KernelDir;
public static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: theringmaster <path-to-kernel>");
return;
}
var xKernelAssemblyPath = args[0];
if (!File.Exists(xKernelAssemblyPath))
{
throw new FileNotFoundException("Kernel Assembly not found! Path: '" + xKernelAssemblyPath + "'");
}
KernelDir = Path.GetDirectoryName(xKernelAssemblyPath);
AssemblyLoadContext.Default.Resolving += Default_Resolving;
var xKernelAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(xKernelAssemblyPath);
CheckRings(xKernelAssembly, Ring.Application);
void CheckRings(Assembly aAssembly, Ring aRing, string aSourceAssemblyName = null)
{
bool xDebugAllowed = false;
if (!RingCache.TryGetValue(aAssembly, out var xRing))
{
var xManifestName = aAssembly.GetManifestResourceNames()
.Where(n => n == aAssembly.GetName().Name + ".Cosmos.cfg")
.SingleOrDefault();
if (xManifestName != null)
{
Dictionary<string, string> xCfg;
using (var xManifestStream = aAssembly.GetManifestResourceStream(xManifestName))
{
xCfg = ParseCfg(xManifestStream);
}
if (xCfg == null)
{
throw new Exception("Invalid Cosmos configuration! Resource name: " + xManifestName);
}
xCfg.TryGetValue("Ring", out var xRingName);
if (!Enum.TryParse(xRingName, true, out xRing))
{
throw new Exception("Unknown ring! Ring: " + xRingName);
}
xCfg.TryGetValue("DebugRing", out var xDebugRing);
xDebugAllowed = xDebugRing.ToLower() == "allowed";
}
}
RingCache.Add(aAssembly, xRing);
// Check Rings
bool xValid = false;
// Same rings
// OR
// External ring, can be referenced by any ring
// OR
// One of the assemblies is Debug
// OR
// Debug ring allowed
if (aRing == xRing || xRing == Ring.External || aRing == Ring.Debug || xRing == Ring.Debug || xDebugAllowed)
{
xValid = true;
}
if (!xValid)
{
switch (aRing)
{
case Ring.Application when xRing == Ring.System:
case Ring.System when xRing == Ring.HAL:
case Ring.Platform when xRing == Ring.CPU:
case Ring.Platform when xRing == Ring.HAL:
return;
}
}
if (!xValid)
{
var xExceptionMessage = "Invalid rings! Source assembly: " + (aSourceAssemblyName ?? "(no assembly)") +
", Ring: " + aRing + "; Referenced assembly: " + aAssembly.GetName().Name +
", Ring: " + xRing;
throw new Exception(xExceptionMessage);
}
if (xRing != Ring.CPU && xRing != Ring.CpuPlug)
{
foreach (var xModule in aAssembly.Modules)
{
// TODO: Check unsafe code
}
}
foreach (var xType in aAssembly.GetTypes())
{
if (xRing != Ring.Plug)
{
if (xType.GetCustomAttribute<Plug>() != null)
{
throw new Exception("Plugs are only allowed in the Plugs ring! Assembly: " + aAssembly.GetName().Name);
}
}
}
foreach (var xReference in aAssembly.GetReferencedAssemblies())
{
try
{
CheckRings(AssemblyLoadContext.Default.LoadFromAssemblyName(xReference), xRing, aAssembly.GetName().Name);
}
catch (FileNotFoundException)
{
}
}
}
}
private static Assembly Default_Resolving(AssemblyLoadContext aContext, AssemblyName aAssemblyName)
{
Assembly xAssembly = null;
if (ResolveAssemblyForDir(KernelDir, out xAssembly))
{
return xAssembly;
}
//if (ResolveAssemblyForDir(CosmosPaths.Kernel, out xAssembly))
//{
// return xAssembly;
//}
return xAssembly;
bool ResolveAssemblyForDir(string aDir, out Assembly aAssembly)
{
aAssembly = null;
var xFiles = Directory.GetFiles(aDir, aAssemblyName.Name + ".*", SearchOption.TopDirectoryOnly);
if (xFiles.Any(f => Path.GetExtension(f) == ".dll"))
{
aAssembly = aContext.LoadFromAssemblyPath(xFiles.Where(f => Path.GetExtension(f) == ".dll").Single());
}
if (xFiles.Any(f => Path.GetExtension(f) == ".exe"))
{
aAssembly = aContext.LoadFromAssemblyPath(xFiles.Where(f => Path.GetExtension(f) == ".exe").Single());
}
return aAssembly != null;
}
}
static Dictionary<string, string> ParseCfg(Stream aStream)
{
var xCfg = new Dictionary<string, string>();
using (var xReader = new StreamReader(aStream))
{
while (xReader.Peek() >= 0)
{
var xLine = xReader.ReadLine();
if (!xLine.Contains(':') || xLine.Count(c => c == ':') > 1)
{
return null;
}
var xProperty = xLine.Split(':');
xCfg.Add(xProperty[0].Trim(), xProperty[1].Trim());
}
}
return xCfg;
}
}
}
| |
/*
* 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 OpenMetaverse;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
public abstract class BaseInventoryConnector : IInventoryService
{
protected static InventoryCache m_cache;
private static bool m_Initialized;
protected virtual void Init(IConfigSource source)
{
if (!m_Initialized)
{
m_cache = new InventoryCache();
m_cache.Init(source, this);
m_Initialized = true;
}
}
/// <summary>
/// Create the entire inventory for a given user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public abstract bool CreateUserInventory(UUID user);
/// <summary>
/// Gets the skeleton of the inventory -- folders only
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public abstract List<InventoryFolderBase> GetInventorySkeleton(UUID userId);
/// <summary>
/// Synchronous inventory fetch.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public abstract InventoryCollection GetUserInventory(UUID userID);
/// <summary>
/// Request the inventory for a user. This is an asynchronous operation that will call the callback when the
/// inventory has been received
/// </summary>
/// <param name="userID"></param>
/// <param name="callback"></param>
public abstract void GetUserInventory(UUID userID, InventoryReceiptCallback callback);
/// <summary>
/// Retrieve the root inventory folder for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
public InventoryFolderBase GetRootFolder(UUID userID)
{
// Root folder is here as system type Folder.
return m_cache.GetFolderForType(userID, AssetType.Folder);
}
public abstract Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID);
/// <summary>
/// Gets the user folder for the given folder-type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_cache.GetFolderForType(userID, type);
}
/// <summary>
/// Gets everything (folders and items) inside a folder
/// </summary>
/// <param name="userId"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public abstract InventoryCollection GetFolderContent(UUID userID, UUID folderID);
/// <summary>
/// Gets the items inside a folder
/// </summary>
/// <param name="userID"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public abstract List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID);
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public abstract bool AddFolder(InventoryFolderBase folder);
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public abstract bool UpdateFolder(InventoryFolderBase folder);
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public abstract bool MoveFolder(InventoryFolderBase folder);
/// <summary>
/// Delete a list of inventory folders (from trash)
/// </summary>
public abstract bool DeleteFolders(UUID ownerID, List<UUID> folderIDs);
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public abstract bool PurgeFolder(InventoryFolderBase folder);
/// <summary>
/// Add a new item to the user's inventory.
/// If the given item has to parent folder, it tries to find the most
/// suitable folder for it.
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully added</returns>
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
if (item.Folder == UUID.Zero)
{
InventoryFolderBase f = GetFolderForType(item.Owner, (AssetType)item.AssetType);
if (f != null)
item.Folder = f.ID;
else
{
f = GetRootFolder(item.Owner);
if (f != null)
item.Folder = f.ID;
else
return false;
}
}
return AddItemPlain(item);
}
protected abstract bool AddItemPlain(InventoryItemBase item);
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public abstract bool UpdateItem(InventoryItemBase item);
public abstract bool MoveItems(UUID ownerID, List<InventoryItemBase> items);
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public abstract bool DeleteItems(UUID ownerID, List<UUID> itemIDs);
public abstract InventoryItemBase GetItem(InventoryItemBase item);
public abstract InventoryFolderBase GetFolder(InventoryFolderBase folder);
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public abstract bool HasInventoryForUser(UUID userID);
/// <summary>
/// Get the active gestures of the agent.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public abstract List<InventoryItemBase> GetActiveGestures(UUID userId);
public abstract int GetAssetPermissions(UUID userID, UUID assetID);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using gView.Framework.UI;
using gView.Framework.system;
using gView.Framework.IO;
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.system.UI;
using gView.Framework.FDB;
using gView.OGC;
using gView.Framework.Db.UI;
using gView.Framework.OGC.UI;
using gView.Framework.Globalisation;
using System.Windows.Forms;
using gView.DataSources.MSSqlSpatial.DataSources.Sde;
namespace gView.DataSources.MSSqlSpatial.UI
{
[gView.Framework.system.RegisterPlugIn("55AF4451-7A67-48C8-8F41-F2E3A6DA7EB1")]
public class MsSql2008SpatialSdeExplorerGroupObject : ExplorerParentObject, IOgcGroupExplorerObject
{
private IExplorerIcon _icon = new MsSql2008SpatialSdeIcon();
public MsSql2008SpatialSdeExplorerGroupObject()
: base(null, null, 0)
{ }
#region IExplorerGroupObject Members
public IExplorerIcon Icon
{
get { return _icon; }
}
#endregion
#region IExplorerObject Members
public string Name
{
get { return "MsSql 2008 Spatial Geometry (Sde)"; }
}
public string FullName
{
get { return @"OGC\MsSql2008SpatialSde"; }
}
public string Type
{
get { return "MsSql Spatial Connection"; }
}
public new object Object
{
get { return null; }
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return null;
}
#endregion
#region IExplorerParentObject Members
public override void Refresh()
{
base.Refresh();
base.AddChildObject(new MsSql2008SpatialSdeNewConnectionObject(this));
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialSde_connections");
string connStr, id;
while ((connStr = stream.Read(out id)) != null)
{
base.AddChildObject(new MsSql2008SpatialSdeExplorerObject(this, id, connStr));
}
stream.Close();
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
if (this.FullName == FullName)
{
MsSql2008SpatialSdeExplorerGroupObject exObject = new MsSql2008SpatialSdeExplorerGroupObject();
cache.Append(exObject);
return exObject;
}
return null;
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("0B552B1D-49EF-4065-BB93-5F63517161A4")]
public class MsSql2008SpatialSdeNewConnectionObject : ExplorerObjectCls, IExplorerSimpleObject, IExplorerObjectDoubleClick, IExplorerObjectCreatable
{
private IExplorerIcon _icon = new MsSql2008SpatialSdeNewConnectionIcon();
public MsSql2008SpatialSdeNewConnectionObject()
: base(null, null, 0)
{
}
public MsSql2008SpatialSdeNewConnectionObject(IExplorerObject parent)
: base(parent, null, 0)
{
}
#region IExplorerSimpleObject Members
public IExplorerIcon Icon
{
get { return _icon; }
}
#endregion
#region IExplorerObject Members
public string Name
{
get { return LocalizedResources.GetResString("String.NewConnection", "New Connection..."); }
}
public string FullName
{
get { return ""; }
}
public string Type
{
get { return "New MsSql 2008 Spatial Connection"; }
}
public void Dispose()
{
}
public new object Object
{
get { return null; }
}
public IExplorerObject CreateInstanceByFullName(string FullName)
{
return null;
}
#endregion
#region IExplorerObjectDoubleClick Members
public void ExplorerObjectDoubleClick(ExplorerObjectEventArgs e)
{
FormConnectionString dlg = new FormConnectionString();
dlg.ProviderID = "mssql";
dlg.UseProviderInConnectionString = false;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string connStr = dlg.ConnectionString;
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialSde_connections", true, true);
string id = ConfigTextStream.ExtractValue(connStr, "Database");
id += "@" + ConfigTextStream.ExtractValue(connStr, "Server");
if (id == "@") id = "MsSql 2008 Spatial Connection";
stream.Write(connStr, ref id);
stream.Close();
e.NewExplorerObject = new MsSql2008SpatialSdeExplorerObject(this.ParentExplorerObject, id, dlg.ConnectionString);
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
return null;
}
#endregion
#region IExplorerObjectCreatable Member
public bool CanCreate(IExplorerObject parentExObject)
{
return (parentExObject is MsSql2008SpatialSdeExplorerGroupObject);
}
public IExplorerObject CreateExplorerObject(IExplorerObject parentExObject)
{
ExplorerObjectEventArgs e = new ExplorerObjectEventArgs();
ExplorerObjectDoubleClick(e);
return e.NewExplorerObject;
}
#endregion
}
public class MsSql2008SpatialSdeExplorerObject : gView.Framework.OGC.UI.ExplorerObjectFeatureClassImport, IExplorerSimpleObject, IExplorerObjectDeletable, IExplorerObjectRenamable, ISerializableExplorerObject
{
private MsSql2008SpatialSdeIcon _icon = new MsSql2008SpatialSdeIcon();
private string _server = "", _connectionString = "", _errMsg = "";
private IFeatureDataset _dataset;
public MsSql2008SpatialSdeExplorerObject() : base(null,typeof(IFeatureDataset)) { }
public MsSql2008SpatialSdeExplorerObject(IExplorerObject parent, string server, string connectionString)
: base(parent,typeof(IFeatureDataset))
{
_server = server;
_connectionString = connectionString;
}
internal string ConnectionString
{
get
{
return _connectionString;
}
}
#region IExplorerObject Members
public string Name
{
get
{
return _server;
}
}
public string FullName
{
get
{
return @"OGC\MsSql2008SpatialSde\" + _server;
}
}
public string Type
{
get { return "MsSql2008SpatialSde Database"; }
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
public object Object
{
get
{
if (_dataset != null) _dataset.Dispose();
_dataset = new SdeDataset();
_dataset.ConnectionString = _connectionString;
_dataset.Open();
return _dataset;
}
}
#endregion
#region IExplorerParentObject Members
public override void Refresh()
{
base.Refresh();
SdeDataset dataset = new SdeDataset();
dataset.ConnectionString = _connectionString;
dataset.Open();
List<IDatasetElement> elements = dataset.Elements;
if (elements == null) return;
foreach (IDatasetElement element in elements)
{
if (element.Class is IFeatureClass)
{
base.AddChildObject(new MsSql2008SpatialSdeFeatureClassExplorerObject(this, element));
}
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
MsSql2008SpatialSdeExplorerGroupObject group = new MsSql2008SpatialSdeExplorerGroupObject();
if (FullName.IndexOf(group.FullName) != 0 || FullName.Length < group.FullName.Length + 2) return null;
group = (MsSql2008SpatialSdeExplorerGroupObject)((cache.Contains(group.FullName)) ? cache[group.FullName] : group);
foreach (IExplorerObject exObject in group.ChildObjects)
{
if (exObject.FullName == FullName)
{
cache.Append(exObject);
return exObject;
}
}
return null;
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted = null;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialSde_connections", true, true);
stream.Remove(this.Name, _connectionString);
stream.Close();
if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this);
return true;
}
#endregion
#region IExplorerObjectRenamable Member
public event ExplorerObjectRenamedEvent ExplorerObjectRenamed = null;
public bool RenameExplorerObject(string newName)
{
bool ret = false;
ConfigTextStream stream = new ConfigTextStream("MsSql2008SpatialSde_connections", true, true);
ret = stream.ReplaceHoleLine(ConfigTextStream.BuildLine(_server, _connectionString), ConfigTextStream.BuildLine(newName, _connectionString));
stream.Close();
if (ret == true)
{
_server = newName;
if (ExplorerObjectRenamed != null) ExplorerObjectRenamed(this);
}
return ret;
}
#endregion
}
[gView.Framework.system.RegisterPlugIn("D159CD92-7872-48F0-81BF-938543C5C2C1")]
public class MsSql2008SpatialSdeFeatureClassExplorerObject : ExplorerObjectCls, IExplorerSimpleObject, ISerializableExplorerObject, IExplorerObjectDeletable
{
private string _fcname = "", _type = "";
private IExplorerIcon _icon = null;
private IFeatureClass _fc = null;
private MsSql2008SpatialSdeExplorerObject _parent = null;
public MsSql2008SpatialSdeFeatureClassExplorerObject() : base(null,typeof(IFeatureClass), 1) { }
public MsSql2008SpatialSdeFeatureClassExplorerObject(MsSql2008SpatialSdeExplorerObject parent, IDatasetElement element)
: base(parent,typeof(IFeatureClass), 1)
{
if (element == null || !(element.Class is IFeatureClass)) return;
_parent = parent;
_fcname = element.Title;
if (element.Class is IFeatureClass)
{
_fc = (IFeatureClass)element.Class;
switch (_fc.GeometryType)
{
case geometryType.Envelope:
case geometryType.Polygon:
_icon = new MsSql2008SpatialSdePolygonIcon();
_type = "Polygon Featureclass";
break;
case geometryType.Multipoint:
case geometryType.Point:
_icon = new MsSql2008SpatialSdePointIcon();
_type = "Point Featureclass";
break;
case geometryType.Polyline:
_icon = new MsSql2008SpatialSdeLineIcon();
_type = "Polyline Featureclass";
break;
default:
_icon = new MsSql2008SpatialSdeLineIcon();
_type = "Featureclass";
break;
}
}
}
internal string ConnectionString
{
get
{
if (_parent == null) return "";
return _parent.ConnectionString;
}
}
#region IExplorerObject Members
public string Name
{
get { return _fcname; }
}
public string FullName
{
get
{
if (_parent == null) return "";
return _parent.FullName + @"\" + this.Name;
}
}
public string Type
{
get { return _type; }
}
public IExplorerIcon Icon
{
get { return _icon; }
}
public void Dispose()
{
if (_fc != null)
{
_fc = null;
}
}
public object Object
{
get
{
return _fc;
}
}
#endregion
#region ISerializableExplorerObject Member
public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName)) return cache[FullName];
FullName = FullName.Replace("/", @"\");
int lastIndex = FullName.LastIndexOf(@"\");
if (lastIndex == -1) return null;
string dsName = FullName.Substring(0, lastIndex);
string fcName = FullName.Substring(lastIndex + 1, FullName.Length - lastIndex - 1);
MsSql2008SpatialSdeExplorerObject dsObject = new MsSql2008SpatialSdeExplorerObject();
dsObject = dsObject.CreateInstanceByFullName(dsName, cache) as MsSql2008SpatialSdeExplorerObject;
if (dsObject == null || dsObject.ChildObjects == null) return null;
foreach (IExplorerObject exObject in dsObject.ChildObjects)
{
if (exObject.Name == fcName)
{
cache.Append(exObject);
return exObject;
}
}
return null;
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted;
public bool DeleteExplorerObject(ExplorerObjectEventArgs e)
{
if (_parent.Object is IFeatureDatabase)
{
if (((IFeatureDatabase)_parent.Object).DeleteFeatureClass(this.Name))
{
if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this);
return true;
}
else
{
MessageBox.Show("ERROR: " + ((IFeatureDatabase)_parent.Object).lastErrorMsg);
return false;
}
}
return false;
}
#endregion
}
class MsSql2008SpatialSdeIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("B22782D4-59D2-448a-A531-DE29B0067DE6");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.cat6;
}
}
#endregion
}
class MsSql2008SpatialSdeNewConnectionIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("56943EE9-DCE8-4ad9-9F13-D306A8A9210E");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.gps_point;
}
}
#endregion
}
public class MsSql2008SpatialSdePointIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("372EBA30-1F19-4109-B476-8B158CAA6360"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_32; }
}
#endregion
}
public class MsSql2008SpatialSdeLineIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("5EA3477F-7616-4775-B233-72C94BE055CA"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_33; }
}
#endregion
}
public class MsSql2008SpatialSdePolygonIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("D1297B06-4306-4d5d-BBC6-10E26792CE5F"); }
}
public System.Drawing.Image Image
{
get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_34; }
}
#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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Text;
namespace System.Reflection.Metadata.Ecma335
{
public sealed partial class MetadataBuilder
{
private sealed class HeapBlobBuilder : BlobBuilder
{
private int _capacityExpansion;
public HeapBlobBuilder(int capacity)
: base(capacity)
{
}
protected override BlobBuilder AllocateChunk(int minimalSize)
{
return new HeapBlobBuilder(Math.Max(Math.Max(minimalSize, ChunkCapacity), _capacityExpansion));
}
internal void SetCapacity(int capacity)
{
_capacityExpansion = Math.Max(0, capacity - Count - FreeBytes);
}
}
// #US heap
private const int UserStringHeapSizeLimit = 0x01000000;
private readonly Dictionary<string, int> _userStrings = new Dictionary<string, int>(256);
private readonly HeapBlobBuilder _userStringBuilder = new HeapBlobBuilder(4 * 1024);
private readonly int _userStringHeapStartOffset;
// #String heap
private Dictionary<string, StringHandle> _strings = new Dictionary<string, StringHandle>(256);
private int[] _stringIndexToResolvedOffsetMap;
private readonly HeapBlobBuilder _stringBuilder = new HeapBlobBuilder(4 * 1024);
private readonly int _stringHeapStartOffset;
// #Blob heap
private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(1024, ByteSequenceComparer.Instance);
private readonly int _blobHeapStartOffset;
private int _blobHeapSize;
// #GUID heap
private readonly Dictionary<Guid, GuidHandle> _guids = new Dictionary<Guid, GuidHandle>();
private readonly HeapBlobBuilder _guidBuilder = new HeapBlobBuilder(16); // full metadata has just a single guid
private bool _streamsAreComplete;
public MetadataBuilder(
int userStringHeapStartOffset = 0,
int stringHeapStartOffset = 0,
int blobHeapStartOffset = 0,
int guidHeapStartOffset = 0)
{
// -1 for the 0 we always write at the beginning of the heap:
if (userStringHeapStartOffset >= UserStringHeapSizeLimit - 1)
{
throw ImageFormatLimitationException.HeapSizeLimitExceeded(HeapIndex.UserString);
}
// Add zero-th entry to all heaps, even in EnC delta.
// We don't want generation-relative handles to ever be IsNil.
// In both full and delta metadata all nil heap handles should have zero value.
// There should be no blob handle that references the 0 byte added at the
// beginning of the delta blob.
_userStringBuilder.WriteByte(0);
_blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle));
_blobHeapSize = 1;
// When EnC delta is applied #US, #String and #Blob heaps are appended.
// Thus indices of strings and blobs added to this generation are offset
// by the sum of respective heap sizes of all previous generations.
_userStringHeapStartOffset = userStringHeapStartOffset;
_stringHeapStartOffset = stringHeapStartOffset;
_blobHeapStartOffset = blobHeapStartOffset;
// Unlike other heaps, #Guid heap in EnC delta is zero-padded.
_guidBuilder.WriteBytes(0, guidHeapStartOffset);
}
/// <summary>
/// Sets the capacity of the specified table.
/// </summary>
/// <param name="heap">Heap index.</param>
/// <param name="byteCount">Number of bytes.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heap"/> is not a valid heap index.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative or zero.</exception>
/// <remarks>
/// Use to reduce allocations if the approximate number of bytes is known ahead of time.
/// </remarks>
public void SetCapacity(HeapIndex heap, int byteCount)
{
if (byteCount <= 0)
{
Throw.ArgumentOutOfRange(nameof(byteCount));
}
switch (heap)
{
case HeapIndex.Blob:
// Not useful to set capacity.
// By the time the blob heap is serialized we know the exact size we need.
break;
case HeapIndex.Guid:
_guidBuilder.SetCapacity(byteCount);
break;
case HeapIndex.String:
_stringBuilder.SetCapacity(byteCount);
break;
case HeapIndex.UserString:
_userStringBuilder.SetCapacity(byteCount);
break;
default:
Throw.ArgumentOutOfRange(nameof(heap));
break;
}
}
public BlobHandle GetOrAddBlob(BlobBuilder builder)
{
// TODO: avoid making a copy if the blob exists in the index
return GetOrAddBlob(builder.ToImmutableArray());
}
public BlobHandle GetOrAddBlob(ImmutableArray<byte> blob)
{
BlobHandle index;
if (!_blobs.TryGetValue(blob, out index))
{
Debug.Assert(!_streamsAreComplete);
index = MetadataTokens.BlobHandle(_blobHeapSize);
_blobs.Add(blob, index);
_blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(blob.Length) + blob.Length;
}
return index;
}
public BlobHandle GetOrAddConstantBlob(object value)
{
string str = value as string;
if (str != null)
{
return GetOrAddBlob(str);
}
var builder = PooledBlobBuilder.GetInstance();
builder.WriteConstant(value);
var result = GetOrAddBlob(builder);
builder.Free();
return result;
}
public BlobHandle GetOrAddBlob(string str)
{
byte[] byteArray = new byte[str.Length * 2];
int i = 0;
foreach (char ch in str)
{
byteArray[i++] = (byte)(ch & 0xFF);
byteArray[i++] = (byte)(ch >> 8);
}
return GetOrAddBlob(ImmutableArray.Create(byteArray));
}
public BlobHandle GetOrAddBlobUtf8(string str)
{
return GetOrAddBlob(ImmutableArray.Create(Encoding.UTF8.GetBytes(str)));
}
public GuidHandle GetOrAddGuid(Guid guid)
{
if (guid == Guid.Empty)
{
return default(GuidHandle);
}
GuidHandle result;
if (_guids.TryGetValue(guid, out result))
{
return result;
}
result = GetNextGuid();
_guids.Add(guid, result);
_guidBuilder.WriteBytes(guid.ToByteArray());
return result;
}
public GuidHandle ReserveGuid(out Blob reservedBlob)
{
var handle = GetNextGuid();
reservedBlob = _guidBuilder.ReserveBytes(16);
return handle;
}
private GuidHandle GetNextGuid()
{
Debug.Assert(!_streamsAreComplete);
// The only GUIDs that are serialized are MVID, EncId, and EncBaseId in the
// Module table. Each of those GUID offsets are relative to the local heap,
// even for deltas, so there's no need for a GetGuidStreamPosition() method
// to offset the positions by the size of the original heap in delta metadata.
// Unlike #Blob, #String and #US streams delta #GUID stream is padded to the
// size of the previous generation #GUID stream before new GUIDs are added.
// Metadata Spec:
// The Guid heap is an array of GUIDs, each 16 bytes wide.
// Its first element is numbered 1, its second 2, and so on.
return MetadataTokens.GuidHandle((_guidBuilder.Count >> 4) + 1);
}
public StringHandle GetOrAddString(string str)
{
StringHandle index;
if (str.Length == 0)
{
index = default(StringHandle);
}
else if (!_strings.TryGetValue(str, out index))
{
Debug.Assert(!_streamsAreComplete);
index = MetadataTokens.StringHandle(_strings.Count + 1); // idx 0 is reserved for empty string
_strings.Add(str, index);
}
return index;
}
public int GetHeapOffset(StringHandle handle)
{
return _stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(handle)];
}
public int GetHeapOffset(BlobHandle handle)
{
int offset = MetadataTokens.GetHeapOffset(handle);
return (offset == 0) ? 0 : _blobHeapStartOffset + offset;
}
public int GetHeapOffset(GuidHandle handle)
{
return MetadataTokens.GetHeapOffset(handle);
}
public int GetHeapOffset(UserStringHandle handle)
{
return MetadataTokens.GetHeapOffset(handle);
}
/// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception>
public UserStringHandle GetOrAddUserString(string str)
{
int index;
if (!_userStrings.TryGetValue(str, out index))
{
Debug.Assert(!_streamsAreComplete);
int startPosition = _userStringBuilder.Count;
int encodedLength = str.Length * 2 + 1;
index = startPosition + _userStringHeapStartOffset;
// Native metadata emitter allows strings to exceed the heap size limit as long
// as the index is within the limits (see https://github.com/dotnet/roslyn/issues/9852)
if (index >= UserStringHeapSizeLimit)
{
throw ImageFormatLimitationException.HeapSizeLimitExceeded(HeapIndex.UserString);
}
_userStrings.Add(str, index);
_userStringBuilder.WriteCompressedInteger(encodedLength);
_userStringBuilder.WriteUTF16(str);
// Write out a trailing byte indicating if the string is really quite simple
byte stringKind = 0;
foreach (char ch in str)
{
if (ch >= 0x7F)
{
stringKind = 1;
}
else
{
switch ((int)ch)
{
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0xE:
case 0xF:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x17:
case 0x18:
case 0x19:
case 0x1A:
case 0x1B:
case 0x1C:
case 0x1D:
case 0x1E:
case 0x1F:
case 0x27:
case 0x2D:
stringKind = 1;
break;
default:
continue;
}
}
break;
}
_userStringBuilder.WriteByte(stringKind);
}
return MetadataTokens.UserStringHandle(index);
}
internal void CompleteHeaps()
{
Debug.Assert(!_streamsAreComplete);
_streamsAreComplete = true;
SerializeStringHeap();
}
public ImmutableArray<int> GetHeapSizes()
{
var heapSizes = new int[MetadataTokens.HeapCount];
heapSizes[(int)HeapIndex.UserString] = _userStringBuilder.Count;
heapSizes[(int)HeapIndex.String] = _stringBuilder.Count;
heapSizes[(int)HeapIndex.Blob] = _blobHeapSize;
heapSizes[(int)HeapIndex.Guid] = _guidBuilder.Count;
return ImmutableArray.CreateRange(heapSizes);
}
/// <summary>
/// Fills in stringIndexMap with data from stringIndex and write to stringWriter.
/// Releases stringIndex as the stringTable is sealed after this point.
/// </summary>
private void SerializeStringHeap()
{
// Sort by suffix and remove stringIndex
var sorted = new List<KeyValuePair<string, StringHandle>>(_strings);
sorted.Sort(new SuffixSort());
_strings = null;
// Create VirtIdx to Idx map and add entry for empty string
_stringIndexToResolvedOffsetMap = new int[sorted.Count + 1];
_stringIndexToResolvedOffsetMap[0] = 0;
_stringBuilder.WriteByte(0);
// Find strings that can be folded
string prev = string.Empty;
foreach (KeyValuePair<string, StringHandle> entry in sorted)
{
int position = _stringHeapStartOffset + _stringBuilder.Count;
// It is important to use ordinal comparison otherwise we'll use the current culture!
if (prev.EndsWith(entry.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(entry.Key[0]))
{
// Map over the tail of prev string. Watch for null-terminator of prev string.
_stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position - (BlobUtilities.GetUTF8ByteCount(entry.Key) + 1);
}
else
{
_stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position;
_stringBuilder.WriteUTF8(entry.Key, allowUnpairedSurrogates: false);
_stringBuilder.WriteByte(0);
}
prev = entry.Key;
}
}
/// <summary>
/// Sorts strings such that a string is followed immediately by all strings
/// that are a suffix of it.
/// </summary>
private class SuffixSort : IComparer<KeyValuePair<string, StringHandle>>
{
public int Compare(KeyValuePair<string, StringHandle> xPair, KeyValuePair<string, StringHandle> yPair)
{
string x = xPair.Key;
string y = yPair.Key;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--)
{
if (x[i] < y[j])
{
return -1;
}
if (x[i] > y[j])
{
return +1;
}
}
return y.Length.CompareTo(x.Length);
}
}
public void WriteHeapsTo(BlobBuilder writer)
{
WriteAligned(_stringBuilder, writer);
WriteAligned(_userStringBuilder, writer);
WriteAligned(_guidBuilder, writer);
WriteAlignedBlobHeap(writer);
}
private void WriteAlignedBlobHeap(BlobBuilder builder)
{
int alignment = BitArithmetic.Align(_blobHeapSize, 4) - _blobHeapSize;
var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize + alignment));
// Perf consideration: With large heap the following loop may cause a lot of cache misses
// since the order of entries in _blobs dictionary depends on the hash of the array values,
// which is not correlated to the heap index. If we observe such issue we should order
// the entries by heap position before running this loop.
foreach (var entry in _blobs)
{
int heapOffset = MetadataTokens.GetHeapOffset(entry.Value);
var blob = entry.Key;
writer.Offset = heapOffset;
writer.WriteCompressedInteger(blob.Length);
writer.WriteBytes(blob);
}
writer.Offset = _blobHeapSize;
writer.WriteBytes(0, alignment);
}
private static void WriteAligned(BlobBuilder source, BlobBuilder target)
{
int length = source.Count;
target.LinkSuffix(source);
target.WriteBytes(0, BitArithmetic.Align(length, 4) - length);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using Server;
using Server.Targeting;
using Server.Targets;
using Server.Mobiles;
using Server.Items;
using Server.Misc;
namespace Server.Commands
{
public class GMbody
{
public static void Initialize()
{
Register( "GMbody", AccessLevel.Counselor, new CommandEventHandler( GM_OnCommand ) );
}
public static void Register( string command, AccessLevel access, CommandEventHandler handler )
{
CommandSystem.Register( command, access, handler );
}
[Usage( "GMbody" )]
[Description( "Helps senior staff members set their body to GM style." )]
public static void GM_OnCommand( CommandEventArgs e )
{
e.Mobile.Target = new GMmeTarget();
}
private class GMmeTarget : Target
{
public GMmeTarget() : base( -1, false, TargetFlags.None )
{
}
private static void DisRobe( Mobile m_from, Container cont, Layer layer )
{
if ( m_from.FindItemOnLayer( layer ) != null )
{
Item item = m_from.FindItemOnLayer( layer );
cont.AddItem( item );
}
}
private static Mobile m_Mobile;
private static void EquipItem( Item item )
{
EquipItem( item, false );
}
private static void EquipItem( Item item, bool mustEquip )
{
if ( !Core.AOS )
item.LootType = LootType.Newbied;
if ( m_Mobile != null && m_Mobile.EquipItem( item ) )
return;
Container pack = m_Mobile.Backpack;
if ( !mustEquip && pack != null )
pack.DropItem( item );
else
item.Delete();
}
private static void PackItem( Item item )
{
if ( !Core.AOS )
item.LootType = LootType.Newbied;
Container pack = m_Mobile.Backpack;
if ( pack != null )
pack.DropItem( item );
else
item.Delete();
}
protected override void OnTarget( Mobile from, object targeted )
{
if ( targeted is Mobile )
{
Mobile targ = (Mobile)targeted;
if ( from != targ )
from.SendMessage( "You may only set your own body to GM style." );
else
{
m_Mobile = from;
CommandLogging.WriteLine( from, "{0} {1} is assuming a GM body", from.AccessLevel, CommandLogging.Format( from ) );
string prefix = Server.Commands.CommandSystem.Prefix;
CommandSystem.Handle( from, String.Format( "{0}AutoSpeedBooster true", prefix ) );
Container pack = from.Backpack;
List<Item> ItemsToDelete = new List<Item>();
foreach (Item item in from.Items)
{
if (item.Layer != Layer.Bank && item.Layer != Layer.Hair && item.Layer != Layer.FacialHair && item.Layer != Layer.Mount && item.Layer != Layer.Backpack)
{
ItemsToDelete.Add(item);
}
}
foreach (Item item in ItemsToDelete)
{
item.Delete();
}
if ( pack == null )
{
pack = new Backpack();
pack.Movable = false;
from.AddItem( pack );
}
else
{
pack.Delete();
pack = new Backpack();
pack.Movable = false;
from.AddItem( pack );
}
from.Hunger = 20;
from.Thirst = 20;
from.Fame = 0;
from.Karma = 0;
from.Kills = 0;
from.Hidden = true;
from.Blessed = true;
from.Hits = from.HitsMax;
from.Mana = from.ManaMax;
from.Stam = from.StamMax;
if(from.AccessLevel >= AccessLevel.Counselor)
{
EquipItem( new StaffRing() );
Spellbook book1 = new Spellbook( (ulong)18446744073709551615 );
Spellbook book2 = new NecromancerSpellbook( (ulong)0xffff );
Spellbook book3 = new BookOfChivalry();
Spellbook book4 = new BookOfBushido();
Spellbook book5 = new BookOfNinjitsu();
PackItem( book1 );
PackItem( book2 );
PackItem( book3 );
PackItem( book4 );
PackItem( book5 );
from.RawStr = 100;
from.RawDex = 100;
from.RawInt = 100;
from.Hits = from.HitsMax;
from.Mana = from.ManaMax;
from.Stam = from.StamMax;
for ( int i = 0; i < targ.Skills.Length; ++i )
targ.Skills[i].Base = 120;
}
if(from.AccessLevel == AccessLevel.Counselor)
{
EquipItem( new CounselorRobe() );
EquipItem( new ThighBoots( 3 ) );
from.Title = "[Counselor]";
}
if(from.AccessLevel == AccessLevel.GameMaster)
{
EquipItem( new GMRobe() );
EquipItem( new ThighBoots( 39 ) );
from.Title = "[GM]";
}
if(from.AccessLevel == AccessLevel.Seer)
{
EquipItem( new SeerRobe() );
EquipItem( new ThighBoots( 467 ) );
from.Title = "[Seer]";
}
if(from.AccessLevel >= AccessLevel.Administrator)
{
PackItem( new StaffCloak() );
EquipItem( new ThighBoots( 1001 ) );
EquipItem( new AdminRobe() );
}
if(from.AccessLevel == AccessLevel.Administrator)
from.Title = "[Admin]";
if(from.AccessLevel == AccessLevel.Developer)
from.Title = "[Developer]";
if(from.AccessLevel == AccessLevel.Owner)
from.Title = "[Owner]";
}
}
}
}
}
}
| |
using ClosedXML.Excel;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Tests.Excel.DataValidations
{
[TestFixture]
public class DataValidationTests
{
[Test]
public void Validation_1()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Data Validation Issue");
IXLCell cell = ws.Cell("E1");
cell.SetValue("Value 1");
cell = cell.CellBelow();
cell.SetValue("Value 2");
cell = cell.CellBelow();
cell.SetValue("Value 3");
cell = cell.CellBelow();
cell.SetValue("Value 4");
ws.Cell("A1").SetValue("Cell below has Validation Only.");
cell = ws.Cell("A2");
cell.GetDataValidation().List(ws.Range("$E$1:$E$4"));
ws.Cell("B1").SetValue("Cell below has Validation with a title.");
cell = ws.Cell("B2");
cell.GetDataValidation().List(ws.Range("$E$1:$E$4"));
cell.GetDataValidation().InputTitle = "Title for B2";
Assert.AreEqual(XLAllowedValues.List, cell.GetDataValidation().AllowedValues);
Assert.AreEqual("'Data Validation Issue'!$E$1:$E$4", cell.GetDataValidation().Value);
Assert.AreEqual("Title for B2", cell.GetDataValidation().InputTitle);
ws.Cell("C1").SetValue("Cell below has Validation with a message.");
cell = ws.Cell("C2");
cell.GetDataValidation().List(ws.Range("$E$1:$E$4"));
cell.GetDataValidation().InputMessage = "Message for C2";
Assert.AreEqual(XLAllowedValues.List, cell.GetDataValidation().AllowedValues);
Assert.AreEqual("'Data Validation Issue'!$E$1:$E$4", cell.GetDataValidation().Value);
Assert.AreEqual("Message for C2", cell.GetDataValidation().InputMessage);
ws.Cell("D1").SetValue("Cell below has Validation with title and message.");
cell = ws.Cell("D2");
cell.GetDataValidation().List(ws.Range("$E$1:$E$4"));
cell.GetDataValidation().InputTitle = "Title for D2";
cell.GetDataValidation().InputMessage = "Message for D2";
Assert.AreEqual(XLAllowedValues.List, cell.GetDataValidation().AllowedValues);
Assert.AreEqual("'Data Validation Issue'!$E$1:$E$4", cell.GetDataValidation().Value);
Assert.AreEqual("Title for D2", cell.GetDataValidation().InputTitle);
Assert.AreEqual("Message for D2", cell.GetDataValidation().InputMessage);
}
[Test]
public void Validation_2()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell("A1").SetValue("A");
ws.Cell("B1").CreateDataValidation().Custom("Sheet1!A1");
IXLWorksheet ws2 = wb.AddWorksheet("Sheet2");
ws2.Cell("A1").SetValue("B");
ws.Cell("B1").CopyTo(ws2.Cell("B1"));
Assert.AreEqual("Sheet1!A1", ws2.Cell("B1").GetDataValidation().Value);
}
[Test, Ignore("Wait for proper formula shifting (#686)")]
public void Validation_3()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell("A1").SetValue("A");
ws.Cell("B1").CreateDataValidation().Custom("A1");
ws.FirstRow().InsertRowsAbove(1);
Assert.AreEqual("A2", ws.Cell("B2").GetDataValidation().Value);
}
[Test]
public void Validation_4()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell("A1").SetValue("A");
ws.Cell("B1").CreateDataValidation().Custom("A1");
ws.Cell("B1").CopyTo(ws.Cell("B2"));
Assert.AreEqual("A2", ws.Cell("B2").GetDataValidation().Value);
}
[Test, Ignore("Wait for proper formula shifting (#686)")]
public void Validation_5()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell("A1").SetValue("A");
ws.Cell("B1").CreateDataValidation().Custom("A1");
ws.FirstColumn().InsertColumnsBefore(1);
Assert.AreEqual("B1", ws.Cell("C1").GetDataValidation().Value);
}
[Test]
public void Validation_6()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell("A1").SetValue("A");
ws.Cell("B1").CreateDataValidation().Custom("A1");
ws.Cell("B1").CopyTo(ws.Cell("C1"));
Assert.AreEqual("B1", ws.Cell("C1").GetDataValidation().Value);
}
[Test]
public void Validation_persists_on_Cell_DataValidation()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("People");
ws.FirstCell().SetValue("Categories")
.CellBelow().SetValue("A")
.CellBelow().SetValue("B");
IXLTable table = ws.RangeUsed().CreateTable();
IXLDataValidation dv = table.DataRange.CreateDataValidation();
dv.ErrorTitle = "Error";
Assert.AreEqual("Error", table.DataRange.FirstCell().GetDataValidation().ErrorTitle);
}
[Test]
public void Validation_persists_on_Worksheet_DataValidations()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("People");
ws.FirstCell().SetValue("Categories")
.CellBelow().SetValue("A");
IXLTable table = ws.RangeUsed().CreateTable();
IXLDataValidation dv = table.DataRange.CreateDataValidation();
dv.ErrorTitle = "Error";
Assert.AreEqual("Error", ws.DataValidations.Single().ErrorTitle);
}
[Test]
[TestCase("A1:C3", 5, false, "A1:C3")]
[TestCase("A1:C3", 2, false, "A1:C4")]
[TestCase("A1:C3", 1, false, "A2:C4")]
[TestCase("A1:C3", 5, true, "A1:C3")]
[TestCase("A1:C3", 2, true, "A1:C4")]
[TestCase("A1:C3", 1, true, "A2:C4")]
public void DataValidationShiftedOnRowInsert(string initialAddress, int rowNum, bool setValue, string expectedAddress)
{
//Arrange
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("DataValidation");
var validation = ws.Range(initialAddress).CreateDataValidation();
validation.WholeNumber.Between(0, 100);
if (setValue)
ws.Range(initialAddress).Value = 50;
//Act
ws.Row(rowNum).InsertRowsAbove(1);
//Assert
Assert.AreEqual(1, ws.DataValidations.Count());
Assert.AreEqual(1, ws.DataValidations.First().Ranges.Count());
Assert.AreEqual(expectedAddress, ws.DataValidations.First().Ranges.First().RangeAddress.ToString());
}
[Test]
[TestCase("A1:C3", 5, false, "A1:C3")]
[TestCase("A1:C3", 2, false, "A1:D3")]
[TestCase("A1:C3", 1, false, "B1:D3")]
[TestCase("A1:C3", 5, true, "A1:C3")]
[TestCase("A1:C3", 2, true, "A1:D3")]
[TestCase("A1:C3", 1, true, "B1:D3")]
public void DataValidationShiftedOnColumnInsert(string initialAddress, int columnNum, bool setValue, string expectedAddress)
{
//Arrange
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("DataValidation");
var validation = ws.Range(initialAddress).CreateDataValidation();
validation.WholeNumber.Between(0, 100);
if (setValue)
ws.Range(initialAddress).Value = 50;
//Act
ws.Column(columnNum).InsertColumnsBefore(1);
//Assert
Assert.AreEqual(1, ws.DataValidations.Count());
Assert.AreEqual(1, ws.DataValidations.First().Ranges.Count());
Assert.AreEqual(expectedAddress, ws.DataValidations.First().Ranges.First().RangeAddress.ToString());
}
[Test]
public void DataValidationClearSplitsRange()
{
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("DataValidation");
var validation = ws.Range("A1:C3").CreateDataValidation();
validation.WholeNumber.Between(0, 100);
//Act
ws.Cell("B2").Clear(XLClearOptions.DataValidation);
//Assert
Assert.IsFalse(ws.Cell("B2").HasDataValidation);
Assert.IsTrue(ws.Range("A1:C3").Cells().Where(c => c.Address.ToString() != "B2").All(c => c.HasDataValidation));
}
}
[Test]
public void NewDataValidationSplitsRange()
{
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("DataValidation");
var validation = ws.Range("A1:C3").CreateDataValidation();
validation.WholeNumber.Between(10, 100);
//Act
ws.Cell("B2").CreateDataValidation().WholeNumber.Between(-100, -0);
//Assert
Assert.AreEqual("-100", ws.Cell("B2").GetDataValidation().MinValue);
Assert.IsTrue(ws.Range("A1:C3").Cells().Where(c => c.Address.ToString() != "B2").All(c => c.HasDataValidation));
Assert.IsTrue(ws.Range("A1:C3").Cells().Where(c => c.Address.ToString() != "B2")
.All(c => c.GetDataValidation().MinValue == "10"));
}
}
[Test]
public void ListLengthOverflow()
{
var values = string.Join(",", Enumerable.Range(1, 20)
.Select(i => Guid.NewGuid().ToString("N")));
Assert.True(values.Length > 255);
using (var wb = new XLWorkbook())
{
var dv = wb.AddWorksheet("Sheet 1").Cell(1, 1).GetDataValidation();
Assert.Throws<ArgumentOutOfRangeException>(() => dv.List(values));
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
dv.TextLength.Between(0, 5);
dv.MinValue = values;
});
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
dv.TextLength.Between(0, 5);
dv.MaxValue = values;
});
}
}
[Test]
public void CannotCreateDataValidationWithoutRange()
{
Assert.Throws<ArgumentNullException>(() => new XLDataValidation(null));
}
[Test]
public void DataValidationHasWorksheetAndRangesWhenCreated()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range = ws.Range("A1:A3");
var dv = new XLDataValidation(range);
Assert.AreSame(ws, dv.Worksheet);
Assert.AreSame(range, dv.Ranges.Single());
}
}
[Test]
public void CanAddRangeFromSameWorksheet()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var ranges3 = ws.Ranges("D1:D3,F1:F3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
dv.AddRanges(ranges3);
Assert.IsTrue(dv.Ranges.Any(r => r == range1));
Assert.IsTrue(dv.Ranges.Any(r => r == range2));
Assert.IsTrue(dv.Ranges.Any(r => r == ranges3.First()));
Assert.IsTrue(dv.Ranges.Any(r => r == ranges3.Last()));
}
}
[Test]
public void CanAddRangeFromAnotherWorksheet()
{
using (var wb = new XLWorkbook())
{
var ws1 = wb.AddWorksheet();
var ws2 = wb.AddWorksheet();
var range1 = ws1.Range("A1:A3");
var range2 = ws2.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
Assert.IsTrue(dv.Ranges.Any(r => r != range2 && r.RangeAddress.ToString() == range2.RangeAddress.ToString()));
}
}
[Test]
public void CanClearRanges()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var ranges3 = ws.Ranges("D1:D3,F1:F3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
dv.AddRanges(ranges3);
dv.ClearRanges();
Assert.IsEmpty(dv.Ranges);
}
}
[Test]
public void CanRemoveExistingRange()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
dv.RemoveRange(range1);
Assert.AreSame(range2, dv.Ranges.Single());
}
}
[Test]
public void RemovingExistingRangeDoesNoFail()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.RemoveRange(range2);
dv.RemoveRange(null);
Assert.AreSame(range1, dv.Ranges.Single());
}
}
[Test]
public void AddRangeFiresEvent()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
IXLRange addedRange = null;
dv.RangeAdded += (s, e) => addedRange = e.Range;
dv.AddRange(range2);
Assert.AreSame(range2, addedRange);
}
}
[Test]
public void AddRangesFiresMultipleEvents()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var ranges = ws.Ranges("D1:D3,F1:F3");
var dv = new XLDataValidation(range1);
var addedRanges = new List<IXLRange>();
dv.RangeAdded += (s, e) => addedRanges.Add(e.Range);
dv.AddRanges(ranges);
Assert.AreEqual(2, addedRanges.Count);
}
}
[Test]
public void RemoveRangeFiresEvent()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
IXLRange removedRange = null;
dv.RangeRemoved += (s, e) => removedRange = e.Range;
dv.RemoveRange(range2);
Assert.AreSame(range2, removedRange);
}
}
[Test]
public void RemoveNonExistingRangeDoesNotFireEvent()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.RangeRemoved += (s, e) => Assert.Fail("Expected not to fire event");
dv.RemoveRange(range2);
}
}
[Test]
public void ClearRangesFiresMultipleEvents()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet();
var range1 = ws.Range("A1:A3");
var range2 = ws.Range("C1:C3");
var dv = new XLDataValidation(range1);
dv.AddRange(range2);
var removedRanges = new List<IXLRange>();
dv.RangeRemoved += (s, e) => removedRanges.Add(e.Range);
dv.ClearRanges();
Assert.AreEqual(2, removedRanges.Count);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Brokerages.Oanda;
using QuantConnect.Util;
using Environment = QuantConnect.Brokerages.Oanda.Environment;
namespace QuantConnect.ToolBox.OandaDownloader
{
/// <summary>
/// Oanda Data Downloader class
/// </summary>
public class OandaDataDownloader : IDataDownloader
{
private readonly OandaBrokerage _brokerage;
private readonly OandaSymbolMapper _symbolMapper = new OandaSymbolMapper();
/// <summary>
/// Initializes a new instance of the <see cref="OandaDataDownloader"/> class
/// </summary>
public OandaDataDownloader(string accessToken, string accountId)
{
// Set Oanda account credentials
_brokerage = new OandaBrokerage(null,
null,
null,
Environment.Trade,
accessToken,
accountId);
}
/// <summary>
/// Checks if downloader can get the data for the Lean symbol
/// </summary>
/// <param name="symbol">The Lean symbol</param>
/// <returns>Returns true if the symbol is available</returns>
public bool HasSymbol(string symbol)
{
return _symbolMapper.IsKnownLeanSymbol(Symbol.Create(symbol, GetSecurityType(symbol), Market.Oanda));
}
/// <summary>
/// Gets the security type for the specified Lean symbol
/// </summary>
/// <param name="symbol">The Lean symbol</param>
/// <returns>The security type</returns>
public SecurityType GetSecurityType(string symbol)
{
return _symbolMapper.GetLeanSecurityType(symbol);
}
/// <summary>
/// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
/// </summary>
/// <param name="dataDownloaderGetParameters">model class for passing in parameters for historical data</param>
/// <returns>Enumerable of base data for this symbol</returns>
public IEnumerable<BaseData> Get(DataDownloaderGetParameters dataDownloaderGetParameters)
{
var symbol = dataDownloaderGetParameters.Symbol;
var resolution = dataDownloaderGetParameters.Resolution;
var startUtc = dataDownloaderGetParameters.StartUtc;
var endUtc = dataDownloaderGetParameters.EndUtc;
var tickType = dataDownloaderGetParameters.TickType;
if (tickType != TickType.Quote)
{
yield break;
}
if (!_symbolMapper.IsKnownLeanSymbol(symbol))
throw new ArgumentException("Invalid symbol requested: " + symbol.Value);
if (resolution == Resolution.Tick)
throw new NotSupportedException("Resolution not available: " + resolution);
if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Cfd)
throw new NotSupportedException("SecurityType not available: " + symbol.ID.SecurityType);
if (endUtc < startUtc)
throw new ArgumentException("The end date must be greater or equal than the start date.");
var barsTotalInPeriod = new List<QuoteBar>();
var barsToSave = new List<QuoteBar>();
// set the starting date/time
var date = startUtc;
var startDateTime = date;
// loop until last date
while (startDateTime <= endUtc.AddDays(1))
{
// request blocks of 5-second bars with a starting date/time
var bars = _brokerage.DownloadQuoteBars(symbol, startDateTime, endUtc.AddDays(1), Resolution.Second, DateTimeZone.Utc).ToList();
if (bars.Count == 0)
break;
var groupedBars = GroupBarsByDate(bars);
if (groupedBars.Count > 1)
{
// we received more than one day, so we save the completed days and continue
while (groupedBars.Count > 1)
{
var currentDate = groupedBars.Keys.First();
if (currentDate > endUtc)
break;
barsToSave.AddRange(groupedBars[currentDate]);
barsTotalInPeriod.AddRange(barsToSave);
barsToSave.Clear();
// remove the completed date
groupedBars.Remove(currentDate);
}
// update the current date
date = groupedBars.Keys.First();
if (date <= endUtc)
{
barsToSave.AddRange(groupedBars[date]);
}
}
else
{
var currentDate = groupedBars.Keys.First();
if (currentDate > endUtc)
break;
// update the current date
date = currentDate;
barsToSave.AddRange(groupedBars[date]);
}
// calculate the next request datetime (next 5-sec bar time)
startDateTime = bars[bars.Count - 1].Time.AddSeconds(5);
}
if (barsToSave.Count > 0)
{
barsTotalInPeriod.AddRange(barsToSave);
}
switch (resolution)
{
case Resolution.Second:
case Resolution.Minute:
case Resolution.Hour:
case Resolution.Daily:
foreach (var bar in LeanData.AggregateQuoteBars(barsTotalInPeriod, symbol, resolution.ToTimeSpan()))
{
yield return bar;
}
break;
}
}
/// <summary>
/// Groups a list of bars into a dictionary keyed by date
/// </summary>
/// <param name="bars"></param>
/// <returns></returns>
private static SortedDictionary<DateTime, List<QuoteBar>> GroupBarsByDate(IEnumerable<QuoteBar> bars)
{
var groupedBars = new SortedDictionary<DateTime, List<QuoteBar>>();
foreach (var bar in bars)
{
var date = bar.Time.Date;
if (!groupedBars.ContainsKey(date))
groupedBars[date] = new List<QuoteBar>();
groupedBars[date].Add(bar);
}
return groupedBars;
}
}
}
| |
// <copyright file="Bridge.Generated.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
/// <summary>
/// This file is auto-generated by a build task. It shouldn't be edited by hand.
/// </summary>
namespace SmallBasic.Bridge
{
using System.Diagnostics;
using Newtonsoft.Json;
using SmallBasic.Utilities;
using SmallBasic.Utilities.Bridge;
internal interface IProcessBridge
{
void OpenExternalLink(string url);
}
internal interface IFileBridge
{
FileBridgeModels.Result AppendContents(FileBridgeModels.PathAndContentsArgs args);
FileBridgeModels.Result CopyFile(FileBridgeModels.SourceAndDestinationArgs args);
FileBridgeModels.Result CreateDirectory(string directoryPath);
FileBridgeModels.Result DeleteDirectory(string directoryPath);
FileBridgeModels.Result DeleteFile(string filePath);
FileBridgeModels.Result<string[]> GetDirectories(string directoryPath);
FileBridgeModels.Result<string[]> GetFiles(string directoryPath);
FileBridgeModels.Result<string> GetTemporaryFilePath();
FileBridgeModels.Result InsertLine(FileBridgeModels.PathAndLineAndContentsArgs args);
FileBridgeModels.Result<string> ReadContents(string filePath);
FileBridgeModels.Result<string> ReadLine(FileBridgeModels.PathAndLineArgs args);
FileBridgeModels.Result WriteContents(FileBridgeModels.PathAndContentsArgs args);
FileBridgeModels.Result WriteLine(FileBridgeModels.PathAndLineAndContentsArgs args);
}
internal interface INetworkBridge
{
ImageListBridgeModels.ImageData LoadImage(string fileNameOrUrl);
string DownloadFile(string url);
string GetWebPageContents(string url);
}
internal static class BridgeExecution
{
private static readonly IProcessBridge Process = new ProcessBridge();
private static readonly IFileBridge File = new FileBridge();
private static readonly INetworkBridge Network = new NetworkBridge();
public static void Run(string[] args)
{
Debug.Assert(args.Length >= 2, "Only intended for bridge calls");
string type = args[0];
string method = args[1];
string filePath = args.Length > 2 ? args[2] : null;
switch (type)
{
case "Process":
{
switch (method)
{
case "OpenExternalLink":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
Process.OpenExternalLink(input);
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(method);
}
}
break;
}
case "File":
{
switch (method)
{
case "AppendContents":
{
FileBridgeModels.PathAndContentsArgs input = JsonConvert.DeserializeObject<FileBridgeModels.PathAndContentsArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.AppendContents(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "CopyFile":
{
FileBridgeModels.SourceAndDestinationArgs input = JsonConvert.DeserializeObject<FileBridgeModels.SourceAndDestinationArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.CopyFile(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "CreateDirectory":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.CreateDirectory(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "DeleteDirectory":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.DeleteDirectory(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "DeleteFile":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.DeleteFile(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "GetDirectories":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result<string[]> output = File.GetDirectories(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "GetFiles":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result<string[]> output = File.GetFiles(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "GetTemporaryFilePath":
{
FileBridgeModels.Result<string> output = File.GetTemporaryFilePath();
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "InsertLine":
{
FileBridgeModels.PathAndLineAndContentsArgs input = JsonConvert.DeserializeObject<FileBridgeModels.PathAndLineAndContentsArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.InsertLine(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "ReadContents":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result<string> output = File.ReadContents(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "ReadLine":
{
FileBridgeModels.PathAndLineArgs input = JsonConvert.DeserializeObject<FileBridgeModels.PathAndLineArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result<string> output = File.ReadLine(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "WriteContents":
{
FileBridgeModels.PathAndContentsArgs input = JsonConvert.DeserializeObject<FileBridgeModels.PathAndContentsArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.WriteContents(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "WriteLine":
{
FileBridgeModels.PathAndLineAndContentsArgs input = JsonConvert.DeserializeObject<FileBridgeModels.PathAndLineAndContentsArgs>(System.IO.File.ReadAllText(filePath));
FileBridgeModels.Result output = File.WriteLine(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(method);
}
}
break;
}
case "Network":
{
switch (method)
{
case "LoadImage":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
ImageListBridgeModels.ImageData output = Network.LoadImage(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "DownloadFile":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
string output = Network.DownloadFile(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
case "GetWebPageContents":
{
string input = JsonConvert.DeserializeObject<string>(System.IO.File.ReadAllText(filePath));
string output = Network.GetWebPageContents(input);
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(output));
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(method);
}
}
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(type);
}
}
}
}
}
| |
using BeardedManStudios.Forge.Networking.Frame;
using BeardedManStudios.Forge.Networking.Unity;
using System;
using UnityEngine;
namespace BeardedManStudios.Forge.Networking.Generated
{
[GeneratedInterpol("{\"inter\":[0,0,0,0,0,0,0,0,0.15,0,0,0]")]
public partial class TestNetworkObject : NetworkObject
{
public const int IDENTITY = 5;
private byte[] _dirtyFields = new byte[2];
#pragma warning disable 0067
public event FieldChangedEvent fieldAltered;
#pragma warning restore 0067
[ForgeGeneratedField]
private byte _fieldByte;
public event FieldEvent<byte> fieldByteChanged;
public Interpolated<byte> fieldByteInterpolation = new Interpolated<byte>() { LerpT = 0f, Enabled = false };
public byte fieldByte
{
get { return _fieldByte; }
set
{
// Don't do anything if the value is the same
if (_fieldByte == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x1;
_fieldByte = value;
hasDirtyFields = true;
}
}
public void SetfieldByteDirty()
{
_dirtyFields[0] |= 0x1;
hasDirtyFields = true;
}
private void RunChange_fieldByte(ulong timestep)
{
if (fieldByteChanged != null) fieldByteChanged(_fieldByte, timestep);
if (fieldAltered != null) fieldAltered("fieldByte", _fieldByte, timestep);
}
[ForgeGeneratedField]
private char _fieldChar;
public event FieldEvent<char> fieldCharChanged;
public Interpolated<char> fieldCharInterpolation = new Interpolated<char>() { LerpT = 0f, Enabled = false };
public char fieldChar
{
get { return _fieldChar; }
set
{
// Don't do anything if the value is the same
if (_fieldChar == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x2;
_fieldChar = value;
hasDirtyFields = true;
}
}
public void SetfieldCharDirty()
{
_dirtyFields[0] |= 0x2;
hasDirtyFields = true;
}
private void RunChange_fieldChar(ulong timestep)
{
if (fieldCharChanged != null) fieldCharChanged(_fieldChar, timestep);
if (fieldAltered != null) fieldAltered("fieldChar", _fieldChar, timestep);
}
[ForgeGeneratedField]
private short _fieldShort;
public event FieldEvent<short> fieldShortChanged;
public Interpolated<short> fieldShortInterpolation = new Interpolated<short>() { LerpT = 0f, Enabled = false };
public short fieldShort
{
get { return _fieldShort; }
set
{
// Don't do anything if the value is the same
if (_fieldShort == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x4;
_fieldShort = value;
hasDirtyFields = true;
}
}
public void SetfieldShortDirty()
{
_dirtyFields[0] |= 0x4;
hasDirtyFields = true;
}
private void RunChange_fieldShort(ulong timestep)
{
if (fieldShortChanged != null) fieldShortChanged(_fieldShort, timestep);
if (fieldAltered != null) fieldAltered("fieldShort", _fieldShort, timestep);
}
[ForgeGeneratedField]
private ushort _fieldUShort;
public event FieldEvent<ushort> fieldUShortChanged;
public Interpolated<ushort> fieldUShortInterpolation = new Interpolated<ushort>() { LerpT = 0f, Enabled = false };
public ushort fieldUShort
{
get { return _fieldUShort; }
set
{
// Don't do anything if the value is the same
if (_fieldUShort == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x8;
_fieldUShort = value;
hasDirtyFields = true;
}
}
public void SetfieldUShortDirty()
{
_dirtyFields[0] |= 0x8;
hasDirtyFields = true;
}
private void RunChange_fieldUShort(ulong timestep)
{
if (fieldUShortChanged != null) fieldUShortChanged(_fieldUShort, timestep);
if (fieldAltered != null) fieldAltered("fieldUShort", _fieldUShort, timestep);
}
[ForgeGeneratedField]
private bool _fieldBool;
public event FieldEvent<bool> fieldBoolChanged;
public Interpolated<bool> fieldBoolInterpolation = new Interpolated<bool>() { LerpT = 0f, Enabled = false };
public bool fieldBool
{
get { return _fieldBool; }
set
{
// Don't do anything if the value is the same
if (_fieldBool == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x10;
_fieldBool = value;
hasDirtyFields = true;
}
}
public void SetfieldBoolDirty()
{
_dirtyFields[0] |= 0x10;
hasDirtyFields = true;
}
private void RunChange_fieldBool(ulong timestep)
{
if (fieldBoolChanged != null) fieldBoolChanged(_fieldBool, timestep);
if (fieldAltered != null) fieldAltered("fieldBool", _fieldBool, timestep);
}
[ForgeGeneratedField]
private int _fieldInt;
public event FieldEvent<int> fieldIntChanged;
public Interpolated<int> fieldIntInterpolation = new Interpolated<int>() { LerpT = 0f, Enabled = false };
public int fieldInt
{
get { return _fieldInt; }
set
{
// Don't do anything if the value is the same
if (_fieldInt == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x20;
_fieldInt = value;
hasDirtyFields = true;
}
}
public void SetfieldIntDirty()
{
_dirtyFields[0] |= 0x20;
hasDirtyFields = true;
}
private void RunChange_fieldInt(ulong timestep)
{
if (fieldIntChanged != null) fieldIntChanged(_fieldInt, timestep);
if (fieldAltered != null) fieldAltered("fieldInt", _fieldInt, timestep);
}
[ForgeGeneratedField]
private uint _fieldUInt;
public event FieldEvent<uint> fieldUIntChanged;
public Interpolated<uint> fieldUIntInterpolation = new Interpolated<uint>() { LerpT = 0f, Enabled = false };
public uint fieldUInt
{
get { return _fieldUInt; }
set
{
// Don't do anything if the value is the same
if (_fieldUInt == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x40;
_fieldUInt = value;
hasDirtyFields = true;
}
}
public void SetfieldUIntDirty()
{
_dirtyFields[0] |= 0x40;
hasDirtyFields = true;
}
private void RunChange_fieldUInt(ulong timestep)
{
if (fieldUIntChanged != null) fieldUIntChanged(_fieldUInt, timestep);
if (fieldAltered != null) fieldAltered("fieldUInt", _fieldUInt, timestep);
}
[ForgeGeneratedField]
private float _fieldFloat;
public event FieldEvent<float> fieldFloatChanged;
public InterpolateFloat fieldFloatInterpolation = new InterpolateFloat() { LerpT = 0f, Enabled = false };
public float fieldFloat
{
get { return _fieldFloat; }
set
{
// Don't do anything if the value is the same
if (_fieldFloat == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[0] |= 0x80;
_fieldFloat = value;
hasDirtyFields = true;
}
}
public void SetfieldFloatDirty()
{
_dirtyFields[0] |= 0x80;
hasDirtyFields = true;
}
private void RunChange_fieldFloat(ulong timestep)
{
if (fieldFloatChanged != null) fieldFloatChanged(_fieldFloat, timestep);
if (fieldAltered != null) fieldAltered("fieldFloat", _fieldFloat, timestep);
}
[ForgeGeneratedField]
private float _fieldFloatInterpolate;
public event FieldEvent<float> fieldFloatInterpolateChanged;
public InterpolateFloat fieldFloatInterpolateInterpolation = new InterpolateFloat() { LerpT = 0.15f, Enabled = true };
public float fieldFloatInterpolate
{
get { return _fieldFloatInterpolate; }
set
{
// Don't do anything if the value is the same
if (_fieldFloatInterpolate == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[1] |= 0x1;
_fieldFloatInterpolate = value;
hasDirtyFields = true;
}
}
public void SetfieldFloatInterpolateDirty()
{
_dirtyFields[1] |= 0x1;
hasDirtyFields = true;
}
private void RunChange_fieldFloatInterpolate(ulong timestep)
{
if (fieldFloatInterpolateChanged != null) fieldFloatInterpolateChanged(_fieldFloatInterpolate, timestep);
if (fieldAltered != null) fieldAltered("fieldFloatInterpolate", _fieldFloatInterpolate, timestep);
}
[ForgeGeneratedField]
private long _fieldLong;
public event FieldEvent<long> fieldLongChanged;
public Interpolated<long> fieldLongInterpolation = new Interpolated<long>() { LerpT = 0f, Enabled = false };
public long fieldLong
{
get { return _fieldLong; }
set
{
// Don't do anything if the value is the same
if (_fieldLong == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[1] |= 0x2;
_fieldLong = value;
hasDirtyFields = true;
}
}
public void SetfieldLongDirty()
{
_dirtyFields[1] |= 0x2;
hasDirtyFields = true;
}
private void RunChange_fieldLong(ulong timestep)
{
if (fieldLongChanged != null) fieldLongChanged(_fieldLong, timestep);
if (fieldAltered != null) fieldAltered("fieldLong", _fieldLong, timestep);
}
[ForgeGeneratedField]
private ulong _fieldULong;
public event FieldEvent<ulong> fieldULongChanged;
public Interpolated<ulong> fieldULongInterpolation = new Interpolated<ulong>() { LerpT = 0f, Enabled = false };
public ulong fieldULong
{
get { return _fieldULong; }
set
{
// Don't do anything if the value is the same
if (_fieldULong == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[1] |= 0x4;
_fieldULong = value;
hasDirtyFields = true;
}
}
public void SetfieldULongDirty()
{
_dirtyFields[1] |= 0x4;
hasDirtyFields = true;
}
private void RunChange_fieldULong(ulong timestep)
{
if (fieldULongChanged != null) fieldULongChanged(_fieldULong, timestep);
if (fieldAltered != null) fieldAltered("fieldULong", _fieldULong, timestep);
}
[ForgeGeneratedField]
private double _fieldDouble;
public event FieldEvent<double> fieldDoubleChanged;
public Interpolated<double> fieldDoubleInterpolation = new Interpolated<double>() { LerpT = 0f, Enabled = false };
public double fieldDouble
{
get { return _fieldDouble; }
set
{
// Don't do anything if the value is the same
if (_fieldDouble == value)
return;
// Mark the field as dirty for the network to transmit
_dirtyFields[1] |= 0x8;
_fieldDouble = value;
hasDirtyFields = true;
}
}
public void SetfieldDoubleDirty()
{
_dirtyFields[1] |= 0x8;
hasDirtyFields = true;
}
private void RunChange_fieldDouble(ulong timestep)
{
if (fieldDoubleChanged != null) fieldDoubleChanged(_fieldDouble, timestep);
if (fieldAltered != null) fieldAltered("fieldDouble", _fieldDouble, timestep);
}
protected override void OwnershipChanged()
{
base.OwnershipChanged();
SnapInterpolations();
}
public void SnapInterpolations()
{
fieldByteInterpolation.current = fieldByteInterpolation.target;
fieldCharInterpolation.current = fieldCharInterpolation.target;
fieldShortInterpolation.current = fieldShortInterpolation.target;
fieldUShortInterpolation.current = fieldUShortInterpolation.target;
fieldBoolInterpolation.current = fieldBoolInterpolation.target;
fieldIntInterpolation.current = fieldIntInterpolation.target;
fieldUIntInterpolation.current = fieldUIntInterpolation.target;
fieldFloatInterpolation.current = fieldFloatInterpolation.target;
fieldFloatInterpolateInterpolation.current = fieldFloatInterpolateInterpolation.target;
fieldLongInterpolation.current = fieldLongInterpolation.target;
fieldULongInterpolation.current = fieldULongInterpolation.target;
fieldDoubleInterpolation.current = fieldDoubleInterpolation.target;
}
public override int UniqueIdentity { get { return IDENTITY; } }
protected override BMSByte WritePayload(BMSByte data)
{
UnityObjectMapper.Instance.MapBytes(data, _fieldByte);
UnityObjectMapper.Instance.MapBytes(data, _fieldChar);
UnityObjectMapper.Instance.MapBytes(data, _fieldShort);
UnityObjectMapper.Instance.MapBytes(data, _fieldUShort);
UnityObjectMapper.Instance.MapBytes(data, _fieldBool);
UnityObjectMapper.Instance.MapBytes(data, _fieldInt);
UnityObjectMapper.Instance.MapBytes(data, _fieldUInt);
UnityObjectMapper.Instance.MapBytes(data, _fieldFloat);
UnityObjectMapper.Instance.MapBytes(data, _fieldFloatInterpolate);
UnityObjectMapper.Instance.MapBytes(data, _fieldLong);
UnityObjectMapper.Instance.MapBytes(data, _fieldULong);
UnityObjectMapper.Instance.MapBytes(data, _fieldDouble);
return data;
}
protected override void ReadPayload(BMSByte payload, ulong timestep)
{
_fieldByte = UnityObjectMapper.Instance.Map<byte>(payload);
fieldByteInterpolation.current = _fieldByte;
fieldByteInterpolation.target = _fieldByte;
RunChange_fieldByte(timestep);
_fieldChar = UnityObjectMapper.Instance.Map<char>(payload);
fieldCharInterpolation.current = _fieldChar;
fieldCharInterpolation.target = _fieldChar;
RunChange_fieldChar(timestep);
_fieldShort = UnityObjectMapper.Instance.Map<short>(payload);
fieldShortInterpolation.current = _fieldShort;
fieldShortInterpolation.target = _fieldShort;
RunChange_fieldShort(timestep);
_fieldUShort = UnityObjectMapper.Instance.Map<ushort>(payload);
fieldUShortInterpolation.current = _fieldUShort;
fieldUShortInterpolation.target = _fieldUShort;
RunChange_fieldUShort(timestep);
_fieldBool = UnityObjectMapper.Instance.Map<bool>(payload);
fieldBoolInterpolation.current = _fieldBool;
fieldBoolInterpolation.target = _fieldBool;
RunChange_fieldBool(timestep);
_fieldInt = UnityObjectMapper.Instance.Map<int>(payload);
fieldIntInterpolation.current = _fieldInt;
fieldIntInterpolation.target = _fieldInt;
RunChange_fieldInt(timestep);
_fieldUInt = UnityObjectMapper.Instance.Map<uint>(payload);
fieldUIntInterpolation.current = _fieldUInt;
fieldUIntInterpolation.target = _fieldUInt;
RunChange_fieldUInt(timestep);
_fieldFloat = UnityObjectMapper.Instance.Map<float>(payload);
fieldFloatInterpolation.current = _fieldFloat;
fieldFloatInterpolation.target = _fieldFloat;
RunChange_fieldFloat(timestep);
_fieldFloatInterpolate = UnityObjectMapper.Instance.Map<float>(payload);
fieldFloatInterpolateInterpolation.current = _fieldFloatInterpolate;
fieldFloatInterpolateInterpolation.target = _fieldFloatInterpolate;
RunChange_fieldFloatInterpolate(timestep);
_fieldLong = UnityObjectMapper.Instance.Map<long>(payload);
fieldLongInterpolation.current = _fieldLong;
fieldLongInterpolation.target = _fieldLong;
RunChange_fieldLong(timestep);
_fieldULong = UnityObjectMapper.Instance.Map<ulong>(payload);
fieldULongInterpolation.current = _fieldULong;
fieldULongInterpolation.target = _fieldULong;
RunChange_fieldULong(timestep);
_fieldDouble = UnityObjectMapper.Instance.Map<double>(payload);
fieldDoubleInterpolation.current = _fieldDouble;
fieldDoubleInterpolation.target = _fieldDouble;
RunChange_fieldDouble(timestep);
}
protected override BMSByte SerializeDirtyFields()
{
dirtyFieldsData.Clear();
dirtyFieldsData.Append(_dirtyFields);
if ((0x1 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldByte);
if ((0x2 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldChar);
if ((0x4 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldShort);
if ((0x8 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldUShort);
if ((0x10 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldBool);
if ((0x20 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldInt);
if ((0x40 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldUInt);
if ((0x80 & _dirtyFields[0]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldFloat);
if ((0x1 & _dirtyFields[1]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldFloatInterpolate);
if ((0x2 & _dirtyFields[1]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldLong);
if ((0x4 & _dirtyFields[1]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldULong);
if ((0x8 & _dirtyFields[1]) != 0)
UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldDouble);
// Reset all the dirty fields
for (int i = 0; i < _dirtyFields.Length; i++)
_dirtyFields[i] = 0;
return dirtyFieldsData;
}
protected override void ReadDirtyFields(BMSByte data, ulong timestep)
{
if (readDirtyFlags == null)
Initialize();
Buffer.BlockCopy(data.byteArr, data.StartIndex(), readDirtyFlags, 0, readDirtyFlags.Length);
data.MoveStartIndex(readDirtyFlags.Length);
if ((0x1 & readDirtyFlags[0]) != 0)
{
if (fieldByteInterpolation.Enabled)
{
fieldByteInterpolation.target = UnityObjectMapper.Instance.Map<byte>(data);
fieldByteInterpolation.Timestep = timestep;
}
else
{
_fieldByte = UnityObjectMapper.Instance.Map<byte>(data);
RunChange_fieldByte(timestep);
}
}
if ((0x2 & readDirtyFlags[0]) != 0)
{
if (fieldCharInterpolation.Enabled)
{
fieldCharInterpolation.target = UnityObjectMapper.Instance.Map<char>(data);
fieldCharInterpolation.Timestep = timestep;
}
else
{
_fieldChar = UnityObjectMapper.Instance.Map<char>(data);
RunChange_fieldChar(timestep);
}
}
if ((0x4 & readDirtyFlags[0]) != 0)
{
if (fieldShortInterpolation.Enabled)
{
fieldShortInterpolation.target = UnityObjectMapper.Instance.Map<short>(data);
fieldShortInterpolation.Timestep = timestep;
}
else
{
_fieldShort = UnityObjectMapper.Instance.Map<short>(data);
RunChange_fieldShort(timestep);
}
}
if ((0x8 & readDirtyFlags[0]) != 0)
{
if (fieldUShortInterpolation.Enabled)
{
fieldUShortInterpolation.target = UnityObjectMapper.Instance.Map<ushort>(data);
fieldUShortInterpolation.Timestep = timestep;
}
else
{
_fieldUShort = UnityObjectMapper.Instance.Map<ushort>(data);
RunChange_fieldUShort(timestep);
}
}
if ((0x10 & readDirtyFlags[0]) != 0)
{
if (fieldBoolInterpolation.Enabled)
{
fieldBoolInterpolation.target = UnityObjectMapper.Instance.Map<bool>(data);
fieldBoolInterpolation.Timestep = timestep;
}
else
{
_fieldBool = UnityObjectMapper.Instance.Map<bool>(data);
RunChange_fieldBool(timestep);
}
}
if ((0x20 & readDirtyFlags[0]) != 0)
{
if (fieldIntInterpolation.Enabled)
{
fieldIntInterpolation.target = UnityObjectMapper.Instance.Map<int>(data);
fieldIntInterpolation.Timestep = timestep;
}
else
{
_fieldInt = UnityObjectMapper.Instance.Map<int>(data);
RunChange_fieldInt(timestep);
}
}
if ((0x40 & readDirtyFlags[0]) != 0)
{
if (fieldUIntInterpolation.Enabled)
{
fieldUIntInterpolation.target = UnityObjectMapper.Instance.Map<uint>(data);
fieldUIntInterpolation.Timestep = timestep;
}
else
{
_fieldUInt = UnityObjectMapper.Instance.Map<uint>(data);
RunChange_fieldUInt(timestep);
}
}
if ((0x80 & readDirtyFlags[0]) != 0)
{
if (fieldFloatInterpolation.Enabled)
{
fieldFloatInterpolation.target = UnityObjectMapper.Instance.Map<float>(data);
fieldFloatInterpolation.Timestep = timestep;
}
else
{
_fieldFloat = UnityObjectMapper.Instance.Map<float>(data);
RunChange_fieldFloat(timestep);
}
}
if ((0x1 & readDirtyFlags[1]) != 0)
{
if (fieldFloatInterpolateInterpolation.Enabled)
{
fieldFloatInterpolateInterpolation.target = UnityObjectMapper.Instance.Map<float>(data);
fieldFloatInterpolateInterpolation.Timestep = timestep;
}
else
{
_fieldFloatInterpolate = UnityObjectMapper.Instance.Map<float>(data);
RunChange_fieldFloatInterpolate(timestep);
}
}
if ((0x2 & readDirtyFlags[1]) != 0)
{
if (fieldLongInterpolation.Enabled)
{
fieldLongInterpolation.target = UnityObjectMapper.Instance.Map<long>(data);
fieldLongInterpolation.Timestep = timestep;
}
else
{
_fieldLong = UnityObjectMapper.Instance.Map<long>(data);
RunChange_fieldLong(timestep);
}
}
if ((0x4 & readDirtyFlags[1]) != 0)
{
if (fieldULongInterpolation.Enabled)
{
fieldULongInterpolation.target = UnityObjectMapper.Instance.Map<ulong>(data);
fieldULongInterpolation.Timestep = timestep;
}
else
{
_fieldULong = UnityObjectMapper.Instance.Map<ulong>(data);
RunChange_fieldULong(timestep);
}
}
if ((0x8 & readDirtyFlags[1]) != 0)
{
if (fieldDoubleInterpolation.Enabled)
{
fieldDoubleInterpolation.target = UnityObjectMapper.Instance.Map<double>(data);
fieldDoubleInterpolation.Timestep = timestep;
}
else
{
_fieldDouble = UnityObjectMapper.Instance.Map<double>(data);
RunChange_fieldDouble(timestep);
}
}
}
public override void InterpolateUpdate()
{
if (IsOwner)
return;
if (fieldByteInterpolation.Enabled && !fieldByteInterpolation.current.UnityNear(fieldByteInterpolation.target, 0.0015f))
{
_fieldByte = (byte)fieldByteInterpolation.Interpolate();
//RunChange_fieldByte(fieldByteInterpolation.Timestep);
}
if (fieldCharInterpolation.Enabled && !fieldCharInterpolation.current.UnityNear(fieldCharInterpolation.target, 0.0015f))
{
_fieldChar = (char)fieldCharInterpolation.Interpolate();
//RunChange_fieldChar(fieldCharInterpolation.Timestep);
}
if (fieldShortInterpolation.Enabled && !fieldShortInterpolation.current.UnityNear(fieldShortInterpolation.target, 0.0015f))
{
_fieldShort = (short)fieldShortInterpolation.Interpolate();
//RunChange_fieldShort(fieldShortInterpolation.Timestep);
}
if (fieldUShortInterpolation.Enabled && !fieldUShortInterpolation.current.UnityNear(fieldUShortInterpolation.target, 0.0015f))
{
_fieldUShort = (ushort)fieldUShortInterpolation.Interpolate();
//RunChange_fieldUShort(fieldUShortInterpolation.Timestep);
}
if (fieldBoolInterpolation.Enabled && !fieldBoolInterpolation.current.UnityNear(fieldBoolInterpolation.target, 0.0015f))
{
_fieldBool = (bool)fieldBoolInterpolation.Interpolate();
//RunChange_fieldBool(fieldBoolInterpolation.Timestep);
}
if (fieldIntInterpolation.Enabled && !fieldIntInterpolation.current.UnityNear(fieldIntInterpolation.target, 0.0015f))
{
_fieldInt = (int)fieldIntInterpolation.Interpolate();
//RunChange_fieldInt(fieldIntInterpolation.Timestep);
}
if (fieldUIntInterpolation.Enabled && !fieldUIntInterpolation.current.UnityNear(fieldUIntInterpolation.target, 0.0015f))
{
_fieldUInt = (uint)fieldUIntInterpolation.Interpolate();
//RunChange_fieldUInt(fieldUIntInterpolation.Timestep);
}
if (fieldFloatInterpolation.Enabled && !fieldFloatInterpolation.current.UnityNear(fieldFloatInterpolation.target, 0.0015f))
{
_fieldFloat = (float)fieldFloatInterpolation.Interpolate();
//RunChange_fieldFloat(fieldFloatInterpolation.Timestep);
}
if (fieldFloatInterpolateInterpolation.Enabled && !fieldFloatInterpolateInterpolation.current.UnityNear(fieldFloatInterpolateInterpolation.target, 0.0015f))
{
_fieldFloatInterpolate = (float)fieldFloatInterpolateInterpolation.Interpolate();
//RunChange_fieldFloatInterpolate(fieldFloatInterpolateInterpolation.Timestep);
}
if (fieldLongInterpolation.Enabled && !fieldLongInterpolation.current.UnityNear(fieldLongInterpolation.target, 0.0015f))
{
_fieldLong = (long)fieldLongInterpolation.Interpolate();
//RunChange_fieldLong(fieldLongInterpolation.Timestep);
}
if (fieldULongInterpolation.Enabled && !fieldULongInterpolation.current.UnityNear(fieldULongInterpolation.target, 0.0015f))
{
_fieldULong = (ulong)fieldULongInterpolation.Interpolate();
//RunChange_fieldULong(fieldULongInterpolation.Timestep);
}
if (fieldDoubleInterpolation.Enabled && !fieldDoubleInterpolation.current.UnityNear(fieldDoubleInterpolation.target, 0.0015f))
{
_fieldDouble = (double)fieldDoubleInterpolation.Interpolate();
//RunChange_fieldDouble(fieldDoubleInterpolation.Timestep);
}
}
private void Initialize()
{
if (readDirtyFlags == null)
readDirtyFlags = new byte[2];
}
public TestNetworkObject() : base() { Initialize(); }
public TestNetworkObject(NetWorker networker, INetworkBehavior networkBehavior = null, int createCode = 0, byte[] metadata = null) : base(networker, networkBehavior, createCode, metadata) { Initialize(); }
public TestNetworkObject(NetWorker networker, uint serverId, FrameStream frame) : base(networker, serverId, frame) { Initialize(); }
// DO NOT TOUCH, THIS GETS GENERATED PLEASE EXTEND THIS CLASS IF YOU WISH TO HAVE CUSTOM CODE ADDITIONS
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SchoolBusAPI.Models;
namespace SchoolBusAPI.Models
{
/// <summary>
/// School Bus inspection details supplementary to the RIP inspection
/// </summary>
[MetaDataExtension (Description = "School Bus inspection details supplementary to the RIP inspection")]
public partial class Inspection : AuditableEntity, IEquatable<Inspection>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public Inspection()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Inspection" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for an Inspection (required).</param>
/// <param name="InspectionDate">The date and time the inspection was conducted. (required).</param>
/// <param name="InspectionTypeCode">The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created (required).</param>
/// <param name="InspectionResultCode">The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here. (required).</param>
/// <param name="CreatedDate">Record creation date and time (required).</param>
/// <param name="SchoolBus">A foreign key reference to the system-generated unique identifier for a School Bus.</param>
/// <param name="Inspector">Defaults for a new inspection to the current user, but can be changed as needed..</param>
/// <param name="Notes">A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application..</param>
/// <param name="RIPInspectionId">The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details..</param>
/// <param name="PreviousNextInspectionDate">The next inspection date for the related School Bus prior to the creation of this record.</param>
/// <param name="PreviousNextInspectionTypeCode">The next inspection type code for the related School Bus prior to the creation of this record.</param>
public Inspection(int Id, DateTime InspectionDate, string InspectionTypeCode, string InspectionResultCode, DateTime CreatedDate, SchoolBus SchoolBus = null, User Inspector = null, string Notes = null, string RIPInspectionId = null, DateTime? PreviousNextInspectionDate = null, string PreviousNextInspectionTypeCode = null)
{
this.Id = Id;
this.InspectionDate = InspectionDate;
this.InspectionTypeCode = InspectionTypeCode;
this.InspectionResultCode = InspectionResultCode;
this.CreatedDate = CreatedDate;
this.SchoolBus = SchoolBus;
this.Inspector = Inspector;
this.Notes = Notes;
this.RIPInspectionId = RIPInspectionId;
this.PreviousNextInspectionDate = PreviousNextInspectionDate;
this.PreviousNextInspectionTypeCode = PreviousNextInspectionTypeCode;
}
/// <summary>
/// A system-generated unique identifier for an Inspection
/// </summary>
/// <value>A system-generated unique identifier for an Inspection</value>
[MetaDataExtension (Description = "A system-generated unique identifier for an Inspection")]
public int Id { get; set; }
/// <summary>
/// The date and time the inspection was conducted.
/// </summary>
/// <value>The date and time the inspection was conducted.</value>
[MetaDataExtension (Description = "The date and time the inspection was conducted.")]
public DateTime InspectionDate { get; set; }
/// <summary>
/// The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created
/// </summary>
/// <value>The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created</value>
[MetaDataExtension (Description = "The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created")]
[MaxLength(255)]
public string InspectionTypeCode { get; set; }
/// <summary>
/// The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here.
/// </summary>
/// <value>The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here.</value>
[MetaDataExtension (Description = "The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here.")]
[MaxLength(255)]
public string InspectionResultCode { get; set; }
/// <summary>
/// Record creation date and time
/// </summary>
/// <value>Record creation date and time</value>
[MetaDataExtension (Description = "Record creation date and time")]
public DateTime CreatedDate { get; set; }
/// <summary>
/// A foreign key reference to the system-generated unique identifier for a School Bus
/// </summary>
/// <value>A foreign key reference to the system-generated unique identifier for a School Bus</value>
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
public SchoolBus SchoolBus { get; set; }
/// <summary>
/// Foreign key for SchoolBus
/// </summary>
[ForeignKey("SchoolBus")]
[JsonIgnore]
[MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a School Bus")]
public int? SchoolBusId { get; set; }
/// <summary>
/// Defaults for a new inspection to the current user, but can be changed as needed.
/// </summary>
/// <value>Defaults for a new inspection to the current user, but can be changed as needed.</value>
[MetaDataExtension (Description = "Defaults for a new inspection to the current user, but can be changed as needed.")]
public User Inspector { get; set; }
/// <summary>
/// Foreign key for Inspector
/// </summary>
[ForeignKey("Inspector")]
[JsonIgnore]
[MetaDataExtension (Description = "Defaults for a new inspection to the current user, but can be changed as needed.")]
public int? InspectorId { get; set; }
/// <summary>
/// A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application.
/// </summary>
/// <value>A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application.</value>
[MetaDataExtension (Description = "A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application.")]
[MaxLength(2048)]
public string Notes { get; set; }
/// <summary>
/// The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details.
/// </summary>
/// <value>The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details.</value>
[MetaDataExtension (Description = "The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details.")]
[MaxLength(255)]
public string RIPInspectionId { get; set; }
/// <summary>
/// The next inspection date for the related School Bus prior to the creation of this record
/// </summary>
/// <value>The next inspection date for the related School Bus prior to the creation of this record</value>
[MetaDataExtension (Description = "The next inspection date for the related School Bus prior to the creation of this record")]
public DateTime? PreviousNextInspectionDate { get; set; }
/// <summary>
/// The next inspection type code for the related School Bus prior to the creation of this record
/// </summary>
/// <value>The next inspection type code for the related School Bus prior to the creation of this record</value>
[MetaDataExtension (Description = "The next inspection type code for the related School Bus prior to the creation of this record")]
[MaxLength(30)]
public string PreviousNextInspectionTypeCode { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Inspection {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" InspectionDate: ").Append(InspectionDate).Append("\n");
sb.Append(" InspectionTypeCode: ").Append(InspectionTypeCode).Append("\n");
sb.Append(" InspectionResultCode: ").Append(InspectionResultCode).Append("\n");
sb.Append(" CreatedDate: ").Append(CreatedDate).Append("\n");
sb.Append(" SchoolBus: ").Append(SchoolBus).Append("\n");
sb.Append(" Inspector: ").Append(Inspector).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" RIPInspectionId: ").Append(RIPInspectionId).Append("\n");
sb.Append(" PreviousNextInspectionDate: ").Append(PreviousNextInspectionDate).Append("\n");
sb.Append(" PreviousNextInspectionTypeCode: ").Append(PreviousNextInspectionTypeCode).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((Inspection)obj);
}
/// <summary>
/// Returns true if Inspection instances are equal
/// </summary>
/// <param name="other">Instance of Inspection to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Inspection other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.InspectionDate == other.InspectionDate ||
this.InspectionDate != null &&
this.InspectionDate.Equals(other.InspectionDate)
) &&
(
this.InspectionTypeCode == other.InspectionTypeCode ||
this.InspectionTypeCode != null &&
this.InspectionTypeCode.Equals(other.InspectionTypeCode)
) &&
(
this.InspectionResultCode == other.InspectionResultCode ||
this.InspectionResultCode != null &&
this.InspectionResultCode.Equals(other.InspectionResultCode)
) &&
(
this.CreatedDate == other.CreatedDate ||
this.CreatedDate != null &&
this.CreatedDate.Equals(other.CreatedDate)
) &&
(
this.SchoolBus == other.SchoolBus ||
this.SchoolBus != null &&
this.SchoolBus.Equals(other.SchoolBus)
) &&
(
this.Inspector == other.Inspector ||
this.Inspector != null &&
this.Inspector.Equals(other.Inspector)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.Equals(other.Notes)
) &&
(
this.RIPInspectionId == other.RIPInspectionId ||
this.RIPInspectionId != null &&
this.RIPInspectionId.Equals(other.RIPInspectionId)
) &&
(
this.PreviousNextInspectionDate == other.PreviousNextInspectionDate ||
this.PreviousNextInspectionDate != null &&
this.PreviousNextInspectionDate.Equals(other.PreviousNextInspectionDate)
) &&
(
this.PreviousNextInspectionTypeCode == other.PreviousNextInspectionTypeCode ||
this.PreviousNextInspectionTypeCode != null &&
this.PreviousNextInspectionTypeCode.Equals(other.PreviousNextInspectionTypeCode)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode();
if (this.InspectionDate != null)
{
hash = hash * 59 + this.InspectionDate.GetHashCode();
} if (this.InspectionTypeCode != null)
{
hash = hash * 59 + this.InspectionTypeCode.GetHashCode();
}
if (this.InspectionResultCode != null)
{
hash = hash * 59 + this.InspectionResultCode.GetHashCode();
}
if (this.CreatedDate != null)
{
hash = hash * 59 + this.CreatedDate.GetHashCode();
}
if (this.SchoolBus != null)
{
hash = hash * 59 + this.SchoolBus.GetHashCode();
}
if (this.Inspector != null)
{
hash = hash * 59 + this.Inspector.GetHashCode();
} if (this.Notes != null)
{
hash = hash * 59 + this.Notes.GetHashCode();
}
if (this.RIPInspectionId != null)
{
hash = hash * 59 + this.RIPInspectionId.GetHashCode();
}
if (this.PreviousNextInspectionDate != null)
{
hash = hash * 59 + this.PreviousNextInspectionDate.GetHashCode();
}
if (this.PreviousNextInspectionTypeCode != null)
{
hash = hash * 59 + this.PreviousNextInspectionTypeCode.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Inspection left, Inspection right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Inspection left, Inspection right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Collection of <see cref="Index.FieldInfo"/>s (accessible by number or by name).
/// <para/>
/// @lucene.experimental
/// </summary>
public class FieldInfos : IEnumerable<FieldInfo>
{
private readonly bool hasFreq;
private readonly bool hasProx;
private readonly bool hasPayloads;
private readonly bool hasOffsets;
private readonly bool hasVectors;
private readonly bool hasNorms;
private readonly bool hasDocValues;
private readonly IDictionary<int, FieldInfo> byNumber = new JCG.SortedDictionary<int, FieldInfo>();
private readonly IDictionary<string, FieldInfo> byName = new JCG.Dictionary<string, FieldInfo>();
private readonly ICollection<FieldInfo> values; // for an unmodifiable iterator
/// <summary>
/// Constructs a new <see cref="FieldInfos"/> from an array of <see cref="Index.FieldInfo"/> objects
/// </summary>
public FieldInfos(FieldInfo[] infos)
{
bool hasVectors = false;
bool hasProx = false;
bool hasPayloads = false;
bool hasOffsets = false;
bool hasFreq = false;
bool hasNorms = false;
bool hasDocValues = false;
foreach (FieldInfo info in infos)
{
if (info.Number < 0)
{
throw new ArgumentException("illegal field number: " + info.Number + " for field " + info.Name);
}
FieldInfo previous;
if (byNumber.TryGetValue(info.Number, out previous))
{
throw new ArgumentException("duplicate field numbers: " + previous.Name + " and " + info.Name + " have: " + info.Number);
}
byNumber[info.Number] = info;
if (byName.TryGetValue(info.Name, out previous))
{
throw new ArgumentException("duplicate field names: " + previous.Number + " and " + info.Number + " have: " + info.Name);
}
byName[info.Name] = info;
hasVectors |= info.HasVectors;
hasProx |= info.IsIndexed && info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
hasFreq |= info.IsIndexed && info.IndexOptions != IndexOptions.DOCS_ONLY;
hasOffsets |= info.IsIndexed && info.IndexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
hasNorms |= info.HasNorms;
hasDocValues |= info.HasDocValues;
hasPayloads |= info.HasPayloads;
}
this.hasVectors = hasVectors;
this.hasProx = hasProx;
this.hasPayloads = hasPayloads;
this.hasOffsets = hasOffsets;
this.hasFreq = hasFreq;
this.hasNorms = hasNorms;
this.hasDocValues = hasDocValues;
this.values = byNumber.Values;
}
/// <summary>
/// Returns <c>true</c> if any fields have freqs </summary>
public virtual bool HasFreq => hasFreq;
/// <summary>
/// Returns <c>true</c> if any fields have positions </summary>
public virtual bool HasProx => hasProx;
/// <summary>
/// Returns <c>true</c> if any fields have payloads </summary>
public virtual bool HasPayloads => hasPayloads;
/// <summary>
/// Returns <c>true</c> if any fields have offsets </summary>
public virtual bool HasOffsets => hasOffsets;
/// <summary>
/// Returns <c>true</c> if any fields have vectors </summary>
public virtual bool HasVectors => hasVectors;
/// <summary>
/// Returns <c>true</c> if any fields have norms </summary>
public virtual bool HasNorms => hasNorms;
/// <summary>
/// Returns <c>true</c> if any fields have <see cref="DocValues"/> </summary>
public virtual bool HasDocValues => hasDocValues;
/// <summary>
/// Returns the number of fields.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
public virtual int Count
{
get
{
if (Debugging.AssertsEnabled) Debugging.Assert(byNumber.Count == byName.Count);
return byNumber.Count;
}
}
/// <summary>
/// Returns an iterator over all the fieldinfo objects present,
/// ordered by ascending field number
/// </summary>
// TODO: what happens if in fact a different order is used?
public virtual IEnumerator<FieldInfo> GetEnumerator()
{
return values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Return the <see cref="Index.FieldInfo"/> object referenced by the <paramref name="fieldName"/> </summary>
/// <returns> the <see cref="Index.FieldInfo"/> object or <c>null</c> when the given <paramref name="fieldName"/>
/// doesn't exist. </returns>
public virtual FieldInfo FieldInfo(string fieldName)
{
FieldInfo ret;
byName.TryGetValue(fieldName, out ret);
return ret;
}
/// <summary>
/// Return the <see cref="Index.FieldInfo"/> object referenced by the <paramref name="fieldNumber"/>. </summary>
/// <param name="fieldNumber"> field's number. </param>
/// <returns> the <see cref="Index.FieldInfo"/> object or null when the given <paramref name="fieldNumber"/>
/// doesn't exist. </returns>
/// <exception cref="ArgumentException"> if <paramref name="fieldNumber"/> is negative </exception>
public virtual FieldInfo FieldInfo(int fieldNumber)
{
if (fieldNumber < 0)
{
throw new ArgumentException("Illegal field number: " + fieldNumber);
}
Index.FieldInfo ret;
byNumber.TryGetValue(fieldNumber, out ret);
return ret;
}
internal sealed class FieldNumbers
{
private readonly IDictionary<int?, string> numberToName;
private readonly IDictionary<string, int?> nameToNumber;
// We use this to enforce that a given field never
// changes DV type, even across segments / IndexWriter
// sessions:
private readonly IDictionary<string, DocValuesType> docValuesType;
// TODO: we should similarly catch an attempt to turn
// norms back on after they were already ommitted; today
// we silently discard the norm but this is badly trappy
private int lowestUnassignedFieldNumber = -1;
internal FieldNumbers()
{
this.nameToNumber = new Dictionary<string, int?>();
this.numberToName = new Dictionary<int?, string>();
this.docValuesType = new Dictionary<string, DocValuesType>();
}
/// <summary>
/// Returns the global field number for the given field name. If the name
/// does not exist yet it tries to add it with the given preferred field
/// number assigned if possible otherwise the first unassigned field number
/// is used as the field number.
/// </summary>
internal int AddOrGet(string fieldName, int preferredFieldNumber, DocValuesType dvType)
{
lock (this)
{
if (dvType != DocValuesType.NONE)
{
DocValuesType currentDVType;
docValuesType.TryGetValue(fieldName, out currentDVType);
if (currentDVType == DocValuesType.NONE) // default value in .NET (value type 0)
{
docValuesType[fieldName] = dvType;
}
else if (currentDVType != DocValuesType.NONE && currentDVType != dvType)
{
throw new ArgumentException("cannot change DocValues type from " + currentDVType + " to " + dvType + " for field \"" + fieldName + "\"");
}
}
int? fieldNumber;
nameToNumber.TryGetValue(fieldName, out fieldNumber);
if (fieldNumber == null)
{
int? preferredBoxed = preferredFieldNumber;
if (preferredFieldNumber != -1 && !numberToName.ContainsKey(preferredBoxed))
{
// cool - we can use this number globally
fieldNumber = preferredBoxed;
}
else
{
// find a new FieldNumber
while (numberToName.ContainsKey(++lowestUnassignedFieldNumber))
{
// might not be up to date - lets do the work once needed
}
fieldNumber = lowestUnassignedFieldNumber;
}
numberToName[fieldNumber] = fieldName;
nameToNumber[fieldName] = fieldNumber;
}
return (int)fieldNumber;
}
}
// used by assert
internal bool ContainsConsistent(int? number, string name, DocValuesType dvType)
{
lock (this)
{
string numberToNameStr;
int? nameToNumberVal;
DocValuesType docValuesType_E;
numberToName.TryGetValue(number, out numberToNameStr);
nameToNumber.TryGetValue(name, out nameToNumberVal);
docValuesType.TryGetValue(name, out docValuesType_E);
return name.Equals(numberToNameStr, StringComparison.Ordinal)
&& number.Equals(nameToNumber[name]) &&
(dvType == DocValuesType.NONE || docValuesType_E == DocValuesType.NONE || dvType == docValuesType_E);
}
}
/// <summary>
/// Returns <c>true</c> if the <paramref name="fieldName"/> exists in the map and is of the
/// same <paramref name="dvType"/>.
/// </summary>
internal bool Contains(string fieldName, DocValuesType dvType)
{
lock (this)
{
// used by IndexWriter.updateNumericDocValue
if (!nameToNumber.ContainsKey(fieldName))
{
return false;
}
else
{
// only return true if the field has the same dvType as the requested one
DocValuesType dvCand;
docValuesType.TryGetValue(fieldName, out dvCand);
return dvType == dvCand;
}
}
}
internal void Clear()
{
lock (this)
{
numberToName.Clear();
nameToNumber.Clear();
docValuesType.Clear();
}
}
internal void SetDocValuesType(int number, string name, DocValuesType dvType)
{
lock (this)
{
if (Debugging.AssertsEnabled) Debugging.Assert(ContainsConsistent(number, name, dvType));
docValuesType[name] = dvType;
}
}
}
internal sealed class Builder
{
private readonly Dictionary<string, FieldInfo> byName = new Dictionary<string, FieldInfo>();
private readonly FieldNumbers globalFieldNumbers;
internal Builder()
: this(new FieldNumbers())
{
}
/// <summary>
/// Creates a new instance with the given <see cref="FieldNumbers"/>.
/// </summary>
internal Builder(FieldNumbers globalFieldNumbers)
{
if (Debugging.AssertsEnabled) Debugging.Assert(globalFieldNumbers != null);
this.globalFieldNumbers = globalFieldNumbers;
}
public void Add(FieldInfos other)
{
foreach (FieldInfo fieldInfo in other)
{
Add(fieldInfo);
}
}
/// <summary>
/// NOTE: this method does not carry over termVector
/// booleans nor docValuesType; the indexer chain
/// (TermVectorsConsumerPerField, DocFieldProcessor) must
/// set these fields when they succeed in consuming
/// the document
/// </summary>
public FieldInfo AddOrUpdate(string name, IIndexableFieldType fieldType)
{
// TODO: really, indexer shouldn't even call this
// method (it's only called from DocFieldProcessor);
// rather, each component in the chain should update
// what it "owns". EG fieldType.indexOptions() should
// be updated by maybe FreqProxTermsWriterPerField:
return AddOrUpdateInternal(name, -1, fieldType.IsIndexed, false, fieldType.OmitNorms, false, fieldType.IndexOptions, fieldType.DocValueType, DocValuesType.NONE);
}
private FieldInfo AddOrUpdateInternal(string name, int preferredFieldNumber, bool isIndexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions indexOptions, DocValuesType docValues, DocValuesType normType)
{
// LUCENENET: Bypass FieldInfo method so we can access the quick boolean check
if (!TryGetFieldInfo(name, out FieldInfo fi) || fi is null)
{
// this field wasn't yet added to this in-RAM
// segment's FieldInfo, so now we get a global
// number for this field. If the field was seen
// before then we'll get the same name and number,
// else we'll allocate a new one:
int fieldNumber = globalFieldNumbers.AddOrGet(name, preferredFieldNumber, docValues);
fi = new FieldInfo(name, isIndexed, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValues, normType, null);
if (Debugging.AssertsEnabled)
{
Debugging.Assert(!byName.ContainsKey(fi.Name));
Debugging.Assert(globalFieldNumbers.ContainsConsistent(fi.Number, fi.Name, fi.DocValuesType));
}
byName[fi.Name] = fi;
}
else
{
fi.Update(isIndexed, storeTermVector, omitNorms, storePayloads, indexOptions);
if (docValues != DocValuesType.NONE)
{
// only pay the synchronization cost if fi does not already have a DVType
bool updateGlobal = !fi.HasDocValues;
fi.DocValuesType = docValues; // this will also perform the consistency check.
if (updateGlobal)
{
// must also update docValuesType map so it's
// aware of this field's DocValueType
globalFieldNumbers.SetDocValuesType(fi.Number, name, docValues);
}
}
if (!fi.OmitsNorms && normType != DocValuesType.NONE)
{
fi.NormType = normType;
}
}
return fi;
}
public FieldInfo Add(FieldInfo fi)
{
// IMPORTANT - reuse the field number if possible for consistent field numbers across segments
return AddOrUpdateInternal(fi.Name, fi.Number, fi.IsIndexed, fi.HasVectors, fi.OmitsNorms, fi.HasPayloads, fi.IndexOptions, fi.DocValuesType, fi.NormType);
}
public bool TryGetFieldInfo(string fieldName, out FieldInfo ret) // LUCENENET specific - changed from FieldInfo to TryGetFieldInfo
{
return byName.TryGetValue(fieldName, out ret);
}
public FieldInfos Finish()
{
return new FieldInfos(byName.Values.ToArray());
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.xssf
{
using System;
using NUnit.Framework;
using NPOI.XSSF.UserModel;
using NPOI.XSSF.UserModel;
[TestFixture]
public class TestSheetProtection
{
private XSSFSheet sheet;
protected void SetUp() {
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("sheetProtection_not_protected.xlsx");
sheet = workbook.GetSheetAt(0);
}
[Test]
public void TestShouldReadWorkbookProtection(){
Assert.IsFalse(sheet.IsAutoFilterLocked());
Assert.IsFalse(sheet.IsDeleteColumnsLocked());
Assert.IsFalse(sheet.IsDeleteRowsLocked());
Assert.IsFalse(sheet.IsFormatCellsLocked());
Assert.IsFalse(sheet.IsFormatColumnsLocked());
Assert.IsFalse(sheet.IsFormatRowsLocked());
Assert.IsFalse(sheet.IsInsertColumnsLocked());
Assert.IsFalse(sheet.IsInsertHyperlinksLocked());
Assert.IsFalse(sheet.IsInsertRowsLocked());
Assert.IsFalse(sheet.IsPivotTablesLocked());
Assert.IsFalse(sheet.IsSortLocked());
Assert.IsFalse(sheet.IsObjectsLocked());
Assert.IsFalse(sheet.IsScenariosLocked());
Assert.IsFalse(sheet.IsSelectLockedCellsLocked());
Assert.IsFalse(sheet.IsSelectUnlockedCellsLocked());
Assert.IsFalse(sheet.IsSheetLocked());
sheet = XSSFTestDataSamples.OpenSampleWorkbook("sheetProtection_allLocked.xlsx").GetSheetAt(0);
Assert.IsTrue(sheet.IsAutoFilterLocked());
Assert.IsTrue(sheet.IsDeleteColumnsLocked());
Assert.IsTrue(sheet.IsDeleteRowsLocked());
Assert.IsTrue(sheet.IsFormatCellsLocked());
Assert.IsTrue(sheet.IsFormatColumnsLocked());
Assert.IsTrue(sheet.IsFormatRowsLocked());
Assert.IsTrue(sheet.IsInsertColumnsLocked());
Assert.IsTrue(sheet.IsInsertHyperlinksLocked());
Assert.IsTrue(sheet.IsInsertRowsLocked());
Assert.IsTrue(sheet.IsPivotTablesLocked());
Assert.IsTrue(sheet.IsSortLocked());
Assert.IsTrue(sheet.IsObjectsLocked());
Assert.IsTrue(sheet.IsScenariosLocked());
Assert.IsTrue(sheet.IsSelectLockedCellsLocked());
Assert.IsTrue(sheet.IsSelectUnlockedCellsLocked());
Assert.IsTrue(sheet.IsSheetLocked());
}
[Test]
public void TestWriteAutoFilter(){
Assert.IsFalse(sheet.IsAutoFilterLocked());
sheet.LockAutoFilter();
Assert.IsFalse(sheet.IsAutoFilterLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsAutoFilterLocked());
sheet.LockAutoFilter(false);
Assert.IsFalse(sheet.IsAutoFilterLocked());
}
[Test]
public void TestWriteDeleteColumns(){
Assert.IsFalse(sheet.IsDeleteColumnsLocked());
sheet.LockDeleteColumns();
Assert.IsFalse(sheet.IsDeleteColumnsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsDeleteColumnsLocked());
sheet.LockDeleteColumns(false);
Assert.IsFalse(sheet.IsDeleteColumnsLocked());
}
[Test]
public void TestWriteDeleteRows(){
Assert.IsFalse(sheet.IsDeleteRowsLocked());
sheet.LockDeleteRows();
Assert.IsFalse(sheet.IsDeleteRowsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsDeleteRowsLocked());
sheet.LockDeleteRows(false);
Assert.IsFalse(sheet.IsDeleteRowsLocked());
}
[Test]
public void TestWriteFormatCells(){
Assert.IsFalse(sheet.IsFormatCellsLocked());
sheet.LockFormatCells();
Assert.IsFalse(sheet.IsFormatCellsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsFormatCellsLocked());
sheet.LockFormatCells(false);
Assert.IsFalse(sheet.IsFormatCellsLocked());
}
[Test]
public void TestWriteFormatColumns(){
Assert.IsFalse(sheet.IsFormatColumnsLocked());
sheet.LockFormatColumns();
Assert.IsFalse(sheet.IsFormatColumnsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsFormatColumnsLocked());
sheet.LockFormatColumns(false);
Assert.IsFalse(sheet.IsFormatColumnsLocked());
}
[Test]
public void TestWriteFormatRows(){
Assert.IsFalse(sheet.IsFormatRowsLocked());
sheet.LockFormatRows();
Assert.IsFalse(sheet.IsFormatRowsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsFormatRowsLocked());
sheet.LockFormatRows(false);
Assert.IsFalse(sheet.IsFormatRowsLocked());
}
[Test]
public void TestWriteInsertColumns(){
Assert.IsFalse(sheet.IsInsertColumnsLocked());
sheet.LockInsertColumns();
Assert.IsFalse(sheet.IsInsertColumnsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsInsertColumnsLocked());
sheet.LockInsertColumns(false);
Assert.IsFalse(sheet.IsInsertColumnsLocked());
}
[Test]
public void TestWriteInsertHyperlinks(){
Assert.IsFalse(sheet.IsInsertHyperlinksLocked());
sheet.LockInsertHyperlinks();
Assert.IsFalse(sheet.IsInsertHyperlinksLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsInsertHyperlinksLocked());
sheet.LockInsertHyperlinks(false);
Assert.IsFalse(sheet.IsInsertHyperlinksLocked());
}
[Test]
public void TestWriteInsertRows(){
Assert.IsFalse(sheet.IsInsertRowsLocked());
sheet.LockInsertRows();
Assert.IsFalse(sheet.IsInsertRowsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsInsertRowsLocked());
sheet.LockInsertRows(false);
Assert.IsFalse(sheet.IsInsertRowsLocked());
}
[Test]
public void TestWritePivotTables(){
Assert.IsFalse(sheet.IsPivotTablesLocked());
sheet.LockPivotTables();
Assert.IsFalse(sheet.IsPivotTablesLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsPivotTablesLocked());
sheet.LockPivotTables(false);
Assert.IsFalse(sheet.IsPivotTablesLocked());
}
[Test]
public void TestWriteSort(){
Assert.IsFalse(sheet.IsSortLocked());
sheet.LockSort();
Assert.IsFalse(sheet.IsSortLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsSortLocked());
sheet.LockSort(false);
Assert.IsFalse(sheet.IsSortLocked());
}
[Test]
public void TestWriteObjects(){
Assert.IsFalse(sheet.IsObjectsLocked());
sheet.LockObjects();
Assert.IsFalse(sheet.IsObjectsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsObjectsLocked());
sheet.LockObjects(false);
Assert.IsFalse(sheet.IsObjectsLocked());
}
[Test]
public void TestWriteScenarios(){
Assert.IsFalse(sheet.IsScenariosLocked());
sheet.LockScenarios();
Assert.IsFalse(sheet.IsScenariosLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsScenariosLocked());
sheet.LockScenarios(false);
Assert.IsFalse(sheet.IsScenariosLocked());
}
[Test]
public void TestWriteSelectLockedCells(){
Assert.IsFalse(sheet.IsSelectLockedCellsLocked());
sheet.LockSelectLockedCells();
Assert.IsFalse(sheet.IsSelectLockedCellsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsSelectLockedCellsLocked());
sheet.LockSelectLockedCells(false);
Assert.IsFalse(sheet.IsSelectLockedCellsLocked());
}
[Test]
public void TestWriteSelectUnlockedCells(){
Assert.IsFalse(sheet.IsSelectUnlockedCellsLocked());
sheet.LockSelectUnlockedCells();
Assert.IsFalse(sheet.IsSelectUnlockedCellsLocked());
sheet.EnableLocking();
Assert.IsTrue(sheet.IsSelectUnlockedCellsLocked());
sheet.LockSelectUnlockedCells(false);
Assert.IsFalse(sheet.IsSelectUnlockedCellsLocked());
}
[Test]
public void TestWriteSelectEnableLocking(){
sheet = XSSFTestDataSamples.OpenSampleWorkbook("sheetProtection_allLocked.xlsx").GetSheetAt(0);
Assert.IsTrue(sheet.IsAutoFilterLocked());
Assert.IsTrue(sheet.IsDeleteColumnsLocked());
Assert.IsTrue(sheet.IsDeleteRowsLocked());
Assert.IsTrue(sheet.IsFormatCellsLocked());
Assert.IsTrue(sheet.IsFormatColumnsLocked());
Assert.IsTrue(sheet.IsFormatRowsLocked());
Assert.IsTrue(sheet.IsInsertColumnsLocked());
Assert.IsTrue(sheet.IsInsertHyperlinksLocked());
Assert.IsTrue(sheet.IsInsertRowsLocked());
Assert.IsTrue(sheet.IsPivotTablesLocked());
Assert.IsTrue(sheet.IsSortLocked());
Assert.IsTrue(sheet.IsObjectsLocked());
Assert.IsTrue(sheet.IsScenariosLocked());
Assert.IsTrue(sheet.IsSelectLockedCellsLocked());
Assert.IsTrue(sheet.IsSelectUnlockedCellsLocked());
Assert.IsTrue(sheet.IsSheetLocked());
sheet.DisableLocking();
Assert.IsFalse(sheet.IsAutoFilterLocked());
Assert.IsFalse(sheet.IsDeleteColumnsLocked());
Assert.IsFalse(sheet.IsDeleteRowsLocked());
Assert.IsFalse(sheet.IsFormatCellsLocked());
Assert.IsFalse(sheet.IsFormatColumnsLocked());
Assert.IsFalse(sheet.IsFormatRowsLocked());
Assert.IsFalse(sheet.IsInsertColumnsLocked());
Assert.IsFalse(sheet.IsInsertHyperlinksLocked());
Assert.IsFalse(sheet.IsInsertRowsLocked());
Assert.IsFalse(sheet.IsPivotTablesLocked());
Assert.IsFalse(sheet.IsSortLocked());
Assert.IsFalse(sheet.IsObjectsLocked());
Assert.IsFalse(sheet.IsScenariosLocked());
Assert.IsFalse(sheet.IsSelectLockedCellsLocked());
Assert.IsFalse(sheet.IsSelectUnlockedCellsLocked());
Assert.IsFalse(sheet.IsSheetLocked());
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.Text;
using Google.GData.Client;
namespace Google.GData.Contacts {
/// <summary>
/// A subclass of FeedQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// The Contacts Data API supports the following standard Google Data API query parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
public class GroupsQuery : FeedQuery {
/// <summary>
/// contacts group base URI
/// </summary>
public const string groupsBaseUri = "https://www.google.com/m8/feeds/groups/";
/// <summary>
/// sort oder value for sorting by lastmodified
/// </summary>
public const string OrderByLastModified = "lastmodified";
/// <summary>
/// sort oder value for sorting ascending
/// </summary>
public const string SortOrderAscending = "ascending";
/// <summary>
/// sort oder value for sorting descending
/// </summary>
public const string SortOrderDescending = "ascending";
/// <summary>
/// base projection value
/// </summary>
public const string baseProjection = "base";
/// <summary>
/// thin projection value
/// </summary>
public const string thinProjection = "thin";
/// <summary>
/// property-key projection value
/// </summary>
public const string propertyProjection = "property-";
/// <summary>
/// full projection value
/// </summary>
public const string fullProjection = "full";
private string orderBy;
private bool showDeleted;
private string sortOrder;
/// <summary>
/// base constructor
/// </summary>
public GroupsQuery()
: base() {
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public GroupsQuery(string queryUri)
: base(queryUri) {
}
/// <summary>
/// convenience method to create an URI based on a userID for a groups feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID"></param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID) {
return CreateGroupsUri(userID, ContactsQuery.fullProjection);
}
/// <summary>
/// convenience method to create an URI based on a userID for a groups feed
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID, string projection) {
return ContactsQuery.groupsBaseUri + ContactsQuery.UserString(userID) + projection;
}
/// <summary>Sorting order direction. Can be either ascending or descending</summary>
/// <returns> </returns>
public string SortOrder {
get { return this.sortOrder; }
set { this.sortOrder = value; }
}
/// <summary>Sorting criterion. The only supported value is lastmodified</summary>
/// <returns> </returns>
public string OrderBy {
get { return this.orderBy; }
set { this.orderBy = value; }
}
/// <summary>Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but
/// an atom:id element and a gd:deleted element. (Google retains placeholders
/// for deleted contacts for 30 days after deletion; during that time,
/// you can request the placeholders using the showdeleted query
/// parameter.) Valid values are true or false.</summary>
/// <returns> </returns>
public bool ShowDeleted {
get { return this.showDeleted; }
set { this.showDeleted = value; }
}
/// <summary>
/// helper to create the userstring for a query
/// </summary>
/// <param name="user">the user to encode, or NULL if default</param>
/// <returns></returns>
protected static string UserString(string user) {
if (user == null) {
return "default/";
}
return Utilities.UriEncodeReserved(user) + "/";
}
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
protected override Uri ParseUri(Uri targetUri) {
base.ParseUri(targetUri);
if (targetUri != null) {
char[] deli = { '?', '&' };
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (String token in tokens) {
if (token.Length > 0) {
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0]) {
case "orderby":
this.OrderBy = parameters[1];
break;
case "sortorder":
this.SortOrder = parameters[1];
break;
case "showdeleted":
if (String.Compare("true", parameters[1], false, CultureInfo.InvariantCulture) == 0) {
this.ShowDeleted = true;
}
break;
}
}
}
}
return this.Uri;
}
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
protected override string CalculateQuery(string basePath) {
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.OrderBy != null && this.OrderBy.Length > 0) {
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "orderby={0}", Utilities.UriEncodeReserved(this.OrderBy));
paramInsertion = '&';
}
if (this.SortOrder != null && this.SortOrder.Length > 0) {
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "sortorder={0}", Utilities.UriEncodeReserved(this.SortOrder));
paramInsertion = '&';
}
if (this.ShowDeleted) {
newPath.Append(paramInsertion);
newPath.Append("showdeleted=true");
paramInsertion = '&';
}
return newPath.ToString();
}
}
/// <summary>
/// A subclass of GroupsQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
public class ContactsQuery : GroupsQuery {
/// <summary>
/// contacts base URI
/// </summary>
public const string contactsBaseUri = "https://www.google.com/m8/feeds/contacts/";
private string group;
/// <summary>
/// base constructor
/// </summary>
public ContactsQuery()
: base() {
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public ContactsQuery(string queryUri)
: base(queryUri) {
}
/// <summary>
/// convenience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID) {
return CreateContactsUri(userID, ContactsQuery.fullProjection);
}
/// <summary>
/// convenience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID, string projection) {
return ContactsQuery.contactsBaseUri + UserString(userID) + projection;
}
/// <summary>Constrains the results to only the contacts belonging to the
/// group specified. Value of this parameter specifies group ID</summary>
/// <returns> </returns>
public string Group {
get { return this.group; }
set { this.group = value; }
}
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
protected override Uri ParseUri(Uri targetUri) {
base.ParseUri(targetUri);
if (targetUri != null) {
char[] deli = { '?', '&' };
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (String token in tokens) {
if (token.Length > 0) {
char[] otherDeli = { '=' };
String[] parameters = token.Split(otherDeli, 2);
switch (parameters[0]) {
case "group":
this.Group = parameters[1];
break;
}
}
}
}
return this.Uri;
}
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
protected override string CalculateQuery(string basePath) {
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (this.Group != null && this.Group.Length > 0) {
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "group={0}", Utilities.UriEncodeReserved(this.Group));
paramInsertion = '&';
}
return newPath.ToString();
}
}
}
| |
#region Apache License
//
// 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.
//
#endregion
// .NET Compact Framework has no support for Win32 Console API's
#if !NETCF
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the console.
/// </summary>
/// <remarks>
/// <para>
/// ColoredConsoleAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific type of message to be set.
/// </para>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes directly to the application's attached console
/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
/// programmatically redirected (for example NUnit does this to capture program output).
/// This appender will ignore these redirections because it needs to use Win32
/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
/// must be used.
/// </para>
/// <para>
/// When configuring the colored console appender, mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red, HighIntensity" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// combination of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// <item><term>HighIntensity</term><description></description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Rick Hobbs</author>
/// <author>Nicko Cadell</author>
public class ColoredConsoleAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible color values for use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the colors.
/// </para>
/// </remarks>
/// <seealso cref="ColoredConsoleAppender" />
[Flags]
public enum Colors : int
{
/// <summary>
/// color is blue
/// </summary>
Blue = 0x0001,
/// <summary>
/// color is green
/// </summary>
Green = 0x0002,
/// <summary>
/// color is red
/// </summary>
Red = 0x0004,
/// <summary>
/// color is white
/// </summary>
White = Blue | Green | Red,
/// <summary>
/// color is yellow
/// </summary>
Yellow = Red | Green,
/// <summary>
/// color is purple
/// </summary>
Purple = Red | Blue,
/// <summary>
/// color is cyan
/// </summary>
Cyan = Green | Blue,
/// <summary>
/// color is intensified
/// </summary>
HighIntensity = 0x0008,
}
#endregion // Colors Enum
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public ColoredConsoleAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string v = value.Trim();
if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colors
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion // Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if FRAMEWORK_4_0_OR_ABOVE
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
if (m_consoleOutputWriter != null)
{
IntPtr consoleHandle = IntPtr.Zero;
if (m_writeToErrorStream)
{
// Write to the error stream
consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}
else
{
// Write to the output stream
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
// Default to white on black
ushort colorInfo = (ushort)Colors.White;
// see if there is a specified lookup
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
colorInfo = levelColors.CombinedColor;
}
// Render the event to a string
string strLoggingMessage = RenderLoggingEvent(loggingEvent);
// get the current console color - to restore later
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);
// set the console colors
SetConsoleTextAttribute(consoleHandle, colorInfo);
// Using WriteConsoleW seems to be unreliable.
// If a large buffer is written, say 15,000 chars
// Followed by a larger buffer, say 20,000 chars
// then WriteConsoleW will fail, last error 8
// 'Not enough storage is available to process this command.'
//
// Although the documentation states that the buffer must
// be less that 64KB (i.e. 32,000 WCHARs) the longest string
// that I can write out a the first call to WriteConsoleW
// is only 30,704 chars.
//
// Unlike the WriteFile API the WriteConsoleW method does not
// seem to be able to partially write out from the input buffer.
// It does have a lpNumberOfCharsWritten parameter, but this is
// either the length of the input buffer if any output was written,
// or 0 when an error occurs.
//
// All results above were observed on Windows XP SP1 running
// .NET runtime 1.1 SP1.
//
// Old call to WriteConsoleW:
//
// WriteConsoleW(
// consoleHandle,
// strLoggingMessage,
// (UInt32)strLoggingMessage.Length,
// out (UInt32)ignoreWrittenCount,
// IntPtr.Zero);
//
// Instead of calling WriteConsoleW we use WriteFile which
// handles large buffers correctly. Because WriteFile does not
// handle the codepage conversion as WriteConsoleW does we
// need to use a System.IO.StreamWriter with the appropriate
// Encoding. The WriteFile calls are wrapped up in the
// System.IO.__ConsoleStream internal class obtained through
// the System.Console.OpenStandardOutput method.
//
// See the ActivateOptions method below for the code that
// retrieves and wraps the stream.
// The windows console uses ScrollConsoleScreenBuffer internally to
// scroll the console buffer when the display buffer of the console
// has been used up. ScrollConsoleScreenBuffer fills the area uncovered
// by moving the current content with the background color
// currently specified on the console. This means that it fills the
// whole line in front of the cursor position with the current
// background color.
// This causes an issue when writing out text with a non default
// background color. For example; We write a message with a Blue
// background color and the scrollable area of the console is full.
// When we write the newline at the end of the message the console
// needs to scroll the buffer to make space available for the new line.
// The ScrollConsoleScreenBuffer internals will fill the newly created
// space with the current background color: Blue.
// We then change the console color back to default (White text on a
// Black background). We write some text to the console, the text is
// written correctly in White with a Black background, however the
// remainder of the line still has a Blue background.
//
// This causes a disjointed appearance to the output where the background
// colors change.
//
// This can be remedied by restoring the console colors before causing
// the buffer to scroll, i.e. before writing the last newline. This does
// assume that the rendered message will end with a newline.
//
// Therefore we identify a trailing newline in the message and don't
// write this to the output, then we restore the console color and write
// a newline. Note that we must AutoFlush before we restore the console
// color otherwise we will have no effect.
//
// There will still be a slight artefact for the last line of the message
// will have the background extended to the end of the line, however this
// is unlikely to cause any user issues.
//
// Note that none of the above is visible while the console buffer is scrollable
// within the console window viewport, the effects only arise when the actual
// buffer is full and needs to be scrolled.
char[] messageCharArray = strLoggingMessage.ToCharArray();
int arrayLength = messageCharArray.Length;
bool appendNewline = false;
// Trim off last newline, if it exists
if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n')
{
arrayLength -= 2;
appendNewline = true;
}
// Write to the output stream
m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);
// Restore the console back to its previous color scheme
SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);
if (appendNewline)
{
// Write the newline, after changing the color scheme
m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
}
}
}
private static readonly char[] s_windowsNewline = {'\r', '\n'};
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
#if FRAMEWORK_4_0_OR_ABOVE
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
System.IO.Stream consoleOutputStream = null;
// Use the Console methods to open a Stream over the console std handle
if (m_writeToErrorStream)
{
// Write to the error stream
consoleOutputStream = Console.OpenStandardError();
}
else
{
// Write to the output stream
consoleOutputStream = Console.OpenStandardOutput();
}
// Lookup the codepage encoding for the console
System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP());
// Create a writer around the console stream
m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100);
m_consoleOutputWriter.AutoFlush = true;
// SuppressFinalize on m_consoleOutputWriter because all it will do is flush
// and close the file handle. Because we have set AutoFlush the additional flush
// is not required. The console file handle should not be closed, so we don't call
// Dispose, Close or the finalizer.
GC.SuppressFinalize(m_consoleOutputWriter);
}
#endregion // Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion // Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;
#endregion // Private Instances Fields
#region Win32 Methods
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern int GetConsoleOutputCP();
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool SetConsoleTextAttribute(
IntPtr consoleHandle,
ushort attributes);
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool GetConsoleScreenBufferInfo(
IntPtr consoleHandle,
out CONSOLE_SCREEN_BUFFER_INFO bufferInfo);
// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
// private static extern bool WriteConsoleW(
// IntPtr hConsoleHandle,
// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer,
// UInt32 bufferLen,
// out UInt32 written,
// IntPtr reserved);
//private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10));
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GetStdHandle(
UInt32 type);
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public UInt16 x;
public UInt16 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SMALL_RECT
{
public UInt16 Left;
public UInt16 Top;
public UInt16 Right;
public UInt16 Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public ushort wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
#endregion // Win32 Methods
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private Colors m_foreColor;
private Colors m_backColor;
private ushort m_combinedColor = 0;
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level.
/// </para>
/// </remarks>
public Colors ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level.
/// </para>
/// </remarks>
public Colors BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) );
}
/// <summary>
/// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for
/// setting the console color.
/// </summary>
internal ushort CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
#endif // !NETCF
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Graphics;
using TK.CustomMap;
using TK.CustomMap.Api.Google;
using TK.CustomMap.Droid;
using TK.CustomMap.Interfaces;
using TK.CustomMap.Models;
using TK.CustomMap.Overlays;
using TK.CustomMap.Utilities;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Color = Xamarin.Forms.Color;
using System.Collections;
using Com.Google.Maps.Android.Clustering;
using Android.OS;
using Android.Content;
[assembly: ExportRenderer(typeof(TKCustomMap), typeof(TKCustomMapRenderer))]
namespace TK.CustomMap.Droid
{
/// <summary>
/// Android Renderer of <see cref="TK.CustomMap.TKCustomMap"/>
/// </summary>
public class TKCustomMapRenderer : ViewRenderer<TKCustomMap, MapView>, IRendererFunctions, GoogleMap.ISnapshotReadyCallback, GoogleMap.IOnCameraIdleListener, IOnMapReadyCallback
{
object _lockObj = new object();
bool _isInitialized;
bool _isLayoutPerformed;
readonly List<TKRoute> _tempRouteList = new List<TKRoute>();
readonly Dictionary<TKRoute, Polyline> _routes = new Dictionary<TKRoute, Polyline>();
readonly Dictionary<TKPolyline, Polyline> _polylines = new Dictionary<TKPolyline, Polyline>();
readonly Dictionary<TKCircle, Circle> _circles = new Dictionary<TKCircle, Circle>();
readonly Dictionary<TKPolygon, Polygon> _polygons = new Dictionary<TKPolygon, Polygon>();
readonly Dictionary<TKCustomMapPin, TKMarker> _markers = new Dictionary<TKCustomMapPin, TKMarker>();
Marker _selectedMarker;
bool _isDragging;
bool _disposed;
byte[] _snapShot;
TileOverlay _tileOverlay;
GoogleMap _googleMap;
ClusterManager _clusterManager;
static Bundle s_bundle;
internal static Bundle Bundle { set { s_bundle = value; } }
GoogleMap Map => _googleMap;
internal TKCustomMap FormsMap
{
get { return Element as TKCustomMap; }
}
IMapFunctions MapFunctions
{
get { return Element as IMapFunctions; }
}
/// <summary>
/// Creates a new instance of <see cref="TKCustomMapRenderer"/>
/// </summary>
/// <param name="context">Android context</param>
public TKCustomMapRenderer(Context context) : base(context)
{ }
/// <inheritdoc />
protected override void OnElementChanged(ElementChangedEventArgs<TKCustomMap> e)
{
if (!TKGoogleMaps.IsInitialized) throw new Exception("Call TKGoogleMaps.Init first");
var oldMapView = Control;
var mapView = new MapView(Context);
mapView.OnCreate(s_bundle);
mapView.OnResume();
SetNativeControl(mapView);
lock (_lockObj)
{
base.OnElementChanged(e);
if (mapView == null) return;
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= FormsMapPropertyChanged;
UnregisterCollections((TKCustomMap)e.OldElement);
if (_googleMap != null)
{
_googleMap.MarkerClick -= OnMarkerClick;
_googleMap.MapClick -= OnMapClick;
_googleMap.MapLongClick -= OnMapLongClick;
_googleMap.MarkerDragEnd -= OnMarkerDragEnd;
_googleMap.MarkerDrag -= OnMarkerDrag;
_googleMap.MarkerDragStart -= OnMarkerDragStart;
_googleMap.InfoWindowClick -= OnInfoWindowClick;
_googleMap.MyLocationChange -= OnUserLocationChange;
_googleMap.SetOnCameraIdleListener(null);
_googleMap = null;
}
}
if (e.NewElement != null)
{
MapFunctions.SetRenderer(this);
mapView.GetMapAsync(this);
FormsMap.PropertyChanged += FormsMapPropertyChanged;
}
}
}
///<inheritdoc/>
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (!_isLayoutPerformed)
{
_isLayoutPerformed = true;
UpdateMapRegion();
_isInitialized = true;
MapFunctions?.RaiseMapReady();
}
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (_disposed) return;
_disposed = true;
if (disposing)
{
if (FormsMap != null)
{
FormsMap.PropertyChanged -= FormsMapPropertyChanged;
UnregisterCollections(FormsMap);
}
if (_googleMap != null)
{
_googleMap.MarkerClick -= OnMarkerClick;
_googleMap.MapClick -= OnMapClick;
_googleMap.MapLongClick -= OnMapLongClick;
_googleMap.MarkerDragEnd -= OnMarkerDragEnd;
_googleMap.MarkerDrag -= OnMarkerDrag;
_googleMap.MarkerDragStart -= OnMarkerDragStart;
_googleMap.InfoWindowClick -= OnInfoWindowClick;
_googleMap.MyLocationChange -= OnUserLocationChange;
_googleMap.SetOnCameraIdleListener(null);
_clusterManager?.Dispose();
_clusterManager = null;
_googleMap.Dispose();
_googleMap = null;
}
}
base.Dispose(disposing);
}
/// <summary>
/// When a property of the Forms map changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void FormsMapPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (_googleMap == null) return;
switch(e.PropertyName)
{
case nameof(TKCustomMap.Pins):
UpdatePins();
break;
case nameof(TKCustomMap.SelectedPin):
SetSelectedItem();
break;
case nameof(TKCustomMap.Polylines):
UpdateLines();
break;
case nameof(TKCustomMap.Circles):
UpdateCircles();
break;
case nameof(TKCustomMap.Polygons):
UpdatePolygons();
break;
case nameof(TKCustomMap.Routes):
UpdateRoutes();
break;
case nameof(TKCustomMap.TilesUrlOptions):
UpdateTileOptions();
break;
case nameof(TKCustomMap.ShowTraffic):
UpdateShowTraffic();
break;
case nameof(TKCustomMap.MapRegion):
UpdateMapRegion();
break;
case nameof(TKCustomMap.IsClusteringEnabled):
UpdateIsClusteringEnabled();
break;
case nameof(TKCustomMap.MapType):
UpdateMapType();
break;
case nameof(TKCustomMap.IsShowingUser):
UpdateIsShowingUser();
break;
case nameof(TKCustomMap.HasScrollEnabled):
UpdateHasScrollEnabled();
break;
case nameof(TKCustomMap.HasZoomEnabled):
UpdateHasZoomEnabled();
break;
}
}
/// <summary>
/// When the map is ready to use
/// </summary>
/// <param name="googleMap">The map instance</param>
public virtual void OnMapReady(GoogleMap googleMap)
{
lock (_lockObj)
{
_googleMap = googleMap;
if (FormsMap.IsClusteringEnabled)
{
_clusterManager = new ClusterManager(Context, _googleMap);
_clusterManager.Renderer = new TKMarkerRenderer(Context, _googleMap, _clusterManager, this);
}
_googleMap.MarkerClick += OnMarkerClick;
_googleMap.MapClick += OnMapClick;
_googleMap.MapLongClick += OnMapLongClick;
_googleMap.MarkerDragEnd += OnMarkerDragEnd;
_googleMap.MarkerDrag += OnMarkerDrag;
_googleMap.MarkerDragStart += OnMarkerDragStart;
_googleMap.InfoWindowClick += OnInfoWindowClick;
_googleMap.MyLocationChange += OnUserLocationChange;
_googleMap.SetOnCameraIdleListener(this);
UpdateTileOptions();
UpdateMapRegion();
UpdatePins();
UpdateRoutes();
UpdateLines();
UpdateCircles();
UpdatePolygons();
UpdateShowTraffic();
UpdateMapType();
UpdateIsShowingUser();
UpdateHasZoomEnabled();
UpdateHasScrollEnabled();
}
}
/// <summary>
/// When the location of the user changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnUserLocationChange(object sender, GoogleMap.MyLocationChangeEventArgs e)
{
if (e.Location == null || FormsMap == null) return;
var newPosition = new Position(e.Location.Latitude, e.Location.Longitude);
MapFunctions.RaiseUserLocationChanged(newPosition);
}
/// <summary>
/// When the info window gets clicked
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var pin = GetPinByMarker(e.Marker);
if (pin == null) return;
if (pin.IsCalloutClickable)
MapFunctions.RaiseCalloutClicked(pin);
}
/// <summary>
/// Dragging process
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMarkerDrag(object sender, GoogleMap.MarkerDragEventArgs e)
{
var item = _markers.SingleOrDefault(i => true == i.Value.Marker?.Id.Equals(e.Marker.Id));
if (item.Key == null) return;
item.Key.Position = e.Marker.Position.ToPosition();
}
/// <summary>
/// When a dragging starts
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMarkerDragStart(object sender, GoogleMap.MarkerDragStartEventArgs e)
{
_isDragging = true;
}
/// <summary>
/// When the camera position changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnCameraChange(object sender, GoogleMap.CameraChangeEventArgs e)
{
if (FormsMap == null) return;
FormsMap.MapRegion = GetCurrentMapRegion(e.Position.Target);
if (FormsMap.IsClusteringEnabled)
{
_clusterManager.OnCameraIdle();
}
}
/// <summary>
/// When a pin gets clicked
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMarkerClick(object sender, GoogleMap.MarkerClickEventArgs e)
{
if (FormsMap == null) return;
var item = _markers.SingleOrDefault(i => true == i.Value.Marker?.Id.Equals(e.Marker.Id));
if (item.Key == null) return;
_selectedMarker = e.Marker;
FormsMap.SelectedPin = item.Key;
if (item.Key.ShowCallout)
{
item.Value.Marker.ShowInfoWindow();
}
}
/// <summary>
/// When a drag of a marker ends
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMarkerDragEnd(object sender, GoogleMap.MarkerDragEndEventArgs e)
{
_isDragging = false;
if (FormsMap == null) return;
var pin = _markers.SingleOrDefault(i => true == i.Value.Marker?.Id.Equals(e.Marker.Id));
if (pin.Key == null) return;
if (FormsMap.IsClusteringEnabled)
{
_clusterManager.RemoveItem(pin.Value);
_clusterManager.AddItem(pin.Value);
_clusterManager.Cluster();
}
MapFunctions.RaisePinDragEnd(pin.Key);
}
/// <summary>
/// When a long click was performed on the map
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
if (FormsMap == null) return;
var position = e.Point.ToPosition();
MapFunctions.RaiseMapLongPress(position);
}
/// <summary>
/// When the map got tapped
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnMapClick(object sender, GoogleMap.MapClickEventArgs e)
{
if (FormsMap == null) return;
var position = e.Point.ToPosition();
if (FormsMap.Routes != null)
{
foreach (var route in FormsMap.Routes.Where(i => i.Selectable))
{
var internalRoute = _routes[route];
if (GmsPolyUtil.IsLocationOnPath(
position,
internalRoute.Points.Select(i => i.ToPosition()),
true,
(int)_googleMap.CameraPosition.Zoom,
FormsMap.MapCenter.Latitude))
{
MapFunctions.RaiseRouteClicked(route);
return;
}
}
}
MapFunctions.RaiseMapClicked(position);
}
/// <summary>
/// Updates the markers when a pin gets added or removed in the collection
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnCustomPinsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKCustomMapPin pin in e.NewItems)
{
AddPin(pin);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TKCustomMapPin pin in e.OldItems)
{
if (!FormsMap.Pins.Contains(pin))
{
RemovePin(pin);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
UpdatePins(false);
}
}
/// <summary>
/// When a property of a pin changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
async void OnPinPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var pin = sender as TKCustomMapPin;
if (pin == null) return;
TKMarker marker = null;
if (!_markers.ContainsKey(pin) || (marker = _markers[pin]) == null) return;
await marker.HandlePropertyChangedAsync(e, _isDragging);
if (FormsMap.IsClusteringEnabled && e.PropertyName == nameof(TKCustomMapPin.Position) && !_isDragging)
{
_clusterManager.RemoveItem(marker);
_clusterManager.AddItem(marker);
_clusterManager.Cluster();
}
}
/// <summary>
/// Collection of routes changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnLineCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKPolyline line in e.NewItems)
{
AddLine(line);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TKPolyline line in e.OldItems)
{
if (!FormsMap.Polylines.Contains(line))
{
_polylines[line].Remove();
line.PropertyChanged -= OnLinePropertyChanged;
_polylines.Remove(line);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
UpdateLines(false);
}
}
/// <summary>
/// A property of a route changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnLinePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var line = (TKPolyline)sender;
if (e.PropertyName == nameof(TKPolyline.LineCoordinates))
{
if (line.LineCoordinates != null && line.LineCoordinates.Count > 1)
{
_polylines[line].Points = new List<LatLng>(line.LineCoordinates.Select(i => i.ToLatLng()));
}
else
{
_polylines[line].Points = null;
}
}
else if (e.PropertyName == nameof(TKPolyline.Color))
{
_polylines[line].Color = line.Color.ToAndroid().ToArgb();
}
else if (e.PropertyName == nameof(TKPolyline.LineWidth))
{
_polylines[line].Width = line.LineWidth;
}
}
/// <summary>
/// Creates all Markers on the map
/// </summary>
void UpdatePins(bool firstUpdate = true)
{
if (_googleMap == null) return;
foreach (var i in _markers)
{
RemovePin(i.Key, false);
}
_markers.Clear();
if (FormsMap.Pins != null)
{
foreach (var pin in FormsMap.Pins)
{
AddPin(pin);
}
if (firstUpdate)
{
var observAble = FormsMap.Pins as INotifyCollectionChanged;
if (observAble != null)
{
observAble.CollectionChanged += OnCustomPinsCollectionChanged;
}
}
MapFunctions.RaisePinsReady();
}
}
/// <summary>
/// Adds a marker to the map
/// </summary>
/// <param name="pin">The Forms Pin</param>
async void AddPin(TKCustomMapPin pin)
{
if (_markers.Keys.Contains(pin)) return;
pin.PropertyChanged += OnPinPropertyChanged;
var tkMarker = new TKMarker(pin, Context);
var markerWithIcon = new MarkerOptions();
await tkMarker.InitializeMarkerOptionsAsync(markerWithIcon);
_markers.Add(pin, tkMarker);
if (FormsMap.IsClusteringEnabled)
{
_clusterManager.AddItem(tkMarker);
_clusterManager.Cluster();
}
else
{
tkMarker.Marker = _googleMap.AddMarker(markerWithIcon);
}
}
/// <summary>
/// Remove a pin from the map and the internal dictionary
/// </summary>
/// <param name="pin">The pin to remove</param>
/// <param name="removeMarker">true to remove the marker from the map</param>
void RemovePin(TKCustomMapPin pin, bool removeMarker = true)
{
if (!_markers.TryGetValue(pin, out var item)) return;
if (_selectedMarker != null)
{
if (item.Marker.Id.Equals(_selectedMarker.Id))
{
FormsMap.SelectedPin = null;
}
}
_clusterManager?.RemoveItem(item);
item.Marker?.Remove();
pin.PropertyChanged -= OnPinPropertyChanged;
if (removeMarker)
{
_markers.Remove(pin);
}
}
/// <summary>
/// Set the selected item on the map
/// </summary>
void SetSelectedItem()
{
if (_selectedMarker != null)
{
_selectedMarker.HideInfoWindow();
_selectedMarker = null;
}
if (FormsMap.SelectedPin != null)
{
if (!_markers.ContainsKey(FormsMap.SelectedPin)) return;
var selectedPin = _markers[FormsMap.SelectedPin];
_selectedMarker = selectedPin.Marker;
if (FormsMap.SelectedPin.ShowCallout)
{
selectedPin.Marker.ShowInfoWindow();
}
MapFunctions.RaisePinSelected(FormsMap.SelectedPin);
}
}
/// <summary>
/// Creates the routes on the map
/// </summary>
void UpdateLines(bool firstUpdate = true)
{
if (_googleMap == null) return;
foreach (var i in _polylines)
{
i.Key.PropertyChanged -= OnLinePropertyChanged;
i.Value.Remove();
}
_polylines.Clear();
if (FormsMap.Polylines != null)
{
foreach (var line in FormsMap.Polylines)
{
AddLine(line);
}
if (firstUpdate)
{
var observAble = FormsMap.Polylines as INotifyCollectionChanged;
if (observAble != null)
{
observAble.CollectionChanged += OnLineCollectionChanged;
}
}
}
}
/// <summary>
/// Updates all circles
/// </summary>
void UpdateCircles(bool firstUpdate = true)
{
if (_googleMap == null) return;
foreach (var i in _circles)
{
i.Key.PropertyChanged -= CirclePropertyChanged;
i.Value.Remove();
}
_circles.Clear();
if (FormsMap.Circles != null)
{
foreach (var circle in FormsMap.Circles)
{
AddCircle(circle);
}
if (firstUpdate)
{
var observAble = FormsMap.Circles as INotifyCollectionChanged;
if (observAble != null)
{
observAble.CollectionChanged += CirclesCollectionChanged;
}
}
}
}
/// <summary>
/// Creates the polygones on the map
/// </summary>
/// <param name="firstUpdate">If the collection updates the first time</param>
void UpdatePolygons(bool firstUpdate = true)
{
if (_googleMap == null) return;
foreach (var i in _polygons)
{
i.Key.PropertyChanged -= OnPolygonPropertyChanged;
i.Value.Remove();
}
_polygons.Clear();
if (FormsMap.Polygons != null)
{
foreach (var i in FormsMap.Polygons)
{
AddPolygon(i);
}
if (firstUpdate)
{
var observAble = FormsMap.Polygons as INotifyCollectionChanged;
if (observAble != null)
{
observAble.CollectionChanged += OnPolygonsCollectionChanged;
}
}
}
}
/// <summary>
/// Create all routes
/// </summary>
/// <param name="firstUpdate">If first update of collection or not</param>
void UpdateRoutes(bool firstUpdate = true)
{
_tempRouteList.Clear();
if (_googleMap == null) return;
foreach (var i in _routes)
{
if (i.Key != null)
i.Key.PropertyChanged -= OnRoutePropertyChanged;
i.Value.Remove();
}
_routes.Clear();
if (FormsMap == null || FormsMap.Routes == null) return;
foreach (var i in FormsMap.Routes)
{
AddRoute(i);
}
if (firstUpdate)
{
var observAble = FormsMap.Routes as INotifyCollectionChanged;
if (observAble != null)
{
observAble.CollectionChanged += OnRouteCollectionChanged;
}
}
}
/// <summary>
/// When the collection of routes changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnRouteCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKRoute route in e.NewItems)
{
AddRoute(route);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TKRoute route in e.OldItems)
{
if (!FormsMap.Routes.Contains(route))
{
_routes[route].Remove();
route.PropertyChanged -= OnRoutePropertyChanged;
_routes.Remove(route);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
UpdateRoutes(false);
}
}
/// <summary>
/// When a property of a route changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnRoutePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var route = (TKRoute)sender;
if (e.PropertyName == nameof(TKRoute.Source) ||
e.PropertyName == nameof(TKRoute.Destination) ||
e.PropertyName == nameof(TKRoute.TravelMode))
{
route.PropertyChanged -= OnRoutePropertyChanged;
_routes[route].Remove();
_routes.Remove(route);
AddRoute(route);
}
else if (e.PropertyName == nameof(TKPolyline.Color))
{
_routes[route].Color = route.Color.ToAndroid().ToArgb();
}
else if (e.PropertyName == nameof(TKPolyline.LineWidth))
{
_routes[route].Width = route.LineWidth;
}
}
/// <summary>
/// When the polygon collection changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnPolygonsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKPolygon poly in e.NewItems)
{
AddPolygon(poly);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TKPolygon poly in e.OldItems)
{
if (!FormsMap.Polygons.Contains(poly))
{
_polygons[poly].Remove();
poly.PropertyChanged -= OnPolygonPropertyChanged;
_polygons.Remove(poly);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
UpdatePolygons(false);
}
}
/// <summary>
/// Adds a polygon to the map
/// </summary>
/// <param name="polygon">The polygon to add</param>
void AddPolygon(TKPolygon polygon)
{
polygon.PropertyChanged += OnPolygonPropertyChanged;
var polygonOptions = new PolygonOptions();
if (polygon.Coordinates != null && polygon.Coordinates.Any())
{
polygonOptions.Add(polygon.Coordinates.Select(i => i.ToLatLng()).ToArray());
}
if (polygon.Color != Color.Default)
{
polygonOptions.InvokeFillColor(polygon.Color.ToAndroid().ToArgb());
}
if (polygon.StrokeColor != Color.Default)
{
polygonOptions.InvokeStrokeColor(polygon.StrokeColor.ToAndroid().ToArgb());
}
polygonOptions.InvokeStrokeWidth(polygon.StrokeWidth);
_polygons.Add(polygon, _googleMap.AddPolygon(polygonOptions));
}
/// <summary>
/// When a property of a <see cref="TKPolygon"/> changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void OnPolygonPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var tkPolygon = (TKPolygon)sender;
switch (e.PropertyName)
{
case nameof(TKPolygon.Coordinates):
_polygons[tkPolygon].Points = tkPolygon.Coordinates.Select(i => i.ToLatLng()).ToList();
break;
case nameof(TKPolygon.Color):
_polygons[tkPolygon].FillColor = tkPolygon.Color.ToAndroid().ToArgb();
break;
case nameof(TKPolygon.StrokeColor):
_polygons[tkPolygon].StrokeColor = tkPolygon.StrokeColor.ToAndroid().ToArgb();
break;
case nameof(TKPolygon.StrokeWidth):
_polygons[tkPolygon].StrokeWidth = tkPolygon.StrokeWidth;
break;
}
}
/// <summary>
/// When the circle collection changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void CirclesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TKCircle circle in e.NewItems)
{
AddCircle(circle);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TKCircle circle in e.OldItems)
{
if (!FormsMap.Circles.Contains(circle))
{
circle.PropertyChanged -= CirclePropertyChanged;
_circles[circle].Remove();
_circles.Remove(circle);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
UpdateCircles(false);
}
}
/// <summary>
/// Adds a circle to the map
/// </summary>
/// <param name="circle">The circle to add</param>
void AddCircle(TKCircle circle)
{
circle.PropertyChanged += CirclePropertyChanged;
var circleOptions = new CircleOptions();
circleOptions.InvokeRadius(circle.Radius);
circleOptions.InvokeCenter(circle.Center.ToLatLng());
if (circle.Color != Color.Default)
{
circleOptions.InvokeFillColor(circle.Color.ToAndroid().ToArgb());
}
if (circle.StrokeColor != Color.Default)
{
circleOptions.InvokeStrokeColor(circle.StrokeColor.ToAndroid().ToArgb());
}
circleOptions.InvokeStrokeWidth(circle.StrokeWidth);
_circles.Add(circle, _googleMap.AddCircle(circleOptions));
}
/// <summary>
/// When a property of a <see cref="TKCircle"/> changed
/// </summary>
/// <param name="sender">Event Sender</param>
/// <param name="e">Event Arguments</param>
void CirclePropertyChanged(object sender, PropertyChangedEventArgs e)
{
var tkCircle = (TKCircle)sender;
var circle = _circles[tkCircle];
switch (e.PropertyName)
{
case nameof(TKCircle.Radius):
circle.Radius = tkCircle.Radius;
break;
case nameof(TKCircle.Center):
circle.Center = tkCircle.Center.ToLatLng();
break;
case nameof(TKCircle.Color):
circle.FillColor = tkCircle.Color.ToAndroid().ToArgb();
break;
case nameof(TKCircle.StrokeColor):
circle.StrokeColor = tkCircle.StrokeColor.ToAndroid().ToArgb();
break;
}
}
/// <summary>
/// Adds a route to the map
/// </summary>
/// <param name="line">The route to add</param>
void AddLine(TKPolyline line)
{
line.PropertyChanged += OnLinePropertyChanged;
var polylineOptions = new PolylineOptions();
if (line.Color != Color.Default)
{
polylineOptions.InvokeColor(line.Color.ToAndroid().ToArgb());
}
if (line.LineWidth > 0)
{
polylineOptions.InvokeWidth(line.LineWidth);
}
if (line.LineCoordinates != null)
{
polylineOptions.Add(line.LineCoordinates.Select(i => i.ToLatLng()).ToArray());
}
_polylines.Add(line, _googleMap.AddPolyline(polylineOptions));
}
/// <summary>
/// Calculates and adds the route to the map
/// </summary>
/// <param name="route">The route to add</param>
async void AddRoute(TKRoute route)
{
if (route == null) return;
_tempRouteList.Add(route);
route.PropertyChanged += OnRoutePropertyChanged;
GmsDirectionResult routeData = null;
string errorMessage = null;
routeData = await GmsDirection.Instance.CalculateRoute(route.Source, route.Destination, route.TravelMode.ToGmsTravelMode());
if (FormsMap == null || Map == null || !_tempRouteList.Contains(route)) return;
if (routeData != null && routeData.Routes != null)
{
if (routeData.Status == GmsDirectionResultStatus.Ok)
{
var r = routeData.Routes.FirstOrDefault();
if (r != null && r.Polyline.Positions != null && r.Polyline.Positions.Any())
{
SetRouteData(route, r);
var routeOptions = new PolylineOptions();
if (route.Color != Color.Default)
{
routeOptions.InvokeColor(route.Color.ToAndroid().ToArgb());
}
if (route.LineWidth > 0)
{
routeOptions.InvokeWidth(route.LineWidth);
}
routeOptions.Add(r.Polyline.Positions.Select(i => i.ToLatLng()).ToArray());
_routes.Add(route, _googleMap.AddPolyline(routeOptions));
MapFunctions.RaiseRouteCalculationFinished(route);
}
else
{
errorMessage = "Unexpected result";
}
}
else
{
errorMessage = routeData.Status.ToString();
}
}
else
{
errorMessage = "Could not connect to api";
}
if (!string.IsNullOrEmpty(errorMessage))
{
var routeCalculationError = new TKRouteCalculationError(route, errorMessage);
MapFunctions.RaiseRouteCalculationFailed(routeCalculationError);
}
}
/// <summary>
/// Sets the route calculation data
/// </summary>
/// <param name="route">The PCL route</param>
/// <param name="routeResult">The rourte api result</param>
void SetRouteData(TKRoute route, GmsRouteResult routeResult)
{
var latLngBounds = new LatLngBounds(
new LatLng(routeResult.Bounds.SouthWest.Latitude, routeResult.Bounds.SouthWest.Longitude),
new LatLng(routeResult.Bounds.NorthEast.Latitude, routeResult.Bounds.NorthEast.Longitude));
var apiSteps = routeResult.Legs.First().Steps;
var steps = new TKRouteStep[apiSteps.Count()];
var routeFunctions = (IRouteFunctions)route;
for (int i = 0; i < steps.Length; i++)
{
steps[i] = new TKRouteStep();
var stepFunctions = (IRouteStepFunctions)steps[i];
var apiStep = apiSteps.ElementAt(i);
stepFunctions.SetDistance(apiStep.Distance.Value);
stepFunctions.SetInstructions(apiStep.HtmlInstructions);
}
routeFunctions.SetSteps(steps);
routeFunctions.SetDistance(routeResult.Legs.First().Distance.Value);
routeFunctions.SetTravelTime(routeResult.Legs.First().Duration.Value);
routeFunctions.SetBounds(
MapSpan.FromCenterAndRadius(
latLngBounds.Center.ToPosition(),
Distance.FromKilometers(
new Position(latLngBounds.Southwest.Latitude, latLngBounds.Southwest.Longitude)
.DistanceTo(
new Position(latLngBounds.Northeast.Latitude, latLngBounds.Northeast.Longitude)) / 2)));
routeFunctions.SetIsCalculated(true);
}
/// <summary>
/// Updates the image of a pin
/// </summary>
/// <param name="pin">The forms pin</param>
/// <param name="markerOptions">The native marker options</param>
async Task UpdateImage(TKCustomMapPin pin, MarkerOptions markerOptions)
{
BitmapDescriptor bitmap;
try
{
if (pin.Image != null)
{
bitmap = BitmapDescriptorFactory.FromBitmap(await pin.Image.ToBitmap(Context));
}
else
{
if (pin.DefaultPinColor != Color.Default)
{
var hue = pin.DefaultPinColor.ToAndroid().GetHue();
bitmap = BitmapDescriptorFactory.DefaultMarker(Math.Min(hue, 359.99f));
}
else
{
bitmap = BitmapDescriptorFactory.DefaultMarker();
}
}
}
catch (Exception)
{
bitmap = BitmapDescriptorFactory.DefaultMarker();
}
markerOptions.SetIcon(bitmap);
}
/// <summary>
/// Updates the image on a marker
/// </summary>
/// <param name="pin">The forms pin</param>
/// <param name="marker">The native marker</param>
async Task UpdateImage(TKCustomMapPin pin, Marker marker)
{
BitmapDescriptor bitmap;
try
{
if (pin.Image != null)
{
bitmap = BitmapDescriptorFactory.FromBitmap(await pin.Image.ToBitmap(Context));
}
else
{
if (pin.DefaultPinColor != Color.Default)
{
var hue = pin.DefaultPinColor.ToAndroid().GetHue();
bitmap = BitmapDescriptorFactory.DefaultMarker(hue);
}
else
{
bitmap = BitmapDescriptorFactory.DefaultMarker();
}
}
}
catch (Exception)
{
bitmap = BitmapDescriptorFactory.DefaultMarker();
}
marker.SetIcon(bitmap);
}
/// <summary>
/// Updates the custom tile provider
/// </summary>
void UpdateTileOptions()
{
if (_tileOverlay != null)
{
_tileOverlay.Remove();
_googleMap.MapType = GoogleMap.MapTypeNormal;
}
if (FormsMap == null || _googleMap == null) return;
if (FormsMap.TilesUrlOptions != null)
{
_googleMap.MapType = GoogleMap.MapTypeNone;
_tileOverlay = _googleMap.AddTileOverlay(
new TileOverlayOptions()
.InvokeTileProvider(
new TKCustomTileProvider(FormsMap.TilesUrlOptions))
.InvokeZIndex(-1));
}
}
/// <summary>
/// Updates the visible map region
/// </summary>
void UpdateMapRegion()
{
if (FormsMap == null || _googleMap == null || !_isLayoutPerformed || FormsMap.MapRegion==null || !FormsMap.IsVisible) return;
if (!FormsMap.MapRegion.Equals(GetCurrentMapRegion(_googleMap.CameraPosition.Target)))
{
MoveToMapRegion(FormsMap.MapRegion, FormsMap.IsRegionChangeAnimated);
}
}
/// <summary>
/// Sets traffic enabled on the google map
/// </summary>
void UpdateShowTraffic()
{
if (FormsMap == null || _googleMap == null) return;
_googleMap.TrafficEnabled = FormsMap.ShowTraffic;
}
/// <summary>
/// Updates clustering
/// </summary>
void UpdateIsClusteringEnabled()
{
if (FormsMap == null || _googleMap == null) return;
if (FormsMap.IsClusteringEnabled)
{
if (_clusterManager == null)
{
_clusterManager = new ClusterManager(Context, _googleMap);
_clusterManager.Renderer = new TKMarkerRenderer(Context, _googleMap, _clusterManager, this);
}
foreach (var marker in _markers.ToList())
{
RemovePin(marker.Key);
AddPin(marker.Key);
}
_clusterManager.Cluster();
}
else
{
foreach (var marker in _markers.ToList())
{
RemovePin(marker.Key);
AddPin(marker.Key);
}
_clusterManager.Cluster();
_clusterManager.Dispose();
_clusterManager = null;
}
}
/// <summary>
/// Updates the map type
/// </summary>
void UpdateMapType()
{
if (FormsMap == null || _googleMap == null) return;
switch(FormsMap.MapType)
{
case MapType.Hybrid:
Map.MapType = GoogleMap.MapTypeHybrid;
break;
case MapType.Satellite:
Map.MapType = GoogleMap.MapTypeSatellite;
break;
case MapType.Street:
Map.MapType = GoogleMap.MapTypeNormal;
break;
}
}
/// <summary>
/// Updates if the user location and user location button are displayed
/// </summary>
void UpdateIsShowingUser()
{
if (FormsMap == null || _googleMap == null) return;
Map.MyLocationEnabled = Map.UiSettings.MyLocationButtonEnabled = FormsMap.IsShowingUser;
}
/// <summary>
/// Updates scroll gesture
/// </summary>
void UpdateHasScrollEnabled()
{
if (FormsMap == null || _googleMap == null) return;
Map.UiSettings.ScrollGesturesEnabled = FormsMap.HasScrollEnabled;
}
/// <summary>
/// Updates zoom gesture/control
/// </summary>
void UpdateHasZoomEnabled()
{
if (FormsMap == null || _googleMap == null) return;
Map.UiSettings.ZoomGesturesEnabled = Map.UiSettings.ZoomControlsEnabled = FormsMap.HasZoomEnabled;
}
/// <summary>
/// Creates a <see cref="LatLngBounds"/> from a collection of <see cref="MapSpan"/>
/// </summary>
/// <param name="spans">The spans to get calculate the bounds from</param>
/// <returns>The bounds</returns>
LatLngBounds BoundsFromMapSpans(params MapSpan[] spans)
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
foreach (var region in spans)
{
builder
.Include(GmsSphericalUtil.ComputeOffset(region.Center, region.Radius.Meters, 0).ToLatLng())
.Include(GmsSphericalUtil.ComputeOffset(region.Center, region.Radius.Meters, 90).ToLatLng())
.Include(GmsSphericalUtil.ComputeOffset(region.Center, region.Radius.Meters, 180).ToLatLng())
.Include(GmsSphericalUtil.ComputeOffset(region.Center, region.Radius.Meters, 270).ToLatLng());
}
return builder.Build();
}
/// <summary>
/// Unregisters all collections
/// </summary>
void UnregisterCollections(TKCustomMap map)
{
UnregisterCollection(map.Pins, OnCustomPinsCollectionChanged, OnPinPropertyChanged);
UnregisterCollection(map.Routes, OnRouteCollectionChanged, OnRoutePropertyChanged);
UnregisterCollection(map.Polylines, OnLineCollectionChanged, OnLinePropertyChanged);
UnregisterCollection(map.Circles, CirclesCollectionChanged, CirclePropertyChanged);
UnregisterCollection(map.Polygons, OnPolygonsCollectionChanged, OnPolygonPropertyChanged);
}
/// <summary>
/// Unregisters one collection and all of its items
/// </summary>
/// <param name="collection">The collection to unregister</param>
/// <param name="observableHandler">The <see cref="NotifyCollectionChangedEventHandler"/> of the collection</param>
/// <param name="propertyHandler">The <see cref="PropertyChangedEventHandler"/> of the collection items</param>
void UnregisterCollection(
IEnumerable collection,
NotifyCollectionChangedEventHandler observableHandler,
PropertyChangedEventHandler propertyHandler)
{
if (collection == null) return;
var observable = collection as INotifyCollectionChanged;
if (observable != null)
{
observable.CollectionChanged -= observableHandler;
}
foreach (INotifyPropertyChanged obj in collection)
{
obj.PropertyChanged -= propertyHandler;
}
}
/// <summary>
/// Gets the current mapregion
/// </summary>
/// <param name="center">Center point</param>
/// <returns>The map region</returns>
MapSpan GetCurrentMapRegion(LatLng center)
{
var map = _googleMap;
if (map == null)
return null;
var projection = map.Projection;
var width = Control.Width;
var height = Control.Height;
var ul = projection.FromScreenLocation(new global::Android.Graphics.Point(0, 0));
var ur = projection.FromScreenLocation(new global::Android.Graphics.Point(width, 0));
var ll = projection.FromScreenLocation(new global::Android.Graphics.Point(0, height));
var lr = projection.FromScreenLocation(new global::Android.Graphics.Point(width, height));
var dlat = Math.Max(Math.Abs(ul.Latitude - lr.Latitude), Math.Abs(ur.Latitude - ll.Latitude));
var dlong = Math.Max(Math.Abs(ul.Longitude - lr.Longitude), Math.Abs(ur.Longitude - ll.Longitude));
return new MapSpan(new Position(center.Latitude, center.Longitude), dlat, dlong);
}
/// <inheritdoc/>
public async Task<byte[]> GetSnapshot()
{
if (_googleMap == null) return null;
_snapShot = null;
_googleMap.Snapshot(this);
while (_snapShot == null) await Task.Delay(10);
return _snapShot;
}
///<inheritdoc/>
public void OnSnapshotReady(Bitmap snapshot)
{
using (var strm = new MemoryStream())
{
snapshot.Compress(Bitmap.CompressFormat.Png, 100, strm);
_snapShot = strm.ToArray();
}
}
///<inheritdoc/>
public void FitMapRegionToPositions(IEnumerable<Position> positions, bool animate = false, int padding = 0)
{
if (_googleMap == null) throw new InvalidOperationException("Map not ready");
if (positions == null) throw new InvalidOperationException("positions can't be null");
LatLngBounds.Builder builder = new LatLngBounds.Builder();
positions.ToList().ForEach(i => builder.Include(i.ToLatLng()));
if (animate)
_googleMap.AnimateCamera(CameraUpdateFactory.NewLatLngBounds(builder.Build(), padding));
else
_googleMap.MoveCamera(CameraUpdateFactory.NewLatLngBounds(builder.Build(), padding));
}
///<inheritdoc/>
public void MoveToMapRegion(MapSpan region, bool animate)
{
if (_googleMap == null) return;
if (region == null) return;
var bounds = BoundsFromMapSpans(region);
if (bounds == null) return;
var cam = CameraUpdateFactory.NewLatLngBounds(bounds, 0);
if (animate && _isInitialized)
_googleMap.AnimateCamera(cam);
else
_googleMap.MoveCamera(cam);
}
///<inheritdoc/>
public void FitToMapRegions(IEnumerable<MapSpan> regions, bool animate = false, int padding = 0)
{
if (_googleMap == null || regions == null || !regions.Any()) return;
var bounds = BoundsFromMapSpans(regions.ToArray());
if (bounds == null) return;
var cam = CameraUpdateFactory.NewLatLngBounds(bounds, padding);
if (animate)
_googleMap.AnimateCamera(cam);
else
_googleMap.MoveCamera(cam);
}
///<inheritdoc/>
public IEnumerable<Position> ScreenLocationsToGeocoordinates(params Xamarin.Forms.Point[] screenLocations)
{
if (_googleMap == null)
throw new InvalidOperationException("Map not initialized");
return screenLocations.Select(i => _googleMap.Projection.FromScreenLocation(i.ToAndroidPoint()).ToPosition());
}
/// <summary>
/// Gets the <see cref="TKCustomMapPin"/> by the native <see cref="Marker"/>
/// </summary>
/// <param name="marker">The marker to search the pin for</param>
/// <returns>The forms pin</returns>
protected TKCustomMapPin GetPinByMarker(Marker marker)
{
return _markers.SingleOrDefault(i => i.Value.Marker?.Id == marker.Id).Key;
}
public void OnCameraIdle()
{
if (FormsMap == null) return;
FormsMap.MapRegion = GetCurrentMapRegion(Map.CameraPosition.Target);
if (FormsMap.IsClusteringEnabled)
{
_clusterManager.OnCameraIdle();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Statistics;
using OpenSim.Grid.Communications.OGS1;
using OpenSim.Grid.Framework;
using OpenSim.Grid.UserServer.Modules;
using Nini.Config;
namespace OpenSim.Grid.UserServer
{
/// <summary>
/// Grid user server main class
/// </summary>
public class OpenUser_Main : BaseOpenSimServer, IGridServiceCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected UserConfig Cfg;
protected UserDataBaseService m_userDataBaseService;
public UserManager m_userManager;
protected UserServerAvatarAppearanceModule m_avatarAppearanceModule;
protected UserServerFriendsModule m_friendsModule;
public UserLoginService m_loginService;
public UserLoginAuthService m_loginAuthService;
public MessageServersConnector m_messagesService;
protected GridInfoServiceModule m_gridInfoService;
protected UserServerCommandModule m_consoleCommandModule;
protected UserServerEventDispatchModule m_eventDispatcher;
protected AvatarCreationModule m_appearanceModule;
protected static string m_consoleType = "local";
protected static IConfigSource m_config = null;
protected static string m_configFile = "UserServer_Config.xml";
public static void Main(string[] args)
{
ArgvConfigSource argvSource = new ArgvConfigSource(args);
argvSource.AddSwitch("Startup", "console", "c");
argvSource.AddSwitch("Startup", "xmlfile", "x");
IConfig startupConfig = argvSource.Configs["Startup"];
if (startupConfig != null)
{
m_consoleType = startupConfig.GetString("console", "local");
m_configFile = startupConfig.GetString("xmlfile", "UserServer_Config.xml");
}
m_config = argvSource;
XmlConfigurator.Configure();
m_log.Info("Launching UserServer...");
OpenUser_Main userserver = new OpenUser_Main();
userserver.Startup();
userserver.Work();
}
public OpenUser_Main()
{
switch (m_consoleType)
{
case "rest":
m_console = new RemoteConsole("User");
break;
case "basic":
m_console = new CommandConsole("User");
break;
default:
m_console = new LocalConsole("User");
break;
}
MainConsole.Instance = m_console;
}
public void Work()
{
m_console.Output("Enter help for a list of commands\n");
while (true)
{
m_console.Prompt();
}
}
protected override void StartupSpecific()
{
IInterServiceInventoryServices inventoryService = StartupCoreComponents();
m_stats = StatsManager.StartCollectingUserStats();
//setup services/modules
StartupUserServerModules();
StartOtherComponents(inventoryService);
//PostInitialise the modules
PostInitialiseModules();
//register http handlers and start http server
m_log.Info("[STARTUP]: Starting HTTP process");
RegisterHttpHandlers();
m_httpServer.Start();
base.StartupSpecific();
}
protected virtual IInterServiceInventoryServices StartupCoreComponents()
{
Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), m_configFile)));
m_httpServer = new BaseHttpServer(Cfg.HttpPort);
if (m_console is RemoteConsole)
{
RemoteConsole c = (RemoteConsole)m_console;
c.SetServer(m_httpServer);
IConfig netConfig = m_config.AddConfig("Network");
netConfig.Set("ConsoleUser", Cfg.ConsoleUser);
netConfig.Set("ConsolePass", Cfg.ConsolePass);
c.ReadConfig(m_config);
}
RegisterInterface<CommandConsole>(m_console);
RegisterInterface<UserConfig>(Cfg);
//Should be in modules?
IInterServiceInventoryServices inventoryService = new OGS1InterServiceInventoryService(Cfg.InventoryUrl);
// IRegionProfileRouter regionProfileService = new RegionProfileServiceProxy();
RegisterInterface<IInterServiceInventoryServices>(inventoryService);
// RegisterInterface<IRegionProfileRouter>(regionProfileService);
return inventoryService;
}
/// <summary>
/// Start up the user manager
/// </summary>
/// <param name="inventoryService"></param>
protected virtual void StartupUserServerModules()
{
m_log.Info("[STARTUP]: Establishing data connection");
//we only need core components so we can request them from here
IInterServiceInventoryServices inventoryService;
TryGet<IInterServiceInventoryServices>(out inventoryService);
CommunicationsManager commsManager = new UserServerCommsManager(inventoryService);
//setup database access service, for now this has to be created before the other modules.
m_userDataBaseService = new UserDataBaseService(commsManager);
m_userDataBaseService.Initialise(this);
//TODO: change these modules so they fetch the databaseService class in the PostInitialise method
m_userManager = new UserManager(m_userDataBaseService);
m_userManager.Initialise(this);
m_avatarAppearanceModule = new UserServerAvatarAppearanceModule(m_userDataBaseService);
m_avatarAppearanceModule.Initialise(this);
m_friendsModule = new UserServerFriendsModule(m_userDataBaseService);
m_friendsModule.Initialise(this);
m_consoleCommandModule = new UserServerCommandModule();
m_consoleCommandModule.Initialise(this);
m_messagesService = new MessageServersConnector();
m_messagesService.Initialise(this);
m_gridInfoService = new GridInfoServiceModule();
m_gridInfoService.Initialise(this);
}
protected virtual void StartOtherComponents(IInterServiceInventoryServices inventoryService)
{
m_appearanceModule = new AvatarCreationModule(m_userDataBaseService, Cfg, inventoryService);
m_appearanceModule.Initialise(this);
StartupLoginService(inventoryService);
//
// Get the minimum defaultLevel to access to the grid
//
m_loginService.setloginlevel((int)Cfg.DefaultUserLevel);
RegisterInterface<UserLoginService>(m_loginService); //TODO: should be done in the login service
m_eventDispatcher = new UserServerEventDispatchModule(m_userManager, m_messagesService, m_loginService);
m_eventDispatcher.Initialise(this);
}
/// <summary>
/// Start up the login service
/// </summary>
/// <param name="inventoryService"></param>
protected virtual void StartupLoginService(IInterServiceInventoryServices inventoryService)
{
m_loginService = new UserLoginService(
m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile), Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy());
if (Cfg.EnableHGLogin)
m_loginAuthService = new UserLoginAuthService(m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile),
Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy());
}
protected virtual void PostInitialiseModules()
{
m_consoleCommandModule.PostInitialise(); //it will register its Console command handlers in here
m_userDataBaseService.PostInitialise();
m_messagesService.PostInitialise();
m_eventDispatcher.PostInitialise(); //it will register event handlers in here
m_gridInfoService.PostInitialise();
m_userManager.PostInitialise();
m_avatarAppearanceModule.PostInitialise();
m_friendsModule.PostInitialise();
m_avatarAppearanceModule.PostInitialise();
}
protected virtual void RegisterHttpHandlers()
{
m_loginService.RegisterHandlers(m_httpServer, Cfg.EnableLLSDLogin, true);
if (m_loginAuthService != null)
m_loginAuthService.RegisterHandlers(m_httpServer);
m_userManager.RegisterHandlers(m_httpServer);
m_friendsModule.RegisterHandlers(m_httpServer);
m_avatarAppearanceModule.RegisterHandlers(m_httpServer);
m_messagesService.RegisterHandlers(m_httpServer);
m_gridInfoService.RegisterHandlers(m_httpServer);
m_avatarAppearanceModule.RegisterHandlers(m_httpServer);
}
public override void ShutdownSpecific()
{
m_eventDispatcher.Close();
}
#region IUGAIMCore
protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>();
/// <summary>
/// Register an Module interface.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iface"></param>
public void RegisterInterface<T>(T iface)
{
lock (m_moduleInterfaces)
{
if (!m_moduleInterfaces.ContainsKey(typeof(T)))
{
m_moduleInterfaces.Add(typeof(T), iface);
}
}
}
public bool TryGet<T>(out T iface)
{
if (m_moduleInterfaces.ContainsKey(typeof(T)))
{
iface = (T)m_moduleInterfaces[typeof(T)];
return true;
}
iface = default(T);
return false;
}
public T Get<T>()
{
return (T)m_moduleInterfaces[typeof(T)];
}
public BaseHttpServer GetHttpServer()
{
return m_httpServer;
}
#endregion
public void TestResponse(List<InventoryFolderBase> resp)
{
m_console.Output("response got");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using LightBDD.Core.Formatting;
using LightBDD.Core.Results;
using LightBDD.Core.Results.Parameters;
using LightBDD.Core.Results.Parameters.Tabular;
namespace LightBDD.Framework.Reporting.Formatters
{
/// <summary>
/// Formats feature results as plain text.
/// </summary>
public class PlainTextReportFormatter : IReportFormatter
{
#region IReportFormatter Members
/// <summary>
/// Formats provided feature results and writes to the <paramref name="stream"/>.
/// </summary>
/// <param name="stream">Stream to write formatted results to.</param>
/// <param name="features">Feature results to format.</param>
public void Format(Stream stream, params IFeatureResult[] features)
{
using (var writer = new StreamWriter(stream))
{
FormatSummary(writer, features);
foreach (var feature in features)
FormatFeature(writer, feature);
}
}
#endregion
private static void FormatDetails(TextWriter writer, IScenarioResult scenario)
{
if (string.IsNullOrWhiteSpace(scenario.StatusDetails))
return;
writer.WriteLine("\t\tDetails:");
writer.Write("\t\t\t");
writer.Write(scenario.StatusDetails.Trim().Replace(Environment.NewLine, Environment.NewLine + "\t\t\t"));
writer.WriteLine();
}
private static void FormatFeature(TextWriter writer, IFeatureResult feature)
{
writer.WriteLine();
writer.Write("Feature: ");
writer.Write(feature.Info.Name);
FormatLabels(writer, feature.Info.Labels);
writer.WriteLine();
if (!string.IsNullOrWhiteSpace(feature.Info.Description))
{
writer.Write("\t");
writer.Write(feature.Info.Description.Replace(Environment.NewLine, Environment.NewLine + "\t"));
writer.WriteLine();
}
foreach (var scenario in feature.GetScenariosOrderedByName())
FormatScenario(writer, scenario);
}
private static void FormatLabels(TextWriter writer, IEnumerable<string> labels)
{
var first = true;
foreach (var label in labels)
{
if (first)
{
writer.Write(' ');
first = false;
}
writer.Write("[");
writer.Write(label);
writer.Write("]");
}
}
private static void FormatScenario(TextWriter writer, IScenarioResult scenario)
{
writer.WriteLine();
writer.Write("\tScenario: ");
writer.Write(scenario.Info.Name);
FormatLabels(writer, scenario.Info.Labels);
writer.Write(" - ");
writer.Write(scenario.Status);
if (scenario.ExecutionTime != null)
{
writer.Write(" (");
writer.Write(scenario.ExecutionTime.Duration.FormatPretty());
writer.Write(")");
}
writer.WriteLine();
if (scenario.Info.Categories.Any())
{
writer.Write("\t\tCategories: ");
writer.WriteLine(string.Join(", ", scenario.Info.Categories));
}
var commentBuilder = new StringBuilder();
foreach (var step in scenario.GetSteps())
FormatStep(writer, step, commentBuilder);
FormatDetails(writer, scenario);
FormatComments(writer, commentBuilder);
}
private static void CollectComments(IStepResult step, StringBuilder commentBuilder)
{
foreach (var comment in step.Comments)
{
commentBuilder.Append("\t\t\tStep ").Append(step.Info.GroupPrefix).Append(step.Info.Number)
.Append(": ")
.AppendLine(comment.Replace(Environment.NewLine, Environment.NewLine + "\t\t\t\t"));
}
}
private static void FormatComments(TextWriter writer, StringBuilder commentBuilder)
{
if (commentBuilder.Length == 0)
return;
writer.WriteLine("\t\tComments:");
writer.Write(commentBuilder);
}
private static void FormatStep(TextWriter writer, IStepResult step, StringBuilder commentBuilder, int indent = 0)
{
var stepIndent = new string('\t', indent + 2);
writer.Write(stepIndent);
writer.Write("Step ");
writer.Write(step.Info.GroupPrefix);
writer.Write(step.Info.Number);
writer.Write(": ");
writer.Write(step.Info.Name);
writer.Write(" - ");
writer.Write(step.Status);
if (step.ExecutionTime != null)
{
writer.Write(" (");
writer.Write(step.ExecutionTime.Duration.FormatPretty());
writer.Write(")");
}
writer.WriteLine();
foreach (var parameterResult in step.Parameters)
FormatParameter(writer, parameterResult, stepIndent);
CollectComments(step, commentBuilder);
foreach (var subStep in step.GetSubSteps())
FormatStep(writer, subStep, commentBuilder, indent + 1);
}
private static void FormatParameter(TextWriter writer, IParameterResult parameterResult, string stepIndent)
{
if (parameterResult.Details is ITabularParameterDetails table)
{
writer.Write(stepIndent);
writer.Write(parameterResult.Name);
writer.WriteLine(":");
new TextTableRenderer(table).Render(writer, stepIndent);
writer.WriteLine();
}
}
private static void FormatSummary(TextWriter writer, IFeatureResult[] features)
{
var timeSummary = features.GetTestExecutionTimeSummary();
writer.WriteLine("Summary:");
var summary = new Dictionary<string, object>
{
{"Test execution start time", timeSummary.Start.ToString("yyyy-MM-dd HH:mm:ss UTC")},
{"Test execution end time", timeSummary.End.ToString("yyyy-MM-dd HH:mm:ss UTC")},
{"Test execution time", timeSummary.Duration.FormatPretty()},
{"Test execution time (aggregated)", timeSummary.Aggregated.FormatPretty()},
{"Number of features", features.Length},
{"Number of scenarios", features.CountScenarios()},
{"Passed scenarios", features.CountScenariosWithStatus(ExecutionStatus.Passed)},
{"Bypassed scenarios", features.CountScenariosWithStatus(ExecutionStatus.Bypassed)},
{"Failed scenarios", features.CountScenariosWithStatus(ExecutionStatus.Failed)},
{"Ignored scenarios", features.CountScenariosWithStatus(ExecutionStatus.Ignored)},
{"Number of steps", features.CountSteps()},
{"Passed steps", features.CountStepsWithStatus(ExecutionStatus.Passed)},
{"Bypassed steps", features.CountStepsWithStatus(ExecutionStatus.Bypassed)},
{"Failed steps", features.CountStepsWithStatus(ExecutionStatus.Failed)},
{"Ignored steps", features.CountStepsWithStatus(ExecutionStatus.Ignored)},
{"Not Run steps", features.CountStepsWithStatus(ExecutionStatus.NotRun)}
};
var maxLength = summary.Keys.Max(k => k.Length);
var format = string.Format("\t{{0,-{0}}}: {{1}}", maxLength);
foreach (var row in summary)
{
writer.Write(format, row.Key, row.Value);
writer.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
#pragma warning disable CS0618 // Type or member is obsolete
public class ComplexTypeModelBinderTest
{
private static readonly IModelMetadataProvider _metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
[Theory]
[InlineData(true, ComplexTypeModelBinder.ValueProviderDataAvailable)]
[InlineData(false, ComplexTypeModelBinder.NoDataAvailable)]
public void CanCreateModel_ReturnsTrue_IfIsTopLevelObject(bool isTopLevelObject, int expectedCanCreate)
{
var bindingContext = CreateContext(GetMetadataForType(typeof(Person)));
bindingContext.IsTopLevelObject = isTopLevelObject;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}
[Fact]
public void CanCreateModel_ReturnsFalse_IfNotIsTopLevelObjectAndModelIsMarkedWithBinderMetadata()
{
var modelMetadata = GetMetadataForProperty(typeof(Document), nameof(Document.SubDocument));
var bindingContext = CreateContext(modelMetadata);
bindingContext.IsTopLevelObject = false;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(ComplexTypeModelBinder.NoDataAvailable, canCreate);
}
[Fact]
public void CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndModelIsMarkedWithBinderMetadata()
{
var bindingContext = CreateContext(GetMetadataForType(typeof(Document)));
bindingContext.IsTopLevelObject = true;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(ComplexTypeModelBinder.ValueProviderDataAvailable, canCreate);
}
[Theory]
[InlineData(ComplexTypeModelBinder.ValueProviderDataAvailable)]
[InlineData(ComplexTypeModelBinder.GreedyPropertiesMayHaveData)]
public void CanCreateModel_CreatesModel_WithAllGreedyProperties(int expectedCanCreate)
{
var bindingContext = CreateContext(GetMetadataForType(typeof(HasAllGreedyProperties)));
bindingContext.IsTopLevelObject = expectedCanCreate == ComplexTypeModelBinder.ValueProviderDataAvailable;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}
[Theory]
[InlineData(ComplexTypeModelBinder.ValueProviderDataAvailable)]
[InlineData(ComplexTypeModelBinder.NoDataAvailable)]
public void CanCreateModel_ReturnsTrue_IfNotIsTopLevelObject_BasedOnValueAvailability(int valueAvailable)
{
// Arrange
var valueProvider = new Mock<IValueProvider>(MockBehavior.Strict);
valueProvider
.Setup(provider => provider.ContainsPrefix("SimpleContainer.Simple.Name"))
.Returns(valueAvailable == ComplexTypeModelBinder.ValueProviderDataAvailable);
var modelMetadata = GetMetadataForProperty(typeof(SimpleContainer), nameof(SimpleContainer.Simple));
var bindingContext = CreateContext(modelMetadata);
bindingContext.IsTopLevelObject = false;
bindingContext.ModelName = "SimpleContainer.Simple";
bindingContext.ValueProvider = valueProvider.Object;
bindingContext.OriginalValueProvider = valueProvider.Object;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
// Result matches whether first Simple property can bind.
Assert.Equal(valueAvailable, canCreate);
}
[Fact]
public void CanCreateModel_ReturnsFalse_IfNotIsTopLevelObjectAndModelHasNoProperties()
{
// Arrange
var bindingContext = CreateContext(GetMetadataForType(typeof(PersonWithNoProperties)));
bindingContext.IsTopLevelObject = false;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(ComplexTypeModelBinder.NoDataAvailable, canCreate);
}
[Fact]
public void CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndModelHasNoProperties()
{
// Arrange
var bindingContext = CreateContext(GetMetadataForType(typeof(PersonWithNoProperties)));
bindingContext.IsTopLevelObject = true;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(ComplexTypeModelBinder.ValueProviderDataAvailable, canCreate);
}
[Theory]
[InlineData(typeof(TypeWithNoBinderMetadata), ComplexTypeModelBinder.NoDataAvailable)]
[InlineData(typeof(TypeWithNoBinderMetadata), ComplexTypeModelBinder.ValueProviderDataAvailable)]
public void CanCreateModel_CreatesModelForValueProviderBasedBinderMetadatas_IfAValueProviderProvidesValue(
Type modelType,
int valueProviderProvidesValue)
{
var valueProvider = new Mock<IValueProvider>();
valueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(valueProviderProvidesValue == ComplexTypeModelBinder.ValueProviderDataAvailable);
var bindingContext = CreateContext(GetMetadataForType(modelType));
bindingContext.IsTopLevelObject = false;
bindingContext.ValueProvider = valueProvider.Object;
bindingContext.OriginalValueProvider = valueProvider.Object;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(valueProviderProvidesValue, canCreate);
}
[Theory]
[InlineData(typeof(TypeWithAtLeastOnePropertyMarkedUsingValueBinderMetadata), ComplexTypeModelBinder.GreedyPropertiesMayHaveData)]
[InlineData(typeof(TypeWithAtLeastOnePropertyMarkedUsingValueBinderMetadata), ComplexTypeModelBinder.ValueProviderDataAvailable)]
[InlineData(typeof(TypeWithUnmarkedAndBinderMetadataMarkedProperties), ComplexTypeModelBinder.GreedyPropertiesMayHaveData)]
[InlineData(typeof(TypeWithUnmarkedAndBinderMetadataMarkedProperties), ComplexTypeModelBinder.ValueProviderDataAvailable)]
public void CanCreateModel_CreatesModelForValueProviderBasedBinderMetadatas_IfPropertyHasGreedyBindingSource(
Type modelType,
int expectedCanCreate)
{
var valueProvider = new Mock<IValueProvider>();
valueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(expectedCanCreate == ComplexTypeModelBinder.ValueProviderDataAvailable);
var bindingContext = CreateContext(GetMetadataForType(modelType));
bindingContext.IsTopLevelObject = false;
bindingContext.ValueProvider = valueProvider.Object;
bindingContext.OriginalValueProvider = valueProvider.Object;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}
[Theory]
[InlineData(typeof(TypeWithAtLeastOnePropertyMarkedUsingValueBinderMetadata), ComplexTypeModelBinder.GreedyPropertiesMayHaveData)]
[InlineData(typeof(TypeWithAtLeastOnePropertyMarkedUsingValueBinderMetadata), ComplexTypeModelBinder.ValueProviderDataAvailable)]
public void CanCreateModel_ForExplicitValueProviderMetadata_UsesOriginalValueProvider(
Type modelType,
int expectedCanCreate)
{
var valueProvider = new Mock<IValueProvider>();
valueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(false);
var originalValueProvider = new Mock<IBindingSourceValueProvider>();
originalValueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(expectedCanCreate == ComplexTypeModelBinder.ValueProviderDataAvailable);
originalValueProvider
.Setup(o => o.Filter(It.IsAny<BindingSource>()))
.Returns<BindingSource>(source => source == BindingSource.Query ? originalValueProvider.Object : null);
var bindingContext = CreateContext(GetMetadataForType(modelType));
bindingContext.IsTopLevelObject = false;
bindingContext.ValueProvider = valueProvider.Object;
bindingContext.OriginalValueProvider = originalValueProvider.Object;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}
[Theory]
[InlineData(typeof(TypeWithUnmarkedAndBinderMetadataMarkedProperties), false, ComplexTypeModelBinder.GreedyPropertiesMayHaveData)]
[InlineData(typeof(TypeWithUnmarkedAndBinderMetadataMarkedProperties), true, ComplexTypeModelBinder.ValueProviderDataAvailable)]
[InlineData(typeof(TypeWithNoBinderMetadata), false, ComplexTypeModelBinder.NoDataAvailable)]
[InlineData(typeof(TypeWithNoBinderMetadata), true, ComplexTypeModelBinder.ValueProviderDataAvailable)]
public void CanCreateModel_UnmarkedProperties_UsesCurrentValueProvider(
Type modelType,
bool valueProviderProvidesValue,
int expectedCanCreate)
{
var valueProvider = new Mock<IValueProvider>();
valueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(valueProviderProvidesValue);
var originalValueProvider = new Mock<IValueProvider>();
originalValueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(false);
var bindingContext = CreateContext(GetMetadataForType(modelType));
bindingContext.IsTopLevelObject = false;
bindingContext.ValueProvider = valueProvider.Object;
bindingContext.OriginalValueProvider = originalValueProvider.Object;
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var canCreate = binder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}
private IActionResult ActionWithComplexParameter(Person parameter) => null;
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
public async Task BindModelAsync_CreatesModel_IfIsTopLevelObject(
bool allowValidatingTopLevelNodes,
bool isBindingRequired)
{
// Arrange
var expectedErrorCount = isBindingRequired ? 1 : 0;
var mockValueProvider = new Mock<IValueProvider>();
mockValueProvider
.Setup(o => o.ContainsPrefix(It.IsAny<string>()))
.Returns(false);
// Mock binder fails to bind all properties.
var mockBinder = new StubModelBinder();
var parameter = typeof(ComplexTypeModelBinderTest)
.GetMethod(nameof(ActionWithComplexParameter), BindingFlags.Instance | BindingFlags.NonPublic)
.GetParameters()[0];
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForParameter(parameter)
.BindingDetails(b => b.IsBindingRequired = isBindingRequired);
var metadata = metadataProvider.GetMetadataForParameter(parameter);
var bindingContext = new DefaultModelBindingContext
{
IsTopLevelObject = true,
ModelMetadata = metadata,
ModelName = string.Empty,
ValueProvider = mockValueProvider.Object,
ModelState = new ModelStateDictionary(),
};
var model = new Person();
var testableBinder = new Mock<TestableComplexTypeModelBinder>(allowValidatingTopLevelNodes)
{
CallBase = true
};
testableBinder
.Setup(o => o.CreateModelPublic(bindingContext))
.Returns(model)
.Verifiable();
testableBinder
.Setup(o => o.CanBindPropertyPublic(bindingContext, It.IsAny<ModelMetadata>()))
.Returns(false);
// Act
await testableBinder.Object.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.Equal(expectedErrorCount, bindingContext.ModelState.ErrorCount);
var returnedPerson = Assert.IsType<Person>(bindingContext.Result.Model);
Assert.Same(model, returnedPerson);
testableBinder.Verify();
}
[Fact]
public async Task BindModelAsync_CreatesModelAndAddsError_IfIsTopLevelObject_WithNoData()
{
// Arrange
var parameter = typeof(ComplexTypeModelBinderTest)
.GetMethod(nameof(ActionWithComplexParameter), BindingFlags.Instance | BindingFlags.NonPublic)
.GetParameters()[0];
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForParameter(parameter)
.BindingDetails(b => b.IsBindingRequired = true);
var metadata = metadataProvider.GetMetadataForParameter(parameter);
var bindingContext = new DefaultModelBindingContext
{
IsTopLevelObject = true,
FieldName = "fieldName",
ModelMetadata = metadata,
ModelName = string.Empty,
ValueProvider = new TestValueProvider(new Dictionary<string, object>()),
ModelState = new ModelStateDictionary(),
};
// Mock binder fails to bind all properties.
var innerBinder = new StubModelBinder();
var binders = new Dictionary<ModelMetadata, IModelBinder>();
foreach (var property in metadataProvider.GetMetadataForProperties(typeof(Person)))
{
binders.Add(property, innerBinder);
}
var binder = new ComplexTypeModelBinder(
binders,
NullLoggerFactory.Instance,
allowValidatingTopLevelNodes: true);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.IsType<Person>(bindingContext.Result.Model);
var keyValuePair = Assert.Single(bindingContext.ModelState);
Assert.Equal(string.Empty, keyValuePair.Key);
var error = Assert.Single(keyValuePair.Value.Errors);
Assert.Equal("A value for the 'fieldName' parameter or property was not provided.", error.ErrorMessage);
}
private IActionResult ActionWithNoSettablePropertiesParameter(PersonWithNoProperties parameter) => null;
[Fact]
public async Task BindModelAsync_CreatesModelAndAddsError_IfIsTopLevelObject_WithNoSettableProperties()
{
// Arrange
var parameter = typeof(ComplexTypeModelBinderTest)
.GetMethod(
nameof(ActionWithNoSettablePropertiesParameter),
BindingFlags.Instance | BindingFlags.NonPublic)
.GetParameters()[0];
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForParameter(parameter)
.BindingDetails(b => b.IsBindingRequired = true);
var metadata = metadataProvider.GetMetadataForParameter(parameter);
var bindingContext = new DefaultModelBindingContext
{
IsTopLevelObject = true,
FieldName = "fieldName",
ModelMetadata = metadata,
ModelName = string.Empty,
ValueProvider = new TestValueProvider(new Dictionary<string, object>()),
ModelState = new ModelStateDictionary(),
};
var binder = new ComplexTypeModelBinder(
new Dictionary<ModelMetadata, IModelBinder>(),
NullLoggerFactory.Instance,
allowValidatingTopLevelNodes: true);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.IsType<PersonWithNoProperties>(bindingContext.Result.Model);
var keyValuePair = Assert.Single(bindingContext.ModelState);
Assert.Equal(string.Empty, keyValuePair.Key);
var error = Assert.Single(keyValuePair.Value.Errors);
Assert.Equal("A value for the 'fieldName' parameter or property was not provided.", error.ErrorMessage);
}
private IActionResult ActionWithAllPropertiesExcludedParameter(PersonWithAllPropertiesExcluded parameter) => null;
[Fact]
public async Task BindModelAsync_CreatesModelAndAddsError_IfIsTopLevelObject_WithAllPropertiesExcluded()
{
// Arrange
var parameter = typeof(ComplexTypeModelBinderTest)
.GetMethod(
nameof(ActionWithAllPropertiesExcludedParameter),
BindingFlags.Instance | BindingFlags.NonPublic)
.GetParameters()[0];
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForParameter(parameter)
.BindingDetails(b => b.IsBindingRequired = true);
var metadata = metadataProvider.GetMetadataForParameter(parameter);
var bindingContext = new DefaultModelBindingContext
{
IsTopLevelObject = true,
FieldName = "fieldName",
ModelMetadata = metadata,
ModelName = string.Empty,
ValueProvider = new TestValueProvider(new Dictionary<string, object>()),
ModelState = new ModelStateDictionary(),
};
var binder = new ComplexTypeModelBinder(
new Dictionary<ModelMetadata, IModelBinder>(),
NullLoggerFactory.Instance,
allowValidatingTopLevelNodes: true);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
Assert.IsType<PersonWithAllPropertiesExcluded>(bindingContext.Result.Model);
var keyValuePair = Assert.Single(bindingContext.ModelState);
Assert.Equal(string.Empty, keyValuePair.Key);
var error = Assert.Single(keyValuePair.Value.Errors);
Assert.Equal("A value for the 'fieldName' parameter or property was not provided.", error.ErrorMessage);
}
[Theory]
[InlineData(nameof(MyModelTestingCanUpdateProperty.ReadOnlyInt), false)] // read-only value type
[InlineData(nameof(MyModelTestingCanUpdateProperty.ReadOnlyObject), true)]
[InlineData(nameof(MyModelTestingCanUpdateProperty.ReadOnlySimple), true)]
[InlineData(nameof(MyModelTestingCanUpdateProperty.ReadOnlyString), false)]
[InlineData(nameof(MyModelTestingCanUpdateProperty.ReadWriteString), true)]
public void CanUpdateProperty_ReturnsExpectedValue(string propertyName, bool expected)
{
// Arrange
var propertyMetadata = GetMetadataForProperty(typeof(MyModelTestingCanUpdateProperty), propertyName);
// Act
var canUpdate = ComplexTypeModelBinder.CanUpdatePropertyInternal(propertyMetadata);
// Assert
Assert.Equal(expected, canUpdate);
}
[Theory]
[InlineData(nameof(CollectionContainer.ReadOnlyArray), false)]
[InlineData(nameof(CollectionContainer.ReadOnlyDictionary), true)]
[InlineData(nameof(CollectionContainer.ReadOnlyList), true)]
[InlineData(nameof(CollectionContainer.SettableArray), true)]
[InlineData(nameof(CollectionContainer.SettableDictionary), true)]
[InlineData(nameof(CollectionContainer.SettableList), true)]
public void CanUpdateProperty_CollectionProperty_FalseOnlyForArray(string propertyName, bool expected)
{
// Arrange
var metadataProvider = _metadataProvider;
var metadata = metadataProvider.GetMetadataForProperty(typeof(CollectionContainer), propertyName);
// Act
var canUpdate = ComplexTypeModelBinder.CanUpdatePropertyInternal(metadata);
// Assert
Assert.Equal(expected, canUpdate);
}
[Fact]
public void CreateModel_InstantiatesInstanceOfMetadataType()
{
// Arrange
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = GetMetadataForType(typeof(Person))
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var model = binder.CreateModelPublic(bindingContext);
// Assert
Assert.IsType<Person>(model);
}
[Fact]
public void CreateModel_ForStructModelType_AsTopLevelObject_ThrowsException()
{
// Arrange
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = GetMetadataForType(typeof(PointStruct)),
IsTopLevelObject = true
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() => binder.CreateModelPublic(bindingContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor.",
typeof(PointStruct).FullName),
exception.Message);
}
[Fact]
public void CreateModel_ForClassWithNoParameterlessConstructor_AsElement_ThrowsException()
{
// Arrange
var expectedMessage = "Could not create an instance of type " +
$"'{typeof(ClassWithNoParameterlessConstructor)}'. Model bound complex types must not be abstract " +
"or value types and must have a parameterless constructor.";
var metadata = GetMetadataForType(typeof(ClassWithNoParameterlessConstructor));
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = metadata,
};
var binder = CreateBinder(metadata);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() => binder.CreateModelPublic(bindingContext));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void CreateModel_ForStructModelType_AsProperty_ThrowsException()
{
// Arrange
var bindingContext = new DefaultModelBindingContext
{
ModelMetadata = GetMetadataForProperty(typeof(Location), nameof(Location.Point)),
ModelName = nameof(Location.Point),
IsTopLevelObject = false
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() => binder.CreateModelPublic(bindingContext));
Assert.Equal(
string.Format(
CultureInfo.CurrentCulture,
"Could not create an instance of type '{0}'. Model bound complex types must not be abstract or " +
"value types and must have a parameterless constructor. Alternatively, set the '{1}' property to" +
" a non-null value in the '{2}' constructor.",
typeof(PointStruct).FullName,
nameof(Location.Point),
typeof(Location).FullName),
exception.Message);
}
[Fact]
public async Task BindModelAsync_ModelIsNotNull_DoesNotCallCreateModel()
{
// Arrange
var bindingContext = CreateContext(GetMetadataForType(typeof(Person)), new Person());
var originalModel = bindingContext.Model;
var binders = bindingContext.ModelMetadata.Properties.ToDictionary(
keySelector: item => item,
elementSelector: item => (IModelBinder)null);
var binder = new Mock<TestableComplexTypeModelBinder>(binders) { CallBase = true };
binder
.Setup(b => b.CreateModelPublic(It.IsAny<ModelBindingContext>()))
.Verifiable();
// Act
await binder.Object.BindModelAsync(bindingContext);
// Assert
Assert.Same(originalModel, bindingContext.Model);
binder.Verify(o => o.CreateModelPublic(bindingContext), Times.Never());
}
[Fact]
public async Task BindModelAsync_ModelIsNull_CallsCreateModel()
{
// Arrange
var bindingContext = CreateContext(GetMetadataForType(typeof(Person)), model: null);
var binders = bindingContext.ModelMetadata.Properties.ToDictionary(
keySelector: item => item,
elementSelector: item => (IModelBinder)null);
var testableBinder = new Mock<TestableComplexTypeModelBinder>(binders) { CallBase = true };
testableBinder
.Setup(o => o.CreateModelPublic(bindingContext))
.Returns(new Person())
.Verifiable();
// Act
await testableBinder.Object.BindModelAsync(bindingContext);
// Assert
Assert.NotNull(bindingContext.Model);
Assert.IsType<Person>(bindingContext.Model);
testableBinder.Verify();
}
[Theory]
[InlineData(nameof(PersonWithBindExclusion.FirstName))]
[InlineData(nameof(PersonWithBindExclusion.LastName))]
public void CanBindProperty_GetSetProperty(string property)
{
// Arrange
var metadata = GetMetadataForProperty(typeof(PersonWithBindExclusion), property);
var bindingContext = new DefaultModelBindingContext()
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = new ServiceCollection().BuildServiceProvider(),
},
},
ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion)),
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var result = binder.CanBindPropertyPublic(bindingContext, metadata);
// Assert
Assert.True(result);
}
[Theory]
[InlineData(nameof(PersonWithBindExclusion.NonUpdateableProperty))]
public void CanBindProperty_GetOnlyProperty_WithBindNever(string property)
{
// Arrange
var metadata = GetMetadataForProperty(typeof(PersonWithBindExclusion), property);
var bindingContext = new DefaultModelBindingContext()
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = new ServiceCollection().BuildServiceProvider(),
},
},
ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion)),
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var result = binder.CanBindPropertyPublic(bindingContext, metadata);
// Assert
Assert.False(result);
}
[Theory]
[InlineData(nameof(PersonWithBindExclusion.DateOfBirth))]
[InlineData(nameof(PersonWithBindExclusion.DateOfDeath))]
public void CanBindProperty_GetSetProperty_WithBindNever(string property)
{
// Arrange
var metadata = GetMetadataForProperty(typeof(PersonWithBindExclusion), property);
var bindingContext = new DefaultModelBindingContext()
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
},
ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion)),
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var result = binder.CanBindPropertyPublic(bindingContext, metadata);
// Assert
Assert.False(result);
}
[Theory]
[InlineData(nameof(TypeWithIncludedPropertiesUsingBindAttribute.IncludedExplicitly1), true)]
[InlineData(nameof(TypeWithIncludedPropertiesUsingBindAttribute.IncludedExplicitly2), true)]
[InlineData(nameof(TypeWithIncludedPropertiesUsingBindAttribute.ExcludedByDefault1), false)]
[InlineData(nameof(TypeWithIncludedPropertiesUsingBindAttribute.ExcludedByDefault2), false)]
public void CanBindProperty_WithBindInclude(string property, bool expected)
{
// Arrange
var metadata = GetMetadataForProperty(typeof(TypeWithIncludedPropertiesUsingBindAttribute), property);
var bindingContext = new DefaultModelBindingContext()
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
},
ModelMetadata = GetMetadataForType(typeof(TypeWithIncludedPropertiesUsingBindAttribute)),
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var result = binder.CanBindPropertyPublic(bindingContext, metadata);
// Assert
Assert.Equal(expected, result);
}
[Theory]
[InlineData(nameof(ModelWithMixedBindingBehaviors.Required), true)]
[InlineData(nameof(ModelWithMixedBindingBehaviors.Optional), true)]
[InlineData(nameof(ModelWithMixedBindingBehaviors.Never), false)]
public void CanBindProperty_BindingAttributes_OverridingBehavior(string property, bool expected)
{
// Arrange
var metadata = GetMetadataForProperty(typeof(ModelWithMixedBindingBehaviors), property);
var bindingContext = new DefaultModelBindingContext()
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
},
ModelMetadata = GetMetadataForType(typeof(ModelWithMixedBindingBehaviors)),
};
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
var result = binder.CanBindPropertyPublic(bindingContext, metadata);
// Assert
Assert.Equal(expected, result);
}
[Fact]
[ReplaceCulture]
public async Task BindModelAsync_BindRequiredFieldMissing_RaisesModelError()
{
// Arrange
var model = new ModelWithBindRequired
{
Name = "original value",
Age = -20
};
var property = GetMetadataForProperty(model.GetType(), nameof(ModelWithBindRequired.Age));
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var binder = CreateBinder(bindingContext.ModelMetadata);
binder.Results[property] = ModelBindingResult.Failed();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
var modelStateDictionary = bindingContext.ModelState;
Assert.False(modelStateDictionary.IsValid);
Assert.Single(modelStateDictionary);
// Check Age error.
Assert.True(modelStateDictionary.TryGetValue("theModel.Age", out var entry));
var modelError = Assert.Single(entry.Errors);
Assert.Null(modelError.Exception);
Assert.NotNull(modelError.ErrorMessage);
Assert.Equal("A value for the 'Age' parameter or property was not provided.", modelError.ErrorMessage);
}
[Fact]
[ReplaceCulture]
public async Task BindModelAsync_DataMemberIsRequiredFieldMissing_RaisesModelError()
{
// Arrange
var model = new ModelWithDataMemberIsRequired
{
Name = "original value",
Age = -20
};
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var binder = CreateBinder(bindingContext.ModelMetadata);
var property = GetMetadataForProperty(model.GetType(), nameof(ModelWithDataMemberIsRequired.Age));
binder.Results[property] = ModelBindingResult.Failed();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
var modelStateDictionary = bindingContext.ModelState;
Assert.False(modelStateDictionary.IsValid);
Assert.Single(modelStateDictionary);
// Check Age error.
Assert.True(modelStateDictionary.TryGetValue("theModel.Age", out var entry));
var modelError = Assert.Single(entry.Errors);
Assert.Null(modelError.Exception);
Assert.NotNull(modelError.ErrorMessage);
Assert.Equal("A value for the 'Age' parameter or property was not provided.", modelError.ErrorMessage);
}
[Fact]
[ReplaceCulture]
public async Task BindModelAsync_ValueTypePropertyWithBindRequired_SetToNull_CapturesException()
{
// Arrange
var model = new ModelWithBindRequired
{
Name = "original value",
Age = -20
};
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var binder = CreateBinder(bindingContext.ModelMetadata);
// Attempt to set non-Nullable property to null. BindRequiredAttribute should not be relevant in this
// case because the property did have a result.
var property = GetMetadataForProperty(model.GetType(), nameof(ModelWithBindRequired.Age));
binder.Results[property] = ModelBindingResult.Success(model: null);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
var modelStateDictionary = bindingContext.ModelState;
Assert.False(modelStateDictionary.IsValid);
Assert.Single(modelStateDictionary);
// Check Age error.
Assert.True(modelStateDictionary.TryGetValue("theModel.Age", out var entry));
Assert.Equal(ModelValidationState.Invalid, entry.ValidationState);
var modelError = Assert.Single(entry.Errors);
Assert.Equal(string.Empty, modelError.ErrorMessage);
Assert.IsType<NullReferenceException>(modelError.Exception);
}
[Fact]
public async Task BindModelAsync_ValueTypeProperty_WithBindingOptional_NoValueSet_NoError()
{
// Arrange
var model = new BindingOptionalProperty();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var binder = CreateBinder(bindingContext.ModelMetadata);
var property = GetMetadataForProperty(model.GetType(), nameof(BindingOptionalProperty.ValueTypeRequired));
binder.Results[property] = ModelBindingResult.Failed();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
var modelStateDictionary = bindingContext.ModelState;
Assert.True(modelStateDictionary.IsValid);
}
[Fact]
public async Task BindModelAsync_NullableValueTypeProperty_NoValueSet_NoError()
{
// Arrange
var model = new NullableValueTypeProperty();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var binder = CreateBinder(bindingContext.ModelMetadata);
var property = GetMetadataForProperty(model.GetType(), nameof(NullableValueTypeProperty.NullableValueType));
binder.Results[property] = ModelBindingResult.Failed();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
var modelStateDictionary = bindingContext.ModelState;
Assert.True(modelStateDictionary.IsValid);
}
[Fact]
public async Task BindModelAsync_ValueTypeProperty_NoValue_NoError()
{
// Arrange
var model = new Person();
var containerMetadata = GetMetadataForType(model.GetType());
var bindingContext = CreateContext(containerMetadata, model);
var binder = CreateBinder(bindingContext.ModelMetadata);
var property = GetMetadataForProperty(model.GetType(), nameof(Person.ValueTypeRequired));
binder.Results[property] = ModelBindingResult.Failed();
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.ModelState.IsValid);
Assert.Equal(0, model.ValueTypeRequired);
}
[Fact]
public async Task BindModelAsync_ProvideRequiredField_Success()
{
// Arrange
var model = new Person();
var containerMetadata = GetMetadataForType(model.GetType());
var bindingContext = CreateContext(containerMetadata, model);
var binder = CreateBinder(bindingContext.ModelMetadata);
var property = GetMetadataForProperty(model.GetType(), nameof(Person.ValueTypeRequired));
binder.Results[property] = ModelBindingResult.Success(model: 57);
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.ModelState.IsValid);
Assert.Equal(57, model.ValueTypeRequired);
}
[Fact]
public async Task BindModelAsync_Success()
{
// Arrange
var dob = new DateTime(2001, 1, 1);
var model = new PersonWithBindExclusion
{
DateOfBirth = dob
};
var containerMetadata = GetMetadataForType(model.GetType());
var bindingContext = CreateContext(containerMetadata, model);
var binder = CreateBinder(bindingContext.ModelMetadata);
foreach (var property in containerMetadata.Properties)
{
binder.Results[property] = ModelBindingResult.Failed();
}
var firstNameProperty = containerMetadata.Properties[nameof(model.FirstName)];
binder.Results[firstNameProperty] = ModelBindingResult.Success("John");
var lastNameProperty = containerMetadata.Properties[nameof(model.LastName)];
binder.Results[lastNameProperty] = ModelBindingResult.Success("Doe");
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.Equal("John", model.FirstName);
Assert.Equal("Doe", model.LastName);
Assert.Equal(dob, model.DateOfBirth);
Assert.True(bindingContext.ModelState.IsValid);
}
[Fact]
public void SetProperty_PropertyHasDefaultValue_DefaultValueAttributeDoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadata = GetMetadataForType(typeof(Person));
var propertyMetadata = metadata.Properties[nameof(model.PropertyWithDefaultValue)];
var result = ModelBindingResult.Failed();
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
var person = Assert.IsType<Person>(bindingContext.Model);
Assert.Equal(0m, person.PropertyWithDefaultValue);
Assert.True(bindingContext.ModelState.IsValid);
}
[Fact]
public void SetProperty_PropertyIsPreinitialized_NoValue_DoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadata = GetMetadataForType(typeof(Person));
var propertyMetadata = metadata.Properties[nameof(model.PropertyWithInitializedValue)];
// The null model value won't be used because IsModelBound = false.
var result = ModelBindingResult.Failed();
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
var person = Assert.IsType<Person>(bindingContext.Model);
Assert.Equal("preinitialized", person.PropertyWithInitializedValue);
Assert.True(bindingContext.ModelState.IsValid);
}
[Fact]
public void SetProperty_PropertyIsPreinitialized_DefaultValueAttributeDoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadata = GetMetadataForType(typeof(Person));
var propertyMetadata = metadata.Properties[nameof(model.PropertyWithInitializedValueAndDefault)];
// The null model value won't be used because IsModelBound = false.
var result = ModelBindingResult.Failed();
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
var person = Assert.IsType<Person>(bindingContext.Model);
Assert.Equal("preinitialized", person.PropertyWithInitializedValueAndDefault);
Assert.True(bindingContext.ModelState.IsValid);
}
[Fact]
public void SetProperty_PropertyIsReadOnly_DoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadata = GetMetadataForType(typeof(Person));
var propertyMetadata = metadata.Properties[nameof(model.NonUpdateableProperty)];
var result = ModelBindingResult.Failed();
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
// If didn't throw, success!
}
// Property name, property accessor
public static TheoryData<string, Func<object, object>> MyCanUpdateButCannotSetPropertyData
{
get
{
return new TheoryData<string, Func<object, object>>
{
{
nameof(MyModelTestingCanUpdateProperty.ReadOnlyObject),
model => ((Simple)((MyModelTestingCanUpdateProperty)model).ReadOnlyObject).Name
},
{
nameof(MyModelTestingCanUpdateProperty.ReadOnlySimple),
model => ((MyModelTestingCanUpdateProperty)model).ReadOnlySimple.Name
},
};
}
}
[Theory]
[MemberData(nameof(MyCanUpdateButCannotSetPropertyData))]
public void SetProperty_ValueProvidedAndCanUpdatePropertyTrue_DoesNothing(
string propertyName,
Func<object, object> propertyAccessor)
{
// Arrange
var model = new MyModelTestingCanUpdateProperty();
var type = model.GetType();
var bindingContext = CreateContext(GetMetadataForType(type), model);
var modelState = bindingContext.ModelState;
var propertyMetadata = bindingContext.ModelMetadata.Properties[propertyName];
var result = ModelBindingResult.Success(new Simple { Name = "Hanna" });
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, propertyName, propertyMetadata, result);
// Assert
Assert.Equal("Joe", propertyAccessor(model));
Assert.True(modelState.IsValid);
Assert.Empty(modelState);
}
[Fact]
public void SetProperty_ReadOnlyProperty_IsNoOp()
{
// Arrange
var model = new CollectionContainer();
var originalCollection = model.ReadOnlyList;
var modelMetadata = GetMetadataForType(model.GetType());
var propertyMetadata = GetMetadataForProperty(model.GetType(), nameof(CollectionContainer.ReadOnlyList));
var bindingContext = CreateContext(modelMetadata, model);
var result = ModelBindingResult.Success(new List<string>() { "hi" });
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, propertyMetadata.PropertyName, propertyMetadata, result);
// Assert
Assert.Same(originalCollection, model.ReadOnlyList);
Assert.Empty(model.ReadOnlyList);
}
[Fact]
public void SetProperty_PropertyIsSettable_CallsSetter()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var propertyMetadata = bindingContext.ModelMetadata.Properties[nameof(model.DateOfBirth)];
var result = ModelBindingResult.Success(new DateTime(2001, 1, 1));
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
Assert.True(bindingContext.ModelState.IsValid);
Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);
}
[Fact]
[ReplaceCulture]
public void SetProperty_PropertyIsSettable_SetterThrows_RecordsError()
{
// Arrange
var model = new Person
{
DateOfBirth = new DateTime(1900, 1, 1)
};
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var propertyMetadata = bindingContext.ModelMetadata.Properties[nameof(model.DateOfDeath)];
var result = ModelBindingResult.Success(new DateTime(1800, 1, 1));
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo", propertyMetadata, result);
// Assert
Assert.Equal("Date of death can't be before date of birth. (Parameter 'value')",
bindingContext.ModelState["foo"].Errors[0].Exception.Message);
}
[Fact]
[ReplaceCulture]
public void SetProperty_PropertySetterThrows_CapturesException()
{
// Arrange
var model = new ModelWhosePropertySetterThrows();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
bindingContext.ModelName = "foo";
var propertyMetadata = bindingContext.ModelMetadata.Properties[nameof(model.NameNoAttribute)];
var result = ModelBindingResult.Success(model: null);
var binder = CreateBinder(bindingContext.ModelMetadata);
// Act
binder.SetPropertyPublic(bindingContext, "foo.NameNoAttribute", propertyMetadata, result);
// Assert
Assert.False(bindingContext.ModelState.IsValid);
Assert.Single(bindingContext.ModelState["foo.NameNoAttribute"].Errors);
Assert.Equal("This is a different exception. (Parameter 'value')",
bindingContext.ModelState["foo.NameNoAttribute"].Errors[0].Exception.Message);
}
private static TestableComplexTypeModelBinder CreateBinder(ModelMetadata metadata)
{
var options = Options.Create(new MvcOptions());
var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());
setup.Configure(options.Value);
var lastIndex = options.Value.ModelBinderProviders.Count - 1;
options.Value.ModelBinderProviders.RemoveType<ComplexObjectModelBinderProvider>();
options.Value.ModelBinderProviders.Add(new TestableComplexTypeModelBinderProvider());
var factory = TestModelBinderFactory.Create(options.Value.ModelBinderProviders.ToArray());
return (TestableComplexTypeModelBinder)factory.CreateBinder(new ModelBinderFactoryContext()
{
Metadata = metadata,
BindingInfo = new BindingInfo()
{
BinderModelName = metadata.BinderModelName,
BinderType = metadata.BinderType,
BindingSource = metadata.BindingSource,
PropertyFilterProvider = metadata.PropertyFilterProvider,
},
});
}
private static DefaultModelBindingContext CreateContext(ModelMetadata metadata, object model = null)
{
var valueProvider = new TestValueProvider(new Dictionary<string, object>());
return new DefaultModelBindingContext()
{
BinderModelName = metadata.BinderModelName,
BindingSource = metadata.BindingSource,
IsTopLevelObject = true,
Model = model,
ModelMetadata = metadata,
ModelName = "theModel",
ModelState = new ModelStateDictionary(),
ValueProvider = valueProvider,
};
}
private static ModelMetadata GetMetadataForType(Type type)
{
return _metadataProvider.GetMetadataForType(type);
}
private static ModelMetadata GetMetadataForProperty(Type type, string propertyName)
{
return _metadataProvider.GetMetadataForProperty(type, propertyName);
}
private class Location
{
public PointStruct Point { get; set; }
}
private readonly struct PointStruct
{
public PointStruct(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
}
private class ClassWithNoParameterlessConstructor
{
public ClassWithNoParameterlessConstructor(string name)
{
Name = name;
}
public string Name { get; set; }
}
private class BindingOptionalProperty
{
[BindingBehavior(BindingBehavior.Optional)]
public int ValueTypeRequired { get; set; }
}
private class NullableValueTypeProperty
{
[BindingBehavior(BindingBehavior.Optional)]
public int? NullableValueType { get; set; }
}
private class Person
{
private DateTime? _dateOfDeath;
[BindingBehavior(BindingBehavior.Optional)]
public DateTime DateOfBirth { get; set; }
public DateTime? DateOfDeath
{
get { return _dateOfDeath; }
set
{
if (value < DateOfBirth)
{
throw new ArgumentOutOfRangeException(nameof(value), "Date of death can't be before date of birth.");
}
_dateOfDeath = value;
}
}
[Required(ErrorMessage = "Sample message")]
public int ValueTypeRequired { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NonUpdateableProperty { get; private set; }
[BindingBehavior(BindingBehavior.Optional)]
[DefaultValue(typeof(decimal), "123.456")]
public decimal PropertyWithDefaultValue { get; set; }
public string PropertyWithInitializedValue { get; set; } = "preinitialized";
[DefaultValue("default")]
public string PropertyWithInitializedValueAndDefault { get; set; } = "preinitialized";
}
private class PersonWithNoProperties
{
public string name = null;
}
private class PersonWithAllPropertiesExcluded
{
[BindNever]
public DateTime DateOfBirth { get; set; }
[BindNever]
public DateTime? DateOfDeath { get; set; }
[BindNever]
public string FirstName { get; set; }
[BindNever]
public string LastName { get; set; }
public string NonUpdateableProperty { get; private set; }
}
private class PersonWithBindExclusion
{
[BindNever]
public DateTime DateOfBirth { get; set; }
[BindNever]
public DateTime? DateOfDeath { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NonUpdateableProperty { get; private set; }
}
private class ModelWithBindRequired
{
public string Name { get; set; }
[BindRequired]
public int Age { get; set; }
}
[DataContract]
private class ModelWithDataMemberIsRequired
{
public string Name { get; set; }
[DataMember(IsRequired = true)]
public int Age { get; set; }
}
[BindRequired]
private class ModelWithMixedBindingBehaviors
{
public string Required { get; set; }
[BindNever]
public string Never { get; set; }
[BindingBehavior(BindingBehavior.Optional)]
public string Optional { get; set; }
}
private sealed class MyModelTestingCanUpdateProperty
{
public int ReadOnlyInt { get; private set; }
public string ReadOnlyString { get; private set; }
public object ReadOnlyObject { get; } = new Simple { Name = "Joe" };
public string ReadWriteString { get; set; }
public Simple ReadOnlySimple { get; } = new Simple { Name = "Joe" };
}
private sealed class ModelWhosePropertySetterThrows
{
[Required(ErrorMessage = "This message comes from the [Required] attribute.")]
public string Name
{
get { return null; }
set { throw new ArgumentException("This is an exception.", "value"); }
}
public string NameNoAttribute
{
get { return null; }
set { throw new ArgumentException("This is a different exception.", "value"); }
}
}
private class TypeWithNoBinderMetadata
{
public int UnMarkedProperty { get; set; }
}
private class HasAllGreedyProperties
{
[NonValueBinderMetadata]
public string MarkedWithABinderMetadata { get; set; }
}
// Not a Metadata poco because there is a property with value binder Metadata.
private class TypeWithAtLeastOnePropertyMarkedUsingValueBinderMetadata
{
[NonValueBinderMetadata]
public string MarkedWithABinderMetadata { get; set; }
[ValueBinderMetadata]
public string MarkedWithAValueBinderMetadata { get; set; }
}
// not a Metadata poco because there is an unmarked property.
private class TypeWithUnmarkedAndBinderMetadataMarkedProperties
{
public int UnmarkedProperty { get; set; }
[NonValueBinderMetadata]
public string MarkedWithABinderMetadata { get; set; }
}
[Bind(new[] { nameof(IncludedExplicitly1), nameof(IncludedExplicitly2) })]
private class TypeWithIncludedPropertiesUsingBindAttribute
{
public int ExcludedByDefault1 { get; set; }
public int ExcludedByDefault2 { get; set; }
public int IncludedExplicitly1 { get; set; }
public int IncludedExplicitly2 { get; set; }
}
private class Document
{
[NonValueBinderMetadata]
public string Version { get; set; }
[NonValueBinderMetadata]
public Document SubDocument { get; set; }
}
private class NonValueBinderMetadataAttribute : Attribute, IBindingSourceMetadata
{
public BindingSource BindingSource
{
get { return new BindingSource("Special", string.Empty, isGreedy: true, isFromRequest: true); }
}
}
private class ValueBinderMetadataAttribute : Attribute, IBindingSourceMetadata
{
public BindingSource BindingSource { get { return BindingSource.Query; } }
}
private class ExcludedProvider : IPropertyFilterProvider
{
public Func<ModelMetadata, bool> PropertyFilter
{
get
{
return (m) =>
!string.Equals("Excluded1", m.PropertyName, StringComparison.OrdinalIgnoreCase) &&
!string.Equals("Excluded2", m.PropertyName, StringComparison.OrdinalIgnoreCase);
}
}
}
private class SimpleContainer
{
public Simple Simple { get; set; }
}
private class Simple
{
public string Name { get; set; }
}
private class CollectionContainer
{
public int[] ReadOnlyArray { get; } = new int[4];
// Read-only collections get added values.
public IDictionary<int, string> ReadOnlyDictionary { get; } = new Dictionary<int, string>();
public IList<int> ReadOnlyList { get; } = new List<int>();
// Settable values are overwritten.
public int[] SettableArray { get; set; } = new int[] { 0, 1 };
public IDictionary<int, string> SettableDictionary { get; set; } = new Dictionary<int, string>
{
{ 0, "zero" },
{ 25, "twenty-five" },
};
public IList<int> SettableList { get; set; } = new List<int> { 3, 9, 0 };
}
private class TestableComplexTypeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.IsComplexType)
{
var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
foreach (var property in context.Metadata.Properties)
{
propertyBinders.Add(property, context.CreateBinder(property));
}
return new TestableComplexTypeModelBinder(propertyBinders);
}
return null;
}
}
// Provides the ability to easily mock + call each of these APIs
public class TestableComplexTypeModelBinder : ComplexTypeModelBinder
{
public TestableComplexTypeModelBinder()
: this(new Dictionary<ModelMetadata, IModelBinder>())
{
}
public TestableComplexTypeModelBinder(bool allowValidatingTopLevelNodes)
: this(new Dictionary<ModelMetadata, IModelBinder>(), allowValidatingTopLevelNodes)
{
}
public TestableComplexTypeModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
: base(propertyBinders, NullLoggerFactory.Instance)
{
}
public TestableComplexTypeModelBinder(
IDictionary<ModelMetadata, IModelBinder> propertyBinders,
bool allowValidatingTopLevelNodes)
: base(propertyBinders, NullLoggerFactory.Instance, allowValidatingTopLevelNodes)
{
}
public Dictionary<ModelMetadata, ModelBindingResult> Results { get; } = new Dictionary<ModelMetadata, ModelBindingResult>();
public virtual Task BindPropertyPublic(ModelBindingContext bindingContext)
{
if (Results.Count == 0)
{
return base.BindModelAsync(bindingContext);
}
if (Results.TryGetValue(bindingContext.ModelMetadata, out var result))
{
bindingContext.Result = result;
}
return Task.CompletedTask;
}
protected override Task BindProperty(ModelBindingContext bindingContext)
{
return BindPropertyPublic(bindingContext);
}
public virtual bool CanBindPropertyPublic(
ModelBindingContext bindingContext,
ModelMetadata propertyMetadata)
{
if (Results.Count == 0)
{
return base.CanBindProperty(bindingContext, propertyMetadata);
}
// If this is being used to test binding, then only attempt to bind properties
// we have results for.
return Results.ContainsKey(propertyMetadata);
}
protected override bool CanBindProperty(
ModelBindingContext bindingContext,
ModelMetadata propertyMetadata)
{
return CanBindPropertyPublic(bindingContext, propertyMetadata);
}
public virtual object CreateModelPublic(ModelBindingContext bindingContext)
{
return base.CreateModel(bindingContext);
}
protected override object CreateModel(ModelBindingContext bindingContext)
{
return CreateModelPublic(bindingContext);
}
public virtual void SetPropertyPublic(
ModelBindingContext bindingContext,
string modelName,
ModelMetadata propertyMetadata,
ModelBindingResult result)
{
base.SetProperty(bindingContext, modelName, propertyMetadata, result);
}
protected override void SetProperty(
ModelBindingContext bindingContext,
string modelName,
ModelMetadata propertyMetadata,
ModelBindingResult result)
{
SetPropertyPublic(bindingContext, modelName, propertyMetadata, result);
}
}
}
#pragma warning restore CS0618 // Type or member is obsolete
}
| |
using System;
using System.Collections;
using System.IO;
using NBitcoin.BouncyCastle.Utilities;
using NBitcoin.BouncyCastle.Utilities.Collections;
namespace NBitcoin.BouncyCastle.Asn1
{
public abstract class Asn1Sequence
: Asn1Object, IEnumerable
{
private readonly IList seq;
/**
* return an Asn1Sequence from the given object.
*
* @param obj the object we want converted.
* @exception ArgumentException if the object cannot be converted.
*/
public static Asn1Sequence GetInstance(
object obj)
{
if (obj == null || obj is Asn1Sequence)
{
return (Asn1Sequence)obj;
}
else if (obj is Asn1SequenceParser)
{
return Asn1Sequence.GetInstance(((Asn1SequenceParser)obj).ToAsn1Object());
}
else if (obj is byte[])
{
try
{
return Asn1Sequence.GetInstance(FromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new ArgumentException("failed to construct sequence from byte[]: " + e.Message);
}
}
else if (obj is Asn1Encodable)
{
Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object();
if (primitive is Asn1Sequence)
{
return (Asn1Sequence)primitive;
}
}
throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
}
/**
* Return an ASN1 sequence from a tagged object. There is a special
* case here, if an object appears to have been explicitly tagged on
* reading but we were expecting it to be implicitly tagged in the
* normal course of events it indicates that we lost the surrounding
* sequence - so we need to add it back (this will happen if the tagged
* object is a sequence that contains other sequences). If you are
* dealing with implicitly tagged sequences you really <b>should</b>
* be using this method.
*
* @param obj the tagged object.
* @param explicitly true if the object is meant to be explicitly tagged,
* false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static Asn1Sequence GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
Asn1Object inner = obj.GetObject();
if (explicitly)
{
if (!obj.IsExplicit())
throw new ArgumentException("object implicit - explicit expected.");
return (Asn1Sequence) inner;
}
//
// constructed object which appears to be explicitly tagged
// when it should be implicit means we have to add the
// surrounding sequence.
//
if (obj.IsExplicit())
{
if (obj is BerTaggedObject)
{
return new BerSequence(inner);
}
return new DerSequence(inner);
}
if (inner is Asn1Sequence)
{
return (Asn1Sequence) inner;
}
throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
}
protected internal Asn1Sequence(
int capacity)
{
seq = Platform.CreateArrayList(capacity);
}
public virtual IEnumerator GetEnumerator()
{
return seq.GetEnumerator();
}
[Obsolete("Use GetEnumerator() instead")]
public IEnumerator GetObjects()
{
return GetEnumerator();
}
private class Asn1SequenceParserImpl
: Asn1SequenceParser
{
private readonly Asn1Sequence outer;
private readonly int max;
private int index;
public Asn1SequenceParserImpl(
Asn1Sequence outer)
{
this.outer = outer;
this.max = outer.Count;
}
public IAsn1Convertible ReadObject()
{
if (index == max)
return null;
Asn1Encodable obj = outer[index++];
if (obj is Asn1Sequence)
return ((Asn1Sequence)obj).Parser;
if (obj is Asn1Set)
return ((Asn1Set)obj).Parser;
// NB: Asn1OctetString implements Asn1OctetStringParser directly
// if (obj is Asn1OctetString)
// return ((Asn1OctetString)obj).Parser;
return obj;
}
public Asn1Object ToAsn1Object()
{
return outer;
}
}
public virtual Asn1SequenceParser Parser
{
get { return new Asn1SequenceParserImpl(this); }
}
/**
* return the object at the sequence position indicated by index.
*
* @param index the sequence number (starting at zero) of the object
* @return the object at the sequence position indicated by index.
*/
public virtual Asn1Encodable this[int index]
{
get { return (Asn1Encodable) seq[index]; }
}
[Obsolete("Use 'object[index]' syntax instead")]
public Asn1Encodable GetObjectAt(
int index)
{
return this[index];
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get { return Count; }
}
public virtual int Count
{
get { return seq.Count; }
}
protected override int Asn1GetHashCode()
{
int hc = Count;
foreach (object o in this)
{
hc *= 17;
if (o == null)
{
hc ^= DerNull.Instance.GetHashCode();
}
else
{
hc ^= o.GetHashCode();
}
}
return hc;
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
Asn1Sequence other = asn1Object as Asn1Sequence;
if (other == null)
return false;
if (Count != other.Count)
return false;
IEnumerator s1 = GetEnumerator();
IEnumerator s2 = other.GetEnumerator();
while (s1.MoveNext() && s2.MoveNext())
{
Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
if (!o1.Equals(o2))
return false;
}
return true;
}
private Asn1Encodable GetCurrent(IEnumerator e)
{
Asn1Encodable encObj = (Asn1Encodable)e.Current;
// unfortunately null was allowed as a substitute for DER null
if (encObj == null)
return DerNull.Instance;
return encObj;
}
protected internal void AddObject(
Asn1Encodable obj)
{
seq.Add(obj);
}
public override string ToString()
{
return CollectionUtilities.ToString(seq);
}
}
}
| |
namespace SampleApp
{
partial class PerformanceTest
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this._load = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this._load2 = new System.Windows.Forms.Button();
this._treeView2 = new System.Windows.Forms.TreeView();
this.label2 = new System.Windows.Forms.Label();
this._expand2 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this._expand = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this._treeView = new Aga.Controls.Tree.TreeViewAdv();
this.nodeTextBox1 = new Aga.Controls.Tree.NodeControls.NodeTextBox();
this.SuspendLayout();
//
// _load
//
this._load.Location = new System.Drawing.Point(3, 332);
this._load.Name = "_load";
this._load.Size = new System.Drawing.Size(107, 23);
this._load.TabIndex = 1;
this._load.Text = "Load";
this._load.UseVisualStyleBackColor = true;
this._load.Click += new System.EventHandler(this._load_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(71, 13);
this.label1.TabIndex = 2;
this.label1.Text = "TreeViewAdv";
//
// _load2
//
this._load2.Location = new System.Drawing.Point(273, 332);
this._load2.Name = "_load2";
this._load2.Size = new System.Drawing.Size(107, 23);
this._load2.TabIndex = 3;
this._load2.Text = "Load";
this._load2.UseVisualStyleBackColor = true;
this._load2.Click += new System.EventHandler(this._load2_Click);
//
// _treeView2
//
this._treeView2.HideSelection = false;
this._treeView2.Location = new System.Drawing.Point(273, 32);
this._treeView2.Name = "_treeView2";
this._treeView2.Size = new System.Drawing.Size(269, 294);
this._treeView2.TabIndex = 4;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(275, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(130, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Windows.Forms.TreeView";
//
// _expand2
//
this._expand2.Location = new System.Drawing.Point(273, 361);
this._expand2.Name = "_expand2";
this._expand2.Size = new System.Drawing.Size(107, 23);
this._expand2.TabIndex = 6;
this._expand2.Text = "Expand/Collapse";
this._expand2.UseVisualStyleBackColor = true;
this._expand2.Click += new System.EventHandler(this._expand2_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(116, 337);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(35, 13);
this.label3.TabIndex = 8;
this.label3.Text = "label3";
//
// _expand
//
this._expand.Location = new System.Drawing.Point(3, 361);
this._expand.Name = "_expand";
this._expand.Size = new System.Drawing.Size(107, 23);
this._expand.TabIndex = 9;
this._expand.Text = "Expand/Collapse";
this._expand.UseVisualStyleBackColor = true;
this._expand.Click += new System.EventHandler(this._expand_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(116, 366);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 13);
this.label4.TabIndex = 10;
this.label4.Text = "label4";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(386, 337);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(35, 13);
this.label5.TabIndex = 11;
this.label5.Text = "label5";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(386, 366);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(35, 13);
this.label6.TabIndex = 12;
this.label6.Text = "label6";
//
// _treeView
//
this._treeView.BackColor = System.Drawing.SystemColors.Window;
this._treeView.Cursor = System.Windows.Forms.Cursors.Default;
this._treeView.DefaultToolTipProvider = null;
this._treeView.DragDropMarkColor = System.Drawing.Color.Black;
this._treeView.LineColor = System.Drawing.SystemColors.ControlDark;
this._treeView.LoadOnDemand = true;
this._treeView.Location = new System.Drawing.Point(3, 32);
this._treeView.Model = null;
this._treeView.Name = "_treeView";
this._treeView.NodeControls.Add(this.nodeTextBox1);
this._treeView.SelectedNode = null;
this._treeView.SelectionMode = Aga.Controls.Tree.TreeSelectionMode.Multi;
this._treeView.Size = new System.Drawing.Size(269, 294);
this._treeView.TabIndex = 0;
this._treeView.Text = "treeViewAdv1";
//
// nodeTextBox1
//
this.nodeTextBox1.DataPropertyName = "Text";
this.nodeTextBox1.IncrementalSearchEnabled = true;
this.nodeTextBox1.LeftMargin = 3;
this.nodeTextBox1.ParentColumn = null;
//
// PerformanceTest
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this._expand);
this.Controls.Add(this.label3);
this.Controls.Add(this._expand2);
this.Controls.Add(this.label2);
this.Controls.Add(this._treeView2);
this.Controls.Add(this._load2);
this.Controls.Add(this.label1);
this.Controls.Add(this._load);
this.Controls.Add(this._treeView);
this.Name = "PerformanceTest";
this.Size = new System.Drawing.Size(598, 488);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Aga.Controls.Tree.TreeViewAdv _treeView;
private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBox1;
private System.Windows.Forms.Button _load;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button _load2;
private System.Windows.Forms.TreeView _treeView2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button _expand2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button _expand;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Text;
using System.Text.RegularExpressions;
namespace System
{
static partial class CoreExtensions
{
public static string ReplaceEx(this string text, string oldValue, string newValue, StringComparison comparisonType)
{
if (comparisonType == StringComparison.Ordinal)
return text.Replace(oldValue, newValue);
var textLength = text.Length;
oldValue = oldValue.ToUpperInvariant();
var oldValueLength = oldValue.Length;
var newValueLength = newValue.Length;
//
var startIndex = 0;
var index = 0;
var upperString = text.ToUpperInvariant();
//
var sizeIncrease = Math.Max(0, (textLength / oldValueLength) * (newValueLength - oldValueLength));
var buffer = new char[textLength + sizeIncrease];
var bufferIndex = 0;
int copyCount;
while ((index = upperString.IndexOf(oldValue, startIndex, comparisonType)) != -1)
{
copyCount = index - startIndex; text.CopyTo(startIndex, buffer, bufferIndex, copyCount); bufferIndex += copyCount;
newValue.CopyTo(0, buffer, bufferIndex, newValueLength); bufferIndex += newValueLength;
//for (int textIndex = startIndex; textIndex < index; textIndex++)
// buffer[bufferIndex++] = text[textIndex];
//for (int textIndex = 0; textIndex < newValueLength; textIndex++)
// buffer[bufferIndex++] = newValue[textIndex];
startIndex = index + oldValueLength;
}
if (startIndex == 0)
return text;
copyCount = textLength - startIndex; text.CopyTo(startIndex, buffer, bufferIndex, copyCount); bufferIndex += copyCount;
//for (int textIndex = startIndex; textIndex < textLength; textIndex++)
// buffer[bufferIndex++] = text[textIndex];
return new string(buffer, 0, bufferIndex);
}
/// <summary>
/// Enumeration representing the types of truncation support by a class.
/// </summary>
public enum TextTruncateType
{
Normal,
LastWhitespace,
FromAtomSite,
}
//public static void Guard(this string str, string paramName)
//{
// if (string.IsNullOrEmpty(str))
// throw new ArgumentNullException(paramName);
//}
//public static void Guard(this string str, string paramName, string message)
//{
// if (string.IsNullOrEmpty(str))
// throw new ArgumentNullException(paramName, message);
//}
public static string SpaceOnPascalCase(this string text)
{
if (string.IsNullOrEmpty(text))
return text;
return Regex.Replace(text, "([A-Z])", " $1").Trim();
}
/// <summary>
/// Determines whether value specified is contained in the array provided by performing a case-insensitive
/// culture-invariant string comparision.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="value">The value.</param>
/// <returns>
/// <c>true</c> if [is value in array invariant] [the specified value]; otherwise, <c>false</c>.
/// </returns>
public static bool ExistsIgnoreCase(this string[] array, string value)
{
if (value != null)
{
foreach (string c in array)
if (c != null && string.Equals(c, value, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
foreach (string c in array)
if (c == null)
return true;
return false;
}
/// <summary>
/// Camelizes the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string Camelize(this string text)
{
if (text == null)
throw new ArgumentNullException("text");
return (text.Length > 2 ? char.ToLowerInvariant(text[0]) + text.Substring(1) : text);
}
/// <summary>
/// Counts the of.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="countOfText">The count of text.</param>
/// <returns></returns>
public static int CountOf(this string text, string countOfText)
{
if (text == null)
throw new ArgumentNullException("text");
if (countOfText == null)
throw new ArgumentNullException("countOfText");
var countOfTextLength = countOfText.Length;
var countOfTextRemain = (text.Length - text.Replace(countOfText, string.Empty).Length);
return (countOfTextLength == 1 ? countOfTextRemain : (countOfTextLength == 2 ? countOfTextRemain >> 1 : countOfTextRemain / countOfTextLength));
}
/// <summary>
/// Determine whether a string ends with the provided value.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool EndsWithSlim(this string text, string value)
{
if (text == null)
throw new ArgumentNullException("text");
if (value == null)
throw new ArgumentNullException("value");
var valueLength = value.Length;
return (text.Length < valueLength ? false : (text.Substring(text.Length - valueLength) == value));
}
/// <summary>
/// Determine whether a string ends with the provided value.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <param name="isIgnoreCase">if set to <c>true</c> a case-insensitive compare is performed.</param>
/// <returns></returns>
public static bool EndsWithSlim(this string text, string value, bool isIgnoreCase)
{
if (text == null)
throw new ArgumentNullException("text");
if (value == null)
throw new ArgumentNullException("value");
var valueLength = value.Length;
return (text.Length < valueLength ? false : (string.Compare(text.Substring(text.Length - valueLength), value, isIgnoreCase) == 0));
}
/// <summary>
/// Ensures the ends with.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="suffix">The suffix.</param>
/// <returns></returns>
public static string EnsureEndsWith(this string text, string suffix)
{
return (!string.IsNullOrEmpty(text) && !text.EndsWithSlim(suffix) ? text + suffix : text);
}
/// <summary>
/// Returns the left most portion of the string provided.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="maxLength">Length of the max.</param>
/// <returns></returns>
public static string Left(this string text, int maxLength)
{
if (maxLength < 0)
throw new ArgumentOutOfRangeException("maxLength");
return (string.IsNullOrEmpty(text) ? string.Empty : (text.Length >= maxLength ? text.Substring(0, maxLength) : text));
}
/// <summary>
/// Returns string based on an invariant, case-insensitive string comparison. Returns nullIfText is text is empty.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string NullIf(this string text)
{
return (!string.IsNullOrEmpty(text) ? text : null);
}
/// <summary>
/// Returns string based on an invariant, case-insensitive string comparison. Returns nullIfText is text is empty.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="nullIfText">The null if text.</param>
/// <returns></returns>
public static string NullIf(this string text, string nullIfText)
{
return (text != null && !string.Equals(text, nullIfText, StringComparison.OrdinalIgnoreCase) ? text : null);
}
public static string NullIf(this string text, Predicate<string> condition)
{
if (condition == null)
throw new ArgumentNullException("condition");
return (text != null && !condition(text) ? text : null);
}
/// <summary>
/// Returns a section of the provided text starting at the startIndex.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="startIndex">The start index.</param>
/// <returns>Returns string result.</returns>
public static string Mid(this string text, int startIndex)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
return (text == null || startIndex >= text.Length ? string.Empty : text.Substring(startIndex));
}
/// <summary>
/// Returns a section of the provided text starting at the startIndex and extending up to the maxlength value provided.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="maxLength">Length of the max.</param>
/// <returns>Returns string result.</returns>
public static string Mid(this string text, int startIndex, int maxLength)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex");
if (maxLength < 0)
throw new ArgumentOutOfRangeException("maxLength");
if (text == null || startIndex >= text.Length || (startIndex + maxLength) <= 0)
return string.Empty;
return (text.Length >= (startIndex + maxLength) ? text.Substring(startIndex, maxLength) : text.Substring(startIndex));
}
/// <summary>
/// Parses the the string value representing a prefix based on the defined bindingSet provided.
/// </summary>
/// <param name="bindingSet">The binding set.</param>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static string ParseBoundedPrefix(this string text, string bindingSet, out string prefix)
{
if (bindingSet == null || bindingSet.Length != 2)
throw new ArgumentNullException("bindingSet");
if (text.Length > 0 && text[0] == bindingSet[0])
{
var key = text.IndexOf(bindingSet[1]);
if (key > -1)
{
prefix = text.Substring(1, key - 1);
return text.Substring(key + 1);
}
}
prefix = string.Empty;
return (text ?? string.Empty);
}
/// <summary>
/// Parses the bounded postfix.
/// </summary>
/// <param name="bindingSet">The binding set.</param>
/// <param name="text">The text.</param>
/// <param name="prefix">The prefix.</param>
/// <returns></returns>
public static string ParseBoundedPostfix(this string text, string bindingSet, out string postfix)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns the right-most portion of the provided text, up to the maxLength provided.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="maxLength">Length of the max.</param>
/// <returns></returns>
public static string Right(this string text, int maxLength)
{
if (maxLength < 0)
throw new ArgumentOutOfRangeException("maxLength");
if (string.IsNullOrEmpty(text))
return string.Empty;
return (text.Length >= maxLength ? text.Substring(text.Length - maxLength) : text);
}
/// <summary>
/// Singles the split.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="split">The split.</param>
/// <param name="a">A.</param>
/// <param name="b">The b.</param>
/// <returns></returns>
public static bool SingleSplit(this string text, string split, out string a, out string b)
{
if (text == null)
throw new ArgumentNullException("text");
if (split == null || split.Length == 0)
throw new ArgumentNullException("split");
var splitIndex = text.IndexOf(split);
if (splitIndex > -1)
{
a = text.Substring(0, splitIndex);
b = text.Substring(splitIndex + split.Length);
return true;
}
a = text;
b = string.Empty;
return false;
}
/// <summary>
/// Determine whether a string starts with the provided value.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public static bool StartsWithSlim(this string text, string value)
{
if (text == null)
throw new ArgumentNullException("text");
if (value == null)
throw new ArgumentNullException("value");
var valueLength = value.Length;
return (text.Length < valueLength ? false : text.Substring(0, valueLength) == value);
}
/// <summary>
/// Determine whether a string starts with the provided value.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="value">The value.</param>
/// <param name="isIgnoreCase">if set to <c>true</c> a case-insensitive compare is performed.</param>
/// <returns></returns>
public static bool StartsWithSlim(this string text, string value, bool isIgnoreCase)
{
if (text == null)
throw new ArgumentNullException("text");
if (value == null)
throw new ArgumentNullException("value");
var valueLength = value.Length;
return (text.Length < valueLength ? false : string.Compare(text.Substring(0, valueLength), value, isIgnoreCase) == 0);
}
/// <summary>
/// Truncates the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="maxLength">Length of the max.</param>
/// <returns></returns>
public static string Truncate(this string text, int maxLength) { return Truncate(text, maxLength, TextTruncateType.Normal); }
/// <summary>
/// Truncates the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="maxLength">Length of the max.</param>
/// <param name="textTruncateType">Type of the text truncate.</param>
/// <returns></returns>
public static string Truncate(this string text, int maxLength, TextTruncateType textTruncateType) { return Truncate(text, maxLength, textTruncateType, "..."); }
public static string Truncate(this string text, int maxLength, TextTruncateType textTruncateType, string trailerText)
{
if (string.IsNullOrEmpty(text))
return string.Empty; //? throw new ArgumentNullException("text");
if (maxLength < 0)
throw new ArgumentOutOfRangeException("maxLength");
if (string.IsNullOrEmpty(trailerText))
throw new ArgumentNullException("trailerText");
var trailerTextLength = trailerText.Length;
switch (textTruncateType)
{
case TextTruncateType.Normal:
return (text.Length > maxLength ? (maxLength > trailerTextLength ? text.Substring(0, maxLength - trailerTextLength) + trailerText : text.Substring(0, maxLength)) : text);
case TextTruncateType.LastWhitespace:
if (text.Length > maxLength)
{
if (maxLength > trailerTextLength)
{
var truncatedText = text.Substring(0, maxLength - trailerTextLength);
var whiteIndex = truncatedText.LastIndexOf(' ');
string truncatedTextUntilWhite;
return ((whiteIndex > 0) && ((truncatedTextUntilWhite = truncatedText.Substring(0, whiteIndex).Trim()).Length > 0) ? truncatedTextUntilWhite : truncatedText) + trailerText;
}
return text.Substring(0, maxLength);
}
return text;
case TextTruncateType.FromAtomSite:
// Add room for a word not breaking and the trailer
var b = new StringBuilder(maxLength + 20);
var words = text.Split(new char[] { ' ' });
var index = 0;
while (b.Length + words[index].Length + trailerTextLength < maxLength - trailerTextLength && index < words.GetUpperBound(0))
{
b.Append(words[index]);
b.Append(" ");
index++;
}
// We exited the loop before reaching the end of the array - which would normally be the case.
if (index < words.GetUpperBound(0))
{
// Remove the ending space before attaching the trailer.
b.Remove(b.Length - 1, 1);
b.Append(trailerText);
}
else
b.Append(words[index]);
return b.ToString();
default:
throw new InvalidOperationException();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SmiMetaData.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace Microsoft.SqlServer.Server {
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
// SmiMetaDataProperty defines an extended, optional property to be used on the SmiMetaData class
// This approach to adding properties is added combat the growing number of sparsely-used properties
// that are specially handled on the base classes
internal enum SmiPropertySelector {
DefaultFields = 0x0,
SortOrder = 0x1,
UniqueKey = 0x2,
}
// Simple collection for properties. Could extend to IDictionary support if needed in future.
internal class SmiMetaDataPropertyCollection {
private const int SelectorCount = 3; // number of elements in SmiPropertySelector
private SmiMetaDataProperty[] _properties;
private bool _isReadOnly;
internal static readonly SmiMetaDataPropertyCollection EmptyInstance;
// Singleton empty instances to ensure each property is always non-null
private static readonly SmiDefaultFieldsProperty __emptyDefaultFields = new SmiDefaultFieldsProperty(new List<bool>());
private static readonly SmiOrderProperty __emptySortOrder = new SmiOrderProperty(new List<SmiOrderProperty.SmiColumnOrder>());
private static readonly SmiUniqueKeyProperty __emptyUniqueKey = new SmiUniqueKeyProperty(new List<bool>());
static SmiMetaDataPropertyCollection() {
EmptyInstance = new SmiMetaDataPropertyCollection();
EmptyInstance.SetReadOnly();
}
internal SmiMetaDataPropertyCollection() {
_properties = new SmiMetaDataProperty[SelectorCount];
_isReadOnly = false;
_properties[(int)SmiPropertySelector.DefaultFields] = __emptyDefaultFields;
_properties[(int)SmiPropertySelector.SortOrder] = __emptySortOrder;
_properties[(int)SmiPropertySelector.UniqueKey] = __emptyUniqueKey;
}
internal SmiMetaDataProperty this[SmiPropertySelector key] {
get {
return _properties[(int)key];
}
set {
if (null == value) {
throw ADP.InternalError(ADP.InternalErrorCode.InvalidSmiCall);
}
EnsureWritable();
_properties[(int)key] = value;
}
}
internal bool IsReadOnly {
get {
return _isReadOnly;
}
}
internal IEnumerable<SmiMetaDataProperty> Values {
get {
return new List<SmiMetaDataProperty>(_properties);
}
}
// Allow switching to read only, but not back.
internal void SetReadOnly() {
_isReadOnly = true;
}
private void EnsureWritable() {
if (IsReadOnly) {
throw System.Data.Common.ADP.InternalError(System.Data.Common.ADP.InternalErrorCode.InvalidSmiCall);
}
}
}
// Base class for properties
internal abstract class SmiMetaDataProperty {
internal abstract string TraceString();
}
// Property defining a list of column ordinals that define a unique key
internal class SmiUniqueKeyProperty : SmiMetaDataProperty {
private IList<bool> _columns;
internal SmiUniqueKeyProperty(IList<bool> columnIsKey) {
_columns = new List<bool>(columnIsKey).AsReadOnly();
}
// indexed by column ordinal indicating for each column whether it is key or not
internal bool this[int ordinal] {
get {
if (_columns.Count <= ordinal) {
return false;
}
else {
return _columns[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch) {
Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
") not equal to checked size (" + countToMatch + ")" );
}
internal override string TraceString() {
string returnValue = "UniqueKey(";
bool delimit = false;
for (int columnOrd = 0; columnOrd < _columns.Count; columnOrd++) {
if (delimit) {
returnValue += ",";
}
else {
delimit = true;
}
if (_columns[columnOrd]) {
returnValue += columnOrd.ToString(CultureInfo.InvariantCulture);
}
}
returnValue += ")";
return returnValue;
}
}
// Property defining a sort order for a set of columns (by ordinal and ASC/DESC).
internal class SmiOrderProperty : SmiMetaDataProperty {
internal struct SmiColumnOrder {
internal int SortOrdinal;
internal SortOrder Order;
internal string TraceString() {
return String.Format(CultureInfo.InvariantCulture, "{0} {1}", SortOrdinal, Order);
}
}
private IList<SmiColumnOrder> _columns;
internal SmiOrderProperty(IList<SmiColumnOrder> columnOrders) {
_columns = new List<SmiColumnOrder>(columnOrders).AsReadOnly();
}
// Readonly list of the columnorder instances making up the sort order
// order in list indicates precedence
internal SmiColumnOrder this[int ordinal] {
get {
if (_columns.Count <= ordinal) {
SmiColumnOrder order = new SmiColumnOrder();
order.Order = SortOrder.Unspecified;
order.SortOrdinal = -1;
return order;
}
else {
return _columns[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch) {
Debug.Assert(0 == _columns.Count || countToMatch == _columns.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _columns.Count +
") not equal to checked size (" + countToMatch + ")" );
}
internal override string TraceString() {
string returnValue = "SortOrder(";
bool delimit = false;
foreach(SmiColumnOrder columnOrd in _columns) {
if (delimit) {
returnValue += ",";
}
else {
delimit = true;
}
if (System.Data.SqlClient.SortOrder.Unspecified != columnOrd.Order) {
returnValue += columnOrd.TraceString();
}
}
returnValue += ")";
return returnValue;
}
}
// property defining inheritance relationship(s)
internal class SmiDefaultFieldsProperty : SmiMetaDataProperty {
#region private fields
private IList<bool> _defaults;
#endregion
#region internal interface
internal SmiDefaultFieldsProperty(IList<bool> defaultFields) {
_defaults = new List<bool>(defaultFields).AsReadOnly();
}
internal bool this[int ordinal] {
get {
if (_defaults.Count <= ordinal) {
return false;
}
else {
return _defaults[ordinal];
}
}
}
[Conditional("DEBUG")]
internal void CheckCount(int countToMatch) {
Debug.Assert(0 == _defaults.Count || countToMatch == _defaults.Count,
"SmiDefaultFieldsProperty.CheckCount: DefaultFieldsProperty size (" + _defaults.Count +
") not equal to checked size (" + countToMatch + ")" );
}
internal override string TraceString() {
string returnValue = "DefaultFields(";
bool delimit = false;
for(int columnOrd = 0; columnOrd < _defaults.Count; columnOrd++) {
if (delimit) {
returnValue += ",";
}
else {
delimit = true;
}
if (_defaults[columnOrd]) {
returnValue += columnOrd;
}
}
returnValue += ")";
return returnValue;
}
#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.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
namespace System
{
// CONTRACT with Runtime
// The UIntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
[CLSCompliant(false)]
public struct UIntPtr
{
unsafe private void* _value;
[Intrinsic]
public static readonly UIntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(uint value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((uint)value);
#endif
}
[Intrinsic]
[SecurityCritical] // required to match contract
[NonVersionable]
public unsafe UIntPtr(void* value)
{
_value = value;
}
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe uint ToUInt32()
{
#if BIT64
return checked((uint)_value);
#else
return (uint)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe ulong ToUInt64()
{
return (ulong)_value;
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
[Intrinsic]
[SecurityCritical] // required to match contract
[NonVersionable]
public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
[Intrinsic]
[SecurityCritical] // required to match contract
[NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator uint (UIntPtr value)
{
#if BIT64
return checked((uint)value._value);
#else
return (uint)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator ulong (UIntPtr value)
{
return (ulong)value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1._value != value2._value;
}
public static unsafe int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((ulong)_value).ToString(FormatProvider.InvariantCulture);
#else
return ((uint)_value).ToString(FormatProvider.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
return (_value == ((UIntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
namespace System.Net
{
/// <devdoc>
/// <para>
/// An HTTP-specific implementation of the
/// <see cref='System.Net.WebResponse'/> class.
/// </para>
/// </devdoc>
[Serializable]
public class HttpWebResponse : WebResponse, ISerializable
{
private HttpResponseMessage _httpResponseMessage;
private Uri _requestUri;
private CookieCollection _cookies;
private WebHeaderCollection _webHeaderCollection = null;
private string _characterSet = null;
private bool _isVersionHttp11 = true;
public HttpWebResponse() { }
[ObsoleteAttribute("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebResponse(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer cookieContainer)
{
_httpResponseMessage = _message;
_requestUri = requestUri;
// Match Desktop behavior. If the request didn't set a CookieContainer, we don't populate the response's CookieCollection.
if (cookieContainer != null)
{
_cookies = cookieContainer.GetCookies(requestUri);
}
else
{
_cookies = new CookieCollection();
}
}
public override bool IsMutuallyAuthenticated
{
get
{
return base.IsMutuallyAuthenticated;
}
}
public override long ContentLength
{
get
{
CheckDisposed();
long? length = _httpResponseMessage.Content.Headers.ContentLength;
return length.HasValue ? length.Value : -1;
}
}
public override string ContentType
{
get
{
CheckDisposed();
// We use TryGetValues() instead of the strongly type Headers.ContentType property so that
// we return a string regardless of it being fully RFC conformant. This matches current
// .NET Framework behavior.
IEnumerable<string> values;
if (_httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out values))
{
// In most cases, there is only one media type value as per RFC. But for completeness, we
// return all values in cases of overly malformed strings.
var builder = new StringBuilder();
int ndx = 0;
foreach (string value in values)
{
if (ndx > 0)
{
builder.Append(',');
}
builder.Append(value);
ndx++;
}
return builder.ToString();
}
else
{
return string.Empty;
}
}
}
public String ContentEncoding
{
get
{
CheckDisposed();
return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding);
}
}
public virtual CookieCollection Cookies
{
get
{
CheckDisposed();
return _cookies;
}
set
{
CheckDisposed();
_cookies = value;
}
}
public DateTime LastModified
{
get
{
CheckDisposed();
string lastmodHeaderValue = Headers["Last-Modified"];
if (string.IsNullOrEmpty(lastmodHeaderValue))
{
return DateTime.Now;
}
DateTime dtOut;
HttpDateParse.ParseHttpDate(lastmodHeaderValue, out dtOut);
return dtOut;
}
}
/// <devdoc>
/// <para>
/// Gets the name of the server that sent the response.
/// </para>
/// </devdoc>
public string Server
{
get
{
CheckDisposed();
return string.IsNullOrEmpty( Headers["Server"])? string.Empty : Headers["Server"];
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets
/// the version of the HTTP protocol used in the response.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
CheckDisposed();
return _isVersionHttp11 ? HttpVersion.Version11 : HttpVersion.Version10;
}
}
public override WebHeaderCollection Headers
{
get
{
CheckDisposed();
if (_webHeaderCollection == null)
{
_webHeaderCollection = new WebHeaderCollection();
foreach (var header in _httpResponseMessage.Headers)
{
_webHeaderCollection[header.Key] = GetHeaderValueAsString(header.Value);
}
if (_httpResponseMessage.Content != null)
{
foreach (var header in _httpResponseMessage.Content.Headers)
{
_webHeaderCollection[header.Key] = GetHeaderValueAsString(header.Value);
}
}
}
return _webHeaderCollection;
}
}
public virtual string Method
{
get
{
CheckDisposed();
return _httpResponseMessage.RequestMessage.Method.Method;
}
}
public override Uri ResponseUri
{
get
{
CheckDisposed();
// The underlying System.Net.Http API will automatically update
// the .RequestUri property to be the final URI of the response.
return _httpResponseMessage.RequestMessage.RequestUri;
}
}
public virtual HttpStatusCode StatusCode
{
get
{
CheckDisposed();
return _httpResponseMessage.StatusCode;
}
}
public virtual string StatusDescription
{
get
{
CheckDisposed();
return _httpResponseMessage.ReasonPhrase;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CharacterSet
{
get
{
CheckDisposed();
string contentType = Headers["Content-Type"];
if (_characterSet == null && !string.IsNullOrWhiteSpace(contentType))
{
//sets characterset so the branch is never executed again.
_characterSet = String.Empty;
//first string is the media type
string srchString = contentType.ToLower();
//media subtypes of text type has a default as specified by rfc 2616
if (srchString.Trim().StartsWith("text/"))
{
_characterSet = "ISO-8859-1";
}
//one of the parameters may be the character set
//there must be at least a mediatype for this to be valid
int i = srchString.IndexOf(";");
if (i > 0)
{
//search the parameters
while ((i = srchString.IndexOf("charset", i)) >= 0)
{
i += 7;
//make sure the word starts with charset
if (srchString[i - 8] == ';' || srchString[i - 8] == ' ')
{
//skip whitespace
while (i < srchString.Length && srchString[i] == ' ')
i++;
//only process if next character is '='
//and there is a character after that
if (i < srchString.Length - 1 && srchString[i] == '=')
{
i++;
//get and trim character set substring
int j = srchString.IndexOf(';', i);
//In the past we used
//Substring(i, j). J is the offset not the length
//the qfe is to fix the second parameter so that this it is the
//length. since j points to the next ; the operation j -i
//gives the length of the charset
if (j > i)
_characterSet = contentType.Substring(i, j - i).Trim();
else
_characterSet = contentType.Substring(i).Trim();
//done
break;
}
}
}
}
}
return _characterSet;
}
}
public override bool SupportsHeaders
{
get
{
return true;
}
}
public override Stream GetResponseStream()
{
CheckDisposed();
return _httpResponseMessage.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
}
public string GetResponseHeader(string headerName)
{
CheckDisposed();
string headerValue = Headers[headerName];
return ((headerValue == null) ? String.Empty : headerValue);
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
var httpResponseMessage = _httpResponseMessage;
if (httpResponseMessage != null)
{
httpResponseMessage.Dispose();
_httpResponseMessage = null;
}
}
private void CheckDisposed()
{
if (_httpResponseMessage == null)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private string GetHeaderValueAsString(IEnumerable<string> values)
{
// There is always at least one value even if it is an empty string.
var enumerator = values.GetEnumerator();
bool success = enumerator.MoveNext();
Debug.Assert(success, "There should be at least one value");
string headerValue = enumerator.Current;
if (enumerator.MoveNext())
{
// Multi-valued header
var buffer = new StringBuilder(headerValue);
do
{
buffer.Append(", ");
buffer.Append(enumerator.Current);
} while (enumerator.MoveNext());
return buffer.ToString();
}
return headerValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using bv.common.Configuration;
using bv.common.Core;
using DevExpress.XtraPivotGrid;
using eidss.avr.db.AvrEventArgs.DevExpressEventArgsWrappers;
using eidss.model.Avr.Pivot;
using eidss.model.Resources;
namespace eidss.avr.db.Common
{
public class DisplayTextHandler
{
private readonly Dictionary<CustomSummaryType, string> m_GrandTotalCaption;
private readonly Dictionary<CustomSummaryType, string> m_TotalCaption;
private readonly string[] m_MonthValues;
private readonly string[] m_DayOfWeekValues;
private readonly string m_TotalString;
private readonly string m_GrandTotalString;
public DisplayTextHandler()
{
m_TotalString = EidssMessages.Get("msgRamTotal", "Total");
m_GrandTotalString = EidssMessages.Get("msgRamGrandTotal", "Grand Total");
m_GrandTotalCaption = new Dictionary<CustomSummaryType, string>
{
{CustomSummaryType.Average, EidssMessages.Get("msgRamGrandAverage", "Grand Average")},
{CustomSummaryType.Variance, EidssMessages.Get("msgRamGrandVariance", "Grand Variance")},
{CustomSummaryType.StdDev, EidssMessages.Get("msgRamGrandStdDev", "Grand Standard deviation")}
};
m_TotalCaption = new Dictionary<CustomSummaryType, string>
{
{CustomSummaryType.Average, EidssMessages.Get("msgRamAverage", "Average")},
{CustomSummaryType.Variance, EidssMessages.Get("msgRamVariance", "Variance")},
{CustomSummaryType.StdDev, EidssMessages.Get("msgRamStdDev", "Standard deviation")}
};
m_MonthValues = new[]
{
EidssMessages.Get("January", "January"),
EidssMessages.Get("February", "February"),
EidssMessages.Get("March", "March"),
EidssMessages.Get("April", "April"),
EidssMessages.Get("May", "May"),
EidssMessages.Get("June", "June"),
EidssMessages.Get("July", "July"),
EidssMessages.Get("August", "August"),
EidssMessages.Get("September", "September"),
EidssMessages.Get("October", "October`"),
EidssMessages.Get("November", "November"),
EidssMessages.Get("December", "December")
};
m_DayOfWeekValues = new[]
{
EidssMessages.Get("Monday", "Monday"),
EidssMessages.Get("Tuesday", "Tuesday"),
EidssMessages.Get("Wednesday", "Wednesday"),
EidssMessages.Get("Thursday", "Thursday"),
EidssMessages.Get("Friday", "Friday"),
EidssMessages.Get("Saturday", "Saturday"),
EidssMessages.Get("Sunday", "Sunday")
};
}
public void DisplayStatisticsTotalCaption
(BasePivotFieldDisplayTextEventArgs e, List<CustomSummaryType> summaryTypes)
{
if (e.ValueType == PivotGridValueType.Total)
{
if (e.IsColumn)
{
// todo: [ivan] implement correct translation of totals
// string name = (e.Value == null) ? "" : e.Value.ToString();
// e.DisplayText = string.Format("({0}) {1} {2}", e.DisplayText, name, m_TotalString);
}
else
{
string name = (e.Value == null) ? "" : e.Value.ToString();
e.DisplayText = string.Format("{0} {1}", name, GetGrandTotalDisplayText(summaryTypes, false));
}
}
else if (e.ValueType == PivotGridValueType.GrandTotal)
{
if ((e.DataField != null) && (e.DisplayText != e.DataField.Caption) && (!e.IsColumn))
{
e.DisplayText = GetGrandTotalDisplayText(summaryTypes, true);
}
}
}
public string GetGrandTotalDisplayText(IList<CustomSummaryType> types, bool isGrand)
{
if (types.Count == 1)
{
return GetTotalCaption(types[0], isGrand);
}
var typeBuilder = new StringBuilder();
bool isInserted = false;
foreach (CustomSummaryType type in types)
{
if (isInserted)
{
typeBuilder.AppendFormat(" | {0}", GetTotalCaption(type, isGrand));
}
else
{
typeBuilder.Append(GetTotalCaption(type, isGrand));
}
isInserted = true;
}
return typeBuilder.ToString();
}
private string GetTotalCaption(CustomSummaryType type, bool isGrand)
{
string totalCaption = isGrand
? ((m_GrandTotalCaption.ContainsKey(type)) ? m_GrandTotalCaption[type] : m_GrandTotalString)
: ((m_TotalCaption.ContainsKey(type)) ? m_TotalCaption[type] : m_TotalString);
return totalCaption;
}
public void DisplayCellText(BasePivotCellDisplayTextEventArgs e, CustomSummaryType summaryType, int? precision)
{
//format datetime
var interval = e.GroupInterval;
if (e.Value is DateTime)
{
var date = ((DateTime) e.Value);
int formattedResult;
// it's workaround for old devexpress
// probably in devexpress 12 it doesn't needed
if (date.TryToInt(interval, out formattedResult))
{
e.DisplayText = precision.HasValue && precision.Value >= 0
? ValueToString(formattedResult, precision.Value)
: formattedResult.ToString();
return;
}
//
e.DisplayText = date.ToString(interval);
return;
}
bool dontProcessPrecision = false;
//display month or day of the week name
if ((summaryType == CustomSummaryType.Max || summaryType == CustomSummaryType.Min) &&
!e.IsDataFieldNull && e.Value is int)
{
dontProcessPrecision = interval.IsDate();
var value = (int) e.Value;
switch (interval)
{
case PivotGroupInterval.DateMonth:
int monthIndex = value - 1;
if (monthIndex >= 0 && monthIndex < 12)
{
e.DisplayText = m_MonthValues[monthIndex];
return;
}
break;
case PivotGroupInterval.DateDayOfWeek:
int dayIndex = value - 1;
if (dayIndex >= 0 && dayIndex < 7)
{
e.DisplayText = m_DayOfWeekValues[dayIndex];
return;
}
break;
}
}
//// display Asterisk of zero when no value found
if (Utils.IsEmpty(e.Value))
{
if (summaryType != CustomSummaryType.Max && summaryType != CustomSummaryType.Min)
{
e.DisplayText = "0";
}
else if (BaseSettings.ShowAvrAsterisk && Utils.IsEmpty(e.Value))
{
e.DisplayText = BaseSettings.Asterisk;
}
return;
}
if (precision.HasValue && precision.Value >= 0 && !dontProcessPrecision)
{
// display numbers with presision
e.DisplayText = ValueToString(e.Value, precision.Value);
}
}
public static string ValueToString(object value, int precision)
{
if (precision > 16 || precision < 0)
{
throw new ArgumentOutOfRangeException("precision", "Argument should have value from 0 to 16");
}
string format = "N" + precision; //m_NumberFormats[precision]);
if ((value is double) || (value is float))
{
return ((double) value).ToString(format);
}
if (value is decimal)
{
return ((decimal) value).ToString(format);
}
if (value is long)
{
return ((long) value).ToString(format);
}
if (value is int)
{
return ((int) value).ToString(format);
}
return (value == null) ? string.Empty : value.ToString();
}
public void DisplayAsterisk(BasePivotFieldDisplayTextEventArgs e)
{
if (BaseSettings.ShowAvrAsterisk && Utils.IsEmpty(e.DisplayText))
{
e.DisplayText = BaseSettings.Asterisk;
}
}
public void DisplayAsterisk(BasePivotCellDisplayTextEventArgs e)
{
if (BaseSettings.ShowAvrAsterisk && Utils.IsEmpty(e.Value))
{
e.DisplayText = BaseSettings.Asterisk;
}
}
}
}
| |
<head>
<?cs
####### If building devsite, add some meta data needed for when generating the top nav ######### ?>
<?cs
if:devsite ?>
<meta name="top_category" value="<?cs
if:ndk ?>ndk<?cs
elif:(guide||develop||training||reference||tools||sdk||google||reference.gms||reference.gcm||samples) ?>develop<?cs
elif:(topic||libraries||instantapps) ?>develop<?cs
elif:(distribute||googleplay||essentials||users||engage||monetize||disttools||stories||analyze) ?>distribute<?cs
elif:(design||vision||material||patterns||devices||designdownloads) ?>design<?cs
elif:(about||versions||wear||tv||auto) ?>about<?cs
elif:wearpreview ?>about<?cs
elif:work ?>about<?cs
elif:preview ?>preview<?cs
else ?>none<?cs
/if ?>" />
<?cs set:dac_subcategory_set = #1 ?>
<meta name="subcategory" value="<?cs
if:ndk ?><?cs
if:guide ?>guide<?cs
elif:samples ?>samples<?cs
if:(samplesDocPage&&!samplesProjectIndex) ?> samples-docpage<?cs /if ?><?cs
elif:reference ?>reference<?cs
elif:downloads ?>downloads<?cs
else ?>none<?cs set:dac_subcategory_set = #0 ?><?cs /if ?><?cs
else ?><?cs
if:(guide||develop||training||reference||tools||sdk||samples) ?><?cs
if:guide ?>guide<?cs
elif:training ?><?cs
if:page.trainingcourse ?>trainingcourse<?cs
else ?>training<?cs /if ?><?cs
elif:reference ?>reference<?cs
elif:samples ?>samples<?cs
if:(samplesDocPage&&!samplesProjectIndex) ?> samples-docpage<?cs /if ?><?cs
else ?>none<?cs set:dac_subcategory_set = #0 ?><?cs /if ?><?cs
elif:(google||reference.gms||reference.gcm) ?>google<?cs
elif:(topic||libraries) ?><?cs
if:libraries ?>libraries<?cs
elif:instantapps ?>instantapps<?cs
else ?>none<?cs set:dac_subcategory_set = #0 ?><?cs /if ?><?cs
elif:(distribute||googleplay||essentials||users||engage||monetize||disttools||stories||analyze) ?><?cs
if:googleplay ?>googleplay<?cs
elif:essentials ?>essentials<?cs
elif:users ?>users<?cs
elif:engage ?>engage<?cs
elif:monetize ?>monetize<?cs
elif:disttools ?>disttools<?cs
elif:stories ?>stories<?cs
elif:analyze ?>analyze<?cs
else ?>none<?cs set:dac_subcategory_set = #0 ?><?cs /if ?><?cs
elif:(about||versions||wear||tv||auto) ?>about<?cs
elif:preview ?>preview<?cs
elif:wearpreview ?>wear<?cs
elif:work ?>work<?cs
elif:design ?>design<?cs
elif:walkthru ?>walkthru<?cs
else ?>none<?cs set:dac_subcategory_set = #0 ?><?cs /if ?><?cs
/if ?>" />
<?cs if:nonavpage ?>
<meta name="hide_toc" value='True' />
<?cs elif: !nonavpage && dac_subcategory_set && !tools && !sdk ?>
<meta name="book_path" value="<?cs
if:ndk ?>/ndk<?cs
if:guide ?>/guides<?cs
elif:samples ?>/samples<?cs
elif:reference ?>/reference<?cs
elif:downloads ?>/downloads<?cs /if ?><?cs
else ?><?cs
if:(guide||develop||training||reference||tools||sdk||samples) ?><?cs
if:guide ?>/guide<?cs
elif:training ?>/training<?cs
elif:reference ?>/reference<?cs
elif:samples ?>/samples<?cs /if ?><?cs
elif:(google||reference.gms||reference.gcm) ?>/google<?cs
elif:(topic||libraries) ?>/topic<?cs
if:libraries ?>/libraries<?cs
elif:instantapps ?>/instant-apps<?cs /if ?><?cs
elif:(distribute||googleplay||essentials||users||engage||monetize||disttools||stories||analyze) ?>/distribute<?cs
if:googleplay ?>/googleplay<?cs
elif:essentials ?>/essentials<?cs
elif:users ?>/users<?cs
elif:engage ?>/engage<?cs
elif:monetize ?>/monetize<?cs
elif:disttools ?>/disttools<?cs
elif:stories ?>/stories<?cs
elif:analyze ?>/analyze<?cs /if ?><?cs
elif:(about||versions||wear||tv||auto) ?>/about<?cs
elif:preview ?>/preview<?cs
elif:wearpreview ?>/wear/preview<?cs
elif:work ?>/work<?cs
elif:design ?>/design<?cs
elif:reference.testSupport ?>/reference/android/support/test<?cs
elif:reference.wearableSupport ?>/reference/android/support/wearable<?cs
elif:walkthru ?>/walkthru<?cs /if ?><?cs
/if ?>/_book.yaml" />
<?cs /if ?>
<?cs if:page.tags && page.tags != "" ?>
<meta name="keywords" value='<?cs var:page.tags ?>' />
<?cs /if ?>
<?cs if:meta.tags && meta.tags != "" ?>
<meta name="meta_tags" value='<?cs var:meta.tags ?>' />
<?cs /if ?>
<?cs if:fullpage ?>
<meta name="full_width" value="True" />
<?cs /if ?>
<?cs if:page.landing ?>
<meta name="page_type" value="landing" />
<?cs /if ?>
<?cs if:page.article ?>
<meta name="page_type" value="article" />
<?cs /if ?>
<?cs /if ?><?cs
# END if/else devsite ?>
<?cs
if:!devsite ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<link rel="shortcut icon" type="image/x-icon" href="<?cs var:toroot ?>favicon.ico" />
<link rel="alternate" href="http://developer.android.com/<?cs var:path.canonical ?>" hreflang="en" />
<link rel="alternate" href="http://developer.android.com/intl/es/<?cs var:path.canonical ?>" hreflang="es" />
<link rel="alternate" href="http://developer.android.com/intl/id/<?cs var:path.canonical ?>" hreflang="id" />
<link rel="alternate" href="http://developer.android.com/intl/ja/<?cs var:path.canonical ?>" hreflang="ja" />
<link rel="alternate" href="http://developer.android.com/intl/ko/<?cs var:path.canonical ?>" hreflang="ko" />
<link rel="alternate" href="http://developer.android.com/intl/pt-br/<?cs var:path.canonical ?>" hreflang="pt-br" />
<link rel="alternate" href="http://developer.android.com/intl/ru/<?cs var:path.canonical ?>" hreflang="ru" />
<link rel="alternate" href="http://developer.android.com/intl/vi/<?cs var:path.canonical ?>" hreflang="vi" />
<link rel="alternate" href="http://developer.android.com/intl/zh-cn/<?cs var:path.canonical ?>" hreflang="zh-cn" />
<link rel="alternate" href="http://developer.android.com/intl/zh-tw/<?cs var:path.canonical ?>" hreflang="zh-tw" />
<?cs /if ?><?cs
# END if/else !devsite ?>
<title><?cs
if:devsite ?><?cs
if:page.title ?><?cs
var:html_strip(page.title) ?><?cs
else ?>Android Developers<?cs
/if ?><?cs
else ?><?cs
if:page.title ?><?cs
var:page.title ?> | <?cs
/if ?>Android Developers
<?cs /if ?><?cs
# END if/else devsite ?></title>
<?cs
if:page.metaDescription ?>
<meta name="description" content="<?cs var:page.metaDescription ?>"><?cs
/if ?>
<?cs
if:!devsite ?>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="<?cs
if:android.whichdoc != 'online' ?>http:<?cs
/if ?>//fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="<?cs
if:android.whichdoc != 'online' ?>http:<?cs
/if ?>//fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
title="roboto">
<?cs
if:ndk ?><link rel="stylesheet" href="<?cs
if:android.whichdoc != 'online' ?>http:<?cs
/if ?>//fonts.googleapis.com/css?family=Roboto+Mono:400,500,700" title="roboto-mono" type="text/css"><?cs
/if ?>
<link href="<?cs var:toroot ?>assets/css/default.css?v=16" rel="stylesheet" type="text/css">
<!-- JAVASCRIPT -->
<script src="<?cs if:android.whichdoc != 'online' ?>http:<?cs /if ?>//www.google.com/jsapi" type="text/javascript"></script>
<script src="<?cs var:toroot ?>assets/js/android_3p-bundle.js" type="text/javascript"></script><?cs
if:page.customHeadTag ?>
<?cs var:page.customHeadTag ?><?cs
/if ?>
<script type="text/javascript">
var toRoot = "<?cs var:toroot ?>";
var metaTags = [<?cs var:meta.tags ?>];
var devsite = <?cs if:devsite ?>true<?cs else ?>false<?cs /if ?>;
var useUpdatedTemplates = <?cs if:useUpdatedTemplates ?>true<?cs else ?>false<?cs /if ?>;
</script>
<script src="<?cs var:toroot ?>assets/js/docs.js?v=17" type="text/javascript"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-5831155-1', 'android.com');
ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker);
ga('send', 'pageview');
ga('universal.send', 'pageview'); // Send page view for new tracker.
</script>
<?cs /if ?><?cs
# END if/else !devsite ?>
</head>
| |
// 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.Globalization;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using ErrorCode = Interop.NCrypt.ErrorCode;
namespace Internal.Cryptography
{
internal static class Helpers
{
public static byte[] CloneByteArray(this byte[] src)
{
if (src == null)
{
return null;
}
return (byte[])(src.Clone());
}
//
// The C# construct
//
// fixed (byte* p = new byte[0])
//
// sets "p" to 0 rather than a valid address. Sometimes, we actually want a non-NULL pointer instead. (Some CNG apis actually care whether the buffer pointer is
// NULL or not, even if the accompanying size argument is 0.)
//
// This helper enables the syntax:
//
// fixed (byte* p = new byte[0].MapZeroLengthArrayToNonNullPointer())
//
// which always sets "p" to a non-NULL pointer for a non-null byte array.
//
public static byte[] MapZeroLengthArrayToNonNullPointer(this byte[] src)
{
if (src != null && src.Length == 0)
return new byte[1];
return src;
}
public static CryptographicException ToCryptographicException(this ErrorCode errorCode)
{
return ((int)errorCode).ToCryptographicException();
}
public static SafeNCryptProviderHandle OpenStorageProvider(this CngProvider provider)
{
string providerName = provider.Provider;
SafeNCryptProviderHandle providerHandle;
ErrorCode errorCode = Interop.NCrypt.NCryptOpenStorageProvider(out providerHandle, providerName, 0);
if (errorCode != ErrorCode.ERROR_SUCCESS)
throw errorCode.ToCryptographicException();
return providerHandle;
}
/// <summary>
/// Returns a CNG key property.
/// </summary>
/// <returns>
/// null - if property not defined on key.
/// throws - for any other type of error.
/// </returns>
public static byte[] GetProperty(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
unsafe
{
int numBytesNeeded;
ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, null, 0, out numBytesNeeded, options);
if (errorCode == ErrorCode.NTE_NOT_FOUND)
return null;
if (errorCode != ErrorCode.ERROR_SUCCESS)
throw errorCode.ToCryptographicException();
byte[] propertyValue = new byte[numBytesNeeded];
fixed (byte* pPropertyValue = propertyValue)
{
errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, pPropertyValue, propertyValue.Length, out numBytesNeeded, options);
}
if (errorCode == ErrorCode.NTE_NOT_FOUND)
return null;
if (errorCode != ErrorCode.ERROR_SUCCESS)
throw errorCode.ToCryptographicException();
Array.Resize(ref propertyValue, numBytesNeeded);
return propertyValue;
}
}
/// <summary>
/// Retrieve a well-known CNG string property. (Note: desktop compat: this helper likes to return special values rather than throw exceptions for missing
/// or ill-formatted property values. Only use it for well-known properties that are unlikely to be ill-formatted.)
/// </summary>
public static string GetPropertyAsString(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
byte[] value = ncryptHandle.GetProperty(propertyName, options);
if (value == null)
return null; // Desktop compat: return null if key not present.
if (value.Length == 0)
return string.Empty; // Desktop compat: return empty if property value is 0-length.
unsafe
{
fixed (byte* pValue = value)
{
string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue);
return valueAsString;
}
}
}
/// <summary>
/// Retrieve a well-known CNG dword property. (Note: desktop compat: this helper likes to return special values rather than throw exceptions for missing
/// or ill-formatted property values. Only use it for well-known properties that are unlikely to be ill-formatted.)
/// </summary>
public static int GetPropertyAsDword(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
byte[] value = ncryptHandle.GetProperty(propertyName, options);
if (value == null)
return 0; // Desktop compat: return 0 if key not present.
return BitConverter.ToInt32(value, 0);
}
/// <summary>
/// Retrieve a well-known CNG pointer property. (Note: desktop compat: this helper likes to return special values rather than throw exceptions for missing
/// or ill-formatted property values. Only use it for well-known properties that are unlikely to be ill-formatted.)
/// </summary>
public static IntPtr GetPropertyAsIntPtr(this SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options)
{
unsafe
{
int numBytesNeeded;
IntPtr value;
ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, &value, IntPtr.Size, out numBytesNeeded, options);
if (errorCode == ErrorCode.NTE_NOT_FOUND)
return IntPtr.Zero;
if (errorCode != ErrorCode.ERROR_SUCCESS)
throw errorCode.ToCryptographicException();
return value;
}
}
/// <summary>
/// Modify a CNG key's export policy.
/// </summary>
public static void SetExportPolicy(this SafeNCryptKeyHandle keyHandle, CngExportPolicies exportPolicy)
{
unsafe
{
ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty(keyHandle, KeyPropertyName.ExportPolicy, &exportPolicy, sizeof(CngExportPolicies), CngPropertyOptions.Persist);
if (errorCode != ErrorCode.ERROR_SUCCESS)
throw errorCode.ToCryptographicException();
}
}
public static bool IsLegalSize(this int size, KeySizes[] legalSizes)
{
for (int i = 0; i < legalSizes.Length; i++)
{
// If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
if (legalSizes[i].SkipSize == 0)
{
if (legalSizes[i].MinSize == size)
return true;
}
else
{
for (int j = legalSizes[i].MinSize; j <= legalSizes[i].MaxSize; j += legalSizes[i].SkipSize)
{
if (j == size)
return true;
}
}
}
return false;
}
public static int BitSizeToByteSize(this int bits)
{
return (bits + 7) / 8;
}
public static byte[] GenerateRandom(int count)
{
byte[] buffer = new byte[count];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(buffer);
}
return buffer;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Elasticsearch.Net.Serialization;
using Nest.Resolvers;
using Newtonsoft.Json;
namespace Nest
{
public class NestSerializer : INestSerializer
{
private readonly IConnectionSettingsValues _settings;
private readonly JsonSerializerSettings _serializationSettings;
private readonly ElasticInferrer _infer;
public NestSerializer(IConnectionSettingsValues settings)
{
this._settings = settings;
this._serializationSettings = this.CreateSettings();
this._infer = new ElasticInferrer(this._settings);
}
public virtual byte[] Serialize(object data, SerializationFormatting formatting = SerializationFormatting.Indented)
{
var format = formatting == SerializationFormatting.None ? Formatting.None : Formatting.Indented;
var serialized = JsonConvert.SerializeObject(data, format, this._serializationSettings);
return serialized.Utf8Bytes();
}
public string Stringify(object valueType)
{
if (valueType == null)
return null;
var s = valueType as string;
if (s != null)
return s;
var ss = valueType as string[];
if (ss != null)
return string.Join(",", ss);
var pns = valueType as IEnumerable<object>;
if (pns != null)
return string.Join(",", pns.Select(
oo =>
{
if (oo is PropertyNameMarker)
return this._infer.PropertyName(oo as PropertyNameMarker);
if (oo is PropertyPathMarker)
return this._infer.PropertyPath(oo as PropertyPathMarker);
return oo.ToString();
})
);
var e = valueType as Enum;
if (e != null) return KnownEnums.Resolve(e);
if (valueType is bool)
return ((bool)valueType) ? "true" : "false";
var pn = valueType as PropertyNameMarker;
if (pn != null)
return this._infer.PropertyName(pn);
var pp = valueType as PropertyPathMarker;
if (pp != null)
return this._infer.PropertyPath(pp);
return valueType.ToString();
}
/// <summary>
/// Deserialize an object
/// </summary>
/// <typeparam name="T">The type you want to deserialize too</typeparam>
/// <param name="stream">The stream to deserialize off</param>
public virtual T Deserialize<T>(Stream stream)
{
if (stream == null) return default(T);
var settings = this._serializationSettings;
return DeserializeUsingSettings<T>(stream, settings);
}
/// <summary>
/// Deserialize to type T bypassing checks for custom deserialization state and or BaseResponse return types.
/// </summary>
public T DeserializeInternal<T>(Stream stream, JsonConverter converter)
{
if (stream == null) return default(T);
if (converter == null) return this.Deserialize<T>(stream);
var settings = this.CreateSettings(converter);
return DeserializeUsingSettings<T>(stream, settings);
}
private T DeserializeUsingSettings<T>(Stream stream, JsonSerializerSettings settings = null)
{
if (stream == null) return default(T);
settings = settings ?? _serializationSettings;
var serializer = JsonSerializer.Create(settings);
var jsonTextReader = new JsonTextReader(new StreamReader(stream));
var t = (T)serializer.Deserialize(jsonTextReader, typeof(T));
return t;
}
public virtual Task<T> DeserializeAsync<T>(Stream stream)
{
//TODO sadly json .net async does not read the stream async so
//figure out wheter reading the stream async on our own might be beneficial
//over memory possible memory usage
var tcs = new TaskCompletionSource<T>();
if (stream == null)
{
tcs.SetResult(default(T));
return tcs.Task;
}
var r = this.Deserialize<T>(stream);
tcs.SetResult(r);
return tcs.Task;
}
internal JsonSerializerSettings CreateSettings(JsonConverter piggyBackJsonConverter = null)
{
var piggyBackState = new JsonConverterPiggyBackState { ActualJsonConverter = piggyBackJsonConverter };
var settings = new JsonSerializerSettings()
{
ContractResolver = new ElasticContractResolver(this._settings),
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Ignore
};
if (_settings.ModifyJsonSerializerSettings != null)
_settings.ModifyJsonSerializerSettings(settings);
settings.ContractResolver = new SettingsContractResolver(settings.ContractResolver, this._settings) { PiggyBackState = piggyBackState };
return settings;
}
public string SerializeBulkDescriptor(IBulkRequest bulkRequest)
{
bulkRequest.ThrowIfNull("bulkRequest");
bulkRequest.Operations.ThrowIfEmpty("Bulk request does not define any operations");
var sb = new StringBuilder();
var inferrer = new ElasticInferrer(this._settings);
foreach (var operation in bulkRequest.Operations)
{
var command = operation.Operation;
var index = operation.Index
?? inferrer.IndexName(bulkRequest.Index)
?? inferrer.IndexName(operation.ClrType);
var typeName = operation.Type
?? inferrer.TypeName(bulkRequest.Type)
?? inferrer.TypeName(operation.ClrType);
var id = operation.GetIdForOperation(inferrer);
if (index.EqualsMarker(bulkRequest.Index))
{
operation.Index = null;
}
else
{
operation.Index = index;
}
operation.Type = typeName;
operation.Id = id;
var opJson = this.Serialize(operation, SerializationFormatting.None).Utf8String();
var action = "{{ \"{0}\" : {1} }}\n".F(command, opJson);
sb.Append(action);
var body = operation.GetBody();
if (body == null)
continue;
var jsonCommand = this.Serialize(body, SerializationFormatting.None).Utf8String();
sb.Append(jsonCommand + "\n");
}
var json = sb.ToString();
return json;
}
private class PercolateHeader
{
public IndexNameMarker index { get; set; }
public TypeNameMarker type { get; set; }
public string id { get; set; }
public string percolate_index { get; set; }
public string percolate_type { get; set; }
public string[] routing { get; set; }
public string preference { get; set; }
public string percolate_routing { get; set; }
public string percolate_preference { get; set; }
public long? version { get; set; }
}
public string SerializeMultiPercolate(IMultiPercolateRequest multiPercolateRequest)
{
multiPercolateRequest.ThrowIfNull("multiPercolateRequest");
multiPercolateRequest.Percolations.ThrowIfEmpty("multiPercolateRequest does not define any percolations");
var sb = new StringBuilder();
foreach (var p in multiPercolateRequest.Percolations)
{
var operation = "percolate";
object body = p;
var op = new PercolateHeader();
var countParams = p.GetRequestParameters() ?? new PercolateCountRequestParameters();
op.percolate_index = countParams.GetQueryStringValue<string>("percolate_index");
op.percolate_type = countParams.GetQueryStringValue<string>("percolate_type");
op.routing = countParams.GetQueryStringValue<string[]>("routing");
op.preference = countParams.GetQueryStringValue<string>("preference");
op.percolate_routing = countParams.GetQueryStringValue<string>("percolate_routing");
op.percolate_preference = countParams.GetQueryStringValue<string>("percolate_preference");
op.version = countParams.GetQueryStringValue<long?>("version");
var count = p as IIndexTypePath<PercolateCountRequestParameters>;
var percolate = p as IIndexTypePath<PercolateRequestParameters>;
if (count != null)
{
operation = "count";
if (multiPercolateRequest.Index != null && multiPercolateRequest.Index.EqualsMarker(count.Index))
{
count.Index = null;
}
op.index = count.Index;
op.type = count.Type;
op.id = p.Id;
}
else if (percolate != null)
{
if (multiPercolateRequest.Index != null && multiPercolateRequest.Index.EqualsMarker(percolate.Index))
{
percolate.Index = null;
}
op.index = percolate.Index;
op.type = percolate.Type;
op.id = p.Id;
}
else continue;
var opJson = this.Serialize(op, SerializationFormatting.None).Utf8String();
var action = "{{\"{0}\":{1}}}\n".F(operation, opJson);
sb.Append(action);
if (body == null)
{
sb.Append("{}\n");
continue;
}
var jsonCommand = this.Serialize(body, SerializationFormatting.None).Utf8String();
sb.Append(jsonCommand + "\n");
}
return sb.ToString();
}
/// <summary>
/// _msearch needs a specialized json format in the body
/// </summary>
public string SerializeMultiSearch(IMultiSearchRequest multiSearchRequest)
{
var sb = new StringBuilder();
var inferrer = new ElasticInferrer(this._settings);
var indexName = inferrer.IndexName(multiSearchRequest.Index);
foreach (var operation in multiSearchRequest.Operations.Values)
{
var path = operation.ToPathInfo(this._settings);
if (path.Index == indexName)
{
path.Index = null;
}
var op = new
{
index = path.Index,
type = path.Type,
search_type = this.GetSearchType(operation, multiSearchRequest),
preference = operation.Preference,
routing = operation.Routing,
ignore_unavailable = operation.IgnoreUnavalable
};
var opJson = this.Serialize(op, SerializationFormatting.None).Utf8String();
var action = "{0}\n".F(opJson);
sb.Append(action);
var searchJson = this.Serialize(operation, SerializationFormatting.None).Utf8String();
sb.Append(searchJson + "\n");
}
var json = sb.ToString();
return json;
}
protected string GetSearchType(ISearchRequest descriptor, IMultiSearchRequest multiSearchRequest)
{
if (descriptor.SearchType != null)
{
return descriptor.SearchType.Value.GetStringValue();
}
return multiSearchRequest.RequestParameters.GetQueryStringValue<string>("search_type");
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_TASKS
using System.Threading.Tasks;
#endif
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security;
using System.Threading;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
namespace Microsoft.Scripting.Interpreter {
public sealed class LightLambdaCompileEventArgs : EventArgs {
public Delegate Compiled { get; private set; }
internal LightLambdaCompileEventArgs(Delegate compiled) {
Compiled = compiled;
}
}
public partial class LightLambda {
private readonly StrongBox<object>[] _closure;
private readonly Interpreter _interpreter;
private static readonly CacheDict<Type, Func<LightLambda, Delegate>> _runCache = new CacheDict<Type, Func<LightLambda, Delegate>>(100);
// Adaptive compilation support
private readonly LightDelegateCreator _delegateCreator;
private Delegate _compiled;
private int _compilationThreshold;
/// <summary>
/// Provides notification that the LightLambda has been compiled.
/// </summary>
public event EventHandler<LightLambdaCompileEventArgs> Compile;
internal LightLambda(LightDelegateCreator delegateCreator, StrongBox<object>[] closure, int compilationThreshold) {
_delegateCreator = delegateCreator;
_closure = closure;
_interpreter = delegateCreator.Interpreter;
_compilationThreshold = compilationThreshold;
}
private static Func<LightLambda, Delegate> GetRunDelegateCtor(Type delegateType) {
lock (_runCache) {
Func<LightLambda, Delegate> fastCtor;
if (_runCache.TryGetValue(delegateType, out fastCtor)) {
return fastCtor;
}
return MakeRunDelegateCtor(delegateType);
}
}
private static Func<LightLambda, Delegate> MakeRunDelegateCtor(Type delegateType) {
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
Type[] paramTypes;
string name = "Run";
if (paramInfos.Length >= MaxParameters) {
return null;
}
if (method.ReturnType == typeof(void)) {
name += "Void";
paramTypes = new Type[paramInfos.Length];
} else {
paramTypes = new Type[paramInfos.Length + 1];
paramTypes[paramTypes.Length - 1] = method.ReturnType;
}
MethodInfo runMethod;
if (method.ReturnType == typeof(void) && paramTypes.Length == 2 &&
paramInfos[0].ParameterType.IsByRef && paramInfos[1].ParameterType.IsByRef) {
runMethod = typeof(LightLambda).GetMethod("RunVoidRef2", BindingFlags.NonPublic | BindingFlags.Instance);
paramTypes[0] = paramInfos[0].ParameterType.GetElementType();
paramTypes[1] = paramInfos[1].ParameterType.GetElementType();
} else if (method.ReturnType == typeof(void) && paramTypes.Length == 0) {
runMethod = typeof(LightLambda).GetMethod("RunVoid0", BindingFlags.NonPublic | BindingFlags.Instance);
} else {
for (int i = 0; i < paramInfos.Length; i++) {
paramTypes[i] = paramInfos[i].ParameterType;
if (paramTypes[i].IsByRef) {
return null;
}
}
if (DelegateHelpers.MakeDelegate(paramTypes) == delegateType) {
name = "Make" + name + paramInfos.Length;
MethodInfo ctorMethod = typeof(LightLambda).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(paramTypes);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)ctorMethod.CreateDelegate(typeof(Func<LightLambda, Delegate>));
}
runMethod = typeof(LightLambda).GetMethod(name + paramInfos.Length, BindingFlags.NonPublic | BindingFlags.Instance);
}
#if FEATURE_LCG && !SILVERLIGHT && !WP75
try {
DynamicMethod dm = new DynamicMethod("FastCtor", typeof(Delegate), new[] { typeof(LightLambda) }, typeof(LightLambda), true);
var ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldftn, runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod);
ilgen.Emit(OpCodes.Newobj, delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
ilgen.Emit(OpCodes.Ret);
return _runCache[delegateType] = (Func<LightLambda, Delegate>)dm.CreateDelegate(typeof(Func<LightLambda, Delegate>));
} catch (SecurityException) {
}
#endif
// we don't have permission for restricted skip visibility dynamic methods, use the slower Delegate.CreateDelegate.
var targetMethod = runMethod.IsGenericMethodDefinition ? runMethod.MakeGenericMethod(paramTypes) : runMethod;
return _runCache[delegateType] = lambda => targetMethod.CreateDelegate(delegateType, lambda);
}
//TODO enable sharing of these custom delegates
private Delegate CreateCustomDelegate(Type delegateType) {
PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Synchronously compiling a custom delegate");
var method = delegateType.GetMethod("Invoke");
var paramInfos = method.GetParameters();
var parameters = new ParameterExpression[paramInfos.Length];
var parametersAsObject = new Expression[paramInfos.Length];
for (int i = 0; i < paramInfos.Length; i++) {
ParameterExpression parameter = Expression.Parameter(paramInfos[i].ParameterType, paramInfos[i].Name);
parameters[i] = parameter;
parametersAsObject[i] = Expression.Convert(parameter, typeof(object));
}
var data = Expression.NewArrayInit(typeof(object), parametersAsObject);
var self = AstUtils.Constant(this);
var runMethod = typeof(LightLambda).GetMethod("Run");
var body = Expression.Convert(Expression.Call(self, runMethod, data), method.ReturnType);
var lambda = Expression.Lambda(delegateType, body, parameters);
return lambda.Compile();
}
internal Delegate MakeDelegate(Type delegateType) {
Func<LightLambda, Delegate> fastCtor = GetRunDelegateCtor(delegateType);
if (fastCtor != null) {
return fastCtor(this);
} else {
return CreateCustomDelegate(delegateType);
}
}
private bool TryGetCompiled() {
// Use the compiled delegate if available.
if (_delegateCreator.HasCompiled) {
_compiled = _delegateCreator.CreateCompiledDelegate(_closure);
// Send it to anyone who's interested.
var compileEvent = Compile;
if (compileEvent != null && _delegateCreator.SameDelegateType) {
compileEvent(this, new LightLambdaCompileEventArgs(_compiled));
}
return true;
}
// Don't lock here, it's a frequently hit path.
//
// There could be multiple threads racing, but that is okay.
// Two bad things can happen:
// * We miss decrements (some thread sets the counter forward)
// * We might enter the "if" branch more than once.
//
// The first is okay, it just means we take longer to compile.
// The second we explicitly guard against inside of Compile().
//
// We can't miss 0. The first thread that writes -1 must have read 0 and hence start compilation.
if (unchecked(_compilationThreshold--) == 0) {
#if SILVERLIGHT
if (PlatformAdaptationLayer.IsCompactFramework) {
_compilationThreshold = Int32.MaxValue;
return false;
}
#endif
if (_interpreter.CompileSynchronously) {
_delegateCreator.Compile(null);
return TryGetCompiled();
} else {
// Kick off the compile on another thread so this one can keep going
#if FEATURE_TASKS
new Task(_delegateCreator.Compile, null).Start();
#else
ThreadPool.QueueUserWorkItem(_delegateCreator.Compile, null);
#endif
}
}
return false;
}
private InterpretedFrame MakeFrame() {
return new InterpretedFrame(_interpreter, _closure);
}
internal void RunVoidRef2<T0, T1>(ref T0 arg0, ref T1 arg1) {
if (_compiled != null || TryGetCompiled()) {
((ActionRef<T0, T1>)_compiled)(ref arg0, ref arg1);
return;
}
// copy in and copy out for today...
var frame = MakeFrame();
frame.Data[0] = arg0;
frame.Data[1] = arg1;
var currentFrame = frame.Enter();
try {
_interpreter.Run(frame);
} finally {
frame.Leave(currentFrame);
arg0 = (T0)frame.Data[0];
arg1 = (T1)frame.Data[1];
}
}
public object Run(params object[] arguments) {
if (_compiled != null || TryGetCompiled()) {
try {
return _compiled.DynamicInvoke(arguments);
} catch (TargetInvocationException e) {
throw ExceptionHelpers.UpdateForRethrow(e.InnerException);
}
}
var frame = MakeFrame();
for (int i = 0; i < arguments.Length; i++) {
frame.Data[i] = arguments[i];
}
var currentFrame = frame.Enter();
try {
_interpreter.Run(frame);
} finally {
frame.Leave(currentFrame);
}
return frame.Pop();
}
}
}
| |
//
// TrackEditorDialog.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// 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 Mono.Addins;
using Gtk;
using Hyena.Gui;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.Kernel;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration.Schema;
using Banshee.Widgets;
using Banshee.Gui.Dialogs;
using Banshee.Collection.Gui;
namespace Banshee.Gui.TrackEditor
{
public class TrackEditorDialog : BansheeDialog
{
public delegate void EditorTrackOperationClosure (EditorTrackInfo track);
private VBox main_vbox;
private Frame header_image_frame;
private Image header_image;
private Label header_title_label;
private Label header_artist_label;
private Label header_album_label;
private Label edit_notif_label;
private object tooltip_host;
private DateTime dialog_launch_datetime = DateTime.Now;
private Notebook notebook;
public Notebook Notebook {
get { return notebook; }
}
private Button nav_backward_button;
private Button nav_forward_button;
private PulsingButton sync_all_button;
private EditorMode mode;
internal EditorMode Mode {
get { return mode; }
}
private bool readonly_tabs = false;
private List<ITrackEditorPage> pages = new List<ITrackEditorPage> ();
public event EventHandler Navigated;
private TrackEditorDialog (TrackListModel model, EditorMode mode)
: this (model, mode, false)
{
}
private TrackEditorDialog (TrackListModel model, EditorMode mode, bool readonlyTabs) : base (
mode == EditorMode.Edit ? Catalog.GetString ("Track Editor") : Catalog.GetString ("Track Properties"))
{
readonly_tabs = readonlyTabs;
this.mode = mode;
LoadTrackModel (model);
if (mode == EditorMode.Edit || readonly_tabs) {
WidthRequest = 525;
if (mode == EditorMode.Edit) {
AddStockButton (Stock.Cancel, ResponseType.Cancel);
AddStockButton (Stock.Save, ResponseType.Ok);
}
} else {
SetSizeRequest (400, 500);
}
if (mode == EditorMode.View) {
AddStockButton (Stock.Close, ResponseType.Close, true);
}
tooltip_host = TooltipSetter.CreateHost ();
AddNavigationButtons ();
main_vbox = new VBox ();
main_vbox.Spacing = 12;
main_vbox.BorderWidth = 0;
main_vbox.Show ();
VBox.PackStart (main_vbox, true, true, 0);
BuildHeader ();
BuildNotebook ();
BuildFooter ();
LoadModifiers ();
LoadTrackToEditor ();
}
#region UI Building
private void AddNavigationButtons ()
{
if (TrackCount <= 1) {
return;
}
nav_backward_button = new Button (Stock.GoBack);
nav_backward_button.UseStock = true;
nav_backward_button.Clicked += delegate { NavigateBackward (); };
nav_backward_button.Show ();
TooltipSetter.Set (tooltip_host, nav_backward_button, Catalog.GetString ("Show the previous track"));
nav_forward_button = new Button (Stock.GoForward);
nav_forward_button.UseStock = true;
nav_forward_button.Clicked += delegate { NavigateForward (); };
nav_forward_button.Show ();
TooltipSetter.Set (tooltip_host, nav_forward_button, Catalog.GetString ("Show the next track"));
ActionArea.PackStart (nav_backward_button, false, false, 0);
ActionArea.PackStart (nav_forward_button, false, false, 0);
ActionArea.SetChildSecondary (nav_backward_button, true);
ActionArea.SetChildSecondary (nav_forward_button, true);
}
private void BuildHeader ()
{
Table header = new Table (3, 3, false);
header.ColumnSpacing = 5;
header_image_frame = new Frame ();
header_image = new Image ();
header_image.IconName = "media-optical";
header_image.PixelSize = 64;
header_image_frame.Add (
CoverArtEditor.For (header_image,
(x, y) => true,
() => CurrentTrack,
() => LoadCoverArt (CurrentTrack)
)
);
header.Attach (header_image_frame, 0, 1, 0, 3,
AttachOptions.Fill, AttachOptions.Expand, 0, 0);
AddHeaderRow (header, 0, Catalog.GetString ("Title:"), out header_title_label);
AddHeaderRow (header, 1, Catalog.GetString ("Artist:"), out header_artist_label);
AddHeaderRow (header, 2, Catalog.GetString ("Album:"), out header_album_label);
header.ShowAll ();
main_vbox.PackStart (header, false, false, 0);
}
private TrackInfo CurrentTrack {
get { return TrackCount == 0 ? null : GetTrack (CurrentTrackIndex); }
}
private void AddHeaderRow (Table header, uint row, string title, out Label label)
{
Label title_label = new Label ();
title_label.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (title));
title_label.Xalign = 0.0f;
header.Attach (title_label, 1, 2, row, row + 1,
AttachOptions.Fill, AttachOptions.Expand, 0, 0);
label = new Label ();
label.Xalign = 0.0f;
label.Ellipsize = Pango.EllipsizeMode.End;
header.Attach (label, 2, 3, row, row + 1,
AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Expand, 0, 0);
}
private void BuildNotebook ()
{
notebook = new Notebook ();
notebook.Show ();
Gtk.Widget page_to_focus = null;
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/NotebookPage")) {
try {
ITrackEditorPage page = (ITrackEditorPage)node.CreateInstance ();
bool show = false;
if (mode == EditorMode.Edit && (page.PageType != PageType.ViewOnly)) {
show = true;
} else if (mode == EditorMode.View) {
if (readonly_tabs) {
show = page.PageType != PageType.EditOnly;
} else {
show = page.PageType == PageType.View || page.PageType == PageType.ViewOnly;
}
}
if (show) {
if (page is StatisticsPage && mode == EditorMode.View) {
page_to_focus = (StatisticsPage)page;
}
pages.Add (page);
page.Initialize (this);
page.Widget.Show ();
}
} catch (Exception e) {
Hyena.Log.Exception ("Failed to initialize NotebookPage extension node. Ensure it implements ITrackEditorPage.", e);
}
}
pages.Sort (delegate (ITrackEditorPage a, ITrackEditorPage b) { return a.Order.CompareTo (b.Order); });
foreach (ITrackEditorPage page in pages) {
Container container = page.Widget as Container;
if (container == null) {
VBox box = new VBox ();
box.PackStart (page.Widget, true, true, 0);
container = box;
}
container.BorderWidth = 12;
notebook.AppendPage (container, page.TabWidget == null ? new Label (page.Title) : page.TabWidget);
}
main_vbox.PackStart (notebook, true, true, 0);
if (page_to_focus != null) {
notebook.CurrentPage = notebook.PageNum (page_to_focus);
}
}
private void BuildFooter ()
{
if (mode == EditorMode.View || TrackCount < 2) {
return;
}
HBox button_box = new HBox ();
button_box.Spacing = 6;
if (TrackCount > 1) {
sync_all_button = new PulsingButton ();
sync_all_button.FocusInEvent += delegate {
ForeachWidget<SyncButton> (delegate (SyncButton button) {
button.StartPulsing ();
});
};
sync_all_button.FocusOutEvent += delegate {
if (sync_all_button.State == StateType.Prelight) {
return;
}
ForeachWidget<SyncButton> (delegate (SyncButton button) {
button.StopPulsing ();
});
};
sync_all_button.StateChanged += delegate {
if (sync_all_button.HasFocus) {
return;
}
ForeachWidget<SyncButton> (delegate (SyncButton button) {
if (sync_all_button.State == StateType.Prelight) {
button.StartPulsing ();
} else {
button.StopPulsing ();
}
});
};
sync_all_button.Clicked += delegate {
InvokeFieldSync ();
};
Alignment alignment = new Alignment (0.5f, 0.5f, 0.0f, 0.0f);
HBox box = new HBox ();
box.Spacing = 2;
box.PackStart (new Image (Stock.Copy, IconSize.Button), false, false, 0);
box.PackStart (new Label (Catalog.GetString ("Sync all field _values")), false, false, 0);
alignment.Add (box);
sync_all_button.Add (alignment);
TooltipSetter.Set (tooltip_host, sync_all_button, Catalog.GetString (
"Apply the values of all common fields set for this track to all of the tracks selected in this editor"));
button_box.PackStart (sync_all_button, false, false, 0);
foreach (Widget child in ActionArea.Children) {
child.SizeAllocated += OnActionAreaChildSizeAllocated;
}
edit_notif_label = new Label ();
edit_notif_label.Xalign = 1.0f;
button_box.PackEnd (edit_notif_label, false, false, 0);
}
main_vbox.PackStart (button_box, false, false, 0);
button_box.ShowAll ();
}
private void LoadModifiers ()
{
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/Modifier")) {
try {
ITrackEditorModifier mod = (ITrackEditorModifier)node.CreateInstance ();
mod.Modify (this);
} catch (Exception e) {
Hyena.Log.Exception ("Failed to initialize TrackEditor/Modifier extension node. Ensure it implements ITrackEditorModifier.", e);
}
}
}
public void ForeachWidget<T> (WidgetAction<T> action) where T : class
{
for (int i = 0; i < notebook.NPages; i++) {
GtkUtilities.ForeachWidget (notebook.GetNthPage (i) as Container, action);
}
}
private void InvokeFieldSync ()
{
for (int i = 0; i < notebook.NPages; i++) {
var field_page = notebook.GetNthPage (i) as FieldPage;
if (field_page != null) {
foreach (var slot in field_page.FieldSlots) {
if (slot.Sync != null && (slot.SyncButton == null || slot.SyncButton.Sensitive)) {
slot.Sync ();
}
}
}
}
}
private int action_area_children_allocated = 0;
private void OnActionAreaChildSizeAllocated (object o, SizeAllocatedArgs args)
{
Widget [] children = ActionArea.Children;
if (++action_area_children_allocated != children.Length) {
return;
}
sync_all_button.WidthRequest = Math.Max (sync_all_button.Allocation.Width,
(children[1].Allocation.X + children[1].Allocation.Width) - children[0].Allocation.X - 1);
}
#endregion
#region Track Model/Changes API
private CachedList<DatabaseTrackInfo> db_selection;
private List<TrackInfo> memory_selection;
private Dictionary<TrackInfo, EditorTrackInfo> edit_map = new Dictionary<TrackInfo, EditorTrackInfo> ();
private int current_track_index;
protected void LoadTrackModel (TrackListModel model)
{
DatabaseTrackListModel db_model = model as DatabaseTrackListModel;
if (db_model != null) {
db_selection = CachedList<DatabaseTrackInfo>.CreateFromModelSelection (db_model);
} else {
memory_selection = new List<TrackInfo> ();
foreach (TrackInfo track in model.SelectedItems) {
memory_selection.Add (track);
}
}
}
public void LoadTrackToEditor ()
{
TrackInfo current_track = null;
EditorTrackInfo editor_track = LoadTrack (current_track_index, out current_track);
if (editor_track == null) {
return;
}
// Update the Header
header_title_label.Text = current_track.DisplayTrackTitle;
header_artist_label.Text = current_track.DisplayArtistName;
header_album_label.Text = current_track.DisplayAlbumTitle;
if (edit_notif_label != null) {
edit_notif_label.Markup = String.Format (Catalog.GetString ("<i>Editing {0} of {1} items</i>"),
CurrentTrackIndex + 1, TrackCount);
}
LoadCoverArt (current_track);
// Disconnect all the undo adapters
ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) {
undoable.DisconnectUndo ();
});
foreach (ITrackEditorPage page in pages) {
page.LoadTrack (editor_track);
}
// Connect all the undo adapters
ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) {
undoable.ConnectUndo (editor_track);
});
// Update Navigation
if (TrackCount > 0 && nav_backward_button != null && nav_forward_button != null) {
nav_backward_button.Sensitive = CanGoBackward;
nav_forward_button.Sensitive = CanGoForward;
}
// If there was a widget focused already (eg the Title entry), GrabFocus on it,
// which causes its text to be selected, ready for editing.
Widget child = FocusChild;
while (child != null) {
Container container = child as Container;
if (container != null) {
child = container.FocusChild;
} else if (child != null) {
child.GrabFocus ();
child = null;
}
}
}
private void LoadCoverArt (TrackInfo current_track)
{
if (current_track == null)
return;
var artwork = ServiceManager.Get<ArtworkManager> ();
var cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64);
header_image.Clear ();
header_image.Pixbuf = cover_art;
if (cover_art == null) {
header_image.IconName = "media-optical";
header_image.PixelSize = 64;
header_image_frame.ShadowType = ShadowType.None;
} else {
header_image_frame.ShadowType = ShadowType.In;
}
header_image.QueueDraw ();
}
public void ForeachNonCurrentTrack (EditorTrackOperationClosure closure)
{
for (int i = 0; i < TrackCount; i++) {
if (i == current_track_index) {
continue;
}
EditorTrackInfo track = LoadTrack (i);
if (track != null) {
closure (track);
}
}
}
public EditorTrackInfo LoadTrack (int index)
{
return LoadTrack (index, true);
}
public EditorTrackInfo LoadTrack (int index, bool alwaysLoad)
{
TrackInfo source_track;
return LoadTrack (index, alwaysLoad, out source_track);
}
private EditorTrackInfo LoadTrack (int index, out TrackInfo sourceTrack)
{
return LoadTrack (index, true, out sourceTrack);
}
private EditorTrackInfo LoadTrack (int index, bool alwaysLoad, out TrackInfo sourceTrack)
{
sourceTrack = GetTrack (index);
EditorTrackInfo editor_track = null;
if (sourceTrack == null) {
// Something bad happened here
return null;
}
if (!edit_map.TryGetValue (sourceTrack, out editor_track) && alwaysLoad) {
editor_track = new EditorTrackInfo (sourceTrack);
editor_track.EditorIndex = index;
editor_track.EditorCount = TrackCount;
edit_map.Add (sourceTrack, editor_track);
}
return editor_track;
}
private TrackInfo GetTrack (int index)
{
return db_selection != null ? db_selection[index] : memory_selection[index];
}
protected virtual void OnNavigated ()
{
EventHandler handler = Navigated;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
public void NavigateForward ()
{
if (current_track_index < TrackCount - 1) {
current_track_index++;
LoadTrackToEditor ();
OnNavigated ();
}
}
public void NavigateBackward ()
{
if (current_track_index > 0) {
current_track_index--;
LoadTrackToEditor ();
OnNavigated ();
}
}
public int TrackCount {
get { return db_selection != null ? db_selection.Count : memory_selection.Count; }
}
public int CurrentTrackIndex {
get { return current_track_index; }
}
public bool CanGoBackward {
get { return current_track_index > 0; }
}
public bool CanGoForward {
get { return current_track_index >= 0 && current_track_index < TrackCount - 1; }
}
#endregion
#region Saving
public void Save ()
{
List<int> primary_sources = new List<int> ();
// TODO: wrap in db transaction
try {
DatabaseTrackInfo.NotifySaved = false;
for (int i = 0; i < TrackCount; i++) {
// Save any tracks that were actually loaded into the editor
EditorTrackInfo track = LoadTrack (i, false);
if (track == null || track.SourceTrack == null) {
continue;
}
SaveTrack (track);
if (track.SourceTrack is DatabaseTrackInfo) {
// If the source track is from the database, save its parent for notification later
int id = (track.SourceTrack as DatabaseTrackInfo).PrimarySourceId;
if (!primary_sources.Contains (id)) {
primary_sources.Add (id);
}
}
}
// Finally, notify the affected primary sources
foreach (int id in primary_sources) {
PrimarySource psrc = PrimarySource.GetById (id);
if (psrc != null) {
psrc.NotifyTracksChanged ();
}
}
} finally {
DatabaseTrackInfo.NotifySaved = true;
}
}
private void SaveTrack (EditorTrackInfo track)
{
TrackInfo.ExportableMerge (track, track.SourceTrack);
track.SourceTrack.Save ();
if (track.SourceTrack.TrackEqual (ServiceManager.PlayerEngine.CurrentTrack)) {
TrackInfo.ExportableMerge (track, ServiceManager.PlayerEngine.CurrentTrack);
ServiceManager.PlayerEngine.TrackInfoUpdated ();
}
}
#endregion
#region Static Helpers
public static void RunEdit (TrackListModel model)
{
Run (model, EditorMode.Edit);
}
public static void RunView (TrackListModel model, bool readonlyTabs)
{
Run (model, EditorMode.View, readonlyTabs);
}
public static void Run (TrackListModel model, EditorMode mode)
{
Run (new TrackEditorDialog (model, mode));
}
private static void Run (TrackListModel model, EditorMode mode, bool readonlyTabs)
{
Run (new TrackEditorDialog (model, mode, readonlyTabs));
}
private static void Run (TrackEditorDialog track_editor)
{
track_editor.Response += delegate (object o, ResponseArgs args) {
if (args.ResponseId == ResponseType.Ok) {
track_editor.Save ();
} else {
int changed_count = 0;
for (int i = 0; i < track_editor.TrackCount; i++) {
EditorTrackInfo track = track_editor.LoadTrack (i, false);
if (track != null) {
track.GenerateDiff ();
if (track.DiffCount > 0) {
changed_count++;
}
}
}
if (changed_count == 0) {
track_editor.Destroy ();
return;
}
HigMessageDialog message_dialog = new HigMessageDialog (
track_editor, DialogFlags.Modal, MessageType.Warning, ButtonsType.None,
String.Format (Catalog.GetPluralString (
"Save the changes made to the open track?",
"Save the changes made to {0} of {1} open tracks?",
track_editor.TrackCount), changed_count, track_editor.TrackCount),
String.Empty
);
UpdateCancelMessage (track_editor, message_dialog);
uint timeout = 0;
timeout = GLib.Timeout.Add (1000, delegate {
bool result = UpdateCancelMessage (track_editor, message_dialog);
if (!result) {
timeout = 0;
}
return result;
});
message_dialog.AddButton (Catalog.GetString ("Close _without Saving"), ResponseType.Close, false);
message_dialog.AddButton (Stock.Cancel, ResponseType.Cancel, false);
message_dialog.AddButton (Stock.Save, ResponseType.Ok, true);
try {
switch ((ResponseType)message_dialog.Run ()) {
case ResponseType.Ok:
track_editor.Save ();
break;
case ResponseType.Close:
break;
case ResponseType.Cancel:
case ResponseType.DeleteEvent:
return;
}
} finally {
if (timeout > 0) {
GLib.Source.Remove (timeout);
}
message_dialog.Destroy ();
}
}
track_editor.Destroy ();
};
//track_editor.Run ();
track_editor.Show ();
}
private static bool UpdateCancelMessage (TrackEditorDialog trackEditor, HigMessageDialog messageDialog)
{
if (messageDialog == null) {
return false;
}
messageDialog.MessageLabel.Text = String.Format (Catalog.GetString (
"If you don't save, changes from the last {0} will be permanently lost."),
Banshee.Sources.DurationStatusFormatters.ApproximateVerboseFormatter (
DateTime.Now - trackEditor.dialog_launch_datetime
)
);
return messageDialog.IsMapped;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Fabrikam.Module1.Uc1.Services.WebApi.v1.Areas.HelpPage.ModelDescriptions;
using Fabrikam.Module1.Uc1.Services.WebApi.v1.Areas.HelpPage.Models;
namespace Fabrikam.Module1.Uc1.Services.WebApi.v1.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) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Data;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Statistics;
using OpenSim.Services.Interfaces;
namespace OpenSim.Framework.Communications
{
/// <summary>
/// Base class for user management (create, read, etc)
/// </summary>
public abstract class UserManagerBase
: IUserService, IUserAdminService, IAvatarService, IMessagingService, IAuthentication
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// List of plugins to search for user data
/// </value>
private List<IUserDataPlugin> m_plugins = new List<IUserDataPlugin>();
protected CommunicationsManager m_commsManager;
protected IInventoryService m_InventoryService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="commsManager"></param>
public UserManagerBase(CommunicationsManager commsManager)
{
m_commsManager = commsManager;
}
public virtual void SetInventoryService(IInventoryService invService)
{
m_InventoryService = invService;
}
/// <summary>
/// Add a new user data plugin - plugins will be requested in the order they were added.
/// </summary>
/// <param name="plugin">The plugin that will provide user data</param>
public void AddPlugin(IUserDataPlugin plugin)
{
m_plugins.Add(plugin);
}
/// <summary>
/// Adds a list of user data plugins, as described by `provider' and
/// `connect', to `_plugins'.
/// </summary>
/// <param name="provider">
/// The filename of the inventory server plugin DLL.
/// </param>
/// <param name="connect">
/// The connection string for the storage backend.
/// </param>
public void AddPlugin(string provider, string connect)
{
m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IUserDataPlugin>(provider, connect));
}
#region UserProfile
public virtual void AddTemporaryUserProfile(UserProfileData userProfile)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
plugin.AddTemporaryUserProfile(userProfile);
}
}
public virtual UserProfileData GetUserProfile(string fname, string lname)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
UserProfileData profile = plugin.GetUserByName(fname, lname);
if (profile != null)
{
profile.CurrentAgent = GetUserAgent(profile.ID);
return profile;
}
}
return null;
}
public void LogoutUsers(UUID regionID)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
plugin.LogoutUsers(regionID);
}
}
public void ResetAttachments(UUID userID)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
plugin.ResetAttachments(userID);
}
}
public UserProfileData GetUserProfile(Uri uri)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
UserProfileData profile = plugin.GetUserByUri(uri);
if (null != profile)
return profile;
}
return null;
}
public virtual UserAgentData GetAgentByUUID(UUID userId)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
UserAgentData agent = plugin.GetAgentByUUID(userId);
if (agent != null)
{
return agent;
}
}
return null;
}
public Uri GetUserUri(UserProfileData userProfile)
{
throw new NotImplementedException();
}
// see IUserService
public virtual UserProfileData GetUserProfile(UUID uuid)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
UserProfileData profile = plugin.GetUserByUUID(uuid);
if (null != profile)
{
profile.CurrentAgent = GetUserAgent(profile.ID);
return profile;
}
}
return null;
}
public virtual List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
{
List<AvatarPickerAvatar> allPickerList = new List<AvatarPickerAvatar>();
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
List<AvatarPickerAvatar> pickerList = plugin.GeneratePickerResults(queryID, query);
if (pickerList != null)
allPickerList.AddRange(pickerList);
}
catch (Exception)
{
m_log.Error(
"[USERSTORAGE]: Unable to generate AgentPickerData via " + plugin.Name + "(" + query + ")");
}
}
return allPickerList;
}
public virtual bool UpdateUserProfile(UserProfileData data)
{
bool result = false;
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.UpdateUserProfile(data);
result = true;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[USERSTORAGE]: Unable to set user {0} {1} via {2}: {3}",
data.FirstName, data.SurName, plugin.Name, e.ToString());
}
}
return result;
}
#endregion
#region Get UserAgent
/// <summary>
/// Loads a user agent by uuid (not called directly)
/// </summary>
/// <param name="uuid">The agent's UUID</param>
/// <returns>Agent profiles</returns>
public UserAgentData GetUserAgent(UUID uuid)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
UserAgentData result = plugin.GetAgentByUUID(uuid);
if (result != null)
return result;
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return null;
}
/// <summary>
/// Loads a user agent by name (not called directly)
/// </summary>
/// <param name="name">The agent's name</param>
/// <returns>A user agent</returns>
public UserAgentData GetUserAgent(string name)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
UserAgentData result = plugin.GetAgentByName(name);
if (result != null)
return result;
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return null;
}
/// <summary>
/// Loads a user agent by name (not called directly)
/// </summary>
/// <param name="fname">The agent's firstname</param>
/// <param name="lname">The agent's lastname</param>
/// <returns>A user agent</returns>
public UserAgentData GetUserAgent(string fname, string lname)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
UserAgentData result = plugin.GetAgentByName(fname, lname);
if (result != null)
return result;
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to find user via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return null;
}
public virtual List<FriendListItem> GetUserFriendList(UUID ownerID)
{
List<FriendListItem> allFriends = new List<FriendListItem>();
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
List<FriendListItem> friends = plugin.GetUserFriendList(ownerID);
if (friends != null)
allFriends.AddRange(friends);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to GetUserFriendList via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return allFriends;
}
public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos (List<UUID> uuids)
{
//Dictionary<UUID, FriendRegionInfo> allFriendRegions = new Dictionary<UUID, FriendRegionInfo>();
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
Dictionary<UUID, FriendRegionInfo> friendRegions = plugin.GetFriendRegionInfos(uuids);
if (friendRegions != null)
return friendRegions;
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to GetFriendRegionInfos via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return new Dictionary<UUID, FriendRegionInfo>();
}
public void StoreWebLoginKey(UUID agentID, UUID webLoginKey)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.StoreWebLoginKey(agentID, webLoginKey);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to Store WebLoginKey via " + plugin.Name + "(" + e.ToString() + ")");
}
}
}
public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.AddNewUserFriend(friendlistowner, friend, perms);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to AddNewUserFriend via " + plugin.Name + "(" + e.ToString() + ")");
}
}
}
public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.RemoveUserFriend(friendlistowner, friend);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to RemoveUserFriend via " + plugin.Name + "(" + e.ToString() + ")");
}
}
}
public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.UpdateUserFriendPerms(friendlistowner, friend, perms);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to UpdateUserFriendPerms via " + plugin.Name + "(" + e.ToString() + ")");
}
}
}
/// <summary>
/// Resets the currentAgent in the user profile
/// </summary>
/// <param name="agentID">The agent's ID</param>
public virtual void ClearUserAgent(UUID agentID)
{
UserProfileData profile = GetUserProfile(agentID);
if (profile == null)
{
return;
}
profile.CurrentAgent = null;
UpdateUserProfile(profile);
}
#endregion
#region CreateAgent
/// <summary>
/// Creates and initialises a new user agent - make sure to use CommitAgent when done to submit to the DB
/// </summary>
/// <param name="profile">The users profile</param>
/// <param name="request">The users loginrequest</param>
public void CreateAgent(UserProfileData profile, XmlRpcRequest request)
{
//m_log.DebugFormat("[USER MANAGER]: Creating agent {0} {1}", profile.Name, profile.ID);
UserAgentData agent = new UserAgentData();
// User connection
agent.AgentOnline = true;
if (request.Params.Count > 1)
{
if (request.Params[1] != null)
{
IPEndPoint RemoteIPEndPoint = (IPEndPoint)request.Params[1];
agent.AgentIP = RemoteIPEndPoint.Address.ToString();
agent.AgentPort = (uint)RemoteIPEndPoint.Port;
}
}
// Generate sessions
RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
byte[] randDataS = new byte[16];
byte[] randDataSS = new byte[16];
rand.GetBytes(randDataS);
rand.GetBytes(randDataSS);
agent.SecureSessionID = new UUID(randDataSS, 0);
agent.SessionID = new UUID(randDataS, 0);
// Profile UUID
agent.ProfileID = profile.ID;
// Current location/position/alignment
if (profile.CurrentAgent != null)
{
agent.Region = profile.CurrentAgent.Region;
agent.Handle = profile.CurrentAgent.Handle;
agent.Position = profile.CurrentAgent.Position;
agent.LookAt = profile.CurrentAgent.LookAt;
}
else
{
agent.Region = profile.HomeRegionID;
agent.Handle = profile.HomeRegion;
agent.Position = profile.HomeLocation;
agent.LookAt = profile.HomeLookAt;
}
// What time did the user login?
agent.LoginTime = Util.UnixTimeSinceEpoch();
agent.LogoutTime = 0;
profile.CurrentAgent = agent;
}
public void CreateAgent(UserProfileData profile, OSD request)
{
//m_log.DebugFormat("[USER MANAGER]: Creating agent {0} {1}", profile.Name, profile.ID);
UserAgentData agent = new UserAgentData();
// User connection
agent.AgentOnline = true;
//if (request.Params.Count > 1)
//{
// IPEndPoint RemoteIPEndPoint = (IPEndPoint)request.Params[1];
// agent.AgentIP = RemoteIPEndPoint.Address.ToString();
// agent.AgentPort = (uint)RemoteIPEndPoint.Port;
//}
// Generate sessions
RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();
byte[] randDataS = new byte[16];
byte[] randDataSS = new byte[16];
rand.GetBytes(randDataS);
rand.GetBytes(randDataSS);
agent.SecureSessionID = new UUID(randDataSS, 0);
agent.SessionID = new UUID(randDataS, 0);
// Profile UUID
agent.ProfileID = profile.ID;
// Current location/position/alignment
if (profile.CurrentAgent != null)
{
agent.Region = profile.CurrentAgent.Region;
agent.Handle = profile.CurrentAgent.Handle;
agent.Position = profile.CurrentAgent.Position;
agent.LookAt = profile.CurrentAgent.LookAt;
}
else
{
agent.Region = profile.HomeRegionID;
agent.Handle = profile.HomeRegion;
agent.Position = profile.HomeLocation;
agent.LookAt = profile.HomeLookAt;
}
// What time did the user login?
agent.LoginTime = Util.UnixTimeSinceEpoch();
agent.LogoutTime = 0;
profile.CurrentAgent = agent;
}
/// <summary>
/// Saves a target agent to the database
/// </summary>
/// <param name="profile">The users profile</param>
/// <returns>Successful?</returns>
public bool CommitAgent(ref UserProfileData profile)
{
//m_log.DebugFormat("[USER MANAGER]: Committing agent {0} {1}", profile.Name, profile.ID);
// TODO: how is this function different from setUserProfile? -> Add AddUserAgent() here and commit both tables "users" and "agents"
// TODO: what is the logic should be?
bool ret = false;
ret = AddUserAgent(profile.CurrentAgent);
ret = ret & UpdateUserProfile(profile);
return ret;
}
/// <summary>
/// Process a user logoff from OpenSim.
/// </summary>
/// <param name="userid"></param>
/// <param name="regionid"></param>
/// <param name="regionhandle"></param>
/// <param name="position"></param>
/// <param name="lookat"></param>
public virtual void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
{
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddLogout();
UserProfileData userProfile = GetUserProfile(userid);
if (userProfile != null)
{
UserAgentData userAgent = userProfile.CurrentAgent;
if (userAgent != null)
{
userAgent.AgentOnline = false;
userAgent.LogoutTime = Util.UnixTimeSinceEpoch();
//userAgent.sessionID = UUID.Zero;
if (regionid != UUID.Zero)
{
userAgent.Region = regionid;
}
userAgent.Handle = regionhandle;
userAgent.Position = position;
userAgent.LookAt = lookat;
//userProfile.CurrentAgent = userAgent;
userProfile.LastLogin = userAgent.LogoutTime;
CommitAgent(ref userProfile);
}
else
{
// If currentagent is null, we can't reference it here or the UserServer crashes!
m_log.Info("[LOGOUT]: didn't save logout position: " + userid.ToString());
}
}
else
{
m_log.Warn("[LOGOUT]: Unknown User logged out");
}
}
public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
{
LogOffUser(userid, regionid, regionhandle, new Vector3(posx, posy, posz), new Vector3());
}
#endregion
/// <summary>
/// Add a new user
/// </summary>
/// <param name="firstName">first name</param>
/// <param name="lastName">last name</param>
/// <param name="password">password</param>
/// <param name="email">email</param>
/// <param name="regX">location X</param>
/// <param name="regY">location Y</param>
/// <returns>The UUID of the created user profile. On failure, returns UUID.Zero</returns>
public virtual UUID AddUser(string firstName, string lastName, string password, string email, uint regX, uint regY)
{
return AddUser(firstName, lastName, password, email, regX, regY, UUID.Random());
}
/// <summary>
/// Add a new user
/// </summary>
/// <param name="firstName">first name</param>
/// <param name="lastName">last name</param>
/// <param name="password">password</param>
/// <param name="email">email</param>
/// <param name="regX">location X</param>
/// <param name="regY">location Y</param>
/// <param name="SetUUID">UUID of avatar.</param>
/// <returns>The UUID of the created user profile. On failure, returns UUID.Zero</returns>
public virtual UUID AddUser(
string firstName, string lastName, string password, string email, uint regX, uint regY, UUID SetUUID)
{
UserProfileData user = new UserProfileData();
user.PasswordSalt = Util.Md5Hash(UUID.Random().ToString());
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + user.PasswordSalt);
user.HomeLocation = new Vector3(128, 128, 100);
user.ID = SetUUID;
user.FirstName = firstName;
user.SurName = lastName;
user.PasswordHash = md5PasswdHash;
user.Created = Util.UnixTimeSinceEpoch();
user.HomeLookAt = new Vector3(100, 100, 100);
user.HomeRegionX = regX;
user.HomeRegionY = regY;
user.Email = email;
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.AddNewUserProfile(user);
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to add user via " + plugin.Name + "(" + e.ToString() + ")");
}
}
UserProfileData userProf = GetUserProfile(SetUUID);
if (userProf == null)
{
return UUID.Zero;
}
else
{
//
// WARNING: This is a horrible hack
// The purpose here is to avoid touching the user server at this point.
// There are dragons there that I can't deal with right now.
// diva 06/09/09
//
if (m_InventoryService != null)
{
// local service (standalone)
m_log.Debug("[USERSTORAGE]: using IInventoryService to create user's inventory");
m_InventoryService.CreateUserInventory(userProf.ID);
}
else if (m_commsManager.InterServiceInventoryService != null)
{
// used by the user server
m_log.Debug("[USERSTORAGE]: using m_commsManager.InterServiceInventoryService to create user's inventory");
m_commsManager.InterServiceInventoryService.CreateNewUserInventory(userProf.ID);
}
return userProf.ID;
}
}
/// <summary>
/// Reset a user password.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="newPassword"></param>
/// <returns>true if the update was successful, false otherwise</returns>
public virtual bool ResetUserPassword(string firstName, string lastName, string newPassword)
{
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(newPassword) + ":" + String.Empty);
UserProfileData profile = GetUserProfile(firstName, lastName);
if (null == profile)
{
m_log.ErrorFormat("[USERSTORAGE]: Could not find user {0} {1}", firstName, lastName);
return false;
}
profile.PasswordHash = md5PasswdHash;
profile.PasswordSalt = String.Empty;
UpdateUserProfile(profile);
return true;
}
public abstract UserProfileData SetupMasterUser(string firstName, string lastName);
public abstract UserProfileData SetupMasterUser(string firstName, string lastName, string password);
public abstract UserProfileData SetupMasterUser(UUID uuid);
/// <summary>
/// Add an agent using data plugins.
/// </summary>
/// <param name="agentdata">The agent data to be added</param>
/// <returns>
/// true if at least one plugin added the user agent. false if no plugin successfully added the agent
/// </returns>
public virtual bool AddUserAgent(UserAgentData agentdata)
{
bool result = false;
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.AddNewUserAgent(agentdata);
result = true;
}
catch (Exception e)
{
m_log.Error("[USERSTORAGE]: Unable to add agent via " + plugin.Name + "(" + e.ToString() + ")");
}
}
return result;
}
/// <summary>
/// Get avatar appearance information
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public virtual AvatarAppearance GetUserAppearance(UUID user)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
AvatarAppearance appearance = plugin.GetUserAppearance(user);
if (appearance != null)
return appearance;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[USERSTORAGE]: Unable to find user appearance {0} via {1} ({2})", user, plugin.Name, e);
}
}
return null;
}
public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance)
{
foreach (IUserDataPlugin plugin in m_plugins)
{
try
{
plugin.UpdateUserAppearance(user, appearance);
}
catch (Exception e)
{
m_log.ErrorFormat("[USERSTORAGE]: Unable to update user appearance {0} via {1} ({2})", user.ToString(), plugin.Name, e.ToString());
}
}
}
#region IAuthentication
protected Dictionary<UUID, List<string>> m_userKeys = new Dictionary<UUID, List<string>>();
/// <summary>
/// This generates authorization keys in the form
/// http://userserver/uuid
/// after verifying that the caller is, indeed, authorized to request a key
/// </summary>
/// <param name="url">URL of the user server</param>
/// <param name="userID">The user ID requesting the new key</param>
/// <param name="authToken">The original authorization token for that user, obtained during login</param>
/// <returns></returns>
public string GetNewKey(string url, UUID userID, UUID authToken)
{
UserProfileData profile = GetUserProfile(userID);
string newKey = string.Empty;
if (!url.EndsWith("/"))
url = url + "/";
if (profile != null)
{
// I'm overloading webloginkey for this, so that no changes are needed in the DB
// The uses of webloginkey are fairly mutually exclusive
if (profile.WebLoginKey.Equals(authToken))
{
newKey = UUID.Random().ToString();
List<string> keys;
lock (m_userKeys)
{
if (m_userKeys.ContainsKey(userID))
{
keys = m_userKeys[userID];
}
else
{
keys = new List<string>();
m_userKeys.Add(userID, keys);
}
keys.Add(newKey);
}
m_log.InfoFormat("[USERAUTH]: Successfully generated new auth key for user {0}", userID);
}
else
m_log.Warn("[USERAUTH]: Unauthorized key generation request. Denying new key.");
}
else
m_log.Warn("[USERAUTH]: User not found.");
return url + newKey;
}
/// <summary>
/// This verifies the uuid portion of the key given out by GenerateKey
/// </summary>
/// <param name="userID"></param>
/// <param name="key"></param>
/// <returns></returns>
public bool VerifyKey(UUID userID, string key)
{
lock (m_userKeys)
{
if (m_userKeys.ContainsKey(userID))
{
List<string> keys = m_userKeys[userID];
if (keys.Contains(key))
{
// Keys are one-time only, so remove it
keys.Remove(key);
return true;
}
return false;
}
else
return false;
}
}
public virtual bool VerifySession(UUID userID, UUID sessionID)
{
UserProfileData userProfile = GetUserProfile(userID);
if (userProfile != null && userProfile.CurrentAgent != null)
{
m_log.DebugFormat(
"[USER AUTH]: Verifying session {0} for {1}; current session {2}",
sessionID, userID, userProfile.CurrentAgent.SessionID);
if (userProfile.CurrentAgent.SessionID == sessionID)
{
return true;
}
}
return false;
}
public virtual bool AuthenticateUserByPassword(UUID userID, string password)
{
// m_log.DebugFormat("[USER AUTH]: Authenticating user {0} given password {1}", userID, password);
UserProfileData userProfile = GetUserProfile(userID);
if (null == userProfile)
return false;
string md5PasswordHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + userProfile.PasswordSalt);
// m_log.DebugFormat(
// "[USER AUTH]: Submitted hash {0}, stored hash {1}", md5PasswordHash, userProfile.PasswordHash);
if (md5PasswordHash == userProfile.PasswordHash)
return true;
else
return false;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SplineTrailRenderer : MonoBehaviour
{
public enum MeshDisposition { Continuous, Fragmented };
public enum FadeType { None, MeshShrinking, Alpha, Both }
public class AdvancedParameters
{
public int baseNbQuad = 500;
public int nbQuadIncrement = 200;
//public bool releaseMemoryOnClear = true;
public int nbSegmentToParametrize = 3; //0 means all segments
public float lengthToRedraw = 0; //0 means fadeDistance and should suffice, but you can
//redraw a smaller section when there is no fade as an
//optimization
public bool shiftMeshData = true; //optimization to prevent memory shortage on very long
//trails. May induce lag spikes when shifting.
//todo: fix the exception induced by modifying the max length (mesh sliding)
}
public bool emit = true;
public float emissionDistance = 1f;
public float height = 1f;
public float width = 0.2f;
public Color vertexColor = Color.white;
public Vector3 normal = new Vector3(0, 0, 1);
public bool dynamicNormalUpdate = false;
public MeshDisposition meshDisposition = MeshDisposition.Continuous;
public FadeType fadeType = FadeType.None;
public float fadeLengthBegin = 5f;
public float fadeLengthEnd = 5f;
//public float fadeSpeed = 0f;
public float maxLength = 500f;
public bool debugDrawSpline = false;
private AdvancedParameters advancedParameters = new AdvancedParameters();
[HideInInspector]
public CatmullRomSpline spline;
private const int NbVertexPerQuad = 4;
private const int NbTriIndexPerQuad = 6;
Vector3[] vertices;
int[] triangles;
Vector2[] uv;
Vector2[] uv2;
Color[] colors;
Vector3[] normals;
private Vector3 origin;
private int maxInstanciedTriCount = 0;
private Mesh mesh;
private int allocatedNbQuad;
private int lastStartingQuad;
private int quadOffset;
public void Clear()
{
Init();
}
public void ImitateTrail(SplineTrailRenderer trail)
{
emit = trail.emit;
emissionDistance = trail.emissionDistance;
height = trail.height;
width = trail.width;
vertexColor = trail.vertexColor;
normal = trail.normal;
meshDisposition = trail.meshDisposition;
fadeType = trail.fadeType;
fadeLengthBegin = trail.fadeLengthBegin;
fadeLengthEnd = trail.fadeLengthEnd;
maxLength = 500;// trail.maxLength;
debugDrawSpline = trail.debugDrawSpline;
GetComponent<Renderer>().material = trail.GetComponent<Renderer>().material;
}
private void Start ()
{
if(spline == null)
{
Init();
}
}
private void LateUpdate()
{
if(emit)
{
List<Knot> knots = spline.knots;
Vector3 point = transform.position;
knots[knots.Count-1].position = point;
knots[knots.Count-2].position = point;
if(Vector3.Distance(knots[knots.Count-3].position, point) > emissionDistance &&
Vector3.Distance(knots[knots.Count-4].position, point) > emissionDistance)
{
knots.Add(new Knot(point));
}
}
RenderMesh();
}
private void RenderMesh()
{
if(advancedParameters.nbSegmentToParametrize == 0)
spline.Parametrize();
else
spline.Parametrize(spline.NbSegments - advancedParameters.nbSegmentToParametrize, spline.NbSegments);
float length = Mathf.Max(spline.Length() - 0.1f, 0);
int nbQuad = ((int)(1f/width * length)) + 1 - quadOffset;
if(allocatedNbQuad < nbQuad) //allocate more memory for the mesh
{
Reallocate(nbQuad);
length = Mathf.Max(spline.Length() - 0.1f, 0);
nbQuad = ((int)(1f/width * length)) + 1 - quadOffset;
}
int startingQuad = lastStartingQuad;
float lastDistance = startingQuad * width + quadOffset * width;
maxInstanciedTriCount = System.Math.Max(maxInstanciedTriCount, (nbQuad-1) * NbTriIndexPerQuad);
Vector3 n = normal;
if(dynamicNormalUpdate)
{
if(n == Vector3.zero)
{
n = (transform.position - Camera.main.transform.position).normalized;
}
for(int i=0; i<normals.Length; i++)
{
normals[i] = n;
}
}
CatmullRomSpline.Marker marker = new CatmullRomSpline.Marker();
spline.PlaceMarker(marker, lastDistance);
Vector3 lastPosition = spline.GetPosition(marker);
Vector3 lastTangent = spline.GetTangent(marker);
Vector3 lastBinormal = CatmullRomSpline.ComputeBinormal(lastTangent, n);
int drawingEnd = meshDisposition == MeshDisposition.Fragmented ? nbQuad-1 : nbQuad-1;
float startingDist = lastDistance;
for(int i=startingQuad; i<drawingEnd; i++)
{
float distance = lastDistance+width;
int firstVertexIndex = i * NbVertexPerQuad;
int firstTriIndex = i * NbTriIndexPerQuad;
spline.MoveMarker(marker, distance);
Vector3 position = spline.GetPosition(marker);
Vector3 tangent = spline.GetTangent(marker);
Vector3 binormal = CatmullRomSpline.ComputeBinormal(tangent, n);
float h = FadeMultiplier(lastDistance, length);
float h2 = FadeMultiplier(distance, length);
float rh = h * height, rh2 = h2 * height;
if(fadeType == FadeType.Alpha || fadeType == FadeType.None)
{
rh = h > 0 ? height : 0;
rh2 = h2 > 0 ? height : 0;
}
if(meshDisposition == MeshDisposition.Continuous)
{
vertices[firstVertexIndex] = transform.InverseTransformPoint(lastPosition - origin + (lastBinormal * (rh * 0.5f)));
vertices[firstVertexIndex + 1] = transform.InverseTransformPoint(lastPosition - origin + (-lastBinormal * (rh * 0.5f)));
vertices[firstVertexIndex + 2] = transform.InverseTransformPoint(position - origin + (binormal * (rh2 * 0.5f)));
vertices[firstVertexIndex + 3] = transform.InverseTransformPoint(position - origin + (-binormal * (rh2 * 0.5f)));
Debug.DrawLine(position, position - origin + (-binormal * (rh2 * 0.5f)), Color.red);
uv[firstVertexIndex] = new Vector2(lastDistance/height, 1);
uv[firstVertexIndex + 1] = new Vector2(lastDistance/height, 0);
uv[firstVertexIndex + 2] = new Vector2(distance/height, 1);
uv[firstVertexIndex + 3] = new Vector2(distance/height, 0);
}
else
{
Vector3 pos = lastPosition + (lastTangent * width * -0.5f) - origin;
vertices[firstVertexIndex] = transform.InverseTransformPoint(pos + (lastBinormal * (rh * 0.5f)));
vertices[firstVertexIndex + 1] = transform.InverseTransformPoint(pos + (-lastBinormal * (rh * 0.5f)));
vertices[firstVertexIndex + 2] = transform.InverseTransformPoint(pos + (lastTangent * width) + (lastBinormal * (rh * 0.5f)));
vertices[firstVertexIndex + 3] = transform.InverseTransformPoint(pos + (lastTangent * width) + (-lastBinormal * (rh * 0.5f)));
uv[firstVertexIndex] = new Vector2(0, 1);
uv[firstVertexIndex + 1] = new Vector2(0, 0);
uv[firstVertexIndex + 2] = new Vector2(1, 1);
uv[firstVertexIndex + 3] = new Vector2(1, 0);
}
float relLength = length-startingDist;
uv2[firstVertexIndex] = new Vector2((lastDistance-startingDist)/relLength, 1);
uv2[firstVertexIndex + 1] = new Vector2((lastDistance-startingDist)/relLength, 0);
uv2[firstVertexIndex + 2] = new Vector2((distance-startingDist)/relLength, 1);
uv2[firstVertexIndex + 3] = new Vector2((distance-startingDist)/relLength, 0);
triangles[firstTriIndex] = firstVertexIndex;
triangles[firstTriIndex + 1] = firstVertexIndex + 1;
triangles[firstTriIndex + 2] = firstVertexIndex + 2;
triangles[firstTriIndex + 3] = firstVertexIndex + 2;
triangles[firstTriIndex + 4] = firstVertexIndex + 1;
triangles[firstTriIndex + 5] = firstVertexIndex + 3;
colors[firstVertexIndex] = vertexColor;
colors[firstVertexIndex + 1] = vertexColor;
colors[firstVertexIndex + 2] = vertexColor;
colors[firstVertexIndex + 3] = vertexColor;
if(fadeType == FadeType.Alpha || fadeType == FadeType.Both)
{
colors[firstVertexIndex].a *= h;
colors[firstVertexIndex + 1].a *= h;
colors[firstVertexIndex + 2].a *= h2;
colors[firstVertexIndex + 3].a *= h2;
}
lastPosition = position;
lastTangent = tangent;
lastBinormal = binormal;
lastDistance = distance;
}
for(int i=(nbQuad-1)*NbTriIndexPerQuad; i<maxInstanciedTriCount; i++) //clear a few tri ahead
triangles[i] = 0;
lastStartingQuad = advancedParameters.lengthToRedraw == 0 ?
System.Math.Max(0, nbQuad - ((int)(maxLength / width) + 5)) :
System.Math.Max(0, nbQuad - ((int)(advancedParameters.lengthToRedraw / width) + 5));
mesh.Clear();
mesh.vertices = vertices;
mesh.uv = uv;
mesh.uv2 = uv2;
mesh.triangles = triangles;
mesh.colors = colors;
mesh.normals = normals;
}
private void OnDrawGizmos()
{
//DebugDrawEquallySpacedDots();
if(advancedParameters != null && spline != null && debugDrawSpline)
{
spline.DebugDrawSpline();
//spline.DebugDrawSubKnots();
}
}
private void Init()
{
if (spline == null)
{
spline = new CatmullRomSpline();
}
//We set the origin onto the right hand
origin = Vector3.zero;//transform.position;
mesh = GetComponent<MeshFilter>().mesh;
#if UNITY_4_0
mesh.MarkDynamic();
#endif
allocatedNbQuad = advancedParameters.baseNbQuad;
maxInstanciedTriCount = 0;
lastStartingQuad = 0;
quadOffset = 0;
vertices = new Vector3[advancedParameters.baseNbQuad * NbVertexPerQuad];
triangles = new int[advancedParameters.baseNbQuad * NbTriIndexPerQuad];
uv = new Vector2[advancedParameters.baseNbQuad * NbVertexPerQuad];
uv2 = new Vector2[advancedParameters.baseNbQuad * NbVertexPerQuad];
colors = new Color[advancedParameters.baseNbQuad * NbVertexPerQuad];
normals = new Vector3[advancedParameters.baseNbQuad * NbVertexPerQuad];
Vector3 n = normal;
if(n == Vector3.zero)
{
n = (transform.position - Camera.main.transform.position).normalized;
}
for(int i=0; i<normals.Length; i++)
{
normals[i] = n;
}
//spline.knots.Clear();
spline.Clear();
List<Knot> knots = spline.knots;
Vector3 point = transform.position;
knots.Add(new Knot(point));
knots.Add(new Knot(point));
knots.Add(new Knot(point));
knots.Add(new Knot(point));
knots.Add(new Knot(point));
}
private void Reallocate(int nbQuad)
{
if(advancedParameters.shiftMeshData && lastStartingQuad > 0/*advancedParameters.nbQuadIncrement / 4*/) //slide
{
int newIndex = 0;
for(int i=lastStartingQuad; i<nbQuad; i++)
{
vertices[newIndex] = vertices[i];
triangles[newIndex] = triangles[i];
uv[newIndex] = uv[i];
colors[newIndex] = colors[i];
normals[newIndex] = normals[i];
newIndex++;
}
quadOffset += lastStartingQuad;
lastStartingQuad = 0;
}
float length = Mathf.Max(spline.Length() - 0.1f, 0);
nbQuad = ((int)(1f/width * length)) + 1 - quadOffset;
if(allocatedNbQuad < nbQuad)
{
if((allocatedNbQuad + advancedParameters.nbQuadIncrement) * NbVertexPerQuad > 65000)
{
Clear();
return;
}
allocatedNbQuad += advancedParameters.nbQuadIncrement;
Vector3[] vertices_2 = new Vector3[allocatedNbQuad * NbVertexPerQuad];
int[] triangles_2 = new int[allocatedNbQuad * NbTriIndexPerQuad];
Vector2[] uv_2 = new Vector2[allocatedNbQuad * NbVertexPerQuad];
Vector2[] uv2_2 = new Vector2[allocatedNbQuad * NbVertexPerQuad];
Color[] colors_2 = new Color[allocatedNbQuad * NbVertexPerQuad];
Vector3[] normals_2 = new Vector3[allocatedNbQuad * NbVertexPerQuad];
vertices.CopyTo(vertices_2, 0);
triangles.CopyTo(triangles_2, 0);
uv.CopyTo(uv_2, 0);
uv2.CopyTo(uv2_2, 0);
colors.CopyTo(colors_2, 0);
normals.CopyTo(normals_2, 0);
vertices = vertices_2;
triangles = triangles_2;
uv = uv_2;
uv2 = uv2_2;
colors = colors_2;
normals = normals_2;
}
}
float FadeMultiplier(float distance, float length)
{
float ha = Mathf.Clamp01((distance - Mathf.Max(length-maxLength, 0)) / fadeLengthBegin);
float hb = Mathf.Clamp01((length-distance) / fadeLengthEnd);
return Mathf.Min(ha, hb);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
/// <summary>
/// Array operations.
/// </summary>
public partial class Array : Microsoft.Rest.IServiceOperations<AutoRestComplexTestService>, IArray
{
/// <summary>
/// Initializes a new instance of the Array class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Array(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types with array property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ArrayWrapper>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutValidWithHttpMessagesAsync(System.Collections.Generic.IList<string> array = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/valid").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ArrayWrapper>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with array property which is empty
/// </summary>
/// <param name='array'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutEmptyWithHttpMessagesAsync(System.Collections.Generic.IList<string> array = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
ArrayWrapper complexBody = new ArrayWrapper();
if (array != null)
{
complexBody.Array = array;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/empty").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with array property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<ArrayWrapper>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/array/notprovided").ToString();
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.HttpOperationResponse<ArrayWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ArrayWrapper>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* 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.Text;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Holds individual statistic details
/// </summary>
public class Stat : IDisposable
{
/// <summary>
/// Category of this stat (e.g. cache, scene, etc).
/// </summary>
public string Category { get; private set; }
/// <summary>
/// Containing name for this stat.
/// FIXME: In the case of a scene, this is currently the scene name (though this leaves
/// us with a to-be-resolved problem of non-unique region names).
/// </summary>
/// <value>
/// The container.
/// </value>
public string Container { get; private set; }
public StatType StatType { get; private set; }
public MeasuresOfInterest MeasuresOfInterest { get; private set; }
/// <summary>
/// Action used to update this stat when the value is requested if it's a pull type.
/// </summary>
public Action<Stat> PullAction { get; private set; }
public StatVerbosity Verbosity { get; private set; }
public string ShortName { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public virtual string UnitName { get; private set; }
public virtual double Value
{
get
{
// Asking for an update here means that the updater cannot access this value without infinite recursion.
// XXX: A slightly messy but simple solution may be to flick a flag so we can tell if this is being
// called by the pull action and just return the value.
if (StatType == StatType.Pull)
PullAction(this);
return m_value;
}
set
{
m_value = value;
}
}
private double m_value;
/// <summary>
/// Historical samples for calculating measures of interest average.
/// </summary>
/// <remarks>
/// Will be null if no measures of interest require samples.
/// </remarks>
private static Queue<double> m_samples;
/// <summary>
/// Maximum number of statistical samples.
/// </summary>
/// <remarks>
/// At the moment this corresponds to 1 minute since the sampling rate is every 2.5 seconds as triggered from
/// the main Watchdog.
/// </remarks>
private static int m_maxSamples = 24;
public Stat(
string shortName,
string name,
string description,
string unitName,
string category,
string container,
StatType type,
Action<Stat> pullAction,
StatVerbosity verbosity)
: this(
shortName,
name,
description,
unitName,
category,
container,
type,
MeasuresOfInterest.None,
pullAction,
verbosity)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name='shortName'>Short name for the stat. Must not contain spaces. e.g. "LongFrames"</param>
/// <param name='name'>Human readable name for the stat. e.g. "Long frames"</param>
/// <param name='description'>Description of stat</param>
/// <param name='unitName'>
/// Unit name for the stat. Should be preceeded by a space if the unit name isn't normally appeneded immediately to the value.
/// e.g. " frames"
/// </param>
/// <param name='category'>Category under which this stat should appear, e.g. "scene". Do not capitalize.</param>
/// <param name='container'>Entity to which this stat relates. e.g. scene name if this is a per scene stat.</param>
/// <param name='type'>Push or pull</param>
/// <param name='pullAction'>Pull stats need an action to update the stat on request. Push stats should set null here.</param>
/// <param name='moi'>Measures of interest</param>
/// <param name='verbosity'>Verbosity of stat. Controls whether it will appear in short stat display or only full display.</param>
public Stat(
string shortName,
string name,
string description,
string unitName,
string category,
string container,
StatType type,
MeasuresOfInterest moi,
Action<Stat> pullAction,
StatVerbosity verbosity)
{
if (StatsManager.SubCommands.Contains(category))
throw new Exception(
string.Format("Stat cannot be in category '{0}' since this is reserved for a subcommand", category));
ShortName = shortName;
Name = name;
Description = description;
UnitName = unitName;
Category = category;
Container = container;
StatType = type;
if (StatType == StatType.Push && pullAction != null)
throw new Exception("A push stat cannot have a pull action");
else
PullAction = pullAction;
MeasuresOfInterest = moi;
if ((moi & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
m_samples = new Queue<double>(m_maxSamples);
Verbosity = verbosity;
}
// IDisposable.Dispose()
public virtual void Dispose()
{
return;
}
/// <summary>
/// Record a value in the sample set.
/// </summary>
/// <remarks>
/// Do not call this if MeasuresOfInterest.None
/// </remarks>
public void RecordValue()
{
double newValue = Value;
lock (m_samples)
{
if (m_samples.Count >= m_maxSamples)
m_samples.Dequeue();
m_samples.Enqueue(newValue);
}
}
public virtual string ToConsoleString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.{1}.{2} : {3} {4}", Category, Container, ShortName, Value, UnitName);
AppendMeasuresOfInterest(sb);
return sb.ToString();
}
public virtual OSDMap ToOSDMap()
{
OSDMap ret = new OSDMap();
ret.Add("Category", OSD.FromString(Category));
ret.Add("Container", OSD.FromString(Container));
ret.Add("ShortName", OSD.FromString(ShortName));
ret.Add("Name", OSD.FromString(Name));
ret.Add("Description", OSD.FromString(Description));
ret.Add("UnitName", OSD.FromString(UnitName));
ret.Add("Value", OSD.FromReal(Value));
return ret;
}
protected void AppendMeasuresOfInterest(StringBuilder sb)
{
if ((MeasuresOfInterest & MeasuresOfInterest.AverageChangeOverTime)
== MeasuresOfInterest.AverageChangeOverTime)
{
double totalChange = 0;
double? lastSample = null;
lock (m_samples)
{
foreach (double s in m_samples)
{
if (lastSample != null)
totalChange += s - (double)lastSample;
lastSample = s;
}
}
int divisor = m_samples.Count <= 1 ? 1 : m_samples.Count - 1;
sb.AppendFormat(", {0:0.##}{1}/s", totalChange / divisor / (Watchdog.WATCHDOG_INTERVAL_MS / 1000), UnitName);
}
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Cassandra.IntegrationTests.TestBase;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Tasks;
namespace Cassandra.IntegrationTests.Core
{
[Timeout(600000), Category("short")]
public class ConnectionTests : TestGlobals
{
[TestFixtureSetUp]
public void SetupFixture()
{
// we just need to make sure that there is a query-able cluster
TestClusterManager.GetTestCluster(1, DefaultMaxClusterCreateRetries, true, false);
}
public ConnectionTests()
{
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;
}
[Test]
public void BasicStartupTest()
{
using (var connection = CreateConnection())
{
Assert.DoesNotThrow(connection.Init);
}
}
[Test]
public void BasicQueryTest()
{
using (var connection = CreateConnection())
{
connection.Init();
//Start a query
var request = new QueryRequest(connection.ProtocolVersion, "SELECT * FROM system.schema_keyspaces", false, QueryProtocolOptions.Default);
var task = connection.Send(request);
task.Wait();
Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
//Result from Cassandra
var output = ValidateResult<OutputRows>(task.Result);
var rs = output.RowSet;
var rows = rs.ToList();
Assert.Greater(rows.Count, 0);
Assert.True(rows[0].GetValue<string>("keyspace_name") != null, "It should contain a keyspace name");
}
}
[Test]
public void PrepareQuery()
{
using (var connection = CreateConnection())
{
connection.Init();
var request = new PrepareRequest(connection.ProtocolVersion, "SELECT * FROM system.schema_keyspaces");
var task = connection.Send(request);
task.Wait();
Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
ValidateResult<OutputPrepared>(task.Result);
}
}
[Test]
public void PrepareResponseErrorFaultsTask()
{
using (var connection = CreateConnection())
{
connection.Init();
var request = new PrepareRequest(connection.ProtocolVersion, "SELECT WILL FAIL");
var task = connection.Send(request);
task.ContinueWith(t =>
{
Assert.AreEqual(TaskStatus.Faulted, t.Status);
Assert.IsInstanceOf<SyntaxError>(t.Exception.InnerException);
}, TaskContinuationOptions.ExecuteSynchronously).Wait();
}
}
[Test]
public void ExecutePreparedTest()
{
using (var connection = CreateConnection())
{
connection.Init();
//Prepare a query
var prepareRequest = new PrepareRequest(connection.ProtocolVersion, "SELECT * FROM system.schema_keyspaces");
var task = connection.Send(prepareRequest);
var prepareOutput = ValidateResult<OutputPrepared>(task.Result);
//Execute the prepared query
var executeRequest = new ExecuteRequest(connection.ProtocolVersion, prepareOutput.QueryId, null, false, QueryProtocolOptions.Default);
task = connection.Send(executeRequest);
var output = ValidateResult<OutputRows>(task.Result);
var rs = output.RowSet;
var rows = rs.ToList();
Assert.Greater(rows.Count, 0);
Assert.True(rows[0].GetValue<string>("keyspace_name") != null, "It should contain a keyspace name");
}
}
[Test]
public void ExecutePreparedWithParamTest()
{
using (var connection = CreateConnection())
{
connection.Init();
var prepareRequest = new PrepareRequest(connection.ProtocolVersion, "SELECT * FROM system.schema_columnfamilies WHERE keyspace_name = ?");
var task = connection.Send(prepareRequest);
var prepareOutput = ValidateResult<OutputPrepared>(task.Result);
var options = new QueryProtocolOptions(ConsistencyLevel.One, new[] { "system" }, false, 100, null, ConsistencyLevel.Any);
var executeRequest = new ExecuteRequest(connection.ProtocolVersion, prepareOutput.QueryId, null, false, options);
task = connection.Send(executeRequest);
var output = ValidateResult<OutputRows>(task.Result);
var rows = output.RowSet.ToList();
Assert.Greater(rows.Count, 0);
Assert.True(rows[0].GetValue<string>("columnfamily_name") != null, "It should contain a column family name");
}
}
[Test]
[TestCassandraVersion(2, 0)]
public void QueryCompressionLZ4Test()
{
var protocolOptions = new ProtocolOptions().SetCompression(CompressionType.LZ4);
using (var connection = CreateConnection(protocolOptions))
{
connection.Init();
//Start a query
var task = Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default);
task.Wait(360000);
Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
var output = ValidateResult<OutputRows>(task.Result);
var rs = output.RowSet;
var rows = rs.ToList();
Assert.Greater(rows.Count, 0);
Assert.True(rows[0].GetValue<string>("keyspace_name") != null, "It should contain a keyspace name");
}
}
[Test]
public void QueryCompressionSnappyTest()
{
var protocolOptions = new ProtocolOptions().SetCompression(CompressionType.Snappy);
using (var connection = CreateConnection(protocolOptions, null))
{
connection.Init();
//Start a query
var task = Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default);
task.Wait(360000);
Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
var output = ValidateResult<OutputRows>(task.Result);
var rs = output.RowSet;
var rows = rs.ToList();
Assert.Greater(rows.Count, 0);
Assert.True(rows[0].GetValue<string>("keyspace_name") != null, "It should contain a keyspace name");
}
}
/// <summary>
/// Test that a Response error from Cassandra results in a faulted task
/// </summary>
[Test]
public void QueryResponseErrorFaultsTask()
{
using (var connection = CreateConnection())
{
connection.Init();
//Start a query
var task = Query(connection, "SELECT WILL FAIL", QueryProtocolOptions.Default);
task.ContinueWith(t =>
{
Assert.AreEqual(TaskStatus.Faulted, t.Status);
Assert.IsInstanceOf<SyntaxError>(t.Exception.InnerException);
}, TaskContinuationOptions.ExecuteSynchronously).Wait();
}
}
[Test]
public void QueryMultipleAsyncTest()
{
//Try to fragment the message
var socketOptions = new SocketOptions().SetReceiveBufferSize(128);
using (var connection = CreateConnection(null, socketOptions))
{
connection.Init();
var taskList = new List<Task<AbstractResponse>>();
//Run a query multiple times
for (var i = 0; i < 16; i++)
{
//schema_columns
taskList.Add(Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default));
}
Task.WaitAll(taskList.ToArray());
foreach (var t in taskList)
{
Assert.AreEqual(TaskStatus.RanToCompletion, t.Status);
Assert.NotNull(t.Result);
}
}
}
[Test]
public void QueryMultipleAsyncConsumeAllStreamIdsTest()
{
using (var connection = CreateConnection())
{
connection.Init();
var createKeyspaceTask = Query(connection, "CREATE KEYSPACE ks_conn_consume WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 1}");
TaskHelper.WaitToComplete(createKeyspaceTask, 3000);
var createTableTask = Query(connection, "CREATE TABLE ks_conn_consume.tbl1 (id uuid primary key)");
TaskHelper.WaitToComplete(createTableTask, 3000);
var id = Guid.NewGuid().ToString("D");
var insertTask = Query(connection, "INSERT INTO ks_conn_consume.tbl1 (id) VALUES (" + id + ")");
TaskHelper.WaitToComplete(insertTask, 3000);
Assert.AreEqual(TaskStatus.RanToCompletion, createTableTask.Status);
var taskList = new List<Task>();
//Run the query more times than the max allowed
var selectQuery = "SELECT id FROM ks_conn_consume.tbl1 WHERE id = " + id;
for (var i = 0; i < connection.MaxConcurrentRequests * 2; i++)
{
taskList.Add(Query(connection, selectQuery, QueryProtocolOptions.Default));
}
Task.WaitAll(taskList.ToArray());
Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion), "Not all task completed");
}
}
[Test]
public void QueryMultipleSyncTest()
{
using (var connection = CreateConnection())
{
connection.Init();
//Run a query multiple times
for (var i = 0; i < 8; i++)
{
var task = Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default);
task.Wait(1000);
Assert.AreEqual(TaskStatus.RanToCompletion, task.Status);
Assert.NotNull(task.Result);
}
}
}
[Test]
public void RegisterForEvents()
{
var eventHandle = new AutoResetEvent(false);
CassandraEventArgs eventArgs = null;
using (var connection = CreateConnection())
{
connection.Init();
var eventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange;
var task = connection.Send(new RegisterForEventRequest(connection.ProtocolVersion, eventTypes));
TaskHelper.WaitToComplete(task, 1000);
Assert.IsInstanceOf<ReadyResponse>(task.Result);
connection.CassandraEventResponse += (o, e) =>
{
eventArgs = e;
eventHandle.Set();
};
//create a keyspace and check if gets received as an event
Query(connection, String.Format(TestUtils.CreateKeyspaceSimpleFormat, "test_events_kp", 1)).Wait(1000);
eventHandle.WaitOne(2000);
Assert.IsNotNull(eventArgs);
Assert.IsInstanceOf<SchemaChangeEventArgs>(eventArgs);
Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
Assert.IsNullOrEmpty((eventArgs as SchemaChangeEventArgs).Table);
//create a table and check if gets received as an event
Query(connection, String.Format(TestUtils.CreateTableAllTypes, "test_events_kp.test_table", 1)).Wait(1000);
eventHandle.WaitOne(2000);
Assert.IsNotNull(eventArgs);
Assert.IsInstanceOf<SchemaChangeEventArgs>(eventArgs);
Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
Assert.AreEqual("test_table", (eventArgs as SchemaChangeEventArgs).Table);
if (connection.ProtocolVersion >= 3)
{
//create a udt type
Query(connection, "CREATE TYPE test_events_kp.test_type (street text, city text, zip int);").Wait(1000);
eventHandle.WaitOne(2000);
Assert.IsNotNull(eventArgs);
Assert.IsInstanceOf<SchemaChangeEventArgs>(eventArgs);
Assert.AreEqual(SchemaChangeEventArgs.Reason.Created, (eventArgs as SchemaChangeEventArgs).What);
Assert.AreEqual("test_events_kp", (eventArgs as SchemaChangeEventArgs).Keyspace);
Assert.AreEqual("test_type", (eventArgs as SchemaChangeEventArgs).Type);
}
}
}
[Test, Timeout(5000)]
public void SendAndWait()
{
using (var connection = CreateConnection())
{
connection.Init();
const string query = "SELECT * FROM system.schema_columns";
Query(connection, query).
ContinueWith((t) =>
{
//Try to deadlock
Query(connection, query).Wait();
}, TaskContinuationOptions.ExecuteSynchronously).Wait();
}
}
[Test]
public void StreamModeReadAndWrite()
{
using (var connection = CreateConnection(new ProtocolOptions(), new SocketOptions().SetStreamMode(true)))
{
connection.Init();
var taskList = new List<Task<AbstractResponse>>();
//Run the query multiple times
for (var i = 0; i < 129; i++)
{
taskList.Add(Query(connection, "SELECT * FROM system.schema_columns", QueryProtocolOptions.Default));
}
Task.WaitAll(taskList.ToArray());
Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion), "Not all task completed");
//One last time
var task = Query(connection, "SELECT * FROM system.schema_keyspaces");
Assert.True(task.Result != null);
}
}
[Test]
[Explicit]
public void SslTest()
{
var certs = new X509CertificateCollection();
RemoteCertificateValidationCallback callback = (s, cert, chain, policyErrors) =>
{
if (policyErrors == SslPolicyErrors.None)
{
return true;
}
if ((policyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors &&
chain.ChainStatus.Length == 1 &&
chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
{
//self issued
return true;
}
return false;
};
var sslOptions = new SSLOptions().SetCertificateCollection(certs).SetRemoteCertValidationCallback(callback);
using (var connection = CreateConnection(new ProtocolOptions(ProtocolOptions.DefaultPort, sslOptions)))
{
connection.Init();
var taskList = new List<Task<AbstractResponse>>();
//Run the query multiple times
for (var i = 0; i < 129; i++)
{
taskList.Add(Query(connection, "SELECT * FROM system.schema_columns", QueryProtocolOptions.Default));
}
Task.WaitAll(taskList.ToArray());
Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion), "Not all task completed");
//One last time
var task = Query(connection, "SELECT * FROM system.schema_keyspaces");
Assert.True(task.Result != null);
}
}
[Test]
[Explicit]
public void AuthenticationWithV2Test()
{
byte protocolVersion = 2;
var config = new Configuration(
new Cassandra.Policies(),
new ProtocolOptions(),
new PoolingOptions(),
new SocketOptions(),
new ClientOptions(),
new PlainTextAuthProvider("username", "password"),
null,
new QueryOptions(),
new DefaultAddressTranslator());
using (var connection = CreateConnection(protocolVersion, config))
{
//Authentication will happen on init
connection.Init();
//Try to query
var r = TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM system.schema_keyspaces"), 60000);
Assert.IsInstanceOf<ResultResponse>(r);
}
//Check that it throws an authentication exception when credentials are invalid.
config = new Configuration(
new Cassandra.Policies(),
new ProtocolOptions(),
new PoolingOptions(),
new SocketOptions(),
new ClientOptions(),
new PlainTextAuthProvider("WRONGUSERNAME", "password"),
null,
new QueryOptions(),
new DefaultAddressTranslator());
using (var connection = CreateConnection(protocolVersion, config))
{
Assert.Throws<AuthenticationException>(connection.Init);
}
}
[Test]
[Explicit]
public void AuthenticationWithV1Test()
{
byte protocolVersion = 1;
var config = new Configuration(
new Cassandra.Policies(),
new ProtocolOptions(),
new PoolingOptions(),
new SocketOptions(),
new ClientOptions(),
NoneAuthProvider.Instance,
new SimpleAuthInfoProvider(new Dictionary<string, string> { { "username", "username" }, {"password", "password"} }),
new QueryOptions(),
new DefaultAddressTranslator());
using (var connection = CreateConnection(protocolVersion, config))
{
//Authentication will happen on init
connection.Init();
//Try to query
var r = TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM system.schema_keyspaces"), 60000);
Assert.IsInstanceOf<ResultResponse>(r);
}
//Check that it throws an authentication exception when credentials are invalid.
config = new Configuration(
new Cassandra.Policies(),
new ProtocolOptions(),
new PoolingOptions(),
new SocketOptions(),
new ClientOptions(),
NoneAuthProvider.Instance,
new SimpleAuthInfoProvider(new Dictionary<string, string> { { "username", "WRONGUSERNAME" }, { "password", "password" } }),
new QueryOptions(),
new DefaultAddressTranslator());
using (var connection = CreateConnection(protocolVersion, config))
{
Assert.Throws<AuthenticationException>(connection.Init);
}
}
[Test]
public void UseKeyspaceTest()
{
using (var connection = CreateConnection())
{
connection.Init();
Assert.Null(connection.Keyspace);
connection.Keyspace = "system";
//If it was executed correctly, it should be set
Assert.AreEqual("system", connection.Keyspace);
//Execute a query WITHOUT the keyspace prefix
TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM schema_keyspaces", QueryProtocolOptions.Default));
}
}
[Test]
public void UseKeyspaceWrongNameTest()
{
using (var connection = CreateConnection())
{
connection.Init();
Assert.Null(connection.Keyspace);
Assert.Throws<InvalidQueryException>(() => connection.Keyspace = "DOES_NOT_EXISTS");
//The keyspace should still be null
Assert.Null(connection.Keyspace);
//Execute a query WITH the keyspace prefix still works
TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default));
}
}
[Test]
public void WrongIpInitThrowsException()
{
var socketOptions = new SocketOptions();
socketOptions.SetConnectTimeoutMillis(1000);
var config = new Configuration(
new Cassandra.Policies(),
new ProtocolOptions(),
new PoolingOptions(),
socketOptions,
new ClientOptions(),
NoneAuthProvider.Instance,
null,
new QueryOptions(),
new DefaultAddressTranslator());
try
{
using (var connection = new Connection(1, new IPEndPoint(new IPAddress(new byte[] { 1, 1, 1, 1 }), 9042), config))
{
connection.Init();
Assert.Fail("It must throw an exception");
}
}
catch (SocketException ex)
{
//It should have timed out
Assert.AreEqual(SocketError.TimedOut, ex.SocketErrorCode);
}
try
{
using (var connection = new Connection(1, new IPEndPoint(new IPAddress(new byte[] { 255, 255, 255, 255 }), 9042), config))
{
connection.Init();
Assert.Fail("It must throw an exception");
}
}
catch (SocketException)
{
//Socket exception is just fine.
}
}
[Test]
public void ConnectionCloseFaultsAllPendingTasks()
{
var connection = CreateConnection();
connection.Init();
//Queue a lot of read and writes
var taskList = new List<Task<AbstractResponse>>();
for (var i = 0; i < 1024; i++)
{
taskList.Add(Query(connection, "SELECT * FROM system.schema_keyspaces"));
}
for (var i = 0; i < 1000; i++)
{
if (connection.InFlight > 0)
{
Trace.TraceInformation("Inflight {0}", connection.InFlight);
break;
}
//Wait until there is an operation in flight
Thread.Sleep(50);
}
//Close the socket, this would trigger all pending ops to be called back
connection.Dispose();
try
{
Task.WaitAll(taskList.ToArray());
}
catch (AggregateException)
{
//Its alright, it will fail
}
Assert.True(!taskList.Any(t => t.Status != TaskStatus.RanToCompletion && t.Status != TaskStatus.Faulted), "Must be only completed and faulted task");
//A new call to write will be called back immediately with an exception
var task = Query(connection, "SELECT * FROM system.schema_keyspaces");
//It will throw
Assert.Throws<AggregateException>(() => task.Wait(50));
}
/// <summary>
/// It checks that the connection startup method throws an exception when using a greater protocol version
/// </summary>
[Test]
[TestCassandraVersion(2, 0, Comparison.LessThan)]
public void StartupGreaterProtocolVersionThrows()
{
const byte protocolVersion = 2;
using (var connection = CreateConnection(protocolVersion, new Configuration()))
{
Assert.Throws<UnsupportedProtocolVersionException>(connection.Init);
}
}
[Test]
public void WithHeartbeatEnabledShouldSendRequest()
{
using (var connection = CreateConnection(null, null, new PoolingOptions().SetHeartBeatInterval(500)))
{
connection.Init();
//execute a dummy query
TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default));
var writeCounter = 0;
connection.WriteCompleted += () => writeCounter++;
Thread.Sleep(2200);
Assert.AreEqual(4, writeCounter);
}
}
[Test]
public void WithHeartbeatEnabledShouldRaiseWhenConnectionClosed()
{
using (var connection = CreateConnection(null, null, new PoolingOptions().SetHeartBeatInterval(500)))
{
connection.Init();
//execute a dummy query
TaskHelper.WaitToComplete(Query(connection, "SELECT * FROM system.schema_keyspaces", QueryProtocolOptions.Default));
var called = 0;
connection.OnIdleRequestException += (_) => called++;
connection.Kill();
Thread.Sleep(2000);
Assert.AreEqual(1, called);
}
}
private Connection CreateConnection(ProtocolOptions protocolOptions = null, SocketOptions socketOptions = null, PoolingOptions poolingOptions = null)
{
if (socketOptions == null)
{
socketOptions = new SocketOptions();
}
if (protocolOptions == null)
{
protocolOptions = new ProtocolOptions();
}
var config = new Configuration(
new Cassandra.Policies(),
protocolOptions,
poolingOptions,
socketOptions,
new ClientOptions(false, 20000, null),
NoneAuthProvider.Instance,
null,
new QueryOptions(),
new DefaultAddressTranslator());
return CreateConnection(GetLatestProtocolVersion(), config);
}
/// <summary>
/// Gets the latest protocol depending on the Cassandra Version running the tests
/// </summary>
private byte GetLatestProtocolVersion()
{
var cassandraVersion = CassandraVersion;
byte protocolVersion = 1;
if (cassandraVersion >= Version.Parse("2.1"))
{
protocolVersion = 3;
}
else if (cassandraVersion > Version.Parse("2.0"))
{
protocolVersion = 2;
}
return protocolVersion;
}
private Connection CreateConnection(byte protocolVersion, Configuration config)
{
Trace.TraceInformation("Creating test connection using protocol v{0}", protocolVersion);
return new Connection(protocolVersion, new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 9042), config);
}
private static Task<AbstractResponse> Query(Connection connection, string query, QueryProtocolOptions options = null)
{
if (options == null)
{
options = QueryProtocolOptions.Default;
}
var request = new QueryRequest(connection.ProtocolVersion, query, false, options);
return connection.Send(request);
}
private static T ValidateResult<T>(AbstractResponse response)
{
Assert.IsInstanceOf<ResultResponse>(response);
Assert.IsInstanceOf<T>(((ResultResponse)response).Output);
return (T)((ResultResponse)response).Output;
}
}
}
| |
/*
* 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 info@fyireporting.com |
* |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.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
namespace Reporting.RdlDesign
{
internal enum SingleCtlTypeEnum
{
InteractivityCtl, VisibilityCtl, BorderCtl, FontCtl, BackgroundCtl, BackgroundImage,
ReportParameterCtl, ReportCodeCtl, ReportModulesClassesCtl, ImageCtl, SubreportCtl,
FiltersCtl, SortingCtl, GroupingCtl
}
/// <summary>
/// Summary description for PropertyDialog.
/// </summary>
internal class SingleCtlDialog : System.Windows.Forms.Form
{
private DesignCtl _DesignCtl;
private DesignXmlDraw _Draw; // design draw
private List<XmlNode> _Nodes; // selected nodes
private SingleCtlTypeEnum _Type;
IProperty _Ctl;
private Button bOK;
private Button bCancel;
private Panel pMain;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal SingleCtlDialog(DesignCtl dc, DesignXmlDraw dxDraw, List<XmlNode> sNodes,
SingleCtlTypeEnum type, string[] names)
{
this._Type = type;
this._DesignCtl = dc;
this._Draw = dxDraw;
this._Nodes = sNodes;
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Add the control for the selected ReportItems
// We could have forced the user to create this (and maybe should have)
// instead of using an enum.
UserControl uc = null;
string title = null;
switch (type)
{
case SingleCtlTypeEnum.InteractivityCtl:
title = " - Interactivty";
uc = new InteractivityCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.VisibilityCtl:
title = " - Visibility";
uc = new VisibilityCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.BorderCtl:
title = " - Borders";
uc = new StyleBorderCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.FontCtl:
title = " - Font";
uc = new FontCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.BackgroundCtl:
title = " - Background";
uc = new BackgroundCtl(dxDraw, names, sNodes);
break;
case SingleCtlTypeEnum.ImageCtl:
title = " - Image";
uc = new ImageCtl(dxDraw, sNodes);
break;
case SingleCtlTypeEnum.SubreportCtl:
title = " - Subreport";
uc = new SubreportCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.FiltersCtl:
title = " - Filter";
uc = new FiltersCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.SortingCtl:
title = " - Sorting";
uc = new SortingCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.GroupingCtl:
title = " - Grouping";
uc = new GroupingCtl(dxDraw, sNodes[0]);
break;
case SingleCtlTypeEnum.ReportParameterCtl:
title = " - Report Parameters";
uc = new ReportParameterCtl(dxDraw);
break;
case SingleCtlTypeEnum.ReportCodeCtl:
title = " - Code";
uc = new CodeCtl(dxDraw);
break;
case SingleCtlTypeEnum.ReportModulesClassesCtl:
title = " - Modules and Classes";
uc = new ModulesClassesCtl(dxDraw);
break;
}
_Ctl = uc as IProperty;
if (title != null)
this.Text = this.Text + title;
if (uc == null)
return;
int h = uc.Height;
int w = uc.Width;
uc.Top = 0;
uc.Left = 0;
uc.Dock = DockStyle.Fill;
uc.Parent = this.pMain;
this.Height = h + (this.Height - pMain.Height);
this.Width = w + (this.Width - pMain.Width);
this.ResumeLayout(true);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.pMain = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOK.Location = new System.Drawing.Point(452, 410);
this.bOK.Name = "bOK";
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 0;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(542, 410);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 1;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
this.bCancel.Click += new System.EventHandler(this.bCancel_Click);
//
// pMain
//
this.pMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pMain.Location = new System.Drawing.Point(3, 3);
this.pMain.Name = "pMain";
this.pMain.Size = new System.Drawing.Size(614, 401);
this.pMain.TabIndex = 2;
//
// SingleCtlDialog
//
this.AcceptButton = this.bOK;
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(620, 436);
this.Controls.Add(this.pMain);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SingleCtlDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Properties";
this.ResumeLayout(false);
}
#endregion
private void bOK_Click(object sender, System.EventArgs e)
{
string c = "";
switch (_Type)
{
case SingleCtlTypeEnum.InteractivityCtl:
c = "Interactivity change";
break;
case SingleCtlTypeEnum.VisibilityCtl:
c = "Visibility change";
break;
case SingleCtlTypeEnum.BorderCtl:
c = "Border change";
break;
case SingleCtlTypeEnum.FontCtl:
c = "Appearance change";
break;
case SingleCtlTypeEnum.BackgroundCtl:
case SingleCtlTypeEnum.BackgroundImage:
c = "Background change";
break;
case SingleCtlTypeEnum.FiltersCtl:
c = "Filters change";
break;
case SingleCtlTypeEnum.SortingCtl:
c = "Sort change";
break;
case SingleCtlTypeEnum.GroupingCtl:
c = "Grouping change";
break;
case SingleCtlTypeEnum.ReportCodeCtl:
c = "Report code change";
break;
case SingleCtlTypeEnum.ImageCtl:
c = "Image change";
break;
case SingleCtlTypeEnum.SubreportCtl:
c = "Subreport change";
break;
case SingleCtlTypeEnum.ReportModulesClassesCtl:
c = "Report Modules/Classes change";
break;
}
this._DesignCtl.StartUndoGroup(c);
this._Ctl.Apply();
this._DesignCtl.EndUndoGroup(true);
_DesignCtl.SignalReportChanged();
_Draw.Invalidate();
this.DialogResult = DialogResult.OK;
}
private void bCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
| |
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor
{
/// <summary>Specifies options for encoding and decoding CBOR
/// objects.</summary>
public sealed class CBOREncodeOptions {
/// <summary>Default options for CBOR objects. Disallow duplicate keys,
/// and always encode strings using definite-length encoding.</summary>
public static readonly CBOREncodeOptions Default =
new CBOREncodeOptions(false, false);
/// <summary>Default options for CBOR objects serialized using the
/// CTAP2 canonicalization (used in Web Authentication, among other
/// specifications). Disallow duplicate keys, and always encode strings
/// using definite-length encoding.</summary>
public static readonly CBOREncodeOptions DefaultCtap2Canonical =
new CBOREncodeOptions(false, false, true);
/// <summary>Initializes a new instance of the
/// <see cref='PeterO.Cbor.CBOREncodeOptions'/> class.</summary>
public CBOREncodeOptions() : this(false, false) {
}
/// <summary>Initializes a new instance of the
/// <see cref='PeterO.Cbor.CBOREncodeOptions'/> class.</summary>
/// <param name='useIndefLengthStrings'>A value indicating whether to
/// always encode strings with a definite-length encoding.</param>
/// <param name='allowDuplicateKeys'>A value indicating whether to
/// disallow duplicate keys when reading CBOR objects from a data
/// stream.</param>
public CBOREncodeOptions(
bool useIndefLengthStrings,
bool allowDuplicateKeys)
: this(useIndefLengthStrings, allowDuplicateKeys, false) {
}
/// <summary>Initializes a new instance of the
/// <see cref='PeterO.Cbor.CBOREncodeOptions'/> class.</summary>
/// <param name='useIndefLengthStrings'>A value indicating whether to
/// encode strings with a definite-length encoding in certain
/// cases.</param>
/// <param name='allowDuplicateKeys'>A value indicating whether to
/// allow duplicate keys when reading CBOR objects from a data
/// stream.</param>
/// <param name='ctap2Canonical'>A value indicating whether CBOR
/// objects are written out using the CTAP2 canonical CBOR encoding
/// form, which is useful for implementing Web Authentication.</param>
public CBOREncodeOptions(
bool useIndefLengthStrings,
bool allowDuplicateKeys,
bool ctap2Canonical) {
this.ResolveReferences = false;
this.AllowEmpty = false;
this.UseIndefLengthStrings = useIndefLengthStrings;
this.AllowDuplicateKeys = allowDuplicateKeys;
this.Ctap2Canonical = ctap2Canonical;
}
/// <summary>Initializes a new instance of the
/// <see cref='PeterO.Cbor.CBOREncodeOptions'/> class.</summary>
/// <param name='paramString'>A string setting forth the options to
/// use. This is a semicolon-separated list of options, each of which
/// has a key and a value separated by an equal sign ("="). Whitespace
/// and line separators are not allowed to appear between the
/// semicolons or between the equal signs, nor may the string begin or
/// end with whitespace. The string can be empty, but cannot be null.
/// The following is an example of this parameter:
/// <c>allowduplicatekeys=true;ctap2Canonical=true</c>. The key can be
/// any one of the following where the letters can be any combination
/// of basic upper-case and/or basic lower-case letters:
/// <c>allowduplicatekeys</c>, <c>ctap2canonical</c>,
/// <c>resolvereferences</c>, <c>useindeflengthstrings</c>,
/// <c>allowempty</c>. Keys other than these are ignored. (Keys are
/// compared using a basic case-insensitive comparison, in which two
/// strings are equal if they match after converting the basic
/// upper-case letters A to Z (U+0041 to U+005A) in both strings to
/// basic lower-case letters.) If two or more key/value pairs have
/// equal keys (in a basic case-insensitive comparison), the value
/// given for the last such key is used. The four keys just given can
/// have a value of <c>1</c>, <c>true</c>, <c>yes</c>, or <c>on</c>
/// (where the letters can be any combination of basic upper-case
/// and/or basic lower-case letters), which means true, and any other
/// value meaning false. For example, <c>allowduplicatekeys=Yes</c> and
/// <c>allowduplicatekeys=1</c> both set the <c>AllowDuplicateKeys</c>
/// property to true. In the future, this class may allow other keys to
/// store other kinds of values, not just true or false.</param>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='paramString'/> is null.</exception>
public CBOREncodeOptions(string paramString) {
if (paramString == null) {
throw new ArgumentNullException(nameof(paramString));
}
var parser = new OptionsParser(paramString);
this.ResolveReferences = parser.GetBoolean("resolvereferences",
false);
this.UseIndefLengthStrings = parser.GetBoolean(
"useindeflengthstrings",
false);
this.AllowDuplicateKeys = parser.GetBoolean("allowduplicatekeys",
false);
this.AllowEmpty = parser.GetBoolean("allowempty", false);
this.Ctap2Canonical = parser.GetBoolean("ctap2canonical", false);
}
/// <summary>Gets the values of this options object's properties in
/// text form.</summary>
/// <returns>A text string containing the values of this options
/// object's properties. The format of the string is the same as the
/// one described in the String constructor for this class.</returns>
public override string ToString() {
return new System.Text.StringBuilder()
.Append("allowduplicatekeys=")
.Append(this.AllowDuplicateKeys ? "true" : "false")
.Append(";useindeflengthstrings=")
.Append(this.UseIndefLengthStrings ? "true" : "false")
.Append(";ctap2canonical=")
.Append(this.Ctap2Canonical ? "true" : "false")
.Append(";resolvereferences=")
.Append(this.ResolveReferences ? "true" : "false")
.Append(";allowempty=").Append(this.AllowEmpty ? "true" : "false")
.ToString();
}
/// <summary>Gets a value indicating whether to resolve references to
/// sharable objects and sharable strings in the process of decoding a
/// CBOR object. Enabling this property, however, can cause a security
/// risk if a decoded CBOR object is then re-encoded.</summary>
/// <value>A value indicating whether to resolve references to sharable
/// objects and sharable strings. The default is false.</value>
/// <remarks>
/// <para><b>About sharable objects and references</b></para>
/// <para>Sharable objects are marked with tag 28, and references to
/// those objects are marked with tag 29 (where a reference of 0 means
/// the first sharable object in the CBOR stream, a reference of 1
/// means the second, and so on). Sharable strings (byte strings and
/// text strings) appear within an enclosing object marked with tag
/// 256, and references to them are marked with tag 25; in general, a
/// string is sharable only if storing its reference rather than the
/// string would save space.</para>
/// <para>Note that unlike most other tags, these tags generally care
/// about the relative order in which objects appear in a CBOR stream;
/// thus they are not interoperable with CBOR implementations that
/// follow the generic CBOR data model (since they may list map keys in
/// an unspecified order). Interoperability problems with these tags
/// can be reduced by not using them to mark keys or values of a map or
/// to mark objects within those keys or values.</para>
/// <para><b>Security Note</b></para>
/// <para>When this property is enabled and a decoded CBOR object
/// contains references to sharable CBOR objects within it, those
/// references will be replaced with the sharable objects they refer to
/// (but without making a copy of those objects). However, if shared
/// references are deeply nested and used multiple times, these
/// references can result in a CBOR object that is orders of magnitude
/// bigger than if shared references weren't resolved, and this can
/// cause a denial of service when the decoded CBOR object is then
/// serialized (e.g., with <c>EncodeToBytes()</c>, <c>ToString()</c>,
/// <c>ToJSONString()</c>, or <c>WriteTo</c> ), because object
/// references are expanded in the process.</para>
/// <para>For example, the following object in CBOR diagnostic
/// notation, <c>[28(["xxx", "yyy"]), 28([29(0), 29(0), 29(0)]),
/// 28([29(1), 29(1)]), 28([29(2), 29(2)]), 28([29(3), 29(3)]),
/// 28([29(4), 29(4)]), 28([29(5), 29(5)])]</c>, expands to a CBOR
/// object with a serialized size of about 1831 bytes when this
/// property is enabled, as opposed to about 69 bytes when this
/// property is disabled.</para>
/// <para>One way to mitigate security issues with this property is to
/// limit the maximum supported size a CBORObject can have once
/// serialized to CBOR or JSON. This can be done by passing a so-called
/// "limited memory stream" to the <c>WriteTo</c> or <c>WriteJSONTo</c>
/// methods when serializing the object to JSON or CBOR. A "limited
/// memory stream" is a <c>Stream</c> (or <c>OutputStream</c> in Java)
/// that throws an exception if it would write more bytes than a given
/// maximum size or would seek past that size. (See the documentation
/// for <c>CBORObject.WriteTo</c> or <c>CBORObject.WriteJSONTo</c> for
/// example code.) Another mitigation is to check the CBOR object's
/// type before serializing it, since only arrays and maps can have the
/// security problem described here, or to check the maximum nesting
/// depth of a CBOR array or map before serializing
/// it.</para></remarks>
public bool ResolveReferences {
get;
private set;
}
/// <summary>Gets a value indicating whether to encode strings with an
/// indefinite-length encoding under certain circumstances.</summary>
/// <value>A value indicating whether to encode strings with an
/// indefinite-length encoding under certain circumstances. The default
/// is false.</value>
public bool UseIndefLengthStrings {
get;
private set;
}
/// <summary>Gets a value indicating whether decoding a CBOR object
/// will return <c>null</c> instead of a CBOR object if the stream has
/// no content or the end of the stream is reached before decoding
/// begins. Used only when decoding CBOR objects.</summary>
/// <value>A value indicating whether decoding a CBOR object will
/// return <c>null</c> instead of a CBOR object if the stream has no
/// content or the end of the stream is reached before decoding begins.
/// The default is false.</value>
public bool AllowEmpty {
get;
private set;
}
/// <summary>Gets a value indicating whether to allow duplicate keys
/// when reading CBOR objects from a data stream. Used only when
/// decoding CBOR objects. If this property is <c>true</c> and a CBOR
/// map has two or more values with the same key, the last value of
/// that key set forth in the CBOR map is taken.</summary>
/// <value>A value indicating whether to allow duplicate keys when
/// reading CBOR objects from a data stream. The default is
/// false.</value>
public bool AllowDuplicateKeys {
get;
private set;
}
/// <summary>Gets a value indicating whether CBOR objects:
/// <list>
/// <item>When encoding, are written out using the CTAP2 canonical CBOR
/// encoding form, which is useful for implementing Web
/// Authentication.</item>
/// <item>When decoding, are checked for compliance with the CTAP2
/// canonical encoding form.</item></list> In this form, CBOR tags are
/// not used, map keys are written out in a canonical order, a maximum
/// depth of four levels of arrays and/or maps is allowed, duplicate
/// map keys are not allowed when decoding, and floating-point numbers
/// are written out in their 64-bit encoding form regardless of whether
/// their value can be encoded without loss in a smaller form. This
/// implementation allows CBOR objects whose canonical form exceeds
/// 1024 bytes, the default maximum size for CBOR objects in that form
/// according to the FIDO Client-to-Authenticator Protocol 2
/// specification.</summary>
/// <value><c>true</c> if CBOR objects are written out using the CTAP2
/// canonical CBOR encoding form; otherwise, <c>false</c>. The default
/// is <c>false</c>.</value>
public bool Ctap2Canonical {
get;
private set;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
using osuTK.Graphics;
using JetBrains.Annotations;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneDrawableScrollingRuleset : OsuTestScene
{
/// <summary>
/// The amount of time visible by the "view window" of the playfield.
/// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000,
/// there will be at most 2 hitobjects visible in the "view window".
/// </summary>
private const double time_range = 1000;
private readonly ManualClock testClock = new ManualClock();
private TestDrawableScrollingRuleset drawableRuleset;
[SetUp]
public void Setup() => Schedule(() => testClock.CurrentTime = 0);
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestHitObjectLifetime(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertDead(3);
setTime(3 * time_range);
assertPosition(3, 0f);
assertDead(0);
setTime(0 * time_range);
assertPosition(0, 0f);
assertDead(3);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestNestedHitObject(string pooled)
{
var beatmap = createBeatmap(i =>
{
var h = pooled == "pooled" ? new TestPooledParentHitObject() : new TestParentHitObject();
h.Duration = 300;
h.ChildTimeOffset = i % 3 * 100;
return h;
});
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertHeight(0);
assertChildPosition(0);
setTime(5 * time_range);
assertPosition(5, 0f);
assertHeight(5);
assertChildPosition(5);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestLifetimeRecomputedWhenTimeRangeChanges(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertDead(3);
AddStep("increase time range", () => drawableRuleset.TimeRange.Value = 3 * time_range);
assertPosition(3, 1);
}
[Test]
public void TestRelativeBeatLengthScaleSingleTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
// The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear
// at the bottom of the view window regardless of the timing point's beat length
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
beatmap.ControlPointInfo.Add(12000, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(100000, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleFromSecondTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
// The first timing point should have a relative velocity of 2
assertPosition(0, 0f);
assertPosition(1, 0.5f);
assertPosition(2, 1f);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window
assertPosition(4, 1f);
}
[Test]
public void TestNonRelativeScale()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap);
assertPosition(0, 0f);
assertPosition(1, 1);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen)
// To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom
setTime(3 * time_range + time_range / 2);
assertPosition(4, 1f);
}
[Test]
public void TestSliderMultiplierDoesNotAffectRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.Difficulty.SliderMultiplier = 2;
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000);
for (int i = 0; i < 5; i++)
assertPosition(i, i / 5f);
}
[Test]
public void TestSliderMultiplierAffectsNonRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.Difficulty.SliderMultiplier = 2;
createTest(beatmap);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000);
assertPosition(0, 0);
assertPosition(1, 1);
}
/// <summary>
/// Get a <see cref="DrawableTestHitObject" /> corresponding to the <paramref name="index"/>'th <see cref="TestHitObject"/>.
/// When the hit object is not alive, `null` is returned.
/// </summary>
[CanBeNull]
private DrawableTestHitObject getDrawableHitObject(int index)
{
var hitObject = drawableRuleset.Beatmap.HitObjects.ElementAt(index);
return (DrawableTestHitObject)drawableRuleset.Playfield.HitObjectContainer.AliveObjects.FirstOrDefault(obj => obj.HitObject == hitObject);
}
private float yScale => drawableRuleset.Playfield.HitObjectContainer.DrawHeight;
private void assertDead(int index) => AddAssert($"hitobject {index} is dead", () => getDrawableHitObject(index) == null);
private void assertHeight(int index) => AddAssert($"hitobject {index} height", () =>
{
var d = getDrawableHitObject(index);
return d != null && Precision.AlmostEquals(d.DrawHeight, yScale * (float)(d.HitObject.Duration / time_range), 0.1f);
});
private void assertChildPosition(int index) => AddAssert($"hitobject {index} child position", () =>
{
var d = getDrawableHitObject(index);
return d is DrawableTestParentHitObject && Precision.AlmostEquals(
d.NestedHitObjects.First().DrawPosition.Y,
yScale * (float)((TestParentHitObject)d.HitObject).ChildTimeOffset / time_range, 0.1f);
});
private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}",
() => Precision.AlmostEquals(getDrawableHitObject(index)?.DrawPosition.Y ?? -1, yScale * relativeY));
private void setTime(double time)
{
AddStep($"set time = {time}", () => testClock.CurrentTime = time);
}
/// <summary>
/// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points.
/// The hitobjects are spaced <see cref="time_range"/> milliseconds apart.
/// </summary>
/// <returns>The <see cref="IBeatmap"/>.</returns>
private IBeatmap createBeatmap(Func<int, TestHitObject> createAction = null)
{
var beatmap = new Beatmap<TestHitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } };
for (int i = 0; i < 10; i++)
{
var h = createAction?.Invoke(i) ?? new TestHitObject();
h.StartTime = i * time_range;
beatmap.HitObjects.Add(h);
}
return beatmap;
}
private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () =>
{
var ruleset = new TestScrollingRuleset();
drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo));
drawableRuleset.FrameStablePlayback = false;
overrideAction?.Invoke(drawableRuleset);
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
Height = 0.75f,
Width = 400,
Masking = true,
Clock = new FramedClock(testClock),
Child = drawableRuleset
};
});
#region Ruleset
private class TestScrollingRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawableScrollingRuleset(this, beatmap, mods);
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, null);
public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description { get; } = string.Empty;
public override string ShortName { get; } = string.Empty;
}
private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject>
{
public bool RelativeScaleBeatLengthsOverride { get; set; }
protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride;
protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping;
public new Bindable<double> TimeRange => base.TimeRange;
public TestDrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
TimeRange.Value = time_range;
}
public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h)
{
switch (h)
{
case TestPooledHitObject _:
case TestPooledParentHitObject _:
return null;
case TestParentHitObject p:
return new DrawableTestParentHitObject(p);
default:
return new DrawableTestHitObject(h);
}
}
protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager();
protected override Playfield CreatePlayfield() => new TestPlayfield();
}
private class TestPlayfield : ScrollingPlayfield
{
public TestPlayfield()
{
AddInternal(new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.2f,
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 150 },
Children = new Drawable[]
{
new Box
{
Anchor = Anchor.TopCentre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Green
},
HitObjectContainer
}
}
}
});
RegisterPool<TestPooledHitObject, DrawableTestPooledHitObject>(1);
RegisterPool<TestPooledParentHitObject, DrawableTestPooledParentHitObject>(1);
}
}
private class TestBeatmapConverter : BeatmapConverter<TestHitObject>
{
public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)
: base(beatmap, ruleset)
{
}
public override bool CanConvert() => true;
protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken) =>
throw new NotImplementedException();
}
#endregion
#region HitObject
private class TestHitObject : HitObject, IHasDuration
{
public double EndTime => StartTime + Duration;
public double Duration { get; set; } = 100;
}
private class TestPooledHitObject : TestHitObject
{
}
private class TestParentHitObject : TestHitObject
{
public double ChildTimeOffset;
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class TestPooledParentHitObject : TestParentHitObject
{
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestPooledHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class DrawableTestHitObject : DrawableHitObject<TestHitObject>
{
public DrawableTestHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.TopCentre;
Origin = Anchor.TopCentre;
Size = new Vector2(100, 25);
AddRangeInternal(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.LightPink
},
new Box
{
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Red
}
});
}
protected override void Update() => LifetimeEnd = HitObject.EndTime;
}
private class DrawableTestPooledHitObject : DrawableTestHitObject
{
public DrawableTestPooledHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSkyBlue;
InternalChildren[1].Colour = Color4.Blue;
}
}
private class DrawableTestParentHitObject : DrawableTestHitObject
{
private readonly Container<DrawableHitObject> container;
public DrawableTestParentHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
InternalChildren[0].Colour = Color4.LightYellow;
InternalChildren[1].Colour = Color4.Yellow;
AddInternal(container = new Container<DrawableHitObject>
{
RelativeSizeAxes = Axes.Both,
});
}
protected override DrawableHitObject CreateNestedHitObject(HitObject hitObject) =>
new DrawableTestHitObject((TestHitObject)hitObject);
protected override void AddNestedHitObject(DrawableHitObject hitObject) => container.Add(hitObject);
protected override void ClearNestedHitObjects() => container.Clear(false);
}
private class DrawableTestPooledParentHitObject : DrawableTestParentHitObject
{
public DrawableTestPooledParentHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSeaGreen;
InternalChildren[1].Colour = Color4.Green;
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
namespace WeifenLuo.WinFormsUI.Docking
{
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
}
#region consts
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 1;
private const int _DocumentButtonGapBottom = 2;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 1;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 0;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 18;
private const int _DocumentIconWidth = 18;
private const int _DocumentTextGapRight = 3;
#endregion
private static Bitmap _imageButtonClose;
private static Bitmap ImageButtonClose
{
get
{
if (_imageButtonClose == null)
_imageButtonClose = Resources.DockPane_Close;
return _imageButtonClose;
}
}
private InertButton m_buttonClose;
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private static Bitmap _imageButtonWindowList;
private static Bitmap ImageButtonWindowList
{
get
{
if (_imageButtonWindowList == null)
_imageButtonWindowList = Resources.DockPane_Option;
return _imageButtonWindowList;
}
}
private static Bitmap _imageButtonWindowListOverflow;
private static Bitmap ImageButtonWindowListOverflow
{
get
{
if (_imageButtonWindowListOverflow == null)
_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return _imageButtonWindowListOverflow;
}
}
private InertButton m_buttonWindowList;
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private static GraphicsPath GraphicsPath
{
get { return VS2005AutoHideStrip.GraphicsPath; }
}
private IContainer m_components;
private ToolTip m_toolTip;
private IContainer Components
{
get { return m_components; }
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private static string _toolTipClose;
private static string ToolTipClose
{
get
{
if (_toolTipClose == null)
_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return _toolTipClose;
}
}
private static string _toolTipSelect;
private static string ToolTipSelect
{
get
{
if (_toolTipSelect == null)
_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return _toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private static Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private static Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private static Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
public VS2005DockPaneStrip(DockPane pane) : base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose (disposing);
}
private static Font TextFont
{
get { return SystemInformation.MenuFont; }
}
private Font m_font;
private Font m_boldFont;
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int m_startDisplayingTab = 0;
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int m_endDisplayingTab = 0;
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int m_firstDisplayingTab = 0;
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool m_documentTabsOverflow = false;
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
protected internal override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop,
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
if (rect.Width > 0 && rect.Height > 0)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode))
{
e.Graphics.FillRectangle(brush, rect);
}
}
base.OnPaint (e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
protected internal override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
int y = rectTab.Top;
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage=true; anyWidthWithinAverage && remainedTabs>0;)
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth --;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected internal override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i=0; i<count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, Tabs[i] as TabVS2005, rectTab);
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = GetTabRectangle(Tabs.IndexOf(tabActive));
if (rectTab.IntersectsWith(rectTabOnly))
DrawTab(g, tabActive, rectTab);
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i=0; i<Tabs.Count; i++)
DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i));
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab, rect);
else
DrawTab_Document(g, tab, rect);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
// Draws the full angle piece for active content (or first tab)
if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
// Draws the partial angle for non-active content
else
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90);
}
else
{
// Draws the top horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
// Draws the rounded corner oppposite the angled side
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
}
else
{
// Draw the vertical line opposite the angled side
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
else
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect)
{
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
g.DrawPath(PenToolWindowTabBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path);
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect)
{
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += rect.X;
rectBack.X = 0;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabActiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode;
g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path);
g.DrawPath(PenDocumentTabInactiveBorder, path);
Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip m_selectMenu;
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
private void WindowList_Click(object sender, EventArgs e)
{
int x = 0;
int y = ButtonWindowList.Location.Y + ButtonWindowList.Height;
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
SelectMenu.Show(ButtonWindowList, x, y);
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
bool showCloseButton = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
ButtonClose.Enabled = showCloseButton;
ButtonClose.Visible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance != DockPane.AppearanceStyle.Document)
{
base.OnLayout(levent);
return;
}
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * (height / buttonHeight);
buttonHeight = height;
}
#region activeware
//buttonWidth = 16;
buttonHeight = 18;
#endregion
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
//y -= 2;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (ButtonClose.Visible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
OnRefreshChanges();
base.OnLayout (levent);
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
}
protected internal override int HitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
if (!TabsRectangle.Contains(ptMouse))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(ptMouse))
return Tabs.IndexOf(tab);
}
return -1;
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.