context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.Collections.Generic;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// Huffman tree used for inflation
/// </summary>
public class InflaterHuffmanTree
{
#region Constants
private const int MAX_BITLEN = 15;
#endregion Constants
#region Instance Fields
private short[] tree;
#endregion Instance Fields
/// <summary>
/// Literal length tree
/// </summary>
public static InflaterHuffmanTree defLitLenTree;
/// <summary>
/// Distance tree
/// </summary>
public static InflaterHuffmanTree defDistTree;
static InflaterHuffmanTree()
{
try
{
byte[] codeLengths = new byte[288];
int i = 0;
while (i < 144)
{
codeLengths[i++] = 8;
}
while (i < 256)
{
codeLengths[i++] = 9;
}
while (i < 280)
{
codeLengths[i++] = 7;
}
while (i < 288)
{
codeLengths[i++] = 8;
}
defLitLenTree = new InflaterHuffmanTree(codeLengths);
codeLengths = new byte[32];
i = 0;
while (i < 32)
{
codeLengths[i++] = 5;
}
defDistTree = new InflaterHuffmanTree(codeLengths);
}
catch (Exception)
{
throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
}
}
#region Constructors
/// <summary>
/// Constructs a Huffman tree from the array of code lengths.
/// </summary>
/// <param name = "codeLengths">
/// the array of code lengths
/// </param>
public InflaterHuffmanTree(IList<byte> codeLengths)
{
BuildTree(codeLengths);
}
#endregion Constructors
private void BuildTree(IList<byte> codeLengths)
{
int[] blCount = new int[MAX_BITLEN + 1];
int[] nextCode = new int[MAX_BITLEN + 1];
for (int i = 0; i < codeLengths.Count; i++)
{
int bits = codeLengths[i];
if (bits > 0)
{
blCount[bits]++;
}
}
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++)
{
nextCode[bits] = code;
code += blCount[bits] << (16 - bits);
if (bits >= 10)
{
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
/* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g
if (code != 65536)
{
throw new SharpZipBaseException("Code lengths don't add up properly.");
}
*/
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--)
{
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7)
{
tree[DeflaterHuffman.BitReverse(i)] = (short)((-treePtr << 4) | bits);
treePtr += 1 << (bits - 9);
}
}
for (int i = 0; i < codeLengths.Count; i++)
{
int bits = codeLengths[i];
if (bits == 0)
{
continue;
}
code = nextCode[bits];
int revcode = DeflaterHuffman.BitReverse(code);
if (bits <= 9)
{
do
{
tree[revcode] = (short)((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < 512);
}
else
{
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do
{
tree[subTree | (revcode >> 9)] = (short)((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
/// <summary>
/// Reads the next symbol from input. The symbol is encoded using the
/// huffman tree.
/// </summary>
/// <param name="input">
/// input the input source.
/// </param>
/// <returns>
/// the next symbol, or -1 if not enough input is available.
/// </returns>
public int GetSymbol(StreamManipulator input)
{
int lookahead, symbol;
if ((lookahead = input.PeekBits(9)) >= 0)
{
symbol = tree[lookahead];
int bitlen = symbol & 15;
if (symbol >= 0)
{
if(bitlen == 0){
throw new SharpZipBaseException("Encountered invalid codelength 0");
}
input.DropBits(bitlen);
return symbol >> 4;
}
int subtree = -(symbol >> 4);
if ((lookahead = input.PeekBits(bitlen)) >= 0)
{
symbol = tree[subtree | (lookahead >> 9)];
input.DropBits(symbol & 15);
return symbol >> 4;
}
else
{
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[subtree | (lookahead >> 9)];
if ((symbol & 15) <= bits)
{
input.DropBits(symbol & 15);
return symbol >> 4;
}
else
{
return -1;
}
}
}
else // Less than 9 bits
{
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[lookahead];
if (symbol >= 0 && (symbol & 15) <= bits)
{
input.DropBits(symbol & 15);
return symbol >> 4;
}
else
{
return -1;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexConstructorTests
{
public static IEnumerable<object[]> Ctor_TestData()
{
yield return new object[] { "foo", RegexOptions.None, Timeout.InfiniteTimeSpan };
yield return new object[] { "foo", RegexOptions.RightToLeft, Timeout.InfiniteTimeSpan };
yield return new object[] { "foo", RegexOptions.Compiled, Timeout.InfiniteTimeSpan };
yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant, Timeout.InfiniteTimeSpan };
yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled, Timeout.InfiniteTimeSpan };
yield return new object[] { "foo", RegexOptions.None, new TimeSpan(1) };
yield return new object[] { "foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue - 1) };
}
[Theory]
[MemberData(nameof(Ctor_TestData))]
public static void Ctor(string pattern, RegexOptions options, TimeSpan matchTimeout)
{
if (matchTimeout == Timeout.InfiniteTimeSpan)
{
if (options == RegexOptions.None)
{
Regex regex1 = new Regex(pattern);
Assert.Equal(pattern, regex1.ToString());
Assert.Equal(options, regex1.Options);
Assert.False(regex1.RightToLeft);
Assert.Equal(matchTimeout, regex1.MatchTimeout);
}
Regex regex2 = new Regex(pattern, options);
Assert.Equal(pattern, regex2.ToString());
Assert.Equal(options, regex2.Options);
Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex2.RightToLeft);
Assert.Equal(matchTimeout, regex2.MatchTimeout);
}
Regex regex3 = new Regex(pattern, options, matchTimeout);
Assert.Equal(pattern, regex3.ToString());
Assert.Equal(options, regex3.Options);
Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex3.RightToLeft);
Assert.Equal(matchTimeout, regex3.MatchTimeout);
}
[Fact]
public static void Ctor_Invalid()
{
// Pattern is null
Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null));
Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None));
Assert.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None, new TimeSpan()));
// Options are invalid
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1)));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1), new TimeSpan()));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x400, new TimeSpan()));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.RightToLeft));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Singleline));
Assert.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace));
// MatchTimeout is invalid
Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, new TimeSpan(-1)));
Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue)));
}
[Fact]
public void CacheSize_Get()
{
Assert.Equal(15, Regex.CacheSize);
}
[Theory]
[InlineData(0)]
[InlineData(12)]
public void CacheSize_Set(int newCacheSize)
{
int originalCacheSize = Regex.CacheSize;
Regex.CacheSize = newCacheSize;
Assert.Equal(newCacheSize, Regex.CacheSize);
Regex.CacheSize = originalCacheSize;
}
[Fact]
public void CacheSize_Set_NegativeValue_ThrowsArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => Regex.CacheSize = -1);
}
[Theory]
// \d, \D, \s, \S, \w, \W, \P, \p inside character range
[InlineData(@"cat([a-\d]*)dog", RegexOptions.None)]
[InlineData(@"([5-\D]*)dog", RegexOptions.None)]
[InlineData(@"cat([6-\s]*)dog", RegexOptions.None)]
[InlineData(@"cat([c-\S]*)", RegexOptions.None)]
[InlineData(@"cat([7-\w]*)", RegexOptions.None)]
[InlineData(@"cat([a-\W]*)dog", RegexOptions.None)]
[InlineData(@"([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)", RegexOptions.None)]
[InlineData(@"([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", RegexOptions.None)]
[InlineData(@"[\p]", RegexOptions.None)]
[InlineData(@"[\P]", RegexOptions.None)]
[InlineData(@"([\pcat])", RegexOptions.None)]
[InlineData(@"([\Pcat])", RegexOptions.None)]
[InlineData(@"(\p{", RegexOptions.None)]
[InlineData(@"(\p{Ll", RegexOptions.None)]
// \x, \u, \a, \b, \e, \f, \n, \r, \t, \v, \c, inside character range
[InlineData(@"(cat)([\o]*)(dog)", RegexOptions.None)]
// Use < in a group
[InlineData(@"cat(?<0>dog)", RegexOptions.None)]
[InlineData(@"cat(?<1dog>dog)", RegexOptions.None)]
[InlineData(@"cat(?<dog)_*>dog)", RegexOptions.None)]
[InlineData(@"cat(?<dog!>)_*>dog)", RegexOptions.None)]
[InlineData(@"cat(?<dog >)_*>dog)", RegexOptions.None)]
[InlineData(@"cat(?<dog<>)_*>dog)", RegexOptions.None)]
[InlineData(@"cat(?<>dog)", RegexOptions.None)]
[InlineData(@"cat(?<->dog)", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\w+(?<dog-16>dog)", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\w+(?<dog-1uosn>dog)", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\w+(?<dog-catdog>dog)", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\w+(?<dog-()*!@>dog)", RegexOptions.None)]
// Use (? in a group
[InlineData("cat(?(?#COMMENT)cat)", RegexOptions.None)]
[InlineData("cat(?(?'cat'cat)dog)", RegexOptions.None)]
[InlineData("cat(?(?<cat>cat)dog)", RegexOptions.None)]
[InlineData("cat(?(?afdcat)dog)", RegexOptions.None)]
// Pattern whitespace
[InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.IgnorePatternWhitespace)]
[InlineData(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.None)]
// Back reference
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\kcat", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<cat2>", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.ECMAScript)]
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.None)]
[InlineData(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.ECMAScript)]
// Octal, decimal
[InlineData(@"(cat)(\7)", RegexOptions.None)]
[InlineData(@"(cat)\s+(?<2147483648>dog)", RegexOptions.None)]
[InlineData(@"(cat)\s+(?<21474836481097>dog)", RegexOptions.None)]
// Scan control
[InlineData(@"(cat)(\c*)(dog)", RegexOptions.None)]
[InlineData(@"(cat)\c", RegexOptions.None)]
[InlineData(@"(cat)(\c *)(dog)", RegexOptions.None)]
[InlineData(@"(cat)(\c?*)(dog)", RegexOptions.None)]
[InlineData("(cat)(\\c\0*)(dog)", RegexOptions.None)]
[InlineData(@"(cat)(\c`*)(dog)", RegexOptions.None)]
[InlineData(@"(cat)(\c\|*)(dog)", RegexOptions.None)]
[InlineData(@"(cat)(\c\[*)(dog)", RegexOptions.None)]
// Nested quantifiers
[InlineData("^[abcd]{0,16}*$", RegexOptions.None)]
[InlineData("^[abcd]{1,}*$", RegexOptions.None)]
[InlineData("^[abcd]{1}*$", RegexOptions.None)]
[InlineData("^[abcd]{0,16}?*$", RegexOptions.None)]
[InlineData("^[abcd]{1,}?*$", RegexOptions.None)]
[InlineData("^[abcd]{1}?*$", RegexOptions.None)]
[InlineData("^[abcd]*+$", RegexOptions.None)]
[InlineData("^[abcd]+*$", RegexOptions.None)]
[InlineData("^[abcd]?*$", RegexOptions.None)]
[InlineData("^[abcd]*?+$", RegexOptions.None)]
[InlineData("^[abcd]+?*$", RegexOptions.None)]
[InlineData("^[abcd]??*$", RegexOptions.None)]
[InlineData("^[abcd]*{0,5}$", RegexOptions.None)]
[InlineData("^[abcd]+{0,5}$", RegexOptions.None)]
[InlineData("^[abcd]?{0,5}$", RegexOptions.None)]
// Invalid character escapes
[InlineData(@"\u", RegexOptions.None)]
[InlineData(@"\ua", RegexOptions.None)]
[InlineData(@"\u0", RegexOptions.None)]
[InlineData(@"\x", RegexOptions.None)]
[InlineData(@"\x2", RegexOptions.None)]
// Invalid character class
[InlineData("[", RegexOptions.None)]
[InlineData("[]", RegexOptions.None)]
[InlineData("[a", RegexOptions.None)]
[InlineData("[^", RegexOptions.None)]
[InlineData("[cat", RegexOptions.None)]
[InlineData("[^cat", RegexOptions.None)]
[InlineData("[a-", RegexOptions.None)]
[InlineData(@"\p{", RegexOptions.None)]
[InlineData(@"\p{cat", RegexOptions.None)]
[InlineData(@"\p{cat}", RegexOptions.None)]
[InlineData(@"\P{", RegexOptions.None)]
[InlineData(@"\P{cat", RegexOptions.None)]
[InlineData(@"\P{cat}", RegexOptions.None)]
// Invalid grouping constructs
[InlineData("(", RegexOptions.None)]
[InlineData("(?", RegexOptions.None)]
[InlineData("(?<", RegexOptions.None)]
[InlineData("(?<cat>", RegexOptions.None)]
[InlineData("(?'", RegexOptions.None)]
[InlineData("(?'cat'", RegexOptions.None)]
[InlineData("(?:", RegexOptions.None)]
[InlineData("(?imn", RegexOptions.None)]
[InlineData("(?imn )", RegexOptions.None)]
[InlineData("(?=", RegexOptions.None)]
[InlineData("(?!", RegexOptions.None)]
[InlineData("(?<=", RegexOptions.None)]
[InlineData("(?<!", RegexOptions.None)]
[InlineData("(?>", RegexOptions.None)]
[InlineData("(?)", RegexOptions.None)]
[InlineData("(?<)", RegexOptions.None)]
[InlineData("(?')", RegexOptions.None)]
[InlineData(@"\1", RegexOptions.None)]
[InlineData(@"\1", RegexOptions.None)]
[InlineData(@"\k", RegexOptions.None)]
[InlineData(@"\k<", RegexOptions.None)]
[InlineData(@"\k<1", RegexOptions.None)]
[InlineData(@"\k<cat", RegexOptions.None)]
[InlineData(@"\k<>", RegexOptions.None)]
// Invalid alternation constructs
[InlineData("(?(", RegexOptions.None)]
[InlineData("(?()|", RegexOptions.None)]
[InlineData("(?(cat", RegexOptions.None)]
[InlineData("(?(cat)|", RegexOptions.None)]
// Regex with 0 numeric names
[InlineData("foo(?<0>bar)", RegexOptions.None)]
[InlineData("foo(?'0'bar)", RegexOptions.None)]
// Regex without closing >
[InlineData("foo(?<1bar)", RegexOptions.None)]
[InlineData("foo(?'1bar)", RegexOptions.None)]
// Misc
[InlineData(@"\p{klsak", RegexOptions.None)]
[InlineData("(?r:cat)", RegexOptions.None)]
[InlineData("(?c:cat)", RegexOptions.None)]
[InlineData("(??e:cat)", RegexOptions.None)]
// Character class subtraction
[InlineData("[a-f-[]]+", RegexOptions.None)]
// Not character class substraction
[InlineData("[A-[]+", RegexOptions.None)]
public void Ctor_InvalidPattern(string pattern, RegexOptions options)
{
Assert.Throws<ArgumentException>(() => new Regex(pattern, options));
}
}
}
| |
/*
*
* 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 J2N.IO;
using J2N.Text;
using Lucene.Net;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
/*
Egothor Software License version 1.00
Copyright (C) 1997-2004 Leo Galambos.
Copyright (C) 2002-2004 "Egothor developers"
on behalf of the Egothor Project.
All rights reserved.
This software is copyrighted by the "Egothor developers". If this
license applies to a single file or document, the "Egothor developers"
are the people or entities mentioned as copyright holders in that file
or document. If this license applies to the Egothor project as a
whole, the copyright holders are the people or entities mentioned in
the file CREDITS. This file can be found in the same location as this
license in the distribution.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, the list of contributors, this list of conditions, and the
following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, the list of contributors, this list of conditions, and the
disclaimer that follows these conditions in the documentation
and/or other materials provided with the distribution.
3. The name "Egothor" must not be used to endorse or promote products
derived from this software without prior written permission. For
written permission, please contact Leo.G@seznam.cz
4. Products derived from this software may not be called "Egothor",
nor may "Egothor" appear in their name, without prior written
permission from Leo.G@seznam.cz.
In addition, we request that you include in the end-user documentation
provided with the redistribution and/or in the software itself an
acknowledgement equivalent to the following:
"This product includes software developed by the Egothor Project.
http://egothor.sf.net/"
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE EGOTHOR PROJECT OR ITS 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.
This software consists of voluntary contributions made by many
individuals on behalf of the Egothor Project and was originally
created by Leo Galambos (Leo.G@seznam.cz).
*/
namespace Egothor.Stemmer
{
public class TestCompile_ : LuceneTestCase
{
[Test]
public void TestCompile()
{
DirectoryInfo dir = CreateTempDir("testCompile");
dir.Create();
FileInfo output;
using (Stream input = GetType().getResourceAsStream("testRules.txt"))
{
output = new FileInfo(Path.Combine(dir.FullName, "testRules.txt"));
Copy(input, output);
}
string path = output.FullName;
Compile.Main(new string[] {"test", path });
string compiled = path + ".out";
Trie trie = LoadTrie(compiled);
AssertTrie(trie, path, true, true);
AssertTrie(trie, path, false, true);
new FileInfo(compiled).Delete();
}
[Test]
public void TestCompileBackwards()
{
DirectoryInfo dir = CreateTempDir("testCompile");
dir.Create();
FileInfo output;
using (Stream input = GetType().getResourceAsStream("testRules.txt"))
{
output = new FileInfo(Path.Combine(dir.FullName, "testRules.txt"));
Copy(input, output);
}
string path = output.FullName;
Compile.Main(new string[] { "-test", path });
string compiled = path + ".out";
Trie trie = LoadTrie(compiled);
AssertTrie(trie, path, true, true);
AssertTrie(trie, path, false, true);
new FileInfo(compiled).Delete();
}
[Test]
public void TestCompileMulti()
{
DirectoryInfo dir = CreateTempDir("testCompile");
dir.Create();
FileInfo output;
using (Stream input = GetType().getResourceAsStream("testRules.txt"))
{
output = new FileInfo(Path.Combine(dir.FullName, "testRules.txt"));
Copy(input, output);
}
string path = output.FullName;
Compile.Main(new string[] { "Mtest", path });
string compiled = path + ".out";
Trie trie = LoadTrie(compiled);
AssertTrie(trie, path, true, true);
AssertTrie(trie, path, false, true);
new FileInfo(compiled).Delete();
}
internal static Trie LoadTrie(string path)
{
Trie trie;
using (DataInputStream @is = new DataInputStream(
new FileStream(path, FileMode.Open, FileAccess.Read)))
{
string method = @is.ReadUTF().ToUpperInvariant();
if (method.IndexOf('M') < 0)
{
trie = new Trie(@is);
}
else
{
trie = new MultiTrie(@is);
}
}
return trie;
}
private static void AssertTrie(Trie trie, string file, bool usefull,
bool storeorig)
{
using (TextReader @in =
new StreamReader(new FileStream(file, FileMode.Open), Encoding.UTF8))
{
for (string line = @in.ReadLine(); line != null; line = @in.ReadLine())
{
try
{
line = line.ToLowerInvariant();
StringTokenizer st = new StringTokenizer(line);
st.MoveNext();
string stem = st.Current;
if (storeorig)
{
string cmd = (usefull) ? trie.GetFully(stem) : trie
.GetLastOnPath(stem);
StringBuilder stm = new StringBuilder(stem);
Diff.Apply(stm, cmd);
assertEquals(stem.ToLowerInvariant(), stm.ToString().ToLowerInvariant());
}
while (st.MoveNext())
{
string token = st.Current;
if (token.Equals(stem, StringComparison.Ordinal))
{
continue;
}
string cmd = (usefull) ? trie.GetFully(token) : trie
.GetLastOnPath(token);
StringBuilder stm = new StringBuilder(token);
Diff.Apply(stm, cmd);
assertEquals(stem.ToLowerInvariant(), stm.ToString().ToLowerInvariant());
}
}
catch (InvalidOperationException /*x*/)
{
// no base token (stem) on a line
}
}
}
}
private static void Copy(Stream input, FileInfo output)
{
FileStream os = new FileStream(output.FullName, FileMode.OpenOrCreate, FileAccess.Write);
try
{
byte[] buffer = new byte[1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
os.Write(buffer, 0, len);
}
}
finally
{
os.Dispose();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TesteAdoNetRest.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Linq;
using Lucene.Net.Documents;
using Lucene.Net.Support;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using FSDirectory = Lucene.Net.Store.FSDirectory;
using CompressionTools = Lucene.Net.Documents.CompressionTools;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using TermQuery = Lucene.Net.Search.TermQuery;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
using Lucene.Net.Util;
namespace Lucene.Net.Index
{
/*
Verify we can read the pre-2.1 file format, do searches
against it, and add documents to it.*/
[TestFixture]
public class TestBackwardsCompatibility:LuceneTestCase
{
// Uncomment these cases & run them on an older Lucene
// version, to generate an index to test backwards
// compatibility. Then, cd to build/test/index.cfs and
// run "zip index.<VERSION>.cfs.zip *"; cd to
// build/test/index.nocfs and run "zip
// index.<VERSION>.nocfs.zip *". Then move those 2 zip
// files to your trunk checkout and add them to the
// oldNames array.
/*
public void testCreatePreLocklessCFS() throws IOException {
createIndex("index.cfs", true);
}
public void testCreatePreLocklessNoCFS() throws IOException {
createIndex("index.nocfs", false);
}
*/
public class AnonymousFieldSelector : FieldSelector
{
public FieldSelectorResult Accept(string fieldName)
{
return ("compressed".Equals(fieldName)) ? FieldSelectorResult.SIZE : FieldSelectorResult.LOAD;
}
}
/* Unzips dirName + ".zip" --> dirName, removing dirName
first */
public virtual void Unzip(System.String zipName, System.String destDirName)
{
#if SHARP_ZIP_LIB
// get zip input stream
ICSharpCode.SharpZipLib.Zip.ZipInputStream zipFile;
zipFile = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(System.IO.File.OpenRead(zipName + ".zip"));
// get dest directory name
System.String dirName = FullDir(destDirName);
System.IO.FileInfo fileDir = new System.IO.FileInfo(dirName);
// clean up old directory (if there) and create new directory
RmDir(fileDir.FullName);
System.IO.Directory.CreateDirectory(fileDir.FullName);
// copy file entries from zip stream to directory
ICSharpCode.SharpZipLib.Zip.ZipEntry entry;
while ((entry = zipFile.GetNextEntry()) != null)
{
System.IO.Stream streamout = new System.IO.BufferedStream(new System.IO.FileStream(new System.IO.FileInfo(System.IO.Path.Combine(fileDir.FullName, entry.Name)).FullName, System.IO.FileMode.Create));
byte[] buffer = new byte[8192];
int len;
while ((len = zipFile.Read(buffer, 0, buffer.Length)) > 0)
{
streamout.Write(buffer, 0, len);
}
streamout.Close();
}
zipFile.Close();
#else
Assert.Fail("Needs integration with SharpZipLib");
#endif
}
[Test]
public virtual void TestCreateCFS()
{
System.String dirName = "testindex.cfs";
CreateIndex(dirName, true);
RmDir(dirName);
}
[Test]
public virtual void TestCreateNoCFS()
{
System.String dirName = "testindex.nocfs";
CreateIndex(dirName, true);
RmDir(dirName);
}
internal string[] oldNames = new []
{
"19.cfs", "19.nocfs", "20.cfs", "20.nocfs", "21.cfs", "21.nocfs", "22.cfs",
"22.nocfs", "23.cfs", "23.nocfs", "24.cfs", "24.nocfs", "29.cfs",
"29.nocfs"
};
[Test]
private void assertCompressedFields29(Directory dir, bool shouldStillBeCompressed)
{
int count = 0;
int TEXT_PLAIN_LENGTH = TEXT_TO_COMPRESS.Length*2;
// FieldSelectorResult.SIZE returns 2*number_of_chars for String fields:
int BINARY_PLAIN_LENGTH = BINARY_TO_COMPRESS.Length;
IndexReader reader = IndexReader.Open(dir, true);
try
{
// look into sub readers and check if raw merge is on/off
var readers = new System.Collections.Generic.List<IndexReader>();
ReaderUtil.GatherSubReaders(readers, reader);
foreach (IndexReader ir in readers)
{
FieldsReader fr = ((SegmentReader) ir).GetFieldsReader();
Assert.IsTrue(shouldStillBeCompressed != fr.CanReadRawDocs(),
"for a 2.9 index, FieldsReader.canReadRawDocs() must be false and other way round for a trunk index");
}
// test that decompression works correctly
for (int i = 0; i < reader.MaxDoc; i++)
{
if (!reader.IsDeleted(i))
{
Document d = reader.Document(i);
if (d.Get("content3") != null) continue;
count++;
IFieldable compressed = d.GetFieldable("compressed");
if (int.Parse(d.Get("id"))%2 == 0)
{
Assert.IsFalse(compressed.IsBinary);
Assert.AreEqual(TEXT_TO_COMPRESS, compressed.StringValue,
"incorrectly decompressed string");
}
else
{
Assert.IsTrue(compressed.IsBinary);
Assert.IsTrue(BINARY_TO_COMPRESS.SequenceEqual(compressed.GetBinaryValue()),
"incorrectly decompressed binary");
}
}
}
//check if field was decompressed after optimize
for (int i = 0; i < reader.MaxDoc; i++)
{
if (!reader.IsDeleted(i))
{
Document d = reader.Document(i, new AnonymousFieldSelector());
if (d.Get("content3") != null) continue;
count++;
// read the size from the binary value using BinaryReader (this prevents us from doing the shift ops ourselves):
// ugh, Java uses Big-Endian streams, so we need to do it manually.
byte[] encodedSize = d.GetFieldable("compressed").GetBinaryValue().Take(4).Reverse().ToArray();
int actualSize = BitConverter.ToInt32(encodedSize, 0);
int compressedSize = int.Parse(d.Get("compressedSize"));
bool binary = int.Parse(d.Get("id"))%2 > 0;
int shouldSize = shouldStillBeCompressed
? compressedSize
: (binary ? BINARY_PLAIN_LENGTH : TEXT_PLAIN_LENGTH);
Assert.AreEqual(shouldSize, actualSize, "size incorrect");
if (!shouldStillBeCompressed)
{
Assert.IsFalse(compressedSize == actualSize,
"uncompressed field should have another size than recorded in index");
}
}
}
Assert.AreEqual(34*2, count, "correct number of tests");
}
finally
{
reader.Dispose();
}
}
[Test]
public virtual void TestOptimizeOldIndex()
{
int hasTested29 = 0;
for (int i = 0; i < oldNames.Length; i++)
{
System.String dirName = Paths.CombinePath(Paths.ProjectRootDirectory, "test/core/index/index." + oldNames[i]);
Unzip(dirName, oldNames[i]);
System.String fullPath = FullDir(oldNames[i]);
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(fullPath));
if (oldNames[i].StartsWith("29."))
{
assertCompressedFields29(dir, true);
hasTested29++;
}
IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
w.Optimize();
w.Close();
_TestUtil.CheckIndex(dir);
if (oldNames[i].StartsWith("29."))
{
assertCompressedFields29(dir, false);
hasTested29++;
}
dir.Close();
RmDir(oldNames[i]);
}
Assert.AreEqual(4, hasTested29, "test for compressed field should have run 4 times");
}
[Test]
public virtual void TestSearchOldIndex()
{
for (int i = 0; i < oldNames.Length; i++)
{
System.String dirName = Paths.CombinePath(Paths.ProjectRootDirectory, "test/core/index/index." + oldNames[i]);
Unzip(dirName, oldNames[i]);
searchIndex(oldNames[i], oldNames[i]);
RmDir(oldNames[i]);
}
}
[Test]
public virtual void TestIndexOldIndexNoAdds()
{
for (int i = 0; i < oldNames.Length; i++)
{
System.String dirName = Paths.CombinePath(Paths.ProjectRootDirectory, "test/core/index/index." + oldNames[i]);
Unzip(dirName, oldNames[i]);
ChangeIndexNoAdds(oldNames[i]);
RmDir(oldNames[i]);
}
}
[Test]
public virtual void TestIndexOldIndex()
{
for (int i = 0; i < oldNames.Length; i++)
{
System.String dirName = Paths.CombinePath(Paths.ProjectRootDirectory, "test/core/index/index." + oldNames[i]);
Unzip(dirName, oldNames[i]);
ChangeIndexWithAdds(oldNames[i]);
RmDir(oldNames[i]);
}
}
private void TestHits(ScoreDoc[] hits, int expectedCount, IndexReader reader)
{
int hitCount = hits.Length;
Assert.AreEqual(expectedCount, hitCount, "wrong number of hits");
for (int i = 0; i < hitCount; i++)
{
reader.Document(hits[i].Doc);
reader.GetTermFreqVectors(hits[i].Doc);
}
}
public virtual void searchIndex(System.String dirName, System.String oldName)
{
//QueryParser parser = new QueryParser("contents", new WhitespaceAnalyzer());
//Query query = parser.parse("handle:1");
dirName = FullDir(dirName);
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(dirName));
IndexSearcher searcher = new IndexSearcher(dir, true);
IndexReader reader = searcher.IndexReader;
_TestUtil.CheckIndex(dir);
for (int i = 0; i < 35; i++)
{
if (!reader.IsDeleted(i))
{
Document d = reader.Document(i);
var fields = d.GetFields();
if (!oldName.StartsWith("19.") && !oldName.StartsWith("20.") && !oldName.StartsWith("21.") && !oldName.StartsWith("22."))
{
if (d.GetField("content3") == null)
{
int numFields = oldName.StartsWith("29.") ? 7 : 5;
Assert.AreEqual(numFields, fields.Count);
Field f = d.GetField("id");
Assert.AreEqual("" + i, f.StringValue);
f = (Field) d.GetField("utf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.StringValue);
f = (Field) d.GetField("autf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.StringValue);
f = (Field) d.GetField("content2");
Assert.AreEqual("here is more content with aaa aaa aaa", f.StringValue);
f = (Field) d.GetField("fie\u2C77ld");
Assert.AreEqual("field with non-ascii name", f.StringValue);
}
}
}
// Only ID 7 is deleted
else
Assert.AreEqual(7, i);
}
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
// First document should be #21 since it's norm was
// increased:
Document d2 = searcher.Doc(hits[0].Doc);
Assert.AreEqual("21", d2.Get("id"), "didn't get the right document first");
TestHits(hits, 34, searcher.IndexReader);
if (!oldName.StartsWith("19.") && !oldName.StartsWith("20.") && !oldName.StartsWith("21.") && !oldName.StartsWith("22."))
{
// Test on indices >= 2.3
hits = searcher.Search(new TermQuery(new Term("utf8", "\u0000")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "ab\ud917\udc17cd")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
}
searcher.Close();
dir.Close();
}
private int Compare(System.String name, System.String v)
{
int v0 = System.Int32.Parse(name.Substring(0, (2) - (0)));
int v1 = System.Int32.Parse(v);
return v0 - v1;
}
/* Open pre-lockless index, add docs, do a delete &
* setNorm, and search */
public virtual void ChangeIndexWithAdds(System.String dirName)
{
System.String origDirName = dirName;
dirName = FullDir(dirName);
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(dirName));
// open writer
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.UNLIMITED);
// add 10 docs
for (int i = 0; i < 10; i++)
{
AddDoc(writer, 35 + i);
}
// make sure writer sees right total -- writer seems not to know about deletes in .del?
int expected;
if (Compare(origDirName, "24") < 0)
{
expected = 45;
}
else
{
expected = 46;
}
Assert.AreEqual(expected, writer.MaxDoc(), "wrong doc count");
writer.Close();
// make sure searching sees right # hits
IndexSearcher searcher = new IndexSearcher(dir, true);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Document d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("21", d.Get("id"), "wrong first document");
TestHits(hits, 44, searcher.IndexReader);
searcher.Close();
// make sure we can do delete & setNorm against this
// pre-lockless segment:
IndexReader reader = IndexReader.Open(dir, false);
Term searchTerm = new Term("id", "6");
int delCount = reader.DeleteDocuments(searchTerm);
Assert.AreEqual(1, delCount, "wrong delete count");
reader.SetNorm(22, "content", (float) 2.0);
reader.Close();
// make sure they "took":
searcher = new IndexSearcher(dir, true);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(43, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("22", d.Get("id"), "wrong first document");
TestHits(hits, 43, searcher.IndexReader);
searcher.Close();
// optimize
writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.UNLIMITED);
writer.Optimize();
writer.Close();
searcher = new IndexSearcher(dir, true);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(43, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
TestHits(hits, 43, searcher.IndexReader);
Assert.AreEqual("22", d.Get("id"), "wrong first document");
searcher.Close();
dir.Close();
}
/* Open pre-lockless index, add docs, do a delete &
* setNorm, and search */
public virtual void ChangeIndexNoAdds(System.String dirName)
{
dirName = FullDir(dirName);
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(dirName));
// make sure searching sees right # hits
IndexSearcher searcher = new IndexSearcher(dir, true);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length, "wrong number of hits");
Document d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("21", d.Get("id"), "wrong first document");
searcher.Close();
// make sure we can do a delete & setNorm against this
// pre-lockless segment:
IndexReader reader = IndexReader.Open(dir, false);
Term searchTerm = new Term("id", "6");
int delCount = reader.DeleteDocuments(searchTerm);
Assert.AreEqual(1, delCount, "wrong delete count");
reader.SetNorm(22, "content", (float) 2.0);
reader.Close();
// make sure they "took":
searcher = new IndexSearcher(dir, true);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(33, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("22", d.Get("id"), "wrong first document");
TestHits(hits, 33, searcher.IndexReader);
searcher.Close();
// optimize
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.UNLIMITED);
writer.Optimize();
writer.Close();
searcher = new IndexSearcher(dir, true);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(33, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("22", d.Get("id"), "wrong first document");
TestHits(hits, 33, searcher.IndexReader);
searcher.Close();
dir.Close();
}
public virtual void CreateIndex(System.String dirName, bool doCFS)
{
RmDir(dirName);
dirName = FullDir(dirName);
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(dirName));
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.UseCompoundFile = doCFS;
writer.SetMaxBufferedDocs(10);
for (int i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
Assert.AreEqual(35, writer.MaxDoc(), "wrong doc count");
writer.Close();
// open fresh writer so we get no prx file in the added segment
writer = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.LIMITED);
writer.UseCompoundFile = doCFS;
writer.SetMaxBufferedDocs(10);
AddNoProxDoc(writer);
writer.Close();
// Delete one doc so we get a .del file:
IndexReader reader = IndexReader.Open(dir, false);
Term searchTerm = new Term("id", "7");
int delCount = reader.DeleteDocuments(searchTerm);
Assert.AreEqual(1, delCount, "didn't delete the right number of documents");
// Set one norm so we get a .s0 file:
reader.SetNorm(21, "content", (float) 1.5);
reader.Close();
}
/* Verifies that the expected file names were produced */
[Test]
public virtual void TestExactFileNames()
{
System.String outputDir = "lucene.backwardscompat0.index";
RmDir(outputDir);
try
{
Directory dir = FSDirectory.Open(new System.IO.DirectoryInfo(FullDir(outputDir)));
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true,
IndexWriter.MaxFieldLength.UNLIMITED);
writer.SetRAMBufferSizeMB(16.0);
for (int i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
Assert.AreEqual(35, writer.MaxDoc(), "wrong doc count");
writer.Close();
// Delete one doc so we get a .del file:
IndexReader reader = IndexReader.Open(dir, false);
Term searchTerm = new Term("id", "7");
int delCount = reader.DeleteDocuments(searchTerm);
Assert.AreEqual(1, delCount, "didn't delete the right number of documents");
// Set one norm so we get a .s0 file:
reader.SetNorm(21, "content", (float) 1.5);
reader.Close();
// The numbering of fields can vary depending on which
// JRE is in use. On some JREs we see content bound to
// field 0; on others, field 1. So, here we have to
// figure out which field number corresponds to
// "content", and then set our expected file names below
// accordingly:
CompoundFileReader cfsReader = new CompoundFileReader(dir, "_0.cfs");
FieldInfos fieldInfos = new FieldInfos(cfsReader, "_0.fnm");
int contentFieldIndex = -1;
for (int i = 0; i < fieldInfos.Size(); i++)
{
FieldInfo fi = fieldInfos.FieldInfo(i);
if (fi.name_ForNUnit.Equals("content"))
{
contentFieldIndex = i;
break;
}
}
cfsReader.Close();
Assert.IsTrue(contentFieldIndex != -1,
"could not locate the 'content' field number in the _2.cfs segment");
// Now verify file names:
System.String[] expected;
expected = new System.String[]
{"_0.cfs", "_0_1.del", "_0_1.s" + contentFieldIndex, "segments_3", "segments.gen"};
System.String[] actual = dir.ListAll();
System.Array.Sort(expected);
System.Array.Sort(actual);
if (!CollectionsHelper.Equals(expected, actual))
{
Assert.Fail("incorrect filenames in index: expected:\n " + AsString(expected) +
"\n actual:\n " + AsString(actual));
}
dir.Close();
}
finally
{
RmDir(outputDir);
}
}
private System.String AsString(System.String[] l)
{
System.String s = "";
for (int i = 0; i < l.Length; i++)
{
if (i > 0)
{
s += "\n ";
}
s += l[i];
}
return s;
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(new Field("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
doc.Add(new Field("id", System.Convert.ToString(id), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("autf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("content2", "here is more content with aaa aaa aaa", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.Add(new Field("fie\u2C77ld", "field with non-ascii name", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
/* This was used in 2.9 to generate an index with compressed field:
if (id % 2 == 0)
{
doc.Add(new Field("compressed", TEXT_TO_COMPRESS, Field.Store.COMPRESS, Field.Index.NOT_ANALYZED));
doc.Add(new Field("compressedSize", System.Convert.ToString(TEXT_COMPRESSED_LENGTH), Field.Store.YES, Field.Index.NOT_ANALYZED));
}
else
{
doc.Add(new Field("compressed", BINARY_TO_COMPRESS, Field.Store.COMPRESS));
doc.Add(new Field("compressedSize", System.Convert.ToString(BINARY_COMPRESSED_LENGTH), Field.Store.YES, Field.Index.NOT_ANALYZED));
}*/
// Add numeric fields, to test if flex preserves encoding
doc.Add(new NumericField("trieInt", 4).SetIntValue(id));
doc.Add(new NumericField("trieLong", 4).SetLongValue(id));
writer.AddDocument(doc);
}
private void AddNoProxDoc(IndexWriter writer)
{
Document doc = new Document();
Field f = new Field("content3", "aaa", Field.Store.YES, Field.Index.ANALYZED);
f.OmitTermFreqAndPositions = true;
doc.Add(f);
f = new Field("content4", "aaa", Field.Store.YES, Field.Index.NO);
f.OmitTermFreqAndPositions = true;
doc.Add(f);
writer.AddDocument(doc);
}
private void RmDir(System.String dir)
{
System.IO.FileInfo fileDir = new System.IO.FileInfo(FullDir(dir));
bool tmpBool;
if (System.IO.File.Exists(fileDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(fileDir.FullName);
if (tmpBool)
{
System.IO.FileInfo[] files = FileSupport.GetFiles(fileDir);
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
bool tmpBool2;
if (System.IO.File.Exists(files[i].FullName))
{
System.IO.File.Delete(files[i].FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(files[i].FullName))
{
System.IO.Directory.Delete(files[i].FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
bool generatedAux = tmpBool2;
}
}
bool tmpBool3;
if (System.IO.File.Exists(fileDir.FullName))
{
System.IO.File.Delete(fileDir.FullName);
tmpBool3 = true;
}
else if (System.IO.Directory.Exists(fileDir.FullName))
{
System.IO.Directory.Delete(fileDir.FullName);
tmpBool3 = true;
}
else
tmpBool3 = false;
bool generatedAux2 = tmpBool3;
}
}
public static System.String FullDir(System.String dirName)
{
return new System.IO.FileInfo(System.IO.Path.Combine(AppSettings.Get("tempDir", ""), dirName)).FullName;
}
internal const System.String TEXT_TO_COMPRESS = "this is a compressed field and should appear in 3.0 as an uncompressed field after merge";
// FieldSelectorResult.SIZE returns compressed size for compressed fields,
// which are internally handled as binary;
// do it in the same way like FieldsWriter, do not use
// CompressionTools.compressString() for compressed fields:
internal static readonly byte[] BINARY_TO_COMPRESS = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
/* This was used in 2.9 to generate an index with compressed field
internal static int TEXT_COMPRESSED_LENGTH;
internal static readonly int BINARY_COMPRESSED_LENGTH = CompressionTools.Compress(BINARY_TO_COMPRESS).Length;
static TestBackwardsCompatibility()
{
{
try
{
TEXT_COMPRESSED_LENGTH = CompressionTools.Compress(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(TEXT_TO_COMPRESS)).Length;
}
catch (System.Exception e)
{
throw new System.SystemException();
}
}
}*/
}
}
| |
using ICSharpCode.TextEditor.Document;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ICSharpCode.TextEditor
{
public class Caret : IDisposable
{
private abstract class CaretImplementation : IDisposable
{
public bool RequireRedrawOnPositionChange;
public abstract bool Create(int width, int height);
public abstract void Hide();
public abstract void Show();
public abstract bool SetPosition(int x, int y);
public abstract void PaintCaret(Graphics g);
public abstract void Destroy();
public virtual void Dispose()
{
this.Destroy();
}
}
private class ManagedCaret : Caret.CaretImplementation
{
private Timer timer = new Timer
{
Interval = 300
};
private bool visible;
private bool blink = true;
private int x;
private int y;
private int width;
private int height;
private TextArea textArea;
private Caret parentCaret;
public ManagedCaret(Caret caret)
{
this.RequireRedrawOnPositionChange = true;
this.textArea = caret.textArea;
this.parentCaret = caret;
this.timer.Tick += new EventHandler(this.CaretTimerTick);
}
private void CaretTimerTick(object sender, EventArgs e)
{
this.blink = !this.blink;
if(this.visible)
{
this.textArea.UpdateLine(this.parentCaret.Line);
}
}
public override bool Create(int width, int height)
{
this.visible = true;
this.width = width - 2;
this.height = height;
this.timer.Enabled = true;
return true;
}
public override void Hide()
{
this.visible = false;
}
public override void Show()
{
this.visible = true;
}
public override bool SetPosition(int x, int y)
{
this.x = x - 1;
this.y = y;
return true;
}
public override void PaintCaret(Graphics g)
{
if(this.visible && this.blink)
{
g.DrawRectangle(Pens.Gray, this.x, this.y, this.width, this.height);
}
}
public override void Destroy()
{
this.visible = false;
this.timer.Enabled = false;
}
public override void Dispose()
{
base.Dispose();
this.timer.Dispose();
}
}
private class Win32Caret : Caret.CaretImplementation
{
private TextArea textArea;
[DllImport("User32.dll")]
private static extern bool CreateCaret(IntPtr hWnd, int hBitmap, int nWidth, int nHeight);
[DllImport("User32.dll")]
private static extern bool SetCaretPos(int x, int y);
[DllImport("User32.dll")]
private static extern bool DestroyCaret();
[DllImport("User32.dll")]
private static extern bool ShowCaret(IntPtr hWnd);
[DllImport("User32.dll")]
private static extern bool HideCaret(IntPtr hWnd);
public Win32Caret(Caret caret)
{
this.textArea = caret.textArea;
}
public override bool Create(int width, int height)
{
return Caret.Win32Caret.CreateCaret(this.textArea.Handle, 0, width, height);
}
public override void Hide()
{
Caret.Win32Caret.HideCaret(this.textArea.Handle);
}
public override void Show()
{
Caret.Win32Caret.ShowCaret(this.textArea.Handle);
}
public override bool SetPosition(int x, int y)
{
return Caret.Win32Caret.SetCaretPos(x, y);
}
public override void PaintCaret(Graphics g)
{
}
public override void Destroy()
{
Caret.Win32Caret.DestroyCaret();
}
}
private int line;
private int column;
private int desiredXPos;
private CaretMode caretMode;
private static bool caretCreated;
private bool hidden = true;
private TextArea textArea;
private Point currentPos = new Point(-1, -1);
private Ime ime;
private Caret.CaretImplementation caretImplementation;
private int oldLine = -1;
private bool outstandingUpdate;
private bool firePositionChangedAfterUpdateEnd;
public event EventHandler PositionChanged;
public event EventHandler CaretModeChanged;
public int DesiredColumn
{
get
{
return this.desiredXPos;
}
set
{
this.desiredXPos = value;
}
}
public CaretMode CaretMode
{
get
{
return this.caretMode;
}
set
{
this.caretMode = value;
this.OnCaretModeChanged(EventArgs.Empty);
}
}
public int Line
{
get
{
return this.line;
}
set
{
this.line = value;
this.ValidateCaretPos();
this.UpdateCaretPosition();
this.OnPositionChanged(EventArgs.Empty);
}
}
public LineSegment LineSegment
{
get
{
return textArea.Document.GetLineSegment(this.line);
}
}
public int Column
{
get
{
return this.column;
}
set
{
this.column = value;
this.ValidateCaretPos();
this.UpdateCaretPosition();
this.OnPositionChanged(EventArgs.Empty);
}
}
public TextLocation Position
{
get
{
return new TextLocation(this.column, this.line);
}
set
{
this.line = value.Y;
this.column = value.X;
this.ValidateCaretPos();
this.UpdateCaretPosition();
this.OnPositionChanged(EventArgs.Empty);
}
}
public int Offset
{
get
{
return this.textArea.Document.PositionToOffset(this.Position);
}
}
public Point ScreenPosition
{
get
{
int drawingXPos = this.textArea.TextView.GetDrawingXPos(this.line, this.column);
return new Point(this.textArea.TextView.DrawingPosition.X + drawingXPos, this.textArea.TextView.DrawingPosition.Y + this.textArea.Document.GetVisibleLine(this.line) * this.textArea.TextView.FontHeight - this.textArea.TextView.TextArea.VirtualTop.Y);
}
}
public Caret(TextArea textArea)
{
this.textArea = textArea;
textArea.GotFocus += new EventHandler(this.GotFocus);
textArea.LostFocus += new EventHandler(this.LostFocus);
if(Environment.OSVersion.Platform == PlatformID.Unix)
{
this.caretImplementation = new Caret.ManagedCaret(this);
return;
}
this.caretImplementation = new Caret.Win32Caret(this);
}
public void Dispose()
{
this.textArea.GotFocus -= new EventHandler(this.GotFocus);
this.textArea.LostFocus -= new EventHandler(this.LostFocus);
this.textArea = null;
this.caretImplementation.Dispose();
}
public TextLocation ValidatePosition(TextLocation pos)
{
int lineNumber = Math.Max(0, Math.Min(this.textArea.Document.TotalNumberOfLines - 1, pos.Y));
int num = Math.Max(0, pos.X);
if(num == 2147483647 || !this.textArea.TextEditorProperties.AllowCaretBeyondEOL)
{
LineSegment lineSegment = this.textArea.Document.GetLineSegment(lineNumber);
num = Math.Min(num, lineSegment.Length);
}
return new TextLocation(num, lineNumber);
}
public void ValidateCaretPos()
{
this.line = Math.Max(0, Math.Min(this.textArea.Document.TotalNumberOfLines - 1, this.line));
this.column = Math.Max(0, this.column);
if(this.column == 2147483647 || !this.textArea.TextEditorProperties.AllowCaretBeyondEOL)
{
LineSegment lineSegment = this.textArea.Document.GetLineSegment(this.line);
this.column = Math.Min(this.column, lineSegment.Length);
}
}
private void CreateCaret()
{
while(!Caret.caretCreated)
{
switch(this.caretMode)
{
case CaretMode.InsertMode:
{
Caret.caretCreated = this.caretImplementation.Create(2, this.textArea.TextView.FontHeight);
break;
}
case CaretMode.OverwriteMode:
{
Caret.caretCreated = this.caretImplementation.Create(this.textArea.TextView.SpaceWidth, this.textArea.TextView.FontHeight);
break;
}
}
}
if(this.currentPos.X < 0)
{
this.ValidateCaretPos();
this.currentPos = this.ScreenPosition;
}
this.caretImplementation.SetPosition(this.currentPos.X, this.currentPos.Y);
this.caretImplementation.Show();
}
public void RecreateCaret()
{
this.DisposeCaret();
if(!this.hidden)
{
this.CreateCaret();
}
}
private void DisposeCaret()
{
if(Caret.caretCreated)
{
Caret.caretCreated = false;
this.caretImplementation.Hide();
this.caretImplementation.Destroy();
}
}
private void GotFocus(object sender, EventArgs e)
{
this.hidden = false;
if(!this.textArea.MotherTextEditorControl.IsInUpdate)
{
this.CreateCaret();
this.UpdateCaretPosition();
}
}
private void LostFocus(object sender, EventArgs e)
{
this.hidden = true;
this.DisposeCaret();
}
internal void OnEndUpdate()
{
if(this.outstandingUpdate)
{
this.UpdateCaretPosition();
}
}
private void PaintCaretLine(Graphics g)
{
if(!this.textArea.Document.TextEditorProperties.CaretLine)
{
return;
}
HighlightColor colorFor = this.textArea.Document.HighlightingStrategy.GetColorFor("CaretLine");
g.DrawLine(BrushRegistry.GetDotPen(colorFor.Color), this.currentPos.X, 0, this.currentPos.X, this.textArea.DisplayRectangle.Height);
}
public void UpdateCaretPosition()
{
if(this.textArea.TextEditorProperties.CaretLine)
{
this.textArea.Invalidate();
}
else
{
if(this.caretImplementation.RequireRedrawOnPositionChange)
{
this.textArea.UpdateLine(this.oldLine);
if(this.line != this.oldLine)
{
this.textArea.UpdateLine(this.line);
}
}
else
{
if(this.textArea.MotherTextAreaControl.TextEditorProperties.LineViewerStyle == LineViewerStyle.FullRow && this.oldLine != this.line)
{
this.textArea.UpdateLine(this.oldLine);
this.textArea.UpdateLine(this.line);
}
}
}
this.oldLine = this.line;
if(this.hidden || this.textArea.MotherTextEditorControl.IsInUpdate)
{
this.outstandingUpdate = true;
return;
}
this.outstandingUpdate = false;
this.ValidateCaretPos();
int logicalLine = this.line;
int drawingXPos = this.textArea.TextView.GetDrawingXPos(logicalLine, this.column);
Point screenPosition = this.ScreenPosition;
if(drawingXPos >= 0)
{
this.CreateCaret();
if(!this.caretImplementation.SetPosition(screenPosition.X, screenPosition.Y))
{
this.caretImplementation.Destroy();
Caret.caretCreated = false;
this.UpdateCaretPosition();
}
}
else
{
this.caretImplementation.Destroy();
}
if(this.ime == null)
{
this.ime = new Ime(this.textArea.Handle, this.textArea.Document.TextEditorProperties.Font);
}
else
{
this.ime.HWnd = this.textArea.Handle;
this.ime.Font = this.textArea.Document.TextEditorProperties.Font;
}
this.ime.SetIMEWindowLocation(screenPosition.X, screenPosition.Y);
this.currentPos = screenPosition;
}
[Conditional("DEBUG")]
private static void Log(string text)
{
}
internal void PaintCaret(Graphics g)
{
this.caretImplementation.PaintCaret(g);
this.PaintCaretLine(g);
}
private void FirePositionChangedAfterUpdateEnd(object sender, EventArgs e)
{
this.OnPositionChanged(EventArgs.Empty);
}
protected virtual void OnPositionChanged(EventArgs e)
{
if(this.textArea.MotherTextEditorControl.IsInUpdate)
{
if(!this.firePositionChangedAfterUpdateEnd)
{
this.firePositionChangedAfterUpdateEnd = true;
this.textArea.Document.UpdateCommited += new EventHandler(this.FirePositionChangedAfterUpdateEnd);
}
return;
}
if(this.firePositionChangedAfterUpdateEnd)
{
this.textArea.Document.UpdateCommited -= new EventHandler(this.FirePositionChangedAfterUpdateEnd);
this.firePositionChangedAfterUpdateEnd = false;
}
List<FoldMarker> foldingsFromPosition = this.textArea.Document.FoldingManager.GetFoldingsFromPosition(this.line, this.column);
bool flag = false;
foreach(FoldMarker current in foldingsFromPosition)
{
flag |= current.IsFolded;
current.IsFolded = false;
}
if(flag)
{
this.textArea.Document.FoldingManager.NotifyFoldingsChanged(EventArgs.Empty);
}
if(this.PositionChanged != null)
{
this.PositionChanged(this, e);
}
this.textArea.ScrollToCaret();
}
protected virtual void OnCaretModeChanged(EventArgs e)
{
if(this.CaretModeChanged != null)
{
this.CaretModeChanged(this, e);
}
this.caretImplementation.Hide();
this.caretImplementation.Destroy();
Caret.caretCreated = false;
this.CreateCaret();
this.caretImplementation.Show();
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A three-dimensional vector with doubleing-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3d : IComparable<Vector3d>, IEquatable<Vector3d>
{
/// <summary>X value</summary>
public double X;
/// <summary>Y value</summary>
public double Y;
/// <summary>Z value</summary>
public double Z;
#region Constructors
public Vector3d(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public Vector3d(double value)
{
X = value;
Y = value;
Z = value;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing three eight-byte doubles</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector3d(byte[] byteArray, int pos)
{
X = Y = Z = 0d;
FromBytes(byteArray, pos);
}
public Vector3d(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
public Vector3d(Vector3d vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
#endregion Constructors
#region Public Methods
public double Length()
{
return Math.Sqrt(DistanceSquared(this, Zero));
}
public double LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector3d vec, double tolerance)
{
Vector3d diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector3d vector)
{
return this.Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 24 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[24];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 24);
Array.Reverse(conversionBuffer, 0, 8);
Array.Reverse(conversionBuffer, 8, 8);
Array.Reverse(conversionBuffer, 16, 8);
X = BitConverter.ToDouble(conversionBuffer, 0);
Y = BitConverter.ToDouble(conversionBuffer, 8);
Z = BitConverter.ToDouble(conversionBuffer, 16);
}
else
{
// Little endian architecture
X = BitConverter.ToDouble(byteArray, pos);
Y = BitConverter.ToDouble(byteArray, pos + 8);
Z = BitConverter.ToDouble(byteArray, pos + 16);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 24 byte array containing X, Y, and Z</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[24];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 24 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 8, 8);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 16, 8);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 8);
Array.Reverse(dest, pos + 8, 8);
Array.Reverse(dest, pos + 16, 8);
}
}
#endregion Public Methods
#region Static Methods
public static Vector3d Add(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max)
{
return new Vector3d(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z));
}
public static Vector3d Cross(Vector3d value1, Vector3d value2)
{
return new Vector3d(
value1.Y * value2.Z - value2.Y * value1.Z,
value1.Z * value2.X - value2.Z * value1.X,
value1.X * value2.Y - value2.X * value1.Y);
}
public static double Distance(Vector3d value1, Vector3d value2)
{
return Math.Sqrt(DistanceSquared(value1, value2));
}
public static double DistanceSquared(Vector3d value1, Vector3d value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector3d Divide(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d Divide(Vector3d value1, double value2)
{
double factor = 1d / value2;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static double Dot(Vector3d value1, Vector3d value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount));
}
public static Vector3d Max(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z));
}
public static Vector3d Min(Vector3d value1, Vector3d value2)
{
return new Vector3d(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z));
}
public static Vector3d Multiply(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d Multiply(Vector3d value1, double scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector3d Negate(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d Normalize(Vector3d value)
{
double factor = Distance(value, Zero);
if (factor > Double.Epsilon)
{
factor = 1d / factor;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
}
else
{
value.X = 0d;
value.Y = 0d;
value.Z = 0d;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 3D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3d Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3d(
Double.Parse(split[0].Trim(), Utils.EnUsCulture),
Double.Parse(split[1].Trim(), Utils.EnUsCulture),
Double.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3d result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3d.Zero;
return false;
}
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount)
{
return new Vector3d(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount));
}
public static Vector3d Subtract(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector3d) ? this == (Vector3d)obj : false;
}
public bool Equals(Vector3d other)
{
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2}", X, Y, Z);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector3d value1, Vector3d value2)
{
return value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector3d value1, Vector3d value2)
{
return !(value1 == value2);
}
public static Vector3d operator +(Vector3d value1, Vector3d value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3d operator -(Vector3d value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3d operator -(Vector3d value1, Vector3d value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value1, Vector3d value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3d operator *(Vector3d value, double scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
public static Vector3d operator /(Vector3d value1, Vector3d value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3d operator /(Vector3d value, double divider)
{
double factor = 1d / divider;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
return value;
}
/// <summary>
/// Cross product between two vectors
/// </summary>
public static Vector3d operator %(Vector3d value1, Vector3d value2)
{
return Cross(value1, value2);
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0</summary>
public readonly static Vector3d Zero = new Vector3d();
/// <summary>A vector with a value of 1,1,1</summary>
public readonly static Vector3d One = new Vector3d();
/// <summary>A unit vector facing forward (X axis), value of 1,0,0</summary>
public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d);
/// <summary>A unit vector facing left (Y axis), value of 0,1,0</summary>
public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d);
/// <summary>A unit vector facing up (Z axis), value of 0,0,1</summary>
public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d);
}
}
| |
//
// ListViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Jan Strnadek <jan.strnadek@gmail.com>
// - GetAtRowPosition
// - NSTableView for mouse events
//
// Copyright (c) 2011 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 System.Collections.Generic;
using System.Linq;
using AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
namespace Xwt.Mac
{
public class ListViewBackend: TableViewBackend<NSTableView, IListViewEventSink>, IListViewBackend
{
class ListDelegate: NSTableViewDelegate
{
public ListViewBackend Backend;
public override nfloat GetRowHeight (NSTableView tableView, nint row)
{
// GetView() and GetRowView() can't be used here, hence we use cached
// sizes calculated by the backend or calcuate the height using the template view
nfloat height = Backend.RowHeights[(int)row];
if (height <= -1)
height = Backend.RowHeights [(int)row] = Backend.CalcRowHeight (row, false);
return height;
}
public override NSTableRowView CoreGetRowView (NSTableView tableView, nint row)
{
return tableView.GetRowView (row, false) ?? new TableRowView ();
}
public override NSView GetViewForItem (NSTableView tableView, NSTableColumn tableColumn, nint row)
{
var col = tableColumn as TableColumn;
var cell = tableView.MakeView (tableColumn.Identifier, this) as CompositeCell;
if (cell == null)
cell = col.CreateNewView ();
cell.ObjectValue = NSNumber.FromNInt (row);
return cell;
}
public override nfloat GetSizeToFitColumnWidth (NSTableView tableView, nint column)
{
var tableColumn = Backend.Columns[(int)column] as TableColumn;
var width = tableColumn.HeaderCell.CellSize.Width;
CompositeCell templateCell = null;
for (int i = 0; i < tableView.RowCount; i++) {
var cellView = tableView.GetView (column, i, false) as CompositeCell;
if (cellView == null) { // use template for invisible rows
cellView = templateCell ?? (templateCell = (tableColumn as TableColumn)?.DataView?.Copy () as CompositeCell);
if (cellView != null)
cellView.ObjectValue = NSNumber.FromInt32 (i);
}
width = (nfloat)Math.Max (width, cellView.FittingSize.Width);
}
return width;
}
public override NSIndexSet GetSelectionIndexes(NSTableView tableView, NSIndexSet proposedSelectionIndexes)
{
return Backend.SelectionMode != SelectionMode.None ? proposedSelectionIndexes : new NSIndexSet();
}
}
IListDataSource source;
ListSource tsource;
protected override NSTableView CreateView ()
{
var listView = new NSTableViewBackend (this);
listView.Delegate = new ListDelegate { Backend = this };
return listView;
}
protected override string SelectionChangeEventName {
get { return "NSTableViewSelectionDidChangeNotification"; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ListViewEvent) {
switch ((ListViewEvent)eventId) {
case ListViewEvent.RowActivated:
Table.DoubleClick += HandleDoubleClick;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ListViewEvent) {
switch ((ListViewEvent)eventId) {
case ListViewEvent.RowActivated:
Table.DoubleClick -= HandleDoubleClick;
Table.DoubleAction = null;
break;
}
}
}
void HandleDoubleClick (object sender, EventArgs e)
{
var cr = Table.ClickedRow;
if (cr >= 0) {
ApplicationContext.InvokeUserCode (delegate {
((IListViewEventSink)EventSink).OnRowActivated ((int)cr);
});
}
}
public virtual void SetSource (IListDataSource source, IBackend sourceBackend)
{
this.source = source;
RowHeights = new List<nfloat> ();
for (int i = 0; i < source.RowCount; i++)
RowHeights.Add (-1);
tsource = new ListSource (source);
Table.DataSource = tsource;
//TODO: Reloading single rows would be slightly more efficient.
// According to NSTableView.ReloadData() documentation,
// only the visible rows are reloaded.
source.RowInserted += (sender, e) => {
RowHeights.Insert (e.Row, -1);
Table.ReloadData ();
};
source.RowDeleted += (sender, e) => {
RowHeights.RemoveAt (e.Row);
Table.ReloadData ();
};
source.RowChanged += (sender, e) => {
UpdateRowHeight (e.Row);
Table.ReloadData (NSIndexSet.FromIndex (e.Row), NSIndexSet.FromNSRange (new NSRange (0, Table.ColumnCount)));
};
source.RowsReordered += (sender, e) => { RowHeights.Clear (); Table.ReloadData (); };
}
public override void InvalidateRowHeight (object pos)
{
UpdateRowHeight((int)pos);
}
List<nfloat> RowHeights = new List<nfloat> ();
bool updatingRowHeight;
public void UpdateRowHeight (nint row)
{
if (updatingRowHeight)
return;
RowHeights[(int)row] = CalcRowHeight (row);
Table.NoteHeightOfRowsWithIndexesChanged (NSIndexSet.FromIndex (row));
}
nfloat CalcRowHeight (nint row, bool tryReuse = true)
{
updatingRowHeight = true;
var height = Table.RowHeight;
for (int i = 0; i < Columns.Count; i++) {
CompositeCell cell = tryReuse ? Table.GetView (i, row, false) as CompositeCell : null;
if (cell == null) {
cell = (Columns [i] as TableColumn)?.DataView as CompositeCell;
cell.ObjectValue = NSNumber.FromNInt (row);
height = (nfloat)Math.Max (height, cell.FittingSize.Height);
} else {
height = (nfloat)Math.Max (height, cell.GetRequiredHeightForWidth (cell.Frame.Width));
}
}
updatingRowHeight = false;
return height;
}
public int[] SelectedRows {
get {
int[] sel = new int [Table.SelectedRowCount];
if (sel.Length > 0) {
int i = 0;
foreach (int r in Table.SelectedRows)
sel [i++] = r;
}
return sel;
}
}
public int FocusedRow {
get {
if (Table.SelectedRowCount > 0)
return (int)Table.SelectedRows.FirstIndex;
return -1;
}
set {
SelectRow (value);
}
}
public void SelectRow (int pos)
{
Table.SelectRow (pos, Table.AllowsMultipleSelection);
}
public void UnselectRow (int pos)
{
Table.DeselectRow (pos);
}
public override object GetValue (object pos, int nField)
{
return source.GetValue ((int)pos, nField);
}
public override void SetValue (object pos, int nField, object value)
{
source.SetValue ((int)pos, nField, value);
}
public int CurrentEventRow { get; internal set; }
public override void SetCurrentEventRow (object pos)
{
CurrentEventRow = (int)pos;
}
public int GetRowAtPosition (Point p)
{
return (int) Table.GetRow (new CGPoint ((nfloat)p.X, (nfloat)p.Y));
}
}
class TableRow: NSObject, ITablePosition
{
public int Row;
public object Position {
get { return Row; }
}
}
class ListSource: NSTableViewDataSource
{
IListDataSource source;
public ListSource (IListDataSource source)
{
this.source = source;
}
[Export("tableView:acceptDrop:row:dropOperation:")]
public bool AcceptDrop (NSTableView tableView, INSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
return false;
}
public override string[] FilesDropped (NSTableView tableView, NSUrl dropDestination, NSIndexSet indexSet)
{
return new string [0];
}
public override NSObject GetObjectValue (NSTableView tableView, NSTableColumn tableColumn, nint row)
{
return NSNumber.FromInt32 ((int)row);
}
public override nint GetRowCount (NSTableView tableView)
{
return source.RowCount;
}
public override void SetObjectValue (NSTableView tableView, NSObject theObject, NSTableColumn tableColumn, nint row)
{
}
public override void SortDescriptorsChanged (NSTableView tableView, NSSortDescriptor[] oldDescriptors)
{
}
[Export("tableView:validateDrop:proposedRow:proposedDropOperation:")]
public NSDragOperation ValidateDrop (NSTableView tableView, INSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
return NSDragOperation.None;
}
public override bool WriteRows (NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
{
return false;
}
}
}
| |
using System.Text;
using System.IO;
using SharpCompress.Compressor.Rar;
namespace SharpCompress.Compressor.PPMd.H
{
internal class ModelPPM
{
private void InitBlock()
{
for (int i = 0; i < 25; i++)
{
SEE2Cont[i] = new SEE2Context[16];
}
for (int i2 = 0; i2 < 128; i2++)
{
binSumm[i2] = new int[64];
}
}
public SubAllocator SubAlloc
{
get { return subAlloc; }
}
public virtual SEE2Context DummySEE2Cont
{
get { return dummySEE2Cont; }
}
public virtual int InitRL
{
get { return initRL; }
}
public virtual int EscCount
{
get { return escCount; }
set { this.escCount = value & 0xff; }
}
public virtual int[] CharMask
{
get { return charMask; }
}
public virtual int NumMasked
{
get { return numMasked; }
set { this.numMasked = value; }
}
public virtual int PrevSuccess
{
get { return prevSuccess; }
set { this.prevSuccess = value & 0xff; }
}
public virtual int InitEsc
{
get { return initEsc; }
set { this.initEsc = value; }
}
public virtual int RunLength
{
get { return runLength; }
set { this.runLength = value; }
}
public virtual int HiBitsFlag
{
get { return hiBitsFlag; }
set { this.hiBitsFlag = value & 0xff; }
}
public virtual int[][] BinSumm
{
get { return binSumm; }
}
internal RangeCoder Coder
{
get { return coder; }
}
internal State FoundState
{
get { return foundState; }
}
public virtual byte[] Heap
{
get { return subAlloc.Heap; }
}
public virtual int OrderFall
{
get { return orderFall; }
}
public const int MAX_O = 64; /* maximum allowed model order */
public const int INT_BITS = 7;
public const int PERIOD_BITS = 7;
//UPGRADE_NOTE: Final was removed from the declaration of 'TOT_BITS '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int TOT_BITS = INT_BITS + PERIOD_BITS;
//UPGRADE_NOTE: Final was removed from the declaration of 'INTERVAL '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int INTERVAL = 1 << INT_BITS;
//UPGRADE_NOTE: Final was removed from the declaration of 'BIN_SCALE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
public static readonly int BIN_SCALE = 1 << TOT_BITS;
public const int MAX_FREQ = 124;
private SEE2Context[][] SEE2Cont = new SEE2Context[25][];
private SEE2Context dummySEE2Cont;
private PPMContext minContext; //medContext
private PPMContext maxContext;
private State foundState; // found next state transition
private int numMasked, initEsc, orderFall, maxOrder, runLength, initRL;
private int[] charMask = new int[256];
private int[] NS2Indx = new int[256];
private int[] NS2BSIndx = new int[256];
private int[] HB2Flag = new int[256];
// byte EscCount, PrevSuccess, HiBitsFlag;
private int escCount, prevSuccess, hiBitsFlag;
private int[][] binSumm = new int[128][]; // binary SEE-contexts
private RangeCoder coder;
private SubAllocator subAlloc = new SubAllocator();
private static int[] InitBinEsc = new int[] {0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
// Temp fields
//UPGRADE_NOTE: Final was removed from the declaration of 'tempState1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private State tempState1 = new State(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempState2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private State tempState2 = new State(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempState3 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private State tempState3 = new State(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempState4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private State tempState4 = new State(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempStateRef1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private StateRef tempStateRef1 = new StateRef();
//UPGRADE_NOTE: Final was removed from the declaration of 'tempStateRef2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private StateRef tempStateRef2 = new StateRef();
//UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext1 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private PPMContext tempPPMContext1 = new PPMContext(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext2 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private PPMContext tempPPMContext2 = new PPMContext(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext3 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private PPMContext tempPPMContext3 = new PPMContext(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'tempPPMContext4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private PPMContext tempPPMContext4 = new PPMContext(null);
//UPGRADE_NOTE: Final was removed from the declaration of 'ps '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private int[] ps = new int[MAX_O];
public ModelPPM()
{
InitBlock();
minContext = null;
maxContext = null;
//medContext = null;
}
private void restartModelRare()
{
Utility.Fill(charMask, 0);
subAlloc.initSubAllocator();
initRL = -(maxOrder < 12 ? maxOrder : 12) - 1;
int addr = subAlloc.allocContext();
minContext.Address = addr;
maxContext.Address = addr;
minContext.setSuffix(0);
orderFall = maxOrder;
minContext.NumStats = 256;
minContext.FreqData.SummFreq = minContext.NumStats + 1;
addr = subAlloc.allocUnits(256/2);
foundState.Address = addr;
minContext.FreqData.SetStats(addr);
State state = new State(subAlloc.Heap);
addr = minContext.FreqData.GetStats();
runLength = initRL;
prevSuccess = 0;
for (int i = 0; i < 256; i++)
{
state.Address = addr + i*State.Size;
state.Symbol = i;
state.Freq = 1;
state.SetSuccessor(0);
}
for (int i = 0; i < 128; i++)
{
for (int k = 0; k < 8; k++)
{
for (int m = 0; m < 64; m += 8)
{
binSumm[i][k + m] = BIN_SCALE - InitBinEsc[k]/(i + 2);
}
}
}
for (int i = 0; i < 25; i++)
{
for (int k = 0; k < 16; k++)
{
SEE2Cont[i][k].Initialize(5*i + 10);
}
}
}
private void startModelRare(int MaxOrder)
{
int i, k, m, Step;
escCount = 1;
this.maxOrder = MaxOrder;
restartModelRare();
// Bug Fixed
NS2BSIndx[0] = 0;
NS2BSIndx[1] = 2;
for (int j = 0; j < 9; j++)
{
NS2BSIndx[2 + j] = 4;
}
for (int j = 0; j < 256 - 11; j++)
{
NS2BSIndx[11 + j] = 6;
}
for (i = 0; i < 3; i++)
{
NS2Indx[i] = i;
}
for (m = i, k = 1, Step = 1; i < 256; i++)
{
NS2Indx[i] = m;
if ((--k) == 0)
{
k = ++Step;
m++;
}
}
for (int j = 0; j < 0x40; j++)
{
HB2Flag[j] = 0;
}
for (int j = 0; j < 0x100 - 0x40; j++)
{
HB2Flag[0x40 + j] = 0x08;
}
dummySEE2Cont.Shift = PERIOD_BITS;
}
private void clearMask()
{
escCount = 1;
Utility.Fill(charMask, 0);
}
internal bool decodeInit(Unpack unpackRead, int escChar)
{
int MaxOrder = unpackRead.Char & 0xff;
bool reset = ((MaxOrder & 0x20) != 0);
int MaxMB = 0;
if (reset)
{
MaxMB = unpackRead.Char;
}
else
{
if (subAlloc.GetAllocatedMemory() == 0)
{
return (false);
}
}
if ((MaxOrder & 0x40) != 0)
{
escChar = unpackRead.Char;
unpackRead.PpmEscChar = escChar;
}
coder = new RangeCoder(unpackRead);
if (reset)
{
MaxOrder = (MaxOrder & 0x1f) + 1;
if (MaxOrder > 16)
{
MaxOrder = 16 + (MaxOrder - 16)*3;
}
if (MaxOrder == 1)
{
subAlloc.stopSubAllocator();
return (false);
}
subAlloc.startSubAllocator((MaxMB + 1) << 20);
minContext = new PPMContext(Heap);
//medContext = new PPMContext(Heap);
maxContext = new PPMContext(Heap);
foundState = new State(Heap);
dummySEE2Cont = new SEE2Context();
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 16; j++)
{
SEE2Cont[i][j] = new SEE2Context();
}
}
startModelRare(MaxOrder);
}
return (minContext.Address != 0);
}
public virtual int decodeChar()
{
// Debug
//subAlloc.dumpHeap();
if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd)
{
return (-1);
}
if (minContext.NumStats != 1)
{
if (minContext.FreqData.GetStats() <= subAlloc.PText ||
minContext.FreqData.GetStats() > subAlloc.HeapEnd)
{
return (-1);
}
if (!minContext.decodeSymbol1(this))
{
return (-1);
}
}
else
{
minContext.decodeBinSymbol(this);
}
coder.Decode();
while (foundState.Address == 0)
{
coder.AriDecNormalize();
do
{
orderFall++;
minContext.Address = minContext.getSuffix(); // =MinContext->Suffix;
if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd)
{
return (-1);
}
} while (minContext.NumStats == numMasked);
if (!minContext.decodeSymbol2(this))
{
return (-1);
}
coder.Decode();
}
int Symbol = foundState.Symbol;
if ((orderFall == 0) && foundState.GetSuccessor() > subAlloc.PText)
{
// MinContext=MaxContext=FoundState->Successor;
int addr = foundState.GetSuccessor();
minContext.Address = addr;
maxContext.Address = addr;
}
else
{
updateModel();
//this.foundState.Address=foundState.Address);//TODO just 4 debugging
if (escCount == 0)
{
clearMask();
}
}
coder.AriDecNormalize(); // ARI_DEC_NORMALIZE(Coder.code,Coder.low,Coder.range,Coder.UnpackRead);
return (Symbol);
}
public virtual SEE2Context[][] getSEE2Cont()
{
return SEE2Cont;
}
public virtual void incEscCount(int dEscCount)
{
EscCount = EscCount + dEscCount;
}
public virtual void incRunLength(int dRunLength)
{
RunLength = RunLength + dRunLength;
}
public virtual int[] getHB2Flag()
{
return HB2Flag;
}
public virtual int[] getNS2BSIndx()
{
return NS2BSIndx;
}
public virtual int[] getNS2Indx()
{
return NS2Indx;
}
private int createSuccessors(bool Skip, State p1)
{
//State upState = tempState1.Initialize(null);
StateRef upState = tempStateRef2;
State tempState = tempState1.Initialize(Heap);
// PPM_CONTEXT* pc=MinContext, * UpBranch=FoundState->Successor;
PPMContext pc = tempPPMContext1.Initialize(Heap);
pc.Address = minContext.Address;
PPMContext upBranch = tempPPMContext2.Initialize(Heap);
upBranch.Address = foundState.GetSuccessor();
// STATE * p, * ps[MAX_O], ** pps=ps;
State p = tempState2.Initialize(Heap);
int pps = 0;
bool noLoop = false;
if (!Skip)
{
ps[pps++] = foundState.Address; // *pps++ = FoundState;
if (pc.getSuffix() == 0)
{
noLoop = true;
}
}
if (!noLoop)
{
bool loopEntry = false;
if (p1.Address != 0)
{
p.Address = p1.Address;
pc.Address = pc.getSuffix(); // =pc->Suffix;
loopEntry = true;
}
do
{
if (!loopEntry)
{
pc.Address = pc.getSuffix(); // pc=pc->Suffix;
if (pc.NumStats != 1)
{
p.Address = pc.FreqData.GetStats(); // p=pc->U.Stats
if (p.Symbol != foundState.Symbol)
{
do
{
p.IncrementAddress();
} while (p.Symbol != foundState.Symbol);
}
}
else
{
p.Address = pc.getOneState().Address; // p=&(pc->OneState);
}
} // LOOP_ENTRY:
loopEntry = false;
if (p.GetSuccessor() != upBranch.Address)
{
pc.Address = p.GetSuccessor(); // =p->Successor;
break;
}
ps[pps++] = p.Address;
} while (pc.getSuffix() != 0);
} // NO_LOOP:
if (pps == 0)
{
return pc.Address;
}
upState.Symbol = Heap[upBranch.Address]; // UpState.Symbol=*(byte*)
// UpBranch;
// UpState.Successor=(PPM_CONTEXT*) (((byte*) UpBranch)+1);
upState.SetSuccessor(upBranch.Address + 1); //TODO check if +1 necessary
if (pc.NumStats != 1)
{
if (pc.Address <= subAlloc.PText)
{
return (0);
}
p.Address = pc.FreqData.GetStats();
if (p.Symbol != upState.Symbol)
{
do
{
p.IncrementAddress();
} while (p.Symbol != upState.Symbol);
}
int cf = p.Freq - 1;
int s0 = pc.FreqData.SummFreq - pc.NumStats - cf;
// UpState.Freq=1+((2*cf <= s0)?(5*cf > s0):((2*cf+3*s0-1)/(2*s0)));
upState.Freq = 1 + ((2*cf <= s0) ? (5*cf > s0 ? 1 : 0) : ((2*cf + 3*s0 - 1)/(2*s0)));
}
else
{
upState.Freq = pc.getOneState().Freq; // UpState.Freq=pc->OneState.Freq;
}
do
{
// pc = pc->createChild(this,*--pps,UpState);
tempState.Address = ps[--pps];
pc.Address = pc.createChild(this, tempState, upState);
if (pc.Address == 0)
{
return 0;
}
} while (pps != 0);
return pc.Address;
}
private void updateModelRestart()
{
restartModelRare();
escCount = 0;
}
private void updateModel()
{
//System.out.println("ModelPPM.updateModel()");
// STATE fs = *FoundState, *p = NULL;
StateRef fs = tempStateRef1;
fs.Values = foundState;
State p = tempState3.Initialize(Heap);
State tempState = tempState4.Initialize(Heap);
PPMContext pc = tempPPMContext3.Initialize(Heap);
PPMContext successor = tempPPMContext4.Initialize(Heap);
int ns1, ns, cf, sf, s0;
pc.Address = minContext.getSuffix();
if (fs.Freq < MAX_FREQ/4 && pc.Address != 0)
{
if (pc.NumStats != 1)
{
p.Address = pc.FreqData.GetStats();
if (p.Symbol != fs.Symbol)
{
do
{
p.IncrementAddress();
} while (p.Symbol != fs.Symbol);
tempState.Address = p.Address - State.Size;
if (p.Freq >= tempState.Freq)
{
State.PPMDSwap(p, tempState);
p.DecrementAddress();
}
}
if (p.Freq < MAX_FREQ - 9)
{
p.IncrementFreq(2);
pc.FreqData.IncrementSummFreq(2);
}
}
else
{
p.Address = pc.getOneState().Address;
if (p.Freq < 32)
{
p.IncrementFreq(1);
}
}
}
if (orderFall == 0)
{
foundState.SetSuccessor(createSuccessors(true, p));
minContext.Address = foundState.GetSuccessor();
maxContext.Address = foundState.GetSuccessor();
if (minContext.Address == 0)
{
updateModelRestart();
return;
}
return;
}
subAlloc.Heap[subAlloc.PText] = (byte) fs.Symbol;
subAlloc.incPText();
successor.Address = subAlloc.PText;
if (subAlloc.PText >= subAlloc.FakeUnitsStart)
{
updateModelRestart();
return;
}
// // Debug
// subAlloc.dumpHeap();
if (fs.GetSuccessor() != 0)
{
if (fs.GetSuccessor() <= subAlloc.PText)
{
fs.SetSuccessor(createSuccessors(false, p));
if (fs.GetSuccessor() == 0)
{
updateModelRestart();
return;
}
}
if (--orderFall == 0)
{
successor.Address = fs.GetSuccessor();
if (maxContext.Address != minContext.Address)
{
subAlloc.decPText(1);
}
}
}
else
{
foundState.SetSuccessor(successor.Address);
fs.SetSuccessor(minContext);
}
// // Debug
// subAlloc.dumpHeap();
ns = minContext.NumStats;
s0 = minContext.FreqData.SummFreq - (ns) - (fs.Freq - 1);
for (pc.Address = maxContext.Address; pc.Address != minContext.Address; pc.Address = pc.getSuffix())
{
if ((ns1 = pc.NumStats) != 1)
{
if ((ns1 & 1) == 0)
{
//System.out.println(ns1);
pc.FreqData.SetStats(subAlloc.expandUnits(pc.FreqData.GetStats(), Utility.URShift(ns1, 1)));
if (pc.FreqData.GetStats() == 0)
{
updateModelRestart();
return;
}
}
// bug fixed
// int sum = ((2 * ns1 < ns) ? 1 : 0) +
// 2 * ((4 * ((ns1 <= ns) ? 1 : 0)) & ((pc.getFreqData()
// .getSummFreq() <= 8 * ns1) ? 1 : 0));
int sum = ((2*ns1 < ns) ? 1 : 0) +
2*(((4*ns1 <= ns) ? 1 : 0) & ((pc.FreqData.SummFreq <= 8*ns1) ? 1 : 0));
pc.FreqData.IncrementSummFreq(sum);
}
else
{
p.Address = subAlloc.allocUnits(1);
if (p.Address == 0)
{
updateModelRestart();
return;
}
p.SetValues(pc.getOneState());
pc.FreqData.SetStats(p);
if (p.Freq < MAX_FREQ/4 - 1)
{
p.IncrementFreq(p.Freq);
}
else
{
p.Freq = MAX_FREQ - 4;
}
pc.FreqData.SummFreq = (p.Freq + initEsc + (ns > 3 ? 1 : 0));
}
cf = 2*fs.Freq*(pc.FreqData.SummFreq + 6);
sf = s0 + pc.FreqData.SummFreq;
if (cf < 6*sf)
{
cf = 1 + (cf > sf ? 1 : 0) + (cf >= 4*sf ? 1 : 0);
pc.FreqData.IncrementSummFreq(3);
}
else
{
cf = 4 + (cf >= 9*sf ? 1 : 0) + (cf >= 12*sf ? 1 : 0) + (cf >= 15*sf ? 1 : 0);
pc.FreqData.IncrementSummFreq(cf);
}
p.Address = pc.FreqData.GetStats() + ns1*State.Size;
p.SetSuccessor(successor);
p.Symbol = fs.Symbol;
p.Freq = cf;
pc.NumStats = ++ns1;
}
int address = fs.GetSuccessor();
maxContext.Address = address;
minContext.Address = address;
//TODO-----debug
// int pos = minContext.getFreqData().getStats();
// State a = new State(getHeap());
// a.Address=pos);
// pos+=State.size;
// a.Address=pos);
//--dbg end
return;
}
// Debug
public override System.String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("ModelPPM[");
buffer.Append("\n numMasked=");
buffer.Append(numMasked);
buffer.Append("\n initEsc=");
buffer.Append(initEsc);
buffer.Append("\n orderFall=");
buffer.Append(orderFall);
buffer.Append("\n maxOrder=");
buffer.Append(maxOrder);
buffer.Append("\n runLength=");
buffer.Append(runLength);
buffer.Append("\n initRL=");
buffer.Append(initRL);
buffer.Append("\n escCount=");
buffer.Append(escCount);
buffer.Append("\n prevSuccess=");
buffer.Append(prevSuccess);
buffer.Append("\n foundState=");
buffer.Append(foundState);
buffer.Append("\n coder=");
buffer.Append(coder);
buffer.Append("\n subAlloc=");
buffer.Append(subAlloc);
buffer.Append("\n]");
return buffer.ToString();
}
// Debug
// public void dumpHeap() {
// subAlloc.dumpHeap();
// }
internal bool decodeInit(Stream stream, int maxOrder, int maxMemory)
{
if (stream != null)
coder = new RangeCoder(stream);
if (maxOrder == 1)
{
subAlloc.stopSubAllocator();
return (false);
}
subAlloc.startSubAllocator(maxMemory);
minContext = new PPMContext(Heap);
//medContext = new PPMContext(Heap);
maxContext = new PPMContext(Heap);
foundState = new State(Heap);
dummySEE2Cont = new SEE2Context();
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 16; j++)
{
SEE2Cont[i][j] = new SEE2Context();
}
}
startModelRare(maxOrder);
return (minContext.Address != 0);
}
internal void nextContext()
{
int addr = foundState.GetSuccessor();
if (orderFall == 0 && addr > subAlloc.PText)
{
minContext.Address = addr;
maxContext.Address = addr;
}
else
updateModel();
}
public int decodeChar(LZMA.RangeCoder.Decoder decoder)
{
if (minContext.NumStats != 1)
{
State s = tempState1.Initialize(Heap);
s.Address = minContext.FreqData.GetStats();
int i;
int count, hiCnt;
if ((count = (int) decoder.GetThreshold((uint) minContext.FreqData.SummFreq)) < (hiCnt = s.Freq))
{
byte symbol;
decoder.Decode(0, (uint) s.Freq);
symbol = (byte) s.Symbol;
minContext.update1_0(this, s.Address);
nextContext();
return symbol;
}
prevSuccess = 0;
i = minContext.NumStats - 1;
do
{
s.IncrementAddress();
if ((hiCnt += s.Freq) > count)
{
byte symbol;
decoder.Decode((uint) (hiCnt - s.Freq), (uint) s.Freq);
symbol = (byte) s.Symbol;
minContext.update1(this, s.Address);
nextContext();
return symbol;
}
} while (--i > 0);
if (count >= minContext.FreqData.SummFreq)
return -2;
hiBitsFlag = HB2Flag[foundState.Symbol];
decoder.Decode((uint) hiCnt, (uint) (minContext.FreqData.SummFreq - hiCnt));
for (i = 0; i < 256; i++)
charMask[i] = -1;
charMask[s.Symbol] = 0;
i = minContext.NumStats - 1;
do
{
s.DecrementAddress();
charMask[s.Symbol] = 0;
} while (--i > 0);
}
else
{
State rs = tempState1.Initialize(Heap);
rs.Address = minContext.getOneState().Address;
hiBitsFlag = getHB2Flag()[foundState.Symbol];
int off1 = rs.Freq - 1;
int off2 = minContext.getArrayIndex(this, rs);
int bs = binSumm[off1][off2];
if (decoder.DecodeBit((uint) bs, 14) == 0)
{
byte symbol;
binSumm[off1][off2] = (bs + INTERVAL - minContext.getMean(bs, PERIOD_BITS, 2)) & 0xFFFF;
foundState.Address = rs.Address;
symbol = (byte) rs.Symbol;
rs.IncrementFreq((rs.Freq < 128) ? 1 : 0);
prevSuccess = 1;
incRunLength(1);
nextContext();
return symbol;
}
bs = (bs - minContext.getMean(bs, PERIOD_BITS, 2)) & 0xFFFF;
binSumm[off1][off2] = bs;
initEsc = PPMContext.ExpEscape[Utility.URShift(bs, 10)];
int i;
for (i = 0; i < 256; i++)
charMask[i] = -1;
charMask[rs.Symbol] = 0;
prevSuccess = 0;
}
for (;;)
{
State s = tempState1.Initialize(Heap);
int i;
int freqSum, count, hiCnt;
SEE2Context see;
int num, numMasked = minContext.NumStats;
do
{
orderFall++;
minContext.Address = minContext.getSuffix();
if (minContext.Address <= subAlloc.PText || minContext.Address > subAlloc.HeapEnd)
return -1;
} while (minContext.NumStats == numMasked);
hiCnt = 0;
s.Address = minContext.FreqData.GetStats();
i = 0;
num = minContext.NumStats - numMasked;
do
{
int k = charMask[s.Symbol];
hiCnt += s.Freq & k;
minContext.ps[i] = s.Address;
s.IncrementAddress();
i -= k;
} while (i != num);
see = minContext.makeEscFreq(this, numMasked, out freqSum);
freqSum += hiCnt;
count = (int) decoder.GetThreshold((uint) freqSum);
if (count < hiCnt)
{
byte symbol;
State ps = tempState2.Initialize(Heap);
for (hiCnt = 0, i = 0, ps.Address = minContext.ps[i];
(hiCnt += ps.Freq) <= count;
i++, ps.Address = minContext.ps[i]) ;
s.Address = ps.Address;
decoder.Decode((uint) (hiCnt - s.Freq), (uint) s.Freq);
see.update();
symbol = (byte) s.Symbol;
minContext.update2(this, s.Address);
updateModel();
return symbol;
}
if (count >= freqSum)
return -2;
decoder.Decode((uint) hiCnt, (uint) (freqSum - hiCnt));
see.Summ = see.Summ + freqSum;
do
{
s.Address = minContext.ps[--i];
charMask[s.Symbol] = 0;
} while (i != 0);
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public interface ITileMapEditorHost
{
void BuildIncremental();
void Build(bool force);
}
[InitializeOnLoad]
public static class tk2dTileMapEditorUtility {
static tk2dTileMapEditorUtility() {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
System.Reflection.FieldInfo undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (undoCallback != null) {
undoCallback.SetValue(null, (EditorApplication.CallbackFunction)OnUndoRedo);
}
else {
Debug.LogError("tk2d Undo/Redo callback failed. Undo/Redo not supported in this version of Unity.");
}
#else
Undo.undoRedoPerformed += OnUndoRedo;
#endif
}
static void OnUndoRedo() {
foreach (GameObject go in Selection.gameObjects) {
tk2dUtil.UndoEnabled = false;
tk2dTileMap tilemap = go.GetComponent<tk2dTileMap>();
if (tilemap != null) {
tilemap.ForceBuild();
}
tk2dUtil.UndoEnabled = true;
}
}
}
[CustomEditor(typeof(tk2dTileMap))]
public class tk2dTileMapEditor : Editor, ITileMapEditorHost
{
tk2dTileMap tileMap { get { return (tk2dTileMap)target; } }
tk2dTileMapEditorData editorData;
tk2dTileMapSceneGUI sceneGUI;
tk2dEditor.BrushRenderer _brushRenderer;
tk2dEditor.BrushRenderer brushRenderer
{
get {
if (_brushRenderer == null) _brushRenderer = new tk2dEditor.BrushRenderer(tileMap);
return _brushRenderer;
}
set {
if (value != null) { Debug.LogError("Only alloyed to set to null"); return; }
if (_brushRenderer != null)
{
_brushRenderer.Destroy();
_brushRenderer = null;
}
}
}
tk2dEditor.BrushBuilder _guiBrushBuilder;
tk2dEditor.BrushBuilder guiBrushBuilder
{
get {
if (_guiBrushBuilder == null) _guiBrushBuilder = new tk2dEditor.BrushBuilder();
return _guiBrushBuilder;
}
set {
if (value != null) { Debug.LogError("Only allowed to set to null"); return; }
if (_guiBrushBuilder != null)
{
_guiBrushBuilder = null;
}
}
}
int width, height;
int partitionSizeX, partitionSizeY;
// Sprite collection accessor, cleanup when changed
tk2dSpriteCollectionData _spriteCollection = null;
tk2dSpriteCollectionData SpriteCollection
{
get
{
if (_spriteCollection != tileMap.SpriteCollectionInst)
{
_spriteCollection = tileMap.SpriteCollectionInst;
}
return _spriteCollection;
}
}
void OnEnable()
{
if (Application.isPlaying || !tileMap.AllowEdit)
return;
LoadTileMapData();
}
void OnDestroy() {
tk2dGrid.Done();
tk2dEditorSkin.Done();
tk2dPreferences.inst.Save();
tk2dSpriteThumbnailCache.Done();
}
void InitEditor()
{
// Initialize editor
LoadTileMapData();
}
void OnDisable()
{
brushRenderer = null;
guiBrushBuilder = null;
if (sceneGUI != null)
{
sceneGUI.Destroy();
sceneGUI = null;
}
if (editorData)
{
EditorUtility.SetDirty(editorData);
}
if (tileMap && tileMap.data)
{
EditorUtility.SetDirty(tileMap.data);
}
}
void LoadTileMapData()
{
width = tileMap.width;
height = tileMap.height;
partitionSizeX = tileMap.partitionSizeX;
partitionSizeY = tileMap.partitionSizeY;
GetEditorData();
if (tileMap.data && editorData && tileMap.Editor__SpriteCollection != null)
{
// Rebuild the palette
editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow);
}
// Rebuild the render utility
if (sceneGUI != null)
{
sceneGUI.Destroy();
}
sceneGUI = new tk2dTileMapSceneGUI(this, tileMap, editorData);
// Rebuild the brush renderer
brushRenderer = null;
}
public void Build(bool force, bool incremental)
{
if (force)
{
//if (buildKey != tileMap.buildKey)
//tk2dEditor.TileMap.TileMapUtility.CleanRenderData(tileMap);
tk2dTileMap.BuildFlags buildFlags = tk2dTileMap.BuildFlags.EditMode;
if (!incremental) buildFlags |= tk2dTileMap.BuildFlags.ForceBuild;
tileMap.Build(buildFlags);
}
}
public void Build(bool force) { Build(force, false); }
public void BuildIncremental() { Build(true, true); }
bool Ready
{
get
{
return (tileMap != null && tileMap.data != null && editorData != null & tileMap.Editor__SpriteCollection != null && tileMap.SpriteCollectionInst != null);
}
}
void HighlightTile(Rect rect, Rect tileSize, int tilesPerRow, int x, int y, Color fillColor, Color outlineColor)
{
Rect highlightRect = new Rect(rect.x + x * tileSize.width,
rect.y + y * tileSize.height,
tileSize.width,
tileSize.height);
Vector3[] rectVerts = { new Vector3(highlightRect.x, highlightRect.y, 0),
new Vector3(highlightRect.x + highlightRect.width, highlightRect.y, 0),
new Vector3(highlightRect.x + highlightRect.width, highlightRect.y + highlightRect.height, 0),
new Vector3(highlightRect.x, highlightRect.y + highlightRect.height, 0) };
Handles.DrawSolidRectangleWithOutline(rectVerts, fillColor, outlineColor);
}
Vector2 tiledataScrollPos = Vector2.zero;
int selectedDataTile = -1;
void DrawTileDataSetupPanel()
{
// Sanitize prefabs
if (tileMap.data.tilePrefabs == null)
tileMap.data.tilePrefabs = new GameObject[0];
if (tileMap.data.tilePrefabs.Length != SpriteCollection.Count)
{
System.Array.Resize(ref tileMap.data.tilePrefabs, SpriteCollection.Count);
}
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
tiledataScrollPos = BeginHScrollView(tiledataScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
float displayScale = brushRenderer.LastScale;
Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale);
int tilesPerRow = editorData.paletteTilesPerRow;
int newSelectedPrefab = selectedDataTile;
if (Event.current.type == EventType.MouseUp && rect.Contains(Event.current.mousePosition))
{
Vector2 localClickPosition = Event.current.mousePosition - new Vector2(rect.x, rect.y);
Vector2 tileLocalPosition = new Vector2(localClickPosition.x / tileSize.width, localClickPosition.y / tileSize.height);
int tx = (int)tileLocalPosition.x;
int ty = (int)tileLocalPosition.y;
newSelectedPrefab = ty * tilesPerRow + tx;
}
if (Event.current.type == EventType.Repaint)
{
for (int tileId = 0; tileId < SpriteCollection.Count; ++tileId)
{
Color noDataFillColor = new Color(0, 0, 0, 0.2f);
Color noDataOutlineColor = Color.clear;
Color selectedFillColor = new Color(1,0,0,0.05f);
Color selectedOutlineColor = Color.red;
if (tileMap.data.tilePrefabs[tileId] == null || tileId == selectedDataTile)
{
Color fillColor = (selectedDataTile == tileId)?selectedFillColor:noDataFillColor;
Color outlineColor = (selectedDataTile == tileId)?selectedOutlineColor:noDataOutlineColor;
HighlightTile(rect, tileSize, editorData.paletteTilesPerRow, tileId % tilesPerRow, tileId / tilesPerRow, fillColor, outlineColor);
}
}
}
EndHScrollView();
if (selectedDataTile >= 0 && selectedDataTile < tileMap.data.tilePrefabs.Length)
{
tileMap.data.tilePrefabs[selectedDataTile] = EditorGUILayout.ObjectField("Prefab", tileMap.data.tilePrefabs[selectedDataTile], typeof(GameObject), true) as GameObject;
}
// Add all additional tilemap data
var allTileInfos = tileMap.data.GetOrCreateTileInfo(SpriteCollection.Count);
if (selectedDataTile >= 0 && selectedDataTile < allTileInfos.Length)
{
var tileInfo = allTileInfos[selectedDataTile];
GUILayout.Space(16.0f);
tileInfo.stringVal = (tileInfo.stringVal==null)?"":tileInfo.stringVal;
tileInfo.stringVal = EditorGUILayout.TextField("String", tileInfo.stringVal);
tileInfo.intVal = EditorGUILayout.IntField("Int", tileInfo.intVal);
tileInfo.floatVal = EditorGUILayout.FloatField("Float", tileInfo.floatVal);
tileInfo.enablePrefabOffset = EditorGUILayout.Toggle("Enable Prefab Offset", tileInfo.enablePrefabOffset);
}
if (newSelectedPrefab != selectedDataTile)
{
selectedDataTile = newSelectedPrefab;
Repaint();
}
}
void DrawLayersPanel(bool allowEditing)
{
GUILayout.BeginVertical();
// constrain selected layer
editorData.layer = Mathf.Clamp(editorData.layer, 0, tileMap.data.NumLayers - 1);
if (allowEditing)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tileMap.data.useSortingLayers = GUILayout.Toggle(tileMap.data.useSortingLayers, "Sorting Layers", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
#endif
tileMap.data.layersFixedZ = GUILayout.Toggle(tileMap.data.layersFixedZ, "Fixed Z", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
if (GUILayout.Button("Add Layer", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
editorData.layer = tk2dEditor.TileMap.TileMapUtility.AddNewLayer(tileMap);
}
GUILayout.EndHorizontal();
}
if (tileMap.data.useSortingLayers) {
EditorGUILayout.HelpBox("Unity Sorting Layers take precedence over z sorting. Please ensure your sprites / prefabs are on the correct layers for them to sort properly - they don't automatically inherit the sorting layer/order of the parent.", MessageType.Warning);
}
string zValueLabel = tileMap.data.layersFixedZ ? "Z Value" : "Z Offset";
int numLayers = tileMap.data.NumLayers;
int deleteLayer = -1;
int moveUp = -1;
int moveDown = -1;
for (int layer = numLayers - 1; layer >= 0; --layer)
{
GUILayout.Space(4.0f);
if (allowEditing) {
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG);
GUILayout.BeginHorizontal();
if (editorData.layer == layer) {
string newName = GUILayout.TextField(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true));
tileMap.data.Layers[layer].name = newName;
} else {
if (GUILayout.Button(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true))) {
editorData.layer = layer;
Repaint();
}
}
GUI.enabled = (layer != 0);
if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_down")))
{
moveUp = layer;
Repaint();
}
GUI.enabled = (layer != numLayers - 1);
if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_up")))
{
moveDown = layer;
Repaint();
}
GUI.enabled = numLayers > 1;
if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem")))
{
deleteLayer = layer;
Repaint();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
// Row 2
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.Layers[layer].skipMeshGeneration = !GUILayout.Toggle(!tileMap.data.Layers[layer].skipMeshGeneration, "Render Mesh", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
tileMap.data.Layers[layer].useColor = GUILayout.Toggle(tileMap.data.Layers[layer].useColor, "Color", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
tileMap.data.Layers[layer].generateCollider = GUILayout.Toggle(tileMap.data.Layers[layer].generateCollider, "Collider", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
if (tk2dGuiUtility.EndChangeCheck())
Build(true);
GUILayout.EndHorizontal();
// Row 3
tk2dGuiUtility.BeginChangeCheck();
if (layer == 0 && !tileMap.data.layersFixedZ) {
GUI.enabled = false;
EditorGUILayout.FloatField(zValueLabel, 0.0f);
GUI.enabled = true;
}
else {
tileMap.data.Layers[layer].z = EditorGUILayout.FloatField(zValueLabel, tileMap.data.Layers[layer].z);
}
if (!tileMap.data.layersFixedZ)
tileMap.data.Layers[layer].z = Mathf.Max(0, tileMap.data.Layers[layer].z);
tileMap.data.Layers[layer].unityLayer = EditorGUILayout.LayerField("Unity Layer", tileMap.data.Layers[layer].unityLayer);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
// Unity sorting layers
if (tileMap.data.useSortingLayers) {
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.Layers[layer].sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", tileMap.data.Layers[layer].sortingLayerName);
tileMap.data.Layers[layer].sortingOrder = EditorGUILayout.IntField("Sorting Order in Layer", tileMap.data.Layers[layer].sortingOrder);
if (tk2dGuiUtility.EndChangeCheck()) {
Build(true);
}
}
#endif
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
bool using2DPhysics = (tileMap.SpriteCollectionInst != null && tileMap.SpriteCollectionInst.FirstValidDefinition != null && tileMap.SpriteCollectionInst.FirstValidDefinition.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D);
if (using2DPhysics) {
tileMap.data.Layers[layer].physicsMaterial2D = (PhysicsMaterial2D)EditorGUILayout.ObjectField("Physics Material (2D)", tileMap.data.Layers[layer].physicsMaterial2D, typeof(PhysicsMaterial2D), false);
}
else
#endif
{
tileMap.data.Layers[layer].physicMaterial = (PhysicMaterial)EditorGUILayout.ObjectField("Physic Material", tileMap.data.Layers[layer].physicMaterial, typeof(PhysicMaterial), false);
}
if (tk2dGuiUtility.EndChangeCheck())
Build(true);
GUILayout.EndVertical();
} else {
GUILayout.BeginHorizontal(tk2dEditorSkin.SC_InspectorHeaderBG);
bool layerSelVal = editorData.layer == layer;
bool newLayerSelVal = GUILayout.Toggle(layerSelVal, tileMap.data.Layers[layer].name, EditorStyles.toggle, GUILayout.ExpandWidth(true));
if (newLayerSelVal != layerSelVal)
{
editorData.layer = layer;
Repaint();
}
GUILayout.FlexibleSpace();
var layerGameObject = tileMap.Layers[layer].gameObject;
if (layerGameObject)
{
bool b = GUILayout.Toggle(tk2dEditorUtility.IsGameObjectActive(layerGameObject), "", tk2dEditorSkin.SimpleCheckbox("icon_eye_inactive", "icon_eye"));
if (b != tk2dEditorUtility.IsGameObjectActive(layerGameObject))
tk2dEditorUtility.SetGameObjectActive(layerGameObject, b);
}
GUILayout.EndHorizontal();
}
}
if (deleteLayer != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Deleted layer");
tk2dEditor.TileMap.TileMapUtility.DeleteLayer(tileMap, deleteLayer);
}
if (moveUp != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer");
tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveUp, -1);
}
if (moveDown != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer");
tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveDown, 1);
}
GUILayout.EndVertical();
}
bool Foldout(ref tk2dTileMapEditorData.SetupMode val, tk2dTileMapEditorData.SetupMode ident, string name)
{
bool selected = false;
if ((val & ident) != 0)
selected = true;
//GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
bool newSelected = GUILayout.Toggle(selected, name, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(true));
if (newSelected != selected)
{
if (selected == false)
val = ident;
else
val = 0;
}
return newSelected;
}
int tilePropertiesPreviewIdx = 0;
Vector2 paletteSettingsScrollPos = Vector2.zero;
void DrawSettingsPanel()
{
GUILayout.Space(8);
// Sprite collection
GUILayout.BeginHorizontal();
tk2dSpriteCollectionData newSpriteCollection = tk2dSpriteGuiUtility.SpriteCollectionList("Sprite Collection", tileMap.Editor__SpriteCollection);
if (newSpriteCollection != tileMap.Editor__SpriteCollection) {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Set TileMap Sprite Collection");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Set TileMap Sprite Collection");
#endif
tileMap.Editor__SpriteCollection = newSpriteCollection;
newSpriteCollection.InitMaterialIds();
LoadTileMapData();
EditorUtility.SetDirty(tileMap);
if (Ready)
{
Init(tileMap.data);
tileMap.ForceBuild();
}
}
if (tileMap.Editor__SpriteCollection != null && GUILayout.Button(">", EditorStyles.miniButton, GUILayout.Width(19))) {
tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow( typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor" ) as tk2dSpriteCollectionEditorPopup;
string assetPath = AssetDatabase.GUIDToAssetPath(tileMap.Editor__SpriteCollection.spriteCollectionGUID);
var spriteCollection = AssetDatabase.LoadAssetAtPath(assetPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
v.SetGeneratorAndSelectedSprite(spriteCollection, tileMap.Editor__SpriteCollection.FirstValidDefinitionIndex);
}
GUILayout.EndHorizontal();
GUILayout.Space(8);
// Tilemap data
tk2dTileMapData newData = (tk2dTileMapData)EditorGUILayout.ObjectField("Tile Map Data", tileMap.data, typeof(tk2dTileMapData), false);
if (newData != tileMap.data)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Assign TileMap Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Assign TileMap Data");
#endif
tileMap.data = newData;
LoadTileMapData();
}
if (tileMap.data == null)
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"TileMap needs an data object to proceed. " +
"Please create one or drag an existing data object into the inspector slot.\n",
tk2dGuiUtility.WarningLevel.Info,
"Create") != -1)
{
string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Data", "tileMapData", "asset", "");
if (assetPath.Length > 0)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Create TileMap Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Create TileMap Data");
#endif
tk2dTileMapData tileMapData = ScriptableObject.CreateInstance<tk2dTileMapData>();
AssetDatabase.CreateAsset(tileMapData, assetPath);
tileMap.data = tileMapData;
EditorUtility.SetDirty(tileMap);
Init(tileMapData);
LoadTileMapData();
}
}
}
// Editor data
tk2dTileMapEditorData newEditorData = (tk2dTileMapEditorData)EditorGUILayout.ObjectField("Editor Data", editorData, typeof(tk2dTileMapEditorData), false);
if (newEditorData != editorData)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Assign TileMap Editor Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Assign TileMap Editor Data");
#endif
string assetPath = AssetDatabase.GetAssetPath(newEditorData);
if (assetPath.Length > 0)
{
tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath);
EditorUtility.SetDirty(tileMap);
LoadTileMapData();
}
}
if (editorData == null)
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"TileMap needs an editor data object to proceed. " +
"Please create one or drag an existing data object into the inspector slot.\n",
tk2dGuiUtility.WarningLevel.Info,
"Create") != -1)
{
string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Editor Data", "tileMapEditorData", "asset", "");
if (assetPath.Length > 0)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Create TileMap Editor Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Create TileMap Editor Data");
#endif
tk2dTileMapEditorData tileMapEditorData = ScriptableObject.CreateInstance<tk2dTileMapEditorData>();
AssetDatabase.CreateAsset(tileMapEditorData, assetPath);
tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath);
EditorUtility.SetDirty(tileMap);
LoadTileMapData();
}
}
}
// If not set up, don't bother drawing anything else
if (!Ready)
return;
// this is intentionally read only
GUILayout.Space(8);
GUILayout.BeginHorizontal();
GUI.enabled = false;
EditorGUILayout.ObjectField("Render Data", tileMap.renderData, typeof(GameObject), false);
GUI.enabled = true;
if (tileMap.renderData != null && GUILayout.Button("Unlink", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) {
tk2dEditor.TileMap.TileMapUtility.MakeUnique(tileMap);
}
GUILayout.EndHorizontal();
GUILayout.Space(8);
// tile map size
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Dimensions, "Dimensions"))
{
EditorGUI.indentLevel++;
width = Mathf.Clamp(EditorGUILayout.IntField("Width", width), 1, tk2dEditor.TileMap.TileMapUtility.MaxWidth);
height = Mathf.Clamp(EditorGUILayout.IntField("Height", height), 1, tk2dEditor.TileMap.TileMapUtility.MaxHeight);
partitionSizeX = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeX", partitionSizeX), 4, 32);
partitionSizeY = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeY", partitionSizeY), 4, 32);
// Create a default tilemap with given dimensions
if (!tileMap.AreSpritesInitialized())
{
tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap);
tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, tileMap.partitionSizeX, tileMap.partitionSizeY);
}
if (width != tileMap.width || height != tileMap.height || partitionSizeX != tileMap.partitionSizeX || partitionSizeY != tileMap.partitionSizeY)
{
if ((width < tileMap.width || height < tileMap.height))
{
tk2dGuiUtility.InfoBox("The new size of the tile map is smaller than the current size." +
"Some clipping will occur.", tk2dGuiUtility.WarningLevel.Warning);
}
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Apply", EditorStyles.miniButton))
{
tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, partitionSizeX, partitionSizeY);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Layers, "Layers"))
{
EditorGUI.indentLevel++;
DrawLayersPanel(true);
EditorGUI.indentLevel--;
}
// tilemap info
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Info, "Info"))
{
EditorGUI.indentLevel++;
int numActiveChunks = 0;
if (tileMap.Layers != null)
{
foreach (var layer in tileMap.Layers)
numActiveChunks += layer.NumActiveChunks;
}
EditorGUILayout.LabelField("Active chunks", numActiveChunks.ToString());
int partitionMemSize = partitionSizeX * partitionSizeY * 4;
EditorGUILayout.LabelField("Memory", ((numActiveChunks * partitionMemSize) / 1024).ToString() + "kB" );
int numActiveColorChunks = 0;
if (tileMap.ColorChannel != null)
numActiveColorChunks += tileMap.ColorChannel.NumActiveChunks;
EditorGUILayout.LabelField("Active color chunks", numActiveColorChunks.ToString());
int colorMemSize = (partitionSizeX + 1) * (partitionSizeY + 1) * 4;
EditorGUILayout.LabelField("Memory", ((numActiveColorChunks * colorMemSize) / 1024).ToString() + "kB" );
EditorGUI.indentLevel--;
}
// tile properties
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.TileProperties, "Tile Properties"))
{
EditorGUI.indentLevel++;
// sort method
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.tileType = (tk2dTileMapData.TileType)EditorGUILayout.EnumPopup("Tile Type", tileMap.data.tileType);
if (tileMap.data.tileType != tk2dTileMapData.TileType.Rectangular) {
tk2dGuiUtility.InfoBox("Non-rectangular tile types are still in beta testing.", tk2dGuiUtility.WarningLevel.Info);
}
tileMap.data.sortMethod = (tk2dTileMapData.SortMethod)EditorGUILayout.EnumPopup("Sort Method", tileMap.data.sortMethod);
if (tk2dGuiUtility.EndChangeCheck())
{
tileMap.BeginEditMode();
}
// reset sizes
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Reset sizes");
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.miniButtonRight))
{
Init(tileMap.data);
Build(true);
}
GUILayout.EndHorizontal();
// convert these to pixel units
Vector3 texelSize = SpriteCollection.spriteDefinitions[0].texelSize;
Vector3 tileOriginPixels = new Vector3(tileMap.data.tileOrigin.x / texelSize.x, tileMap.data.tileOrigin.y / texelSize.y, tileMap.data.tileOrigin.z);
Vector3 tileSizePixels = new Vector3(tileMap.data.tileSize.x / texelSize.x, tileMap.data.tileSize.y / texelSize.y, tileMap.data.tileSize.z);
Vector3 newTileOriginPixels = EditorGUILayout.Vector3Field("Origin", tileOriginPixels);
Vector3 newTileSizePixels = EditorGUILayout.Vector3Field("Size", tileSizePixels);
if (newTileOriginPixels != tileOriginPixels ||
newTileSizePixels != tileSizePixels)
{
tileMap.data.tileOrigin = new Vector3(newTileOriginPixels.x * texelSize.x, newTileOriginPixels.y * texelSize.y, newTileOriginPixels.z);
tileMap.data.tileSize = new Vector3(newTileSizePixels.x * texelSize.x, newTileSizePixels.y * texelSize.y, newTileSizePixels.z);
Build(true);
}
// preview tile origin and size setting
Vector2 spritePixelOrigin = Vector2.zero;
Vector2 spritePixelSize = Vector2.one;
tk2dSpriteDefinition[] spriteDefs = tileMap.SpriteCollectionInst.spriteDefinitions;
tk2dSpriteDefinition spriteDef = (tilePropertiesPreviewIdx < spriteDefs.Length) ? spriteDefs[tilePropertiesPreviewIdx] : null;
if (!spriteDef.Valid) spriteDef = null;
if (spriteDef != null) {
spritePixelOrigin = new Vector2(spriteDef.untrimmedBoundsData[0].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[0].y / spriteDef.texelSize.y);
spritePixelSize = new Vector2(spriteDef.untrimmedBoundsData[1].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[1].y / spriteDef.texelSize.y);
}
float zoomFactor = (Screen.width - 32.0f) / (spritePixelSize.x * 2.0f);
EditorGUILayout.BeginScrollView(Vector2.zero, GUILayout.Height(spritePixelSize.y * 2.0f * zoomFactor + 32.0f));
Rect innerRect = new Rect(0, 0, spritePixelSize.x * 2.0f * zoomFactor, spritePixelSize.y * 2.0f * zoomFactor);
tk2dGrid.Draw(innerRect);
if (spriteDef != null) {
// Preview tiles
tk2dSpriteThumbnailCache.DrawSpriteTexture(new Rect(spritePixelSize.x * 0.5f * zoomFactor, spritePixelSize.y * 0.5f * zoomFactor, spritePixelSize.x * zoomFactor, spritePixelSize.y * zoomFactor), spriteDef);
// Preview cursor
Vector2 cursorOffset = (spritePixelSize * 0.5f - spritePixelOrigin) * zoomFactor;
Vector2 cursorSize = new Vector2(tileSizePixels.x * zoomFactor, tileSizePixels.y * zoomFactor);
cursorOffset.x += tileOriginPixels.x * zoomFactor;
cursorOffset.y += tileOriginPixels.y * zoomFactor;
cursorOffset.x += spritePixelSize.x * 0.5f * zoomFactor;
cursorOffset.y += spritePixelSize.y * 0.5f * zoomFactor;
float top = spritePixelSize.y * 2.0f * zoomFactor;
Vector3[] cursorVerts = new Vector3[] {
new Vector3(cursorOffset.x, top - cursorOffset.y, 0),
new Vector3(cursorOffset.x + cursorSize.x, top - cursorOffset.y, 0),
new Vector3(cursorOffset.x + cursorSize.x, top - (cursorOffset.y + cursorSize.y), 0),
new Vector3(cursorOffset.x, top - (cursorOffset.y + cursorSize.y), 0)
};
Handles.DrawSolidRectangleWithOutline(cursorVerts, new Color(1.0f, 1.0f, 1.0f, 0.2f), Color.white);
}
if (GUILayout.Button(new GUIContent("", "Click - preview using different tile"), "label", GUILayout.Width(innerRect.width), GUILayout.Height(innerRect.height))) {
int n = spriteDefs.Length;
for (int i = 0; i < n; ++i) {
if (++tilePropertiesPreviewIdx >= n)
tilePropertiesPreviewIdx = 0;
if (spriteDefs[tilePropertiesPreviewIdx].Valid)
break;
}
}
EditorGUILayout.EndScrollView();
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.PaletteProperties, "Palette Properties"))
{
EditorGUI.indentLevel++;
int newTilesPerRow = Mathf.Clamp(EditorGUILayout.IntField("Tiles Per Row", editorData.paletteTilesPerRow),
1, SpriteCollection.Count);
if (newTilesPerRow != editorData.paletteTilesPerRow)
{
guiBrushBuilder.Reset();
editorData.paletteTilesPerRow = newTilesPerRow;
editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow);
}
GUILayout.BeginHorizontal();
editorData.brushDisplayScale = EditorGUILayout.FloatField("Display Scale", editorData.brushDisplayScale);
editorData.brushDisplayScale = Mathf.Clamp(editorData.brushDisplayScale, 1.0f / 16.0f, 4.0f);
if (GUILayout.Button("Reset", EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)))
{
editorData.brushDisplayScale = 1.0f;
Repaint();
}
GUILayout.EndHorizontal();
EditorGUILayout.PrefixLabel("Preview");
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
paletteSettingsScrollPos = BeginHScrollView(paletteSettingsScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
EndHScrollView();
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Import, "Import"))
{
EditorGUI.indentLevel++;
if (GUILayout.Button("Import TMX"))
{
if (tk2dEditor.TileMap.Importer.Import(tileMap, tk2dEditor.TileMap.Importer.Format.TMX))
{
Build(true);
width = tileMap.width;
height = tileMap.height;
partitionSizeX = tileMap.partitionSizeX;
partitionSizeY = tileMap.partitionSizeY;
}
}
EditorGUI.indentLevel--;
}
}
// Little hack to allow nested scrollviews to behave properly
Vector2 hScrollDelta = Vector2.zero;
Vector2 BeginHScrollView(Vector2 pos, params GUILayoutOption[] options) {
hScrollDelta = Vector2.zero;
if (Event.current.type == EventType.ScrollWheel) {
hScrollDelta.y = Event.current.delta.y;
}
return EditorGUILayout.BeginScrollView(pos, options);
}
void EndHScrollView() {
EditorGUILayout.EndScrollView();
if (hScrollDelta != Vector2.zero) {
Event.current.type = EventType.ScrollWheel;
Event.current.delta = hScrollDelta;
}
}
void DrawColorPaintPanel()
{
if (!tileMap.HasColorChannel())
{
if (GUILayout.Button("Create Color Channel"))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Created Color Channel");
tileMap.CreateColorChannel();
tileMap.BeginEditMode();
}
Repaint();
return;
}
tk2dTileMapToolbar.ColorToolsWindow();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Clear to Color");
if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false)))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Created Color Channel");
tileMap.ColorChannel.Clear(tk2dTileMapToolbar.colorBrushColor);
Build(true);
}
EditorGUILayout.EndHorizontal();
if (tileMap.HasColorChannel())
{
EditorGUILayout.Separator();
if (GUILayout.Button("Delete Color Channel"))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Deleted Color Channel");
tileMap.DeleteColorChannel();
tileMap.BeginEditMode();
Repaint();
return;
}
}
}
int InlineToolbar(string name, int val, string[] names)
{
int selectedIndex = val;
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label(name, EditorStyles.toolbarButton);
GUILayout.FlexibleSpace();
for (int i = 0; i < names.Length; ++i)
{
bool selected = (i == selectedIndex);
bool toggled = GUILayout.Toggle(selected, names[i], EditorStyles.toolbarButton);
if (toggled == true)
{
selectedIndex = i;
}
}
GUILayout.EndHorizontal();
return selectedIndex;
}
bool showSaveSection = false;
bool showLoadSection = false;
void DrawLoadSaveBrushSection(tk2dTileMapEditorBrush activeBrush)
{
// Brush load & save handling
bool startedSave = false;
bool prevGuiEnabled = GUI.enabled;
GUILayout.BeginHorizontal();
if (showLoadSection) GUI.enabled = false;
if (GUILayout.Button(showSaveSection?"Cancel":"Save"))
{
if (showSaveSection == false) startedSave = true;
showSaveSection = !showSaveSection;
if (showSaveSection) showLoadSection = false;
Repaint();
}
GUI.enabled = prevGuiEnabled;
if (showSaveSection) GUI.enabled = false;
if (GUILayout.Button(showLoadSection?"Cancel":"Load"))
{
showLoadSection = !showLoadSection;
if (showLoadSection) showSaveSection = false;
}
GUI.enabled = prevGuiEnabled;
GUILayout.EndHorizontal();
if (showSaveSection)
{
GUI.SetNextControlName("BrushNameEntry");
activeBrush.name = EditorGUILayout.TextField("Name", activeBrush.name);
if (startedSave)
GUI.FocusControl("BrushNameEntry");
if (GUILayout.Button("Save"))
{
if (activeBrush.name.Length == 0)
{
Debug.LogError("Active brush needs a name");
}
else
{
bool replaced = false;
for (int i = 0; i < editorData.brushes.Count; ++i)
{
if (editorData.brushes[i].name == activeBrush.name)
{
editorData.brushes[i] = new tk2dTileMapEditorBrush(activeBrush);
replaced = true;
}
}
if (!replaced)
editorData.brushes.Add(new tk2dTileMapEditorBrush(activeBrush));
showSaveSection = false;
}
}
}
if (showLoadSection)
{
GUILayout.Space(8);
if (editorData.brushes.Count == 0)
GUILayout.Label("No saved brushes.");
GUILayout.BeginVertical();
int deleteBrushId = -1;
for (int i = 0; i < editorData.brushes.Count; ++i)
{
var v = editorData.brushes[i];
GUILayout.BeginHorizontal();
if (GUILayout.Button(v.name, EditorStyles.miniButton))
{
showLoadSection = false;
editorData.activeBrush = new tk2dTileMapEditorBrush(v);
}
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(16)))
{
deleteBrushId = i;
}
GUILayout.EndHorizontal();
}
if (deleteBrushId != -1)
{
editorData.brushes.RemoveAt(deleteBrushId);
Repaint();
}
GUILayout.EndVertical();
}
}
Vector2 paletteScrollPos = Vector2.zero;
Vector2 activeBrushScrollPos = Vector2.zero;
void DrawPaintPanel()
{
var activeBrush = editorData.activeBrush;
if (Ready && (activeBrush == null || activeBrush.Empty))
{
editorData.InitBrushes(tileMap.SpriteCollectionInst);
}
// Draw layer selector
if (tileMap.data.NumLayers > 1)
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label("Layers", EditorStyles.toolbarButton); GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
DrawLayersPanel(false);
EditorGUILayout.Space();
GUILayout.EndVertical();
}
#if TK2D_TILEMAP_EXPERIMENTAL
DrawLoadSaveBrushSection(activeBrush);
#endif
// Draw palette
if (!showLoadSection && !showSaveSection)
{
editorData.showPalette = EditorGUILayout.Foldout(editorData.showPalette, "Palette");
if (editorData.showPalette)
{
// brush name
string selectionDesc = "";
if (activeBrush.tiles.Length == 1) {
int tile = tk2dRuntime.TileMap.BuilderUtil.GetTileFromRawTile(activeBrush.tiles[0].spriteId);
if (tile >= 0 && tile < SpriteCollection.spriteDefinitions.Length)
selectionDesc = SpriteCollection.spriteDefinitions[tile].name;
}
GUILayout.Label(selectionDesc);
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
paletteScrollPos = BeginHScrollView(paletteScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
// palette
Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
float displayScale = brushRenderer.LastScale;
Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale);
guiBrushBuilder.HandleGUI(rect, tileSize, editorData.paletteTilesPerRow, tileMap.SpriteCollectionInst, activeBrush);
EditorGUILayout.Separator();
EndHScrollView();
}
EditorGUILayout.Separator();
}
// Draw brush
if (!showLoadSection)
{
editorData.showBrush = EditorGUILayout.Foldout(editorData.showBrush, "Brush");
if (editorData.showBrush)
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Cursor Tile Opacity");
tk2dTileMapToolbar.workBrushOpacity = EditorGUILayout.Slider(tk2dTileMapToolbar.workBrushOpacity, 0.0f, 1.0f);
GUILayout.EndHorizontal();
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.activeBrush, editorData.paletteTilesPerRow);
activeBrushScrollPos = BeginHScrollView(activeBrushScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
brushRenderer.DrawBrush(tileMap, editorData.activeBrush, editorData.brushDisplayScale, false, editorData.paletteTilesPerRow);
EndHScrollView();
EditorGUILayout.Separator();
}
}
}
/// <summary>
/// Initialize tilemap data to sensible values.
/// Mainly, tileSize and tileOffset
/// </summary>
void Init(tk2dTileMapData tileMapData)
{
if (tileMap.SpriteCollectionInst != null) {
tileMapData.tileSize = tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1];
tileMapData.tileOrigin = this.tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[0] - tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1] * 0.5f;
}
}
void GetEditorData() {
// Don't guess, load editor data every frame
string editorDataPath = AssetDatabase.GUIDToAssetPath(tileMap.editorDataGUID);
editorData = Resources.LoadAssetAtPath(editorDataPath, typeof(tk2dTileMapEditorData)) as tk2dTileMapEditorData;
}
public override void OnInspectorGUI()
{
if (tk2dEditorUtility.IsPrefab(target))
{
tk2dGuiUtility.InfoBox("Editor disabled on prefabs.", tk2dGuiUtility.WarningLevel.Error);
return;
}
if (Application.isPlaying)
{
tk2dGuiUtility.InfoBox("Editor disabled while game is running.", tk2dGuiUtility.WarningLevel.Error);
return;
}
GetEditorData();
if (tileMap.data == null || editorData == null || tileMap.Editor__SpriteCollection == null) {
DrawSettingsPanel();
return;
}
if (tileMap.renderData != null)
{
if (tileMap.renderData.transform.position != tileMap.transform.position) {
tileMap.renderData.transform.position = tileMap.transform.position;
}
if (tileMap.renderData.transform.rotation != tileMap.transform.rotation) {
tileMap.renderData.transform.rotation = tileMap.transform.rotation;
}
if (tileMap.renderData.transform.localScale != tileMap.transform.localScale) {
tileMap.renderData.transform.localScale = tileMap.transform.localScale;
}
}
if (!tileMap.AllowEdit)
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Edit"))
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Tilemap Enter Edit Mode");
#else
tk2dUtil.BeginGroup("Tilemap Enter Edit Mode");
Undo.RegisterCompleteObjectUndo(tileMap, "Tilemap Enter Edit Mode");
#endif
tileMap.BeginEditMode();
InitEditor();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dUtil.EndGroup();
#endif
Repaint();
}
GUILayout.EndHorizontal();
return;
}
// Commit
GUILayout.BeginHorizontal();
if (GUILayout.Button("Commit"))
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Tilemap Leave Edit Mode");
#else
tk2dUtil.BeginGroup("Tilemap Leave Edit Mode");
Undo.RegisterCompleteObjectUndo(tileMap, "Tilemap Leave Edit Mode");
#endif
tileMap.EndEditMode();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dUtil.EndGroup();
#endif
Repaint();
}
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
if (tileMap.editorDataGUID.Length > 0 && editorData == null)
{
// try to load it in
LoadTileMapData();
// failed, so the asset is lost
if (editorData == null)
{
tileMap.editorDataGUID = "";
}
}
if (editorData == null || tileMap.data == null || tileMap.Editor__SpriteCollection == null || !tileMap.AreSpritesInitialized())
{
DrawSettingsPanel();
}
else
{
// In case things have changed
if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap))
Build(true);
string[] toolBarButtonNames = System.Enum.GetNames(typeof(tk2dTileMapEditorData.EditMode));
tk2dTileMapEditorData.EditMode newEditMode = (tk2dTileMapEditorData.EditMode)GUILayout.Toolbar((int)editorData.editMode, toolBarButtonNames );
if (newEditMode != editorData.editMode) {
// Force updating the scene view when mode changes
EditorUtility.SetDirty(target);
editorData.editMode = newEditMode;
}
switch (editorData.editMode)
{
case tk2dTileMapEditorData.EditMode.Paint: DrawPaintPanel(); break;
case tk2dTileMapEditorData.EditMode.Color: DrawColorPaintPanel(); break;
case tk2dTileMapEditorData.EditMode.Settings: DrawSettingsPanel(); break;
case tk2dTileMapEditorData.EditMode.Data: DrawTileDataSetupPanel(); break;
}
}
}
void OnSceneGUI()
{
if (!Ready)
{
return;
}
if (sceneGUI != null && tk2dEditorUtility.IsEditable(target))
{
sceneGUI.OnSceneGUI();
}
if (!Application.isPlaying && tileMap.AllowEdit)
{
// build if necessary
if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap))
Build(true);
else
Build(false);
}
}
[MenuItem("GameObject/Create Other/tk2d/TileMap", false, 13850)]
static void Create()
{
tk2dSpriteCollectionData sprColl = null;
if (sprColl == null)
{
// try to inherit from other TileMaps in scene
tk2dTileMap sceneTileMaps = GameObject.FindObjectOfType(typeof(tk2dTileMap)) as tk2dTileMap;
if (sceneTileMaps)
{
sprColl = sceneTileMaps.Editor__SpriteCollection;
}
}
if (sprColl == null)
{
tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
foreach (var v in spriteCollections)
{
if (v.managedSpriteCollection) continue; // don't wanna pick a managed one
GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
var sc = scgo.GetComponent<tk2dSpriteCollectionData>();
if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0 && sc.allowMultipleAtlases == false)
{
sprColl = sc;
break;
}
}
if (sprColl == null)
{
EditorUtility.DisplayDialog("Create TileMap", "Unable to create sprite as no SpriteCollections have been found.", "Ok");
return;
}
}
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TileMap");
go.transform.position = Vector3.zero;
go.transform.rotation = Quaternion.identity;
tk2dTileMap tileMap = go.AddComponent<tk2dTileMap>();
tileMap.BeginEditMode();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create TileMap");
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// Describes the vusb device
/// First published in Unreleased.
/// </summary>
public partial class VUSB : XenObject<VUSB>
{
public VUSB()
{
}
public VUSB(string uuid,
List<vusb_operations> allowed_operations,
Dictionary<string, vusb_operations> current_operations,
XenRef<VM> VM,
XenRef<USB_group> USB_group,
Dictionary<string, string> other_config,
bool currently_attached)
{
this.uuid = uuid;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VM = VM;
this.USB_group = USB_group;
this.other_config = other_config;
this.currently_attached = currently_attached;
}
/// <summary>
/// Creates a new VUSB from a Proxy_VUSB.
/// </summary>
/// <param name="proxy"></param>
public VUSB(Proxy_VUSB proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VUSB update)
{
uuid = update.uuid;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VM = update.VM;
USB_group = update.USB_group;
other_config = update.other_config;
currently_attached = update.currently_attached;
}
internal void UpdateFromProxy(Proxy_VUSB proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vusb_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vusb_operations(proxy.current_operations);
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
USB_group = proxy.USB_group == null ? null : XenRef<USB_group>.Create(proxy.USB_group);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
currently_attached = (bool)proxy.currently_attached;
}
public Proxy_VUSB ToProxy()
{
Proxy_VUSB result_ = new Proxy_VUSB();
result_.uuid = uuid ?? "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_vusb_operations(current_operations);
result_.VM = VM ?? "";
result_.USB_group = USB_group ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.currently_attached = currently_attached;
return result_;
}
/// <summary>
/// Creates a new VUSB from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VUSB(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
allowed_operations = Helper.StringArrayToEnumList<vusb_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
current_operations = Maps.convert_from_proxy_string_vusb_operations(Marshalling.ParseHashTable(table, "current_operations"));
VM = Marshalling.ParseRef<VM>(table, "VM");
USB_group = Marshalling.ParseRef<USB_group>(table, "USB_group");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
currently_attached = Marshalling.ParseBool(table, "currently_attached");
}
public bool DeepEquals(VUSB other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._USB_group, other._USB_group) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._currently_attached, other._currently_attached);
}
public override string SaveChanges(Session session, string opaqueRef, VUSB server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VUSB.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static VUSB get_record(Session session, string _vusb)
{
return new VUSB((Proxy_VUSB)session.proxy.vusb_get_record(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get a reference to the VUSB instance with the specified UUID.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VUSB> get_by_uuid(Session session, string _uuid)
{
return XenRef<VUSB>.Create(session.proxy.vusb_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static string get_uuid(Session session, string _vusb)
{
return (string)session.proxy.vusb_get_uuid(session.uuid, _vusb ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static List<vusb_operations> get_allowed_operations(Session session, string _vusb)
{
return Helper.StringArrayToEnumList<vusb_operations>(session.proxy.vusb_get_allowed_operations(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static Dictionary<string, vusb_operations> get_current_operations(Session session, string _vusb)
{
return Maps.convert_from_proxy_string_vusb_operations(session.proxy.vusb_get_current_operations(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get the VM field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static XenRef<VM> get_VM(Session session, string _vusb)
{
return XenRef<VM>.Create(session.proxy.vusb_get_vm(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get the USB_group field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static XenRef<USB_group> get_USB_group(Session session, string _vusb)
{
return XenRef<USB_group>.Create(session.proxy.vusb_get_usb_group(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static Dictionary<string, string> get_other_config(Session session, string _vusb)
{
return Maps.convert_from_proxy_string_string(session.proxy.vusb_get_other_config(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Get the currently_attached field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static bool get_currently_attached(Session session, string _vusb)
{
return (bool)session.proxy.vusb_get_currently_attached(session.uuid, _vusb ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vusb, Dictionary<string, string> _other_config)
{
session.proxy.vusb_set_other_config(session.uuid, _vusb ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VUSB.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vusb, string _key, string _value)
{
session.proxy.vusb_add_to_other_config(session.uuid, _vusb ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VUSB. If the key is not in that Map, then do nothing.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vusb, string _key)
{
session.proxy.vusb_remove_from_other_config(session.uuid, _vusb ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a new VUSB record in the database only
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm">The VM</param>
/// <param name="_usb_group"></param>
/// <param name="_other_config"></param>
public static XenRef<VUSB> create(Session session, string _vm, string _usb_group, Dictionary<string, string> _other_config)
{
return XenRef<VUSB>.Create(session.proxy.vusb_create(session.uuid, _vm ?? "", _usb_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
/// Create a new VUSB record in the database only
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vm">The VM</param>
/// <param name="_usb_group"></param>
/// <param name="_other_config"></param>
public static XenRef<Task> async_create(Session session, string _vm, string _usb_group, Dictionary<string, string> _other_config)
{
return XenRef<Task>.Create(session.proxy.async_vusb_create(session.uuid, _vm ?? "", _usb_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse());
}
/// <summary>
/// Unplug the vusb device from the vm.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static void unplug(Session session, string _vusb)
{
session.proxy.vusb_unplug(session.uuid, _vusb ?? "").parse();
}
/// <summary>
/// Unplug the vusb device from the vm.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static XenRef<Task> async_unplug(Session session, string _vusb)
{
return XenRef<Task>.Create(session.proxy.async_vusb_unplug(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Removes a VUSB record from the database
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static void destroy(Session session, string _vusb)
{
session.proxy.vusb_destroy(session.uuid, _vusb ?? "").parse();
}
/// <summary>
/// Removes a VUSB record from the database
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vusb">The opaque_ref of the given vusb</param>
public static XenRef<Task> async_destroy(Session session, string _vusb)
{
return XenRef<Task>.Create(session.proxy.async_vusb_destroy(session.uuid, _vusb ?? "").parse());
}
/// <summary>
/// Return a list of all the VUSBs known to the system.
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VUSB>> get_all(Session session)
{
return XenRef<VUSB>.Create(session.proxy.vusb_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VUSB Records at once, in a single XML RPC call
/// First published in Unreleased.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VUSB>, VUSB> get_all_records(Session session)
{
return XenRef<VUSB>.Create<Proxy_VUSB>(session.proxy.vusb_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<vusb_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<vusb_operations> _allowed_operations;
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, vusb_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, vusb_operations> _current_operations;
/// <summary>
/// VM that owns the VUSB
/// </summary>
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM;
/// <summary>
/// USB group used by the VUSB
/// </summary>
public virtual XenRef<USB_group> USB_group
{
get { return _USB_group; }
set
{
if (!Helper.AreEqual(value, _USB_group))
{
_USB_group = value;
Changed = true;
NotifyPropertyChanged("USB_group");
}
}
}
private XenRef<USB_group> _USB_group;
/// <summary>
/// Additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
/// <summary>
/// is the device currently attached
/// </summary>
public virtual bool currently_attached
{
get { return _currently_attached; }
set
{
if (!Helper.AreEqual(value, _currently_attached))
{
_currently_attached = value;
Changed = true;
NotifyPropertyChanged("currently_attached");
}
}
}
private bool _currently_attached;
}
}
| |
using System;
using System.Text;
namespace ClosedXML.Excel
{
using System.Collections.Generic;
internal class XLBorder : IXLBorder
{
private readonly IXLStylized _container;
private XLBorderStyleValues _bottomBorder;
private XLColor _bottomBorderColor;
private XLBorderStyleValues _diagonalBorder;
private XLColor _diagonalBorderColor;
private Boolean _diagonalDown;
private Boolean _diagonalUp;
private XLBorderStyleValues _leftBorder;
private XLColor _leftBorderColor;
private XLBorderStyleValues _rightBorder;
private XLColor _rightBorderColor;
private XLBorderStyleValues _topBorder;
private XLColor _topBorderColor;
public XLBorder() : this(null, XLWorkbook.DefaultStyle.Border)
{
}
public XLBorder(IXLStylized container, IXLBorder defaultBorder, Boolean useDefaultModify = true)
{
_container = container;
if (defaultBorder == null) return;
_leftBorder = defaultBorder.LeftBorder;
_leftBorderColor = defaultBorder.LeftBorderColor;
_rightBorder = defaultBorder.RightBorder;
_rightBorderColor = defaultBorder.RightBorderColor;
_topBorder = defaultBorder.TopBorder;
_topBorderColor = defaultBorder.TopBorderColor;
_bottomBorder = defaultBorder.BottomBorder;
_bottomBorderColor = defaultBorder.BottomBorderColor;
_diagonalBorder = defaultBorder.DiagonalBorder;
_diagonalBorderColor = defaultBorder.DiagonalBorderColor;
_diagonalUp = defaultBorder.DiagonalUp;
_diagonalDown = defaultBorder.DiagonalDown;
if (useDefaultModify)
{
var d = defaultBorder as XLBorder;
BottomBorderColorModified = d.BottomBorderColorModified;
BottomBorderModified = d.BottomBorderModified;
DiagonalBorderColorModified = d.DiagonalBorderColorModified;
DiagonalBorderModified = d.DiagonalBorderModified;
DiagonalDownModified = d.DiagonalDownModified;
DiagonalUpModified = d.DiagonalUpModified;
LeftBorderColorModified = d.LeftBorderColorModified;
LeftBorderModified = d.LeftBorderModified;
RightBorderColorModified = d.RightBorderColorModified;
RightBorderModified = d.RightBorderModified;
TopBorderColorModified = d.TopBorderColorModified;
TopBorderModified = d.TopBorderModified;
}
}
#region IXLBorder Members
public XLBorderStyleValues OutsideBorder
{
set
{
if (_container == null || _container.UpdatingStyle) return;
if (_container is XLWorksheet || _container is XLConditionalFormat)
{
_container.Style.Border.SetTopBorder(value);
_container.Style.Border.SetBottomBorder(value);
_container.Style.Border.SetLeftBorder(value);
_container.Style.Border.SetRightBorder(value);
}
else
{
foreach (IXLRange r in _container.RangesUsed)
{
r.FirstColumn().Style.Border.LeftBorder = value;
r.LastColumn().Style.Border.RightBorder = value;
r.FirstRow().Style.Border.TopBorder = value;
r.LastRow().Style.Border.BottomBorder = value;
}
}
}
}
public XLColor OutsideBorderColor
{
set
{
if (_container == null || _container.UpdatingStyle) return;
if (_container is XLWorksheet || _container is XLConditionalFormat)
{
_container.Style.Border.SetTopBorderColor(value);
_container.Style.Border.SetBottomBorderColor(value);
_container.Style.Border.SetLeftBorderColor(value);
_container.Style.Border.SetRightBorderColor(value);
}
else
{
foreach (IXLRange r in _container.RangesUsed)
{
r.FirstColumn().Style.Border.LeftBorderColor = value;
r.LastColumn().Style.Border.RightBorderColor = value;
r.FirstRow().Style.Border.TopBorderColor = value;
r.LastRow().Style.Border.BottomBorderColor = value;
}
}
}
}
public XLBorderStyleValues InsideBorder
{
set
{
if (_container == null || _container.UpdatingStyle) return;
var wsContainer = _container as XLWorksheet;
if (wsContainer != null)
{
//wsContainer.CellsUsed().Style.Border.SetOutsideBorder(value);
//wsContainer.UpdatingStyle = true;
wsContainer.Style.Border.SetTopBorder(value);
wsContainer.Style.Border.SetBottomBorder(value);
wsContainer.Style.Border.SetLeftBorder(value);
wsContainer.Style.Border.SetRightBorder(value);
//wsContainer.UpdatingStyle = false;
}
else
{
foreach (IXLRange r in _container.RangesUsed)
{
Dictionary<Int32, XLBorderStyleValues> topBorders = new Dictionary<int, XLBorderStyleValues>();
r.FirstRow().Cells().ForEach(
c =>
topBorders.Add(c.Address.ColumnNumber - r.RangeAddress.FirstAddress.ColumnNumber + 1,
c.Style.Border.TopBorder));
Dictionary<Int32, XLBorderStyleValues> bottomBorders =
new Dictionary<int, XLBorderStyleValues>();
r.LastRow().Cells().ForEach(
c =>
bottomBorders.Add(c.Address.ColumnNumber - r.RangeAddress.FirstAddress.ColumnNumber + 1,
c.Style.Border.BottomBorder));
Dictionary<Int32, XLBorderStyleValues> leftBorders = new Dictionary<int, XLBorderStyleValues>();
r.FirstColumn().Cells().ForEach(
c =>
leftBorders.Add(c.Address.RowNumber - r.RangeAddress.FirstAddress.RowNumber + 1,
c.Style.Border.LeftBorder));
Dictionary<Int32, XLBorderStyleValues> rightBorders = new Dictionary<int, XLBorderStyleValues>();
r.LastColumn().Cells().ForEach(
c =>
rightBorders.Add(c.Address.RowNumber - r.RangeAddress.FirstAddress.RowNumber + 1,
c.Style.Border.RightBorder));
r.Cells().Style.Border.OutsideBorder = value;
topBorders.ForEach(kp => r.FirstRow().Cell(kp.Key).Style.Border.TopBorder = kp.Value);
bottomBorders.ForEach(kp => r.LastRow().Cell(kp.Key).Style.Border.BottomBorder = kp.Value);
leftBorders.ForEach(kp => r.FirstColumn().Cell(kp.Key).Style.Border.LeftBorder = kp.Value);
rightBorders.ForEach(kp => r.LastColumn().Cell(kp.Key).Style.Border.RightBorder = kp.Value);
}
}
}
}
public XLColor InsideBorderColor
{
set
{
if (_container == null || _container.UpdatingStyle) return;
var wsContainer = _container as XLWorksheet;
if (wsContainer != null)
{
//wsContainer.CellsUsed().Style.Border.SetOutsideBorderColor(value);
//wsContainer.UpdatingStyle = true;
wsContainer.Style.Border.SetTopBorderColor(value);
wsContainer.Style.Border.SetBottomBorderColor(value);
wsContainer.Style.Border.SetLeftBorderColor(value);
wsContainer.Style.Border.SetRightBorderColor(value);
//wsContainer.UpdatingStyle = false;
}
else
{
foreach (IXLRange r in _container.RangesUsed)
{
Dictionary<Int32, XLColor> topBorders = new Dictionary<int, XLColor>();
r.FirstRow().Cells().ForEach(
c =>
topBorders.Add(
c.Address.ColumnNumber - r.RangeAddress.FirstAddress.ColumnNumber + 1,
c.Style.Border.TopBorderColor));
Dictionary<Int32, XLColor> bottomBorders = new Dictionary<int, XLColor>();
r.LastRow().Cells().ForEach(
c =>
bottomBorders.Add(
c.Address.ColumnNumber - r.RangeAddress.FirstAddress.ColumnNumber + 1,
c.Style.Border.BottomBorderColor));
Dictionary<Int32, XLColor> leftBorders = new Dictionary<int, XLColor>();
r.FirstColumn().Cells().ForEach(
c =>
leftBorders.Add(
c.Address.RowNumber - r.RangeAddress.FirstAddress.RowNumber + 1,
c.Style.Border.LeftBorderColor));
Dictionary<Int32, XLColor> rightBorders = new Dictionary<int, XLColor>();
r.LastColumn().Cells().ForEach(
c =>
rightBorders.Add(
c.Address.RowNumber - r.RangeAddress.FirstAddress.RowNumber + 1,
c.Style.Border.RightBorderColor));
r.Cells().Style.Border.OutsideBorderColor = value;
topBorders.ForEach(
kp => r.FirstRow().Cell(kp.Key).Style.Border.TopBorderColor = kp.Value);
bottomBorders.ForEach(
kp => r.LastRow().Cell(kp.Key).Style.Border.BottomBorderColor = kp.Value);
leftBorders.ForEach(
kp => r.FirstColumn().Cell(kp.Key).Style.Border.LeftBorderColor = kp.Value);
rightBorders.ForEach(
kp => r.LastColumn().Cell(kp.Key).Style.Border.RightBorderColor = kp.Value);
}
}
}
}
public Boolean LeftBorderModified;
public XLBorderStyleValues LeftBorder
{
get { return _leftBorder; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.LeftBorder = value);
else
{
_leftBorder = value;
LeftBorderModified = true;
}
}
}
public Boolean LeftBorderColorModified;
public XLColor LeftBorderColor
{
get { return _leftBorderColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.LeftBorderColor = value);
else
{
_leftBorderColor = value;
LeftBorderColorModified = true;
}
}
}
public Boolean RightBorderModified;
public XLBorderStyleValues RightBorder
{
get { return _rightBorder; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.RightBorder = value);
else
{
_rightBorder = value;
RightBorderModified = true;
}
}
}
public Boolean RightBorderColorModified;
public XLColor RightBorderColor
{
get { return _rightBorderColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.RightBorderColor = value);
else
{
_rightBorderColor = value;
RightBorderColorModified = true;
}
}
}
public Boolean TopBorderModified;
public XLBorderStyleValues TopBorder
{
get { return _topBorder; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.TopBorder = value);
else
{
_topBorder = value;
TopBorderModified = true;
}
}
}
public Boolean TopBorderColorModified;
public XLColor TopBorderColor
{
get { return _topBorderColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.TopBorderColor = value);
else
{
_topBorderColor = value;
TopBorderColorModified = true;
}
}
}
public Boolean BottomBorderModified;
public XLBorderStyleValues BottomBorder
{
get { return _bottomBorder; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.BottomBorder = value);
else
{
_bottomBorder = value;
BottomBorderModified = true;
}
}
}
public Boolean BottomBorderColorModified;
public XLColor BottomBorderColor
{
get { return _bottomBorderColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.BottomBorderColor = value);
else
{
_bottomBorderColor = value;
BottomBorderColorModified = true;
}
}
}
public Boolean DiagonalBorderModified;
public XLBorderStyleValues DiagonalBorder
{
get { return _diagonalBorder; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.DiagonalBorder = value);
else
{
_diagonalBorder = value;
DiagonalBorderModified = true;
}
}
}
public Boolean DiagonalBorderColorModified;
public XLColor DiagonalBorderColor
{
get { return _diagonalBorderColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.DiagonalBorderColor = value);
else
{
_diagonalBorderColor = value;
DiagonalBorderColorModified = true;
}
}
}
public Boolean DiagonalUpModified;
public Boolean DiagonalUp
{
get { return _diagonalUp; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.DiagonalUp = value);
else
{
_diagonalUp = value;
DiagonalUpModified = true;
}
}
}
public Boolean DiagonalDownModified;
public Boolean DiagonalDown
{
get { return _diagonalDown; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Border.DiagonalDown = value);
else
{
_diagonalDown = value;
DiagonalDownModified = true;
}
}
}
public bool Equals(IXLBorder other)
{
var otherB = other as XLBorder;
return
_leftBorder == otherB._leftBorder
&& _leftBorderColor.Equals(otherB._leftBorderColor)
&& _rightBorder == otherB._rightBorder
&& _rightBorderColor.Equals(otherB._rightBorderColor)
&& _topBorder == otherB._topBorder
&& _topBorderColor.Equals(otherB._topBorderColor)
&& _bottomBorder == otherB._bottomBorder
&& _bottomBorderColor.Equals(otherB._bottomBorderColor)
&& _diagonalBorder == otherB._diagonalBorder
&& _diagonalBorderColor.Equals(otherB._diagonalBorderColor)
&& _diagonalUp == otherB._diagonalUp
&& _diagonalDown == otherB._diagonalDown
;
}
public IXLStyle SetOutsideBorder(XLBorderStyleValues value)
{
OutsideBorder = value;
return _container.Style;
}
public IXLStyle SetOutsideBorderColor(XLColor value)
{
OutsideBorderColor = value;
return _container.Style;
}
public IXLStyle SetInsideBorder(XLBorderStyleValues value)
{
InsideBorder = value;
return _container.Style;
}
public IXLStyle SetInsideBorderColor(XLColor value)
{
InsideBorderColor = value;
return _container.Style;
}
public IXLStyle SetLeftBorder(XLBorderStyleValues value)
{
LeftBorder = value;
return _container.Style;
}
public IXLStyle SetLeftBorderColor(XLColor value)
{
LeftBorderColor = value;
return _container.Style;
}
public IXLStyle SetRightBorder(XLBorderStyleValues value)
{
RightBorder = value;
return _container.Style;
}
public IXLStyle SetRightBorderColor(XLColor value)
{
RightBorderColor = value;
return _container.Style;
}
public IXLStyle SetTopBorder(XLBorderStyleValues value)
{
TopBorder = value;
return _container.Style;
}
public IXLStyle SetTopBorderColor(XLColor value)
{
TopBorderColor = value;
return _container.Style;
}
public IXLStyle SetBottomBorder(XLBorderStyleValues value)
{
BottomBorder = value;
return _container.Style;
}
public IXLStyle SetBottomBorderColor(XLColor value)
{
BottomBorderColor = value;
return _container.Style;
}
public IXLStyle SetDiagonalUp()
{
DiagonalUp = true;
return _container.Style;
}
public IXLStyle SetDiagonalUp(Boolean value)
{
DiagonalUp = value;
return _container.Style;
}
public IXLStyle SetDiagonalDown()
{
DiagonalDown = true;
return _container.Style;
}
public IXLStyle SetDiagonalDown(Boolean value)
{
DiagonalDown = value;
return _container.Style;
}
public IXLStyle SetDiagonalBorder(XLBorderStyleValues value)
{
DiagonalBorder = value;
return _container.Style;
}
public IXLStyle SetDiagonalBorderColor(XLColor value)
{
DiagonalBorderColor = value;
return _container.Style;
}
#endregion
private void SetStyleChanged()
{
if (_container != null) _container.StyleChanged = true;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(LeftBorder.ToString());
sb.Append("-");
sb.Append(LeftBorderColor);
sb.Append("-");
sb.Append(RightBorder.ToString());
sb.Append("-");
sb.Append(RightBorderColor);
sb.Append("-");
sb.Append(TopBorder.ToString());
sb.Append("-");
sb.Append(TopBorderColor);
sb.Append("-");
sb.Append(BottomBorder.ToString());
sb.Append("-");
sb.Append(BottomBorderColor);
sb.Append("-");
sb.Append(DiagonalBorder.ToString());
sb.Append("-");
sb.Append(DiagonalBorderColor);
sb.Append("-");
sb.Append(DiagonalUp.ToString());
sb.Append("-");
sb.Append(DiagonalDown.ToString());
return sb.ToString();
}
public override bool Equals(object obj)
{
return Equals((XLBorder)obj);
}
public override int GetHashCode()
{
return (Int32)LeftBorder
^ LeftBorderColor.GetHashCode()
^ (Int32)RightBorder
^ RightBorderColor.GetHashCode()
^ (Int32)TopBorder
^ TopBorderColor.GetHashCode()
^ (Int32)BottomBorder
^ BottomBorderColor.GetHashCode()
^ (Int32)DiagonalBorder
^ DiagonalBorderColor.GetHashCode()
^ DiagonalUp.GetHashCode()
^ DiagonalDown.GetHashCode();
}
}
}
| |
// 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.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestBasePriorityOnWindows()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestBasePriorityOnUnix()
{
ProcessPriorityClass originalPriority = _process.PriorityClass;
Assert.Equal(ProcessPriorityClass.Normal, originalPriority);
try
{
SetAndCheckBasePriority(ProcessPriorityClass.High, -11);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public void TestUseShellExecute_Unix_Succeeds()
{
using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
{
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(42, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
DateTime timeBeforeProcessStart = DateTime.UtcNow;
Process p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect.");
}
[Fact]
public void TestId()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcess();
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void TestMachineName()
{
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact, PlatformSpecific(~PlatformID.OSX)]
public void TestMainModuleOnNonOSX()
{
string fileName = "corerun";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
fileName = "CoreRun.exe";
Process p = Process.GetCurrentProcess();
Assert.True(p.Modules.Count > 0);
Assert.Equal(fileName, p.MainModule.ModuleName);
Assert.EndsWith(fileName, p.MainModule.FileName);
Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString());
}
[Fact]
public void TestMaxWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestMinWorkingSet()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr addr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
public void TestNonpagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void TestPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void TestPagedSystemMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void TestPeakPagedMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void TestPeakVirtualMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void TestPeakWorkingSet64()
{
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void TestPrivateMemorySize64()
{
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void TestVirtualMemorySize64()
{
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void TestWorkingSet64()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void TestProcessorTime()
{
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[ActiveIssue(5805)]
[Fact]
public void TestProcessStartTime()
{
DateTime systemBootTime = DateTime.UtcNow - TimeSpan.FromMilliseconds(Environment.TickCount);
Process p = CreateProcessLong();
Assert.Throws<InvalidOperationException>(() => p.StartTime);
try
{
p.Start();
// Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time.
// Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will
// be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms.
// On Windows, timer resolution is 15 ms from MSDN DateTime.Now. Hence, allowing error in 15ms [max(10,15)].
long intervalTicks = new TimeSpan(0, 0, 0, 0, 15).Ticks;
long beforeTicks = systemBootTime.Ticks;
try
{
// Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started.
Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id);
long startTicks = p.StartTime.ToUniversalTime().Ticks;
long afterTicks = DateTime.UtcNow.Ticks + intervalTicks;
Assert.InRange(startTicks, beforeTicks, afterTicks);
}
catch (InvalidOperationException)
{
Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks);
}
}
finally
{
if (!p.HasExited)
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
}
[Fact]
[PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix
public void TestPriorityClassUnix()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact, PlatformSpecific(PlatformID.Windows)]
public void TestPriorityClassWindows()
{
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Fact]
public void TestInvalidPriorityClass()
{
Process p = new Process();
Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; });
}
[Fact]
public void TestProcessName()
{
Assert.Equal(_process.ProcessName, HostRunner, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void TestSafeHandle()
{
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void TestSessionId()
{
uint sessionId;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
}
else
{
sessionId = (uint)Interop.getsid(_process.Id);
}
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
Interop.GetCurrentProcessId() :
Interop.getpid();
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
public void TestGetProcessById()
{
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void TestGetProcessesByName()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed");
Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed");
}
public static IEnumerable<object[]> GetTestProcess()
{
Process currentProcess = Process.GetCurrentProcess();
yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") };
yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() };
}
[Theory, PlatformSpecific(PlatformID.Windows)]
[MemberData(nameof(GetTestProcess))]
public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess)
{
Assert.Equal(currentProcess.Id, remoteProcess.Id);
Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
[Fact, PlatformSpecific(PlatformID.AnyUnix)]
public void TestProcessOnRemoteMachineUnix()
{
Process currentProcess = Process.GetCurrentProcess();
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1"));
Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1"));
}
[Fact]
public void TestStartInfo()
{
{
Process process = CreateProcessLong();
process.Start();
Assert.Equal(HostRunner, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = CreateProcessLong();
process.Start();
Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo()));
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
{
Process process = new Process();
process.StartInfo = new ProcessStartInfo(TestConsoleApp);
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
{
Process process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
{
Process process = Process.GetCurrentProcess();
Assert.Throws<System.InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
using (var handle = RemoteInvokeRaw((Func<string, string, string, int>)ConcatThreeArguments,
inputArguments,
start: true,
psi: new ProcessStartInfo { RedirectStandardOutput = true }))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
private static int ConcatThreeArguments(string one, string two, string three)
{
Console.Write(string.Join(",", one, two, three));
return SuccessExitCode;
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace Newtonsoft.Json.Schema
{
public static class __JsonSchema
{
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> Read(IObservable<Newtonsoft.Json.JsonReader> reader)
{
return Observable.Select(reader, (readerLambda) => Newtonsoft.Json.Schema.JsonSchema.Read(readerLambda));
}
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> Read(IObservable<Newtonsoft.Json.JsonReader> reader, IObservable<Newtonsoft.Json.Schema.JsonSchemaResolver> resolver)
{
return Observable.Zip(reader, resolver, (readerLambda, resolverLambda) => Newtonsoft.Json.Schema.JsonSchema.Read(readerLambda, resolverLambda));
}
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> Parse(IObservable<System.String> json)
{
return Observable.Select(json, (jsonLambda) => Newtonsoft.Json.Schema.JsonSchema.Parse(jsonLambda));
}
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> Parse(IObservable<System.String> json, IObservable<Newtonsoft.Json.Schema.JsonSchemaResolver> resolver)
{
return Observable.Zip(json, resolver, (jsonLambda, resolverLambda) => Newtonsoft.Json.Schema.JsonSchema.Parse(jsonLambda, resolverLambda));
}
public static IObservable<System.Reactive.Unit> WriteTo(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<Newtonsoft.Json.JsonWriter> writer)
{
return ObservableExt.ZipExecute(JsonSchemaValue, writer, (JsonSchemaValueLambda, writerLambda) => JsonSchemaValueLambda.WriteTo(writerLambda));
}
public static IObservable<System.Reactive.Unit> WriteTo(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<Newtonsoft.Json.JsonWriter> writer, IObservable<Newtonsoft.Json.Schema.JsonSchemaResolver> resolver)
{
return ObservableExt.ZipExecute(JsonSchemaValue, writer, resolver, (JsonSchemaValueLambda, writerLambda, resolverLambda) => JsonSchemaValueLambda.WriteTo(writerLambda, resolverLambda));
}
public static IObservable<System.String> ToString(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.ToString());
}
public static IObservable<System.String> get_Id(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Id);
}
public static IObservable<System.String> get_Title(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Title);
}
public static IObservable<System.Nullable<System.Boolean>> get_Required(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Required);
}
public static IObservable<System.Nullable<System.Boolean>> get_ReadOnly(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.ReadOnly);
}
public static IObservable<System.Nullable<System.Boolean>> get_Hidden(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Hidden);
}
public static IObservable<System.Nullable<System.Boolean>> get_Transient(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Transient);
}
public static IObservable<System.String> get_Description(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Description);
}
public static IObservable<System.Nullable<Newtonsoft.Json.Schema.JsonSchemaType>> get_Type(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Type);
}
public static IObservable<System.String> get_Pattern(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Pattern);
}
public static IObservable<System.Nullable<System.Int32>> get_MinimumLength(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.MinimumLength);
}
public static IObservable<System.Nullable<System.Int32>> get_MaximumLength(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.MaximumLength);
}
public static IObservable<System.Nullable<System.Double>> get_DivisibleBy(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.DivisibleBy);
}
public static IObservable<System.Nullable<System.Double>> get_Minimum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Minimum);
}
public static IObservable<System.Nullable<System.Double>> get_Maximum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Maximum);
}
public static IObservable<System.Nullable<System.Boolean>> get_ExclusiveMinimum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.ExclusiveMinimum);
}
public static IObservable<System.Nullable<System.Boolean>> get_ExclusiveMaximum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.ExclusiveMaximum);
}
public static IObservable<System.Nullable<System.Int32>> get_MinimumItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.MinimumItems);
}
public static IObservable<System.Nullable<System.Int32>> get_MaximumItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.MaximumItems);
}
public static IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Schema.JsonSchema>> get_Items(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Items);
}
public static IObservable<System.Boolean> get_PositionalItemsValidation(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.PositionalItemsValidation);
}
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> get_AdditionalItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.AdditionalItems);
}
public static IObservable<System.Boolean> get_AllowAdditionalItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.AllowAdditionalItems);
}
public static IObservable<System.Boolean> get_UniqueItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.UniqueItems);
}
public static IObservable<System.Collections.Generic.IDictionary<System.String, Newtonsoft.Json.Schema.JsonSchema>> get_Properties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Properties);
}
public static IObservable<Newtonsoft.Json.Schema.JsonSchema> get_AdditionalProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.AdditionalProperties);
}
public static IObservable<System.Collections.Generic.IDictionary<System.String, Newtonsoft.Json.Schema.JsonSchema>> get_PatternProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.PatternProperties);
}
public static IObservable<System.Boolean> get_AllowAdditionalProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.AllowAdditionalProperties);
}
public static IObservable<System.String> get_Requires(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Requires);
}
public static IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Linq.JToken>> get_Enum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Enum);
}
public static IObservable<System.Nullable<Newtonsoft.Json.Schema.JsonSchemaType>> get_Disallow(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Disallow);
}
public static IObservable<Newtonsoft.Json.Linq.JToken> get_Default(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Default);
}
public static IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Schema.JsonSchema>> get_Extends(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Extends);
}
public static IObservable<System.String> get_Format(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue)
{
return Observable.Select(JsonSchemaValue, (JsonSchemaValueLambda) => JsonSchemaValueLambda.Format);
}
public static IObservable<System.Reactive.Unit> set_Id(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Id = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Title(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Title = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Required(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Required = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_ReadOnly(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.ReadOnly = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Hidden(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Hidden = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Transient(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Transient = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Description(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Description = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Type(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<Newtonsoft.Json.Schema.JsonSchemaType>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Type = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Pattern(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Pattern = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_MinimumLength(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Int32>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.MinimumLength = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_MaximumLength(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Int32>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.MaximumLength = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_DivisibleBy(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Double>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.DivisibleBy = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Minimum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Double>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Minimum = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Maximum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Double>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Maximum = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_ExclusiveMinimum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.ExclusiveMinimum = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_ExclusiveMaximum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Boolean>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.ExclusiveMaximum = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_MinimumItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Int32>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.MinimumItems = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_MaximumItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<System.Int32>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.MaximumItems = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Items(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Schema.JsonSchema>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Items = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PositionalItemsValidation(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.PositionalItemsValidation = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_AdditionalItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<Newtonsoft.Json.Schema.JsonSchema> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.AdditionalItems = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_AllowAdditionalItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.AllowAdditionalItems = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_UniqueItems(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.UniqueItems = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Properties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Collections.Generic.IDictionary<System.String, Newtonsoft.Json.Schema.JsonSchema>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Properties = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_AdditionalProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<Newtonsoft.Json.Schema.JsonSchema> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.AdditionalProperties = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_PatternProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Collections.Generic.IDictionary<System.String, Newtonsoft.Json.Schema.JsonSchema>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.PatternProperties = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_AllowAdditionalProperties(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Boolean> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.AllowAdditionalProperties = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Requires(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Requires = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Enum(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Linq.JToken>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Enum = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Disallow(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Nullable<Newtonsoft.Json.Schema.JsonSchemaType>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Disallow = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Default(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<Newtonsoft.Json.Linq.JToken> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Default = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Extends(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.Collections.Generic.IList<Newtonsoft.Json.Schema.JsonSchema>> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Extends = valueLambda);
}
public static IObservable<System.Reactive.Unit> set_Format(this IObservable<Newtonsoft.Json.Schema.JsonSchema> JsonSchemaValue, IObservable<System.String> value)
{
return ObservableExt.ZipExecute(JsonSchemaValue, value, (JsonSchemaValueLambda, valueLambda) => JsonSchemaValueLambda.Format = valueLambda);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using System.IO;
using gov.va.medora.mdo.dao;
using gov.va.medora.mdo.dao.vista;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaVitalsDao : IVitalsDao
{
AbstractConnection cxn = null;
public VistaVitalsDao(AbstractConnection cxn)
{
this.cxn = cxn;
}
// Get all vital signs for currently selected patient (RDV call)
public VitalSignSet[] getVitalSigns()
{
return getVitalSigns(cxn.Pid);
}
// Get all vital signs for given patient (RDV call)
public VitalSignSet[] getVitalSigns(string dfn)
{
MdoQuery request = buildGetVitalSignsRdvRequest(dfn);
string response = (string)cxn.query(request);
return toVitalSignsFromRdv(response);
}
// Get vital signs within time frame for currently selected patient (RDV call)
public VitalSignSet[] getVitalSigns(string fromDate, string toDate, int maxRex)
{
return getVitalSigns(cxn.Pid,fromDate,toDate,maxRex);
}
// Get vital signs within time frame for given patient (RDV call)
public VitalSignSet[] getVitalSigns(string dfn, string fromDate, string toDate, int maxRex)
{
MdoQuery request = buildGetVitalSignsRdvRequest(dfn, fromDate, toDate, maxRex);
string response = (string)cxn.query(request);
return toVitalSignsFromRdv(response);
}
internal MdoQuery buildGetVitalSignsRdvRequest(string dfn)
{
VistaUtils.CheckRpcParams(dfn);
return VistaUtils.buildReportTextRequest_AllResults(dfn, "OR_VS:VITAL SIGNS~VS;ORDV04;47;");
}
internal MdoQuery buildGetVitalSignsRdvRequest(string dfn, string fromDate, string toDate, int maxRex)
{
VistaUtils.CheckRpcParams(dfn);
return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, maxRex, "OR_VS:VITAL SIGNS~VS;ORDV04;47;");
}
internal VitalSignSet[] toVitalSignsFromRdv(string response)
{
if (response == "")
{
return null;
}
string[] lines = StringUtils.split(response, StringUtils.CRLF);
lines = StringUtils.trimArray(lines);
ArrayList lst = new ArrayList();
VitalSignSet rec = null;
VitalSign s = null;
for (int i = 0; i < lines.Length; i++)
{
string[] flds = StringUtils.split(lines[i], StringUtils.CARET);
int fldnum = Convert.ToInt16(flds[0]);
switch (fldnum)
{
case 1:
if (rec != null)
{
lst.Add(rec);
}
rec = new VitalSignSet();
string[] subflds = StringUtils.split(flds[1], StringUtils.SEMICOLON);
if (subflds.Length == 1)
{
rec.Facility = new SiteId("200", subflds[0]);
}
else
{
rec.Facility = new SiteId(subflds[1], subflds[0]);
}
break;
case 2:
if (flds.Length == 2)
{
rec.Timestamp = VistaTimestamp.toUtcFromRdv(flds[1]);
}
break;
case 3:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.TEMPERATURE);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.TEMPERATURE, s);
break;
case 4:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PULSE);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.PULSE, s);
break;
case 5:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.RESPIRATION);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.RESPIRATION, s);
break;
case 6:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.BLOOD_PRESSURE);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.BLOOD_PRESSURE, s);
break;
case 7:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.HEIGHT);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.HEIGHT, s);
break;
case 8:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.WEIGHT);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.WEIGHT, s);
break;
case 9:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PAIN);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.PAIN, s);
break;
case 10:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PULSE_OXYMETRY);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.PULSE_OXYMETRY, s);
break;
case 11:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.CENTRAL_VENOUS_PRESSURE);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.CENTRAL_VENOUS_PRESSURE, s);
break;
case 12:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.CIRCUMFERENCE_GIRTH);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.CIRCUMFERENCE_GIRTH, s);
break;
case 15:
if (flds.Length == 2)
{
setVitalSignQualifierStrings(rec, flds[1], "Qualifiers");
rec.Qualifiers = flds[1];
}
break;
case 16:
s = new VitalSign();
s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.BODY_MASS_INDEX);
if (flds.Length == 2)
{
s.Value1 = flds[1];
}
rec.addVitalSign(VitalSign.BODY_MASS_INDEX, s);
break;
case 17:
if (flds.Length == 2)
{
setVitalSignQualifierStrings(rec, flds[1], "Units");
rec.Units = flds[1];
}
break;
default:
break;
}
}
lst.Add(rec);
return (VitalSignSet[])lst.ToArray(typeof(VitalSignSet));
}
public VitalSign[] getLatestVitalSigns()
{
return getLatestVitalSigns(cxn.Pid);
}
public VitalSign[] getLatestVitalSigns(string dfn)
{
MdoQuery request = buildGetLatestVitalSignsRequest(dfn);
string response = (string)cxn.query(request);
return toLatestVitalSigns(response);
}
internal MdoQuery buildGetLatestVitalSignsRequest(string dfn)
{
VistaUtils.CheckRpcParams(dfn);
VistaQuery vq = new VistaQuery("ORQQVI VITALS");
vq.addParameter(vq.LITERAL, dfn);
return vq;
}
internal VitalSign[] toLatestVitalSigns(string response)
{
if (!cxn.IsConnected)
{
throw new NotConnectedException();
}
if (response == "")
{
return null;
}
string[] lines = StringUtils.split(response, StringUtils.CRLF);
ArrayList lst = new ArrayList(lines.Length);
string category = "Vital Signs";
for (int i = 0; i < lines.Length; i++)
{
if (lines[i] == "")
{
continue;
}
string[] flds = StringUtils.split(lines[i], StringUtils.CARET);
ObservationType observationType = null;
if (flds[1] == "T")
{
observationType = new ObservationType(flds[0], category, "Temperature");
}
else if (flds[1] == "P")
{
observationType = new ObservationType(flds[0], category, "Pulse");
}
else if (flds[1] == "R")
{
observationType = new ObservationType(flds[0], category, "Respiration");
}
else if (flds[1] == "BP")
{
observationType = new ObservationType(flds[0], category, "Blood Pressure");
}
else if (flds[1] == "HT")
{
observationType = new ObservationType(flds[0], category, "Height");
}
else if (flds[1] == "WT")
{
observationType = new ObservationType(flds[0], category, "Weight");
}
else if (flds[1] == "PN")
{
observationType = new ObservationType(flds[0], category, "Pain");
}
if (observationType == null)
{
continue;
}
VitalSign observation = new VitalSign();
observation.Type = observationType;
observation.Value1 = flds[4];
if (flds.Length == 6)
{
observation.Value2 = flds[5];
}
observation.Timestamp = VistaTimestamp.toUtcString(flds[3]);
lst.Add(observation);
}
return (VitalSign[])lst.ToArray(typeof(VitalSign));
}
internal string getVitalSignQualifierItem(string qualifiers, string key)
{
int p1 = qualifiers.IndexOf(key + ':');
if (p1 == -1)
{
return "";
}
p1 += key.Length + 1;
int p2 = p1;
while (p2 < qualifiers.Length && qualifiers[p2] != ':')
{
p2++;
}
if (p2 < qualifiers.Length)
{
while (qualifiers[p2] != ',')
{
p2--;
}
}
return qualifiers.Substring(p1, p2 - p1).Trim();
}
internal void setVitalSignQualifierStrings(VitalSignSet set, string s, string qualifier)
{
string[] keys = new string[]
{
"TEMP","PULSE","BP","RESP","WT","HT","PAIN","O2","CG","CVP","BMI"
};
for (int i = 0; i < keys.Length; i++)
{
string value = getVitalSignQualifierItem(s, keys[i]);
if (!String.IsNullOrEmpty(value))
{
VitalSign theSign = getSignFromSet(set, keys[i]);
if (theSign == null)
{
continue;
}
if (String.Equals(qualifier, "Units", StringComparison.CurrentCultureIgnoreCase))
{
theSign.Units = value;
if (keys[i] == "BP")
{
theSign = set.getVitalSign(VitalSign.SYSTOLIC_BP);
if (theSign != null)
{
theSign.Units = value;
}
theSign = set.getVitalSign(VitalSign.DIASTOLIC_BP);
if (theSign != null)
{
theSign.Units = value;
}
}
}
else if (String.Equals(qualifier, "Qualifiers", StringComparison.CurrentCultureIgnoreCase))
{
theSign.Qualifiers = value;
if (keys[i] == "BP")
{
theSign = set.getVitalSign(VitalSign.SYSTOLIC_BP);
if (theSign != null)
{
theSign.Qualifiers = value;
}
theSign = set.getVitalSign(VitalSign.DIASTOLIC_BP);
if (theSign != null)
{
theSign.Qualifiers = value;
}
}
}
else
{
throw new Exception("Invalid qualifier: " + qualifier);
}
}
}
}
internal VitalSign getSignFromSet(VitalSignSet set, string key)
{
if (key == "TEMP")
{
return set.getVitalSign(VitalSign.TEMPERATURE);
}
if (key == "PULSE")
{
return set.getVitalSign(VitalSign.PULSE);
}
if (key == "RESP")
{
return set.getVitalSign(VitalSign.RESPIRATION);
}
if (key == "BP")
{
return set.getVitalSign(VitalSign.BLOOD_PRESSURE);
}
if (key == "WT")
{
return set.getVitalSign(VitalSign.WEIGHT);
}
if (key == "HT")
{
return set.getVitalSign(VitalSign.HEIGHT);
}
if (key == "PAIN")
{
return set.getVitalSign(VitalSign.PAIN);
}
if (key == "O2")
{
return set.getVitalSign(VitalSign.PULSE_OXYMETRY);
}
if (key == "CG")
{
return set.getVitalSign(VitalSign.CIRCUMFERENCE_GIRTH);
}
if (key == "CVP")
{
return set.getVitalSign(VitalSign.CENTRAL_VENOUS_PRESSURE);
}
if (key == "BMI")
{
return set.getVitalSign(VitalSign.BODY_MASS_INDEX);
}
return null;
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
namespace AmplifyShaderEditor
{
public class ShortcutKeyData
{
public bool IsPressed;
public Type NodeType;
public string Name;
public ShortcutKeyData( Type type , string name )
{
NodeType = type;
Name = name;
IsPressed = false;
}
}
public class GraphContextMenu
{
private List<ContextMenuItem> m_items;
private Dictionary<Type, NodeAttributes> m_itemsDict;
private Dictionary<Type, NodeAttributes> m_deprecatedItemsDict;
private Dictionary<Type, Type> m_castTypes;
private Dictionary<KeyCode, ShortcutKeyData> m_shortcutTypes;
private GenericMenu m_menu;
private Vector2 m_scaledClickedPos;
private KeyCode m_lastKeyPressed;
public GraphContextMenu( ParentGraph currentGraph )
{
RefreshNodes( currentGraph );
}
public void RefreshNodes( ParentGraph currentGraph )
{
if ( m_items != null )
m_items.Clear();
m_items = new List<ContextMenuItem>();
if ( m_itemsDict != null )
m_itemsDict.Clear();
m_itemsDict = new Dictionary<Type, NodeAttributes>();
if ( m_deprecatedItemsDict != null )
m_deprecatedItemsDict.Clear();
m_deprecatedItemsDict = new Dictionary<Type, NodeAttributes>();
if ( m_castTypes != null )
m_castTypes.Clear();
m_castTypes = new Dictionary<Type, Type>();
if ( m_shortcutTypes != null )
m_shortcutTypes.Clear();
m_shortcutTypes = new Dictionary<KeyCode, ShortcutKeyData>();
m_lastKeyPressed = KeyCode.None;
// Fetch all available nodes by their attributes
IEnumerable<Type> availableTypes = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany( type => type.GetTypes() );
foreach ( Type type in availableTypes )
{
foreach ( NodeAttributes attribute in Attribute.GetCustomAttributes( type ).OfType<NodeAttributes>() )
{
if ( attribute.Available && !attribute.Deprecated )
{
if ( !UIUtils.HasColorCategory( attribute.Category ) )
{
if ( !String.IsNullOrEmpty( attribute.CustomCategoryColor ) )
{
try
{
Color color = new Color();
ColorUtility.TryParseHtmlString( attribute.CustomCategoryColor, out color );
UIUtils.AddColorCategory( attribute.Category, color );
}
catch ( Exception e )
{
Debug.LogException( e );
UIUtils.AddColorCategory( attribute.Category, Constants.DefaultCategoryColor );
}
}
else
{
UIUtils.AddColorCategory( attribute.Category, Constants.DefaultCategoryColor );
}
}
if ( attribute.CastType != null && attribute.CastType.Length > 0 && type != null )
{
for ( int i = 0; i < attribute.CastType.Length; i++ )
{
m_castTypes.Add( attribute.CastType[ i ], type );
}
}
if ( attribute.ShortcutKey != KeyCode.None && type != null )
m_shortcutTypes.Add( attribute.ShortcutKey, new ShortcutKeyData( type, attribute.Name ) );
m_itemsDict.Add( type, attribute );
m_items.Add( new ContextMenuItem( attribute, type, attribute.Name, attribute.Category, attribute.Description, attribute.ShortcutKey, ( Type newType, Vector2 position ) =>
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( newType );
if ( newNode != null )
{
newNode.Vec2Position = position;
currentGraph.AddNode( newNode, true );
if ( UIUtils.InputPortReference.IsValid )
{
OutputPort port = newNode.GetFirstOutputPortOfType( UIUtils.InputPortReference.DataType, true );
if ( port != null )
{
port.ConnectTo( UIUtils.InputPortReference.NodeId, UIUtils.InputPortReference.PortId, UIUtils.InputPortReference.DataType, UIUtils.InputPortReference.TypeLocked );
UIUtils.GetNode( UIUtils.InputPortReference.NodeId ).GetInputPortByUniqueId( UIUtils.InputPortReference.PortId ).ConnectTo( port.NodeId, port.PortId, port.DataType, UIUtils.InputPortReference.TypeLocked );
}
}
if ( UIUtils.OutputPortReference.IsValid )
{
InputPort port = newNode.GetFirstInputPortOfType( UIUtils.OutputPortReference.DataType, true );
if ( port != null )
{
port.ConnectTo( UIUtils.OutputPortReference.NodeId, UIUtils.OutputPortReference.PortId, UIUtils.OutputPortReference.DataType, port.TypeLocked );
UIUtils.GetNode( UIUtils.OutputPortReference.NodeId ).GetOutputPortByUniqueId( UIUtils.OutputPortReference.PortId ).ConnectTo( port.NodeId, port.PortId, port.DataType, port.TypeLocked );
}
}
UIUtils.InvalidateReferences();
}
return newNode;
} ) );
}
else
{
m_deprecatedItemsDict.Add( type, attribute );
}
}
}
//Sort out the final list by name
m_items.Sort( ( ContextMenuItem item0, ContextMenuItem item1 ) => { return item0.Name.CompareTo( item1.Name ); } );
// Add them to the context menu
m_menu = new GenericMenu();
foreach ( ContextMenuItem item in m_items )
{
//The / on the GUIContent creates categories on the context menu
m_menu.AddItem( new GUIContent( item.Category + "/" + item.Name, item.Description ), false, OnItemSelected, item );
}
}
public void Destroy()
{
for ( int i = 0; i < m_items.Count; i++ )
{
m_items[ i ].Destroy();
}
m_items.Clear();
m_items = null;
m_itemsDict.Clear();
m_itemsDict = null;
m_deprecatedItemsDict.Clear();
m_deprecatedItemsDict = null;
m_castTypes.Clear();
m_castTypes = null;
m_shortcutTypes.Clear();
m_shortcutTypes = null;
m_menu = null;
}
public NodeAttributes GetNodeAttributesForType( Type type )
{
if ( type == null )
{
Debug.LogError( "Invalid type detected" );
return null;
}
if ( m_itemsDict.ContainsKey( type ) )
return m_itemsDict[ type ];
return null;
}
public NodeAttributes GetDeprecatedNodeAttributesForType( Type type )
{
if ( m_deprecatedItemsDict.ContainsKey( type ) )
return m_deprecatedItemsDict[ type ];
return null;
}
public void UpdateKeyPress( KeyCode key )
{
if ( key == KeyCode.None )
return;
m_lastKeyPressed = key;
if ( m_shortcutTypes.ContainsKey( key ) )
{
m_shortcutTypes[ key ].IsPressed = true;
}
}
public void UpdateKeyReleased( KeyCode key )
{
if ( key == KeyCode.None )
return;
if ( m_shortcutTypes.ContainsKey( key ) )
{
m_shortcutTypes[ key ].IsPressed = false;
}
}
public ParentNode CreateNodeFromCastType( Type type )
{
if ( m_castTypes.ContainsKey( type ) )
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( m_castTypes[ type ] );
return newNode;
}
return null;
}
public ParentNode CreateNodeFromShortcut( KeyCode key )
{
if ( key == KeyCode.None )
return null;
if ( m_shortcutTypes.ContainsKey( key ) )
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( m_shortcutTypes[ key ].NodeType );
return newNode;
}
return null;
}
public ParentNode CreateNodeFromShortcutKey()
{
if ( m_lastKeyPressed == KeyCode.None )
return null;
if ( m_shortcutTypes.ContainsKey( m_lastKeyPressed ) && m_shortcutTypes[ m_lastKeyPressed ].IsPressed )
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( m_shortcutTypes[ m_lastKeyPressed ].NodeType );
return newNode;
}
return null;
}
public bool CheckShortcutKey()
{
if ( m_lastKeyPressed == KeyCode.None )
return false;
if ( m_shortcutTypes.ContainsKey( m_lastKeyPressed ) && m_shortcutTypes[ m_lastKeyPressed ].IsPressed )
{
return true;
}
return false;
}
void OnItemSelected( object args )
{
ContextMenuItem item = ( ContextMenuItem ) args;
if ( item != null )
item.CreateNodeFuncPtr( item.NodeType, m_scaledClickedPos );
}
public void Show( Vector2 globalClickedPos, Vector2 cameraOffset, float cameraZoom )
{
m_scaledClickedPos = globalClickedPos * cameraZoom - cameraOffset;
m_menu.ShowAsContext();
}
public List<ContextMenuItem> MenuItems
{
get { return m_items; }
}
public KeyCode LastKeyPressed
{
get { return m_lastKeyPressed; }
}
public Dictionary<KeyCode, ShortcutKeyData> NodeShortcuts { get { return m_shortcutTypes; } }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using System.Linq;
using System.Xml.Linq;
using Signum.Utilities.ExpressionTrees;
using System.Runtime.Serialization;
namespace Signum.Entities.Reflection
{
public static class GraphExplorer
{
public static void PropagateModifications(DirectedGraph<Modifiable> inverseGraph)
{
if (inverseGraph == null)
throw new ArgumentNullException(nameof(inverseGraph));
foreach (Modifiable item in inverseGraph)
if (item.Modified == ModifiedState.SelfModified)
Propagate(item, inverseGraph);
}
static void Propagate(Modifiable item, DirectedGraph<Modifiable> inverseGraph)
{
if (item.Modified == ModifiedState.Modified)
return;
item.Modified = ModifiedState.Modified;
foreach (var other in inverseGraph.RelatedTo(item))
Propagate(other, inverseGraph);
}
public static void CleanModifications(IEnumerable<Modifiable> graph)
{
foreach (Modifiable item in graph.Where(a => a.Modified == ModifiedState.SelfModified || a.Modified == ModifiedState.Modified))
item.Modified = ModifiedState.Clean;
}
public static void SetDummyRowIds(IEnumerable<Modifiable> graph)
{
foreach (IMListPrivate mlist in graph.OfType<IMListPrivate>())
{
for (int i = 0; i < ((IList)mlist).Count; i++)
{
if (mlist.GetRowId(i) == null)
mlist.SetRowId(i, DummyRowId);
}
}
}
public static DirectedGraph<Modifiable> FromRootEntity(Modifiable root)
{
return DirectedGraph<Modifiable>.Generate(root, ModifyInspector.EntityExplore, ReferenceEqualityComparer<Modifiable>.Default);
}
public static DirectedGraph<Modifiable> FromRoot(Modifiable root)
{
return DirectedGraph<Modifiable>.Generate(root, ModifyInspector.FullExplore, ReferenceEqualityComparer<Modifiable>.Default);
}
public static DirectedGraph<Modifiable> FromRootVirtual(Modifiable root)
{
return DirectedGraph<Modifiable>.Generate(root, ModifyInspector.FullExploreVirtual, ReferenceEqualityComparer<Modifiable>.Default);
}
public static DirectedGraph<Modifiable> FromRoots<T>(IEnumerable<T> roots)
where T : Modifiable
{
return DirectedGraph<Modifiable>.Generate(roots.Cast<Modifiable>(), ModifyInspector.FullExplore, ReferenceEqualityComparer<Modifiable>.Default);
}
public static DirectedGraph<Modifiable> FromRootsEntity<T>(IEnumerable<T> roots)
where T : Modifiable
{
return DirectedGraph<Modifiable>.Generate(roots.Cast<Modifiable>(), ModifyInspector.EntityExplore, ReferenceEqualityComparer<Modifiable>.Default);
}
public static Dictionary<K, V>? ToDictionaryOrNull<T, K, V>(this IEnumerable<T> collection, Func<T, K> keySelector, Func<T, V?> nullableValueSelector)
where V : class
where K : notnull
{
Dictionary<K, V>? result = null;
foreach (var item in collection)
{
var val = nullableValueSelector(item);
if (val != null)
{
if (result == null)
result = new Dictionary<K, V>();
result.Add(keySelector(item), val);
}
}
return result;
}
public static Dictionary<Guid, IntegrityCheck>? EntityIntegrityCheck(DirectedGraph<Modifiable> graph)
{
return graph.OfType<ModifiableEntity>()
.ToDictionaryOrNull(a => a.temporalId, a => a.IntegrityCheck());
}
public static Dictionary<Guid, IntegrityCheck>? FullIntegrityCheck(DirectedGraph<Modifiable> graph)
{
AssertCloneAttack(graph);
DirectedGraph<Modifiable> identGraph = DirectedGraph<Modifiable>.Generate(graph.Where(a => a is Entity), graph.RelatedTo);
var identErrors = identGraph.OfType<Entity>().Select(ident => ident.EntityIntegrityCheck()).NotNull().SelectMany(errors => errors.Values).ToList();
var modErros = graph.Except(identGraph).OfType<ModifiableEntity>()
.Select(a => a.IntegrityCheck())
.NotNull().ToList();
return identErrors.Concat(modErros).ToDictionaryOrNull(a => a.TemporalId, a => a);
}
public static List<IntegrityCheckWithEntity> WithEntities(this Dictionary<Guid, IntegrityCheck> integrityChecks, DirectedGraph<Modifiable> graph)
{
var modifiableEntities = graph.OfType<ModifiableEntity>().ToDictionary(a => a.temporalId);
return integrityChecks.Values.Select(a => new IntegrityCheckWithEntity(a, modifiableEntities.GetOrThrow(a.TemporalId))).ToList();
}
static void AssertCloneAttack(DirectedGraph<Modifiable> graph)
{
var problems = (from m in graph.OfType<Entity>()
group m by new { Type = m.GetType(), Id = (m as Entity)?.Let(ident => (object?)ident.IdOrNull) ?? (object)m.temporalId } into g
where g.Count() > 1 && g.Count(m => m.Modified == ModifiedState.SelfModified) > 0
select g).ToList();
if (problems.Count == 0)
return;
throw new InvalidOperationException(
"CLONE ATTACK!\r\n\r\n" + problems.ToString(p => "{0} different instances of the same entity ({1}) have been found:\r\n {2}".FormatWith(
p.Count(),
p.Key,
p.ToString(m => " {0}{1}".FormatWith(m.Modified, m), "\r\n")), "\r\n\r\n"));
}
public static bool IsGraphModified(Modifiable modifiable)
{
var graph = FromRoot(modifiable);
return graph.Any(a => a.IsGraphModified);
}
public static DirectedGraph<Modifiable> PreSaving(Func<DirectedGraph<Modifiable>> recreate)
{
return PreSaving(recreate, (Modifiable m, PreSavingContext ctx) =>
{
if (m is ModifiableEntity me)
me.SetTemporalErrors(null);
m.PreSaving(ctx);
});
}
public delegate void ModifyEntityEventHandler(Modifiable m, PreSavingContext ctx);
public static DirectedGraph<Modifiable> PreSaving(Func<DirectedGraph<Modifiable>> recreate, ModifyEntityEventHandler modifier)
{
DirectedGraph<Modifiable> graph = recreate();
PreSavingContext ctx = new PreSavingContext(graph);
bool graphModified = false;
foreach (var m in graph)
{
modifier(m, ctx);
}
if (!graphModified)
return graph; //common case
do
{
var newGraph = recreate();
ctx = new PreSavingContext(graph);
foreach (var m in newGraph.Except(graph))
{
modifier(m, ctx);
}
graph = newGraph;
} while (graphModified);
return graph;
}
static readonly string[] colors =
{
"aquamarine1", "aquamarine4", "blue", "blueviolet",
"brown4", "burlywood", "cadetblue1", "cadetblue",
"chartreuse", "chocolate", "cornflowerblue",
"darkgoldenrod", "darkolivegreen3", "darkorchid", "darkseagreen",
"darkturquoise", "darkviolet", "deeppink", "deepskyblue", "forestgreen"
};
public static PrimaryKey DummyRowId = new PrimaryKey("dummy");
public static string SuperGraphviz(this DirectedGraph<Modifiable> modifiables)
{
Func<Type, string> color = t => colors[Math.Abs(t.FullName!.GetHashCode()) % colors.Length];
var listNodes = modifiables.Nodes.Select(n => new
{
Node = n,
Fillcolor = n is Lite<Entity> ? "white" : color(n.GetType()),
Color =
n is Lite<Entity> ? color(((Lite<Entity>)n).GetType()) :
(n.Modified == ModifiedState.SelfModified ? "red" :
n.Modified == ModifiedState.Modified ? "red4" :
n.Modified == ModifiedState.Sealed ? "gray" : "black"),
Shape = n is Lite<Entity> ? "ellipse" :
n is Entity ? "ellipse" :
n is EmbeddedEntity ? "box" :
Reflector.IsMList(n.GetType()) ? "hexagon" : "plaintext",
Style = n is Entity ? ", style=\"diagonals,filled,bold\"" :
n is Lite<Entity> ? "style=\"solid,bold\"" : "",
Label = n.ToString()!.Etc(30, "..").RemoveDiacritics()
}).ToList();
string nodes = listNodes.ToString(t => " {0} [color={1}, fillcolor={2} shape={3}{4}, label=\"{5}\"]".FormatWith(modifiables.Comparer.GetHashCode(t.Node! /*CSBUG*/), t.Color, t.Fillcolor, t.Shape, t.Style, t.Label), "\r\n");
string arrows = modifiables.Edges.ToString(e => " {0} -> {1}".FormatWith(modifiables.Comparer.GetHashCode(e.From), modifiables.Comparer.GetHashCode(e.To)), "\r\n");
return "digraph \"Grafo\"\r\n{{\r\n node [ style = \"filled,bold\"]\r\n\r\n{0}\r\n\r\n{1}\r\n}}".FormatWith(nodes, arrows);
}
public static DirectedGraph<Entity> ColapseIdentifiables(DirectedGraph<Modifiable> modifiables)
{
DirectedGraph<Entity> result = new DirectedGraph<Entity>(modifiables.Comparer);
foreach (var item in modifiables.OfType<Entity>())
{
var toColapse = modifiables.IndirectlyRelatedTo(item, i => !(i is Entity));
var toColapseFriends = toColapse.SelectMany(i => modifiables.RelatedTo(i).OfType<Entity>());
result.Add(item, toColapseFriends);
result.Add(item, modifiables.RelatedTo(item).OfType<Entity>());
}
return result;
}
public static XDocument EntityDGML(this DirectedGraph<Modifiable> graph)
{
return graph.ToDGML(n =>
n is Entity ? GetAttributes((Entity)n) :
n is Lite<Entity> ? GetAttributes((Lite<Entity>)n) :
n is EmbeddedEntity ? GetAttributes((EmbeddedEntity)n) :
n is MixinEntity ? GetAttributes((MixinEntity)n) :
n.GetType().IsMList() ? GetAttributes((IList)n) :
new[]
{
new XAttribute("Label", n.ToString() ?? "[null]"),
new XAttribute("TypeName", n.GetType().TypeName()),
new XAttribute("Background", ColorExtensions.ToHtmlColor(n.GetType().FullName!.GetHashCode()))
});
}
private static XAttribute[] GetAttributes(Entity ie)
{
return new[]
{
new XAttribute("Label", (ie.ToString() ?? "[null]") + Modified(ie)),
new XAttribute("TypeName", ie.GetType().TypeName()),
new XAttribute("Background", ColorExtensions.ToHtmlColor(ie.GetType().FullName!.GetHashCode())),
new XAttribute("Description", ie.IdOrNull?.ToString() ?? "New")
};
}
private static string Modified(Modifiable ie)
{
return "({0})".FormatWith(ie.Modified);
}
private static XAttribute[] GetAttributes(Lite<Entity> lite)
{
return new[]
{
new XAttribute("Label", (lite.ToString() ?? "[null]") + Modified((Modifiable)lite)),
new XAttribute("TypeName", lite.GetType().TypeName()),
new XAttribute("Stroke", ColorExtensions.ToHtmlColor(lite.EntityType.FullName!.GetHashCode())),
new XAttribute("StrokeThickness", "2"),
new XAttribute("Background", ColorExtensions.ToHtmlColor(lite.EntityType.FullName.GetHashCode()).Replace("#", "#44")),
new XAttribute("Description", lite.IdOrNull?.ToString() ?? "New")
};
}
private static XAttribute[] GetAttributes(EmbeddedEntity ee)
{
return new[]
{
new XAttribute("Label", (ee.ToString() ?? "[null]")+ Modified(ee)),
new XAttribute("TypeName", ee.GetType().TypeName()),
new XAttribute("NodeRadius", 0),
new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName!.GetHashCode())),
};
}
private static XAttribute[] GetAttributes(MixinEntity ee)
{
return new[]
{
new XAttribute("Label", (ee.ToString() ?? "[null]") + Modified(ee)),
new XAttribute("TypeName", ee.GetType().TypeName()),
new XAttribute("Background", ColorExtensions.ToHtmlColor(ee.GetType().FullName!.GetHashCode())),
};
}
private static XAttribute[] GetAttributes(IList list)
{
return new[]
{
new XAttribute("Label", (list.ToString() ?? "[null]") + Modified((Modifiable)list)),
new XAttribute("TypeName", list.GetType().TypeName()),
new XAttribute("NodeRadius", 2),
new XAttribute("Background", ColorExtensions.ToHtmlColor(list.GetType().ElementType()!.FullName!.GetHashCode())),
};
}
public static bool HasChanges(Modifiable mod)
{
return GraphExplorer.FromRootVirtual(mod).Any(a => a.Modified == ModifiedState.SelfModified);
}
public static void SetValidationErrors(DirectedGraph<Modifiable> directedGraph, IntegrityCheckException e)
{
SetValidationErrors(directedGraph, e.Errors);
}
public static void SetValidationErrors(DirectedGraph<Modifiable> directedGraph, Dictionary<Guid, IntegrityCheck> dictionary)
{
var copy = dictionary.ToDictionary();
foreach (var mod in directedGraph.OfType<ModifiableEntity>())
{
if (copy.ContainsKey(mod.temporalId))
{
var ic = copy.Extract(mod.temporalId);
mod.SetTemporalErrors(ic.Errors);
}
}
if (copy.Any())
throw new InvalidOperationException(copy.Values.ToString("\r\n"));
}
}
[Serializable]
public class IntegrityCheckException : Exception
{
public Dictionary<Guid, IntegrityCheck> Errors
{
get { return (Dictionary<Guid, IntegrityCheck>)this.Data["integrityErrors"]!; }
set { this.Data["integrityErrors"] = value; }
}
public IntegrityCheckException(List<IntegrityCheckWithEntity> errors)
: base(errors.ToString("\r\n\r\n"))
{
this.Errors = errors.Select(a => a.IntegrityCheck).ToDictionary(a => a.TemporalId);
}
public IntegrityCheckException(Dictionary<Guid, IntegrityCheck> errors)
: base(errors.Values.ToString("\r\n\r\n"))
{
this.Errors = errors;
}
protected IntegrityCheckException(
SerializationInfo info,
StreamingContext context)
: base(info, context) { }
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.FunctionalTests;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
#if SOCKETS
namespace Microsoft.AspNetCore.Server.Kestrel.Sockets.FunctionalTests
#else
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
#endif
{
public class RequestTests : LoggedTest
{
private const int _connectionStartedEventId = 1;
private const int _connectionResetEventId = 19;
private static readonly int _semaphoreWaitTimeout = Debugger.IsAttached ? 10000 : 2500;
public static Dictionary<string, Func<ListenOptions>> ConnectionMiddlewareData { get; } = new Dictionary<string, Func<ListenOptions>>
{
{ "Loopback", () => new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)) },
{ "PassThrough", () => new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)).UsePassThrough() }
};
public static TheoryData<string> ConnectionMiddlewareDataName => new TheoryData<string>
{
"Loopback",
"PassThrough"
};
[Theory]
[InlineData(10 * 1024 * 1024, true)]
// In the following dataset, send at least 2GB.
// Never change to a lower value, otherwise regression testing for
// https://github.com/aspnet/KestrelHttpServer/issues/520#issuecomment-188591242
// will be lost.
[InlineData((long)int.MaxValue + 1, false)]
public async Task LargeUpload(long contentLength, bool checkBytes)
{
const int bufferLength = 1024 * 1024;
Assert.True(contentLength % bufferLength == 0, $"{nameof(contentLength)} sent must be evenly divisible by {bufferLength}.");
Assert.True(bufferLength % 256 == 0, $"{nameof(bufferLength)} must be evenly divisible by 256");
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = contentLength;
options.Limits.MinRequestBodyDataRate = null;
})
.UseUrls("http://127.0.0.1:0/")
.Configure(app =>
{
app.Run(async context =>
{
// Read the full request body
long total = 0;
var receivedBytes = new byte[bufferLength];
var received = 0;
while ((received = await context.Request.Body.ReadAsync(receivedBytes, 0, receivedBytes.Length)) > 0)
{
if (checkBytes)
{
for (var i = 0; i < received; i++)
{
// Do not use Assert.Equal here, it is to slow for this hot path
Assert.True((byte)((total + i) % 256) == receivedBytes[i], "Data received is incorrect");
}
}
total += received;
}
await context.Response.WriteAsync($"bytesRead: {total}");
});
});
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
{
await host.StartAsync();
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Loopback, host.GetPort()));
socket.Send(Encoding.ASCII.GetBytes("POST / HTTP/1.1\r\nHost: \r\n"));
socket.Send(Encoding.ASCII.GetBytes($"Content-Length: {contentLength}\r\n\r\n"));
var contentBytes = new byte[bufferLength];
if (checkBytes)
{
for (var i = 0; i < contentBytes.Length; i++)
{
contentBytes[i] = (byte)i;
}
}
for (var i = 0; i < contentLength / contentBytes.Length; i++)
{
socket.Send(contentBytes);
}
using (var stream = new NetworkStream(socket))
{
await AssertStreamContains(stream, $"bytesRead: {contentLength}");
}
}
await host.StopAsync();
}
}
[Fact]
public Task RemoteIPv4Address()
{
return TestRemoteIPAddress("127.0.0.1", "127.0.0.1", "127.0.0.1");
}
[ConditionalFact]
[IPv6SupportedCondition]
public Task RemoteIPv6Address()
{
return TestRemoteIPAddress("[::1]", "[::1]", "::1");
}
[Fact]
public async Task DoesNotHangOnConnectionCloseRequest()
{
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseUrls("http://127.0.0.1:0")
.Configure(app =>
{
app.Run(async context =>
{
await context.Response.WriteAsync("hello, world");
});
});
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
using (var client = new HttpClient())
{
await host.StartAsync();
client.DefaultRequestHeaders.Connection.Clear();
client.DefaultRequestHeaders.Connection.Add("close");
var response = await client.GetAsync($"http://127.0.0.1:{host.GetPort()}/");
response.EnsureSuccessStatusCode();
await host.StopAsync();
}
}
[Fact]
public async Task CanHandleMultipleConcurrentRequests()
{
var requestNumber = 0;
var ensureConcurrentRequestTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var server = new TestServer(async context =>
{
if (Interlocked.Increment(ref requestNumber) == 1)
{
await ensureConcurrentRequestTcs.Task.DefaultTimeout();
}
else
{
ensureConcurrentRequestTcs.SetResult();
}
}, new TestServiceContext(LoggerFactory)))
{
using (var connection1 = server.CreateConnection())
using (var connection2 = server.CreateConnection())
{
await connection1.Send(
"GET / HTTP/1.1",
"Host:",
"",
"");
await connection2.Send(
"GET / HTTP/1.1",
"Host:",
"",
"");
await connection1.Receive($"HTTP/1.1 200 OK",
"Content-Length: 0",
$"Date: {server.Context.DateHeaderValue}",
"",
"");
await connection2.Receive($"HTTP/1.1 200 OK",
"Content-Length: 0",
$"Date: {server.Context.DateHeaderValue}",
"",
"");
}
}
}
[Fact]
public async Task ConnectionResetPriorToRequestIsLoggedAsDebug()
{
var connectionStarted = new SemaphoreSlim(0);
var connectionReset = new SemaphoreSlim(0);
var loggedHigherThanDebug = false;
TestSink.MessageLogged += context =>
{
if (context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel" &&
context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel.Connections" &&
context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets")
{
return;
}
if (context.EventId.Id == _connectionStartedEventId)
{
connectionStarted.Release();
}
else if (context.EventId.Id == _connectionResetEventId)
{
connectionReset.Release();
}
if (context.LogLevel > LogLevel.Debug)
{
loggedHigherThanDebug = true;
}
};
await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory)))
{
using (var connection = server.CreateConnection())
{
// Wait until connection is established
Assert.True(await connectionStarted.WaitAsync(TestConstants.DefaultTimeout));
connection.Reset();
}
// If the reset is correctly logged as Debug, the wait below should complete shortly.
// This check MUST come before disposing the server, otherwise there's a race where the RST
// is still in flight when the connection is aborted, leading to the reset never being received
// and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout));
}
Assert.False(loggedHigherThanDebug);
}
[Fact]
public async Task ConnectionResetBetweenRequestsIsLoggedAsDebug()
{
var connectionReset = new SemaphoreSlim(0);
var loggedHigherThanDebug = false;
TestSink.MessageLogged += context =>
{
if (context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel" &&
context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets")
{
return;
}
if (context.LogLevel > LogLevel.Debug)
{
loggedHigherThanDebug = true;
}
if (context.EventId.Id == _connectionResetEventId)
{
connectionReset.Release();
}
};
await using (var server = new TestServer(context => Task.CompletedTask, new TestServiceContext(LoggerFactory)))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"GET / HTTP/1.1",
"Host:",
"",
"");
// Make sure the response is fully received, so a write failure (e.g. EPIPE) doesn't cause
// a more critical log message.
await connection.Receive(
"HTTP/1.1 200 OK",
"Content-Length: 0",
$"Date: {server.Context.DateHeaderValue}",
"",
"");
connection.Reset();
// Force a reset
}
// If the reset is correctly logged as Debug, the wait below should complete shortly.
// This check MUST come before disposing the server, otherwise there's a race where the RST
// is still in flight when the connection is aborted, leading to the reset never being received
// and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout));
}
Assert.False(loggedHigherThanDebug);
}
[Fact]
public async Task ConnectionResetMidRequestIsLoggedAsDebug()
{
var requestStarted = new SemaphoreSlim(0);
var connectionReset = new SemaphoreSlim(0);
var connectionClosing = new SemaphoreSlim(0);
var loggedHigherThanDebug = false;
TestSink.MessageLogged += context =>
{
if (context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel" &&
context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets")
{
return;
}
if (context.LogLevel > LogLevel.Debug)
{
loggedHigherThanDebug = true;
}
if (context.EventId.Id == _connectionResetEventId)
{
connectionReset.Release();
}
};
await using (var server = new TestServer(async context =>
{
requestStarted.Release();
await connectionClosing.WaitAsync();
},
new TestServiceContext(LoggerFactory)))
{
using (var connection = server.CreateConnection())
{
await connection.SendEmptyGet();
// Wait until connection is established
Assert.True(await requestStarted.WaitAsync(TestConstants.DefaultTimeout), "request should have started");
connection.Reset();
}
// If the reset is correctly logged as Debug, the wait below should complete shortly.
// This check MUST come before disposing the server, otherwise there's a race where the RST
// is still in flight when the connection is aborted, leading to the reset never being received
// and therefore not logged.
Assert.True(await connectionReset.WaitAsync(TestConstants.DefaultTimeout), "Connection reset event should have been logged");
connectionClosing.Release();
}
Assert.False(loggedHigherThanDebug, "Logged event should not have been higher than debug.");
}
[Fact]
public async Task ThrowsOnReadAfterConnectionError()
{
var requestStarted = new SemaphoreSlim(0);
var connectionReset = new SemaphoreSlim(0);
var appDone = new SemaphoreSlim(0);
var expectedExceptionThrown = false;
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseUrls("http://127.0.0.1:0")
.Configure(app => app.Run(async context =>
{
requestStarted.Release();
Assert.True(await connectionReset.WaitAsync(_semaphoreWaitTimeout));
try
{
await context.Request.Body.ReadAsync(new byte[1], 0, 1);
}
catch (ConnectionResetException)
{
expectedExceptionThrown = true;
}
appDone.Release();
}));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
{
await host.StartAsync();
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Loopback, host.GetPort()));
socket.LingerState = new LingerOption(true, 0);
socket.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost:\r\nContent-Length: 1\r\n\r\n"));
Assert.True(await requestStarted.WaitAsync(_semaphoreWaitTimeout));
}
connectionReset.Release();
Assert.True(await appDone.WaitAsync(_semaphoreWaitTimeout));
Assert.True(expectedExceptionThrown);
await host.StopAsync();
}
}
[Fact]
public async Task RequestAbortedTokenFiredOnClientFIN()
{
var appStarted = new SemaphoreSlim(0);
var requestAborted = new SemaphoreSlim(0);
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseUrls("http://127.0.0.1:0")
.Configure(app => app.Run(async context =>
{
appStarted.Release();
var token = context.RequestAborted;
token.Register(() => requestAborted.Release(2));
await requestAborted.WaitAsync().DefaultTimeout();
}));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
{
await host.StartAsync();
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Loopback, host.GetPort()));
socket.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost:\r\n\r\n"));
await appStarted.WaitAsync();
socket.Shutdown(SocketShutdown.Send);
await requestAborted.WaitAsync().DefaultTimeout();
}
await host.StopAsync();
}
}
[Fact]
public async Task AbortingTheConnectionSendsFIN()
{
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseUrls("http://127.0.0.1:0")
.Configure(app => app.Run(context =>
{
context.Abort();
return Task.CompletedTask;
}));
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
{
await host.StartAsync();
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Loopback, host.GetPort()));
socket.Send(Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost:\r\n\r\n"));
int result = socket.Receive(new byte[32]);
Assert.Equal(0, result);
}
await host.StopAsync();
}
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
public async Task ConnectionClosedTokenFiresOnClientFIN(string listenOptionsName)
{
var testContext = new TestServiceContext(LoggerFactory);
var appStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var server = new TestServer(context =>
{
appStartedTcs.SetResult();
var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>();
connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
return Task.CompletedTask;
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"GET / HTTP/1.1",
"Host:",
"",
"");
await appStartedTcs.Task.DefaultTimeout();
connection.Shutdown(SocketShutdown.Send);
await connectionClosedTcs.Task.DefaultTimeout();
}
}
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
public async Task ConnectionClosedTokenFiresOnServerFIN(string listenOptionsName)
{
var testContext = new TestServiceContext(LoggerFactory);
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var server = new TestServer(context =>
{
var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>();
connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
return Task.CompletedTask;
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"GET / HTTP/1.1",
"Host:",
"Connection: close",
"",
"");
await connectionClosedTcs.Task.DefaultTimeout();
await connection.ReceiveEnd($"HTTP/1.1 200 OK",
"Content-Length: 0",
"Connection: close",
$"Date: {server.Context.DateHeaderValue}",
"",
"");
}
}
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
public async Task ConnectionClosedTokenFiresOnServerAbort(string listenOptionsName)
{
var testContext = new TestServiceContext(LoggerFactory);
var connectionClosedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var server = new TestServer(context =>
{
var connectionLifetimeFeature = context.Features.Get<IConnectionLifetimeFeature>();
connectionLifetimeFeature.ConnectionClosed.Register(() => connectionClosedTcs.SetResult());
context.Abort();
return Task.CompletedTask;
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"GET / HTTP/1.1",
"Host:",
"",
"");
await connectionClosedTcs.Task.DefaultTimeout();
try
{
await connection.ReceiveEnd();
}
catch (IOException)
{
// The server is forcefully closing the connection so an IOException:
// "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
// isn't guaranteed but not unexpected.
}
}
}
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
public async Task RequestsCanBeAbortedMidRead(string listenOptionsName)
{
// This needs a timeout.
const int applicationAbortedConnectionId = 34;
var testContext = new TestServiceContext(LoggerFactory);
var readTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var registrationTcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var requestId = 0;
await using (var server = new TestServer(async httpContext =>
{
requestId++;
var response = httpContext.Response;
var request = httpContext.Request;
var lifetime = httpContext.Features.Get<IHttpRequestLifetimeFeature>();
lifetime.RequestAborted.Register(() => registrationTcs.TrySetResult(requestId));
if (requestId == 1)
{
response.Headers["Content-Length"] = new[] { "5" };
await response.WriteAsync("World");
}
else
{
var readTask = request.Body.CopyToAsync(Stream.Null);
lifetime.Abort();
try
{
await readTask;
}
catch (Exception ex)
{
readTcs.SetException(ex);
throw;
}
finally
{
await registrationTcs.Task.DefaultTimeout();
}
readTcs.SetException(new Exception("This shouldn't be reached."));
}
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
// Full request and response
await connection.Send(
"POST / HTTP/1.1",
"Host:",
"Content-Length: 5",
"",
"Hello");
await connection.Receive(
"HTTP/1.1 200 OK",
"Content-Length: 5",
$"Date: {testContext.DateHeaderValue}",
"",
"World");
// Never send the body so CopyToAsync always fails.
await connection.Send("POST / HTTP/1.1",
"Host:",
"Content-Length: 5",
"",
"");
await connection.WaitForConnectionClose();
}
}
await Assert.ThrowsAsync<TaskCanceledException>(async () => await readTcs.Task);
// The cancellation token for only the last request should be triggered.
var abortedRequestId = await registrationTcs.Task.DefaultTimeout();
Assert.Equal(2, abortedRequestId);
Assert.Single(TestSink.Writes.Where(w => w.LoggerName == "Microsoft.AspNetCore.Server.Kestrel.Connections" &&
w.EventId == applicationAbortedConnectionId));
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
public async Task ServerCanAbortConnectionAfterUnobservedClose(string listenOptionsName)
{
const int connectionPausedEventId = 4;
const int connectionFinSentEventId = 7;
const int maxRequestBufferSize = 4096;
var readCallbackUnwired = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var clientClosedConnection = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var serverClosedConnection = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var appFuncCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
TestSink.MessageLogged += context =>
{
if (context.LoggerName != "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets")
{
return;
}
if (context.EventId.Id == connectionPausedEventId)
{
readCallbackUnwired.TrySetResult();
}
else if (context.EventId == connectionFinSentEventId)
{
serverClosedConnection.SetResult();
}
};
var testContext = new TestServiceContext(LoggerFactory)
{
ServerOptions =
{
Limits =
{
MaxRequestBufferSize = maxRequestBufferSize,
MaxRequestLineSize = maxRequestBufferSize,
MaxRequestHeadersTotalSize = maxRequestBufferSize,
}
}
};
var scratchBuffer = new byte[maxRequestBufferSize * 8];
await using (var server = new TestServer(async context =>
{
await clientClosedConnection.Task;
context.Abort();
await serverClosedConnection.Task;
appFuncCompleted.SetResult();
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"POST / HTTP/1.1",
"Host:",
$"Content-Length: {scratchBuffer.Length}",
"",
"");
var ignore = connection.Stream.WriteAsync(scratchBuffer, 0, scratchBuffer.Length);
// Wait until the read callback is no longer hooked up so that the connection disconnect isn't observed.
await readCallbackUnwired.Task.DefaultTimeout();
}
clientClosedConnection.SetResult();
await appFuncCompleted.Task.DefaultTimeout();
}
Assert.Single(TestSink.Writes.Where(c => c.EventId.Name == "ConnectionStop"));
}
[Theory]
[MemberData(nameof(ConnectionMiddlewareDataName))]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/27157")]
public async Task AppCanHandleClientAbortingConnectionMidRequest(string listenOptionsName)
{
var readTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var appStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var testContext = new TestServiceContext(LoggerFactory);
var scratchBuffer = new byte[4096];
await using (var server = new TestServer(async context =>
{
appStartedTcs.SetResult();
try
{
await context.Request.Body.CopyToAsync(Stream.Null); ;
}
catch (Exception ex)
{
readTcs.SetException(ex);
throw;
}
readTcs.SetException(new Exception("This shouldn't be reached."));
}, testContext, ConnectionMiddlewareData[listenOptionsName]()))
{
using (var connection = server.CreateConnection())
{
await connection.Send(
"POST / HTTP/1.1",
"Host:",
$"Content-Length: {scratchBuffer.Length * 2}",
"",
"");
await appStartedTcs.Task.DefaultTimeout();
await connection.Stream.WriteAsync(scratchBuffer, 0, scratchBuffer.Length);
connection.Reset();
}
await Assert.ThrowsAnyAsync<IOException>(() => readTcs.Task).DefaultTimeout();
}
Assert.Single(TestSink.Writes.Where(c => c.EventId.Name == "ConnectionStop"));
}
private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress)
{
var builder = TransportSelector.GetHostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseKestrel()
.UseUrls($"http://{registerAddress}:0")
.Configure(app =>
{
app.Run(async context =>
{
var connection = context.Connection;
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
RemoteIPAddress = connection.RemoteIpAddress?.ToString(),
RemotePort = connection.RemotePort,
LocalIPAddress = connection.LocalIpAddress?.ToString(),
LocalPort = connection.LocalPort
}));
});
});
})
.ConfigureServices(AddTestLogging);
using (var host = builder.Build())
using (var client = new HttpClient())
{
await host.StartAsync();
var response = await client.GetAsync($"http://{requestAddress}:{host.GetPort()}/");
response.EnsureSuccessStatusCode();
var connectionFacts = await response.Content.ReadAsStringAsync();
Assert.NotEmpty(connectionFacts);
var facts = JsonConvert.DeserializeObject<JObject>(connectionFacts);
Assert.Equal(expectAddress, facts["RemoteIPAddress"].Value<string>());
Assert.NotEmpty(facts["RemotePort"].Value<string>());
await host.StopAsync();
}
}
// THIS IS NOT GENERAL PURPOSE. If the initial characters could repeat, this is broken. However, since we're
// looking for /bytesWritten: \d+/ and the initial "b" cannot occur elsewhere in the pattern, this works.
private static async Task AssertStreamContains(Stream stream, string expectedSubstring)
{
var expectedBytes = Encoding.ASCII.GetBytes(expectedSubstring);
var exptectedLength = expectedBytes.Length;
var responseBuffer = new byte[exptectedLength];
var matchedChars = 0;
while (matchedChars < exptectedLength)
{
var count = await stream.ReadAsync(responseBuffer, 0, exptectedLength - matchedChars).DefaultTimeout();
if (count == 0)
{
Assert.True(false, "Stream completed without expected substring.");
}
for (var i = 0; i < count && matchedChars < exptectedLength; i++)
{
if (responseBuffer[i] == expectedBytes[matchedChars])
{
matchedChars++;
}
else
{
matchedChars = 0;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
namespace Umbraco.Core.Macros
{
/// <summary>
/// Parses the macro syntax in a string and renders out it's contents
/// </summary>
internal class MacroTagParser
{
private static readonly Regex MacroRteContent = new Regex(@"(<!--\s*?)(<\?UMBRACO_MACRO.*?/>)(\s*?-->)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
private static readonly Regex MacroPersistedFormat = new Regex(@"(<\?UMBRACO_MACRO (?:.+?)?macroAlias=[""']([^""\'\n\r]+?)[""'].+?)(?:/>|>.*?</\?UMBRACO_MACRO>)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This formats the persisted string to something useful for the rte so that the macro renders properly since we
/// persist all macro formats like {?UMBRACO_MACRO macroAlias=\"myMacro\" /}
/// </summary>
/// <param name="persistedContent"></param>
/// <param name="htmlAttributes">The html attributes to be added to the div</param>
/// <returns></returns>
/// <remarks>
/// This converts the persisted macro format to this:
///
/// {div class='umb-macro-holder'}
/// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> -->
/// {ins}Macro alias: {strong}My Macro{/strong}{/ins}
/// {/div}
///
/// </remarks>
internal static string FormatRichTextPersistedDataForEditor(string persistedContent, IDictionary<string ,string> htmlAttributes)
{
return MacroPersistedFormat.Replace(persistedContent, match =>
{
if (match.Groups.Count >= 3)
{
//<div class="umb-macro-holder myMacro mceNonEditable">
var alias = match.Groups[2].Value;
var sb = new StringBuilder("<div class=\"umb-macro-holder ");
//sb.Append(alias.ToSafeAlias());
sb.Append("mceNonEditable\"");
foreach (var htmlAttribute in htmlAttributes)
{
sb.Append(" ");
sb.Append(htmlAttribute.Key);
sb.Append("=\"");
sb.Append(htmlAttribute.Value);
sb.Append("\"");
}
sb.AppendLine(">");
sb.Append("<!-- ");
sb.Append(match.Groups[1].Value.Trim());
sb.Append(" />");
sb.AppendLine(" -->");
sb.Append("<ins>");
sb.Append("Macro alias: ");
sb.Append("<strong>");
sb.Append(alias);
sb.Append("</strong></ins></div>");
return sb.ToString();
}
//replace with nothing if we couldn't find the syntax for whatever reason
return "";
});
}
/// <summary>
/// This formats the string content posted from a rich text editor that contains macro contents to be persisted.
/// </summary>
/// <returns></returns>
/// <remarks>
///
/// This is required because when editors are using the rte, the html that is contained in the editor might actually be displaying
/// the entire macro content, when the data is submitted the editor will clear most of this data out but we'll still need to parse it properly
/// and ensure the correct sytnax is persisted to the db.
///
/// When a macro is inserted into the rte editor, the html will be:
///
/// {div class='umb-macro-holder'}
/// <!-- <?UMBRACO_MACRO macroAlias=\"myMacro\" /> -->
/// This could be some macro content
/// {/div}
///
/// What this method will do is remove the {div} and parse out the commented special macro syntax: {?UMBRACO_MACRO macroAlias=\"myMacro\" /}
/// since this is exactly how we need to persist it to the db.
///
/// </remarks>
internal static string FormatRichTextContentForPersistence(string rteContent)
{
if (string.IsNullOrEmpty(rteContent))
{
return string.Empty;
}
var html = new HtmlDocument();
html.LoadHtml(rteContent);
//get all the comment nodes we want
var commentNodes = html.DocumentNode.SelectNodes("//comment()[contains(., '<?UMBRACO_MACRO')]");
if (commentNodes == null)
{
//There are no macros found, just return the normal content
return rteContent;
}
//replace each containing parent <div> with the comment node itself.
foreach (var c in commentNodes)
{
var div = c.ParentNode;
var divContainer = div.ParentNode;
divContainer.ReplaceChild(c, div);
}
var parsed = html.DocumentNode.OuterHtml;
//now replace all the <!-- and --> with nothing
return MacroRteContent.Replace(parsed, match =>
{
if (match.Groups.Count >= 3)
{
//get the 3rd group which is the macro syntax
return match.Groups[2].Value;
}
//replace with nothing if we couldn't find the syntax for whatever reason
return string.Empty;
});
}
/// <summary>
/// This will accept a text block and seach/parse it for macro markup.
/// When either a text block or a a macro is found, it will call the callback method.
/// </summary>
/// <param name="text"> </param>
/// <param name="textFoundCallback"></param>
/// <param name="macroFoundCallback"></param>
/// <returns></returns>
/// <remarks>
/// This method simply parses the macro contents, it does not create a string or result,
/// this is up to the developer calling this method to implement this with the callbacks.
/// </remarks>
internal static void ParseMacros(
string text,
Action<string> textFoundCallback,
Action<string, Dictionary<string, string>> macroFoundCallback )
{
if (textFoundCallback == null) throw new ArgumentNullException("textFoundCallback");
if (macroFoundCallback == null) throw new ArgumentNullException("macroFoundCallback");
string elementText = text;
var fieldResult = new StringBuilder(elementText);
//NOTE: This is legacy code, this is definitely not the correct way to do a while loop! :)
var stop = false;
while (!stop)
{
var tagIndex = fieldResult.ToString().ToLower().IndexOf("<?umbraco");
if (tagIndex < 0)
tagIndex = fieldResult.ToString().ToLower().IndexOf("<umbraco:macro");
if (tagIndex > -1)
{
var tempElementContent = "";
//text block found, call the call back method
textFoundCallback(fieldResult.ToString().Substring(0, tagIndex));
fieldResult.Remove(0, tagIndex);
var tag = fieldResult.ToString().Substring(0, fieldResult.ToString().IndexOf(">") + 1);
var attributes = XmlHelper.GetAttributesFromElement(tag);
// Check whether it's a single tag (<?.../>) or a tag with children (<?..>...</?...>)
if (tag.Substring(tag.Length - 2, 1) != "/" && tag.IndexOf(" ") > -1)
{
String closingTag = "</" + (tag.Substring(1, tag.IndexOf(" ") - 1)) + ">";
// Tag with children are only used when a macro is inserted by the umbraco-editor, in the
// following format: "<?UMBRACO_MACRO ...><IMG SRC="..."..></?UMBRACO_MACRO>", so we
// need to delete extra information inserted which is the image-tag and the closing
// umbraco_macro tag
if (fieldResult.ToString().IndexOf(closingTag) > -1)
{
fieldResult.Remove(0, fieldResult.ToString().IndexOf(closingTag));
}
}
var macroAlias = attributes.ContainsKey("macroalias") ? attributes["macroalias"] : attributes["alias"];
//call the callback now that we have the macro parsed
macroFoundCallback(macroAlias, attributes);
fieldResult.Remove(0, fieldResult.ToString().IndexOf(">") + 1);
fieldResult.Insert(0, tempElementContent);
}
else
{
//text block found, call the call back method
textFoundCallback(fieldResult.ToString());
stop = true; //break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.GrainDirectory;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
public class TestGrain : Grain, ITestGrain
{
private string label;
private ILogger logger;
private IDisposable timer;
public TestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
if (this.GetPrimaryKeyLong() == -2)
throw new ArgumentException("Primary key cannot be -2 for this test case");
label = this.GetPrimaryKeyLong().ToString();
logger.Info("OnActivateAsync");
return base.OnActivateAsync();
}
public override Task OnDeactivateAsync()
{
logger.Info("!!! OnDeactivateAsync");
return base.OnDeactivateAsync();
}
public Task<long> GetKey()
{
return Task.FromResult(this.GetPrimaryKeyLong());
}
public Task<string> GetLabel()
{
return Task.FromResult(label);
}
public async Task DoLongAction(TimeSpan timespan, string str)
{
logger.Info("DoLongAction {0} received", str);
await Task.Delay(timespan);
}
public Task SetLabel(string label)
{
this.label = label;
logger.Info("SetLabel {0} received", label);
return Task.CompletedTask;
}
public Task StartTimer()
{
logger.Info("StartTimer.");
timer = base.RegisterTimer(TimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
private Task TimerTick(object data)
{
logger.Info("TimerTick.");
return Task.CompletedTask;
}
public async Task<Tuple<string, string>> TestRequestContext()
{
string bar1 = null;
RequestContext.Set("jarjar", "binks");
var task = Task.Factory.StartNew(() =>
{
bar1 = (string) RequestContext.Get("jarjar");
logger.Info("bar = {0}.", bar1);
});
string bar2 = null;
var ac = Task.Factory.StartNew(() =>
{
bar2 = (string) RequestContext.Get("jarjar");
logger.Info("bar = {0}.", bar2);
});
await Task.WhenAll(task, ac);
return new Tuple<string, string>(bar1, bar2);
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task<string> GetActivationId()
{
return Task.FromResult(Data.ActivationId.ToString());
}
public Task<ITestGrain> GetGrainReference()
{
return Task.FromResult(this.AsReference<ITestGrain>());
}
public Task<IGrain[]> GetMultipleGrainInterfaces_Array()
{
var grains = new IGrain[5];
for (var i = 0; i < grains.Length; i++)
{
grains[i] = GrainFactory.GetGrain<ITestGrain>(i);
}
return Task.FromResult(grains);
}
public Task<List<IGrain>> GetMultipleGrainInterfaces_List()
{
var grains = new IGrain[5];
for (var i = 0; i < grains.Length; i++)
{
grains[i] = GrainFactory.GetGrain<ITestGrain>(i);
}
return Task.FromResult(grains.ToList());
}
}
internal class GuidTestGrain : Grain, IGuidTestGrain
{
private string label;
private ILogger logger;
public GuidTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
//if (this.GetPrimaryKeyLong() == -2)
// throw new ArgumentException("Primary key cannot be -2 for this test case");
label = this.GetPrimaryKey().ToString();
logger.Info("OnActivateAsync");
return Task.CompletedTask;
}
public Task<Guid> GetKey()
{
return Task.FromResult(this.GetPrimaryKey());
}
public Task<string> GetLabel()
{
return Task.FromResult(label);
}
public Task SetLabel(string label)
{
this.label = label;
return Task.CompletedTask;
}
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(RuntimeIdentity);
}
public Task<string> GetActivationId()
{
return Task.FromResult(Data.ActivationId.ToString());
}
}
internal class OneWayGrain : Grain, IOneWayGrain, ISimpleGrainObserver
{
private int count;
private TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
private IOneWayGrain other;
private Catalog catalog;
public OneWayGrain(Catalog catalog)
{
this.catalog = catalog;
}
private ILocalGrainDirectory LocalGrainDirectory => this.ServiceProvider.GetRequiredService<ILocalGrainDirectory>();
private ILocalSiloDetails LocalSiloDetails => this.ServiceProvider.GetRequiredService<ILocalSiloDetails>();
public Task Notify()
{
this.count++;
return Task.CompletedTask;
}
public Task Notify(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return Task.CompletedTask;
}
public ValueTask NotifyValueTask(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return default;
}
public async Task<bool> NotifyOtherGrain(IOneWayGrain otherGrain, ISimpleGrainObserver observer)
{
var task = otherGrain.Notify(observer);
var completedSynchronously = task.Status == TaskStatus.RanToCompletion;
await task;
return completedSynchronously;
}
public async Task<bool> NotifyOtherGrainValueTask(IOneWayGrain otherGrain, ISimpleGrainObserver observer)
{
var task = otherGrain.NotifyValueTask(observer);
var completedSynchronously = task.IsCompleted;
await task;
return completedSynchronously;
}
public async Task<IOneWayGrain> GetOtherGrain()
{
return this.other ?? (this.other = await GetGrainOnOtherSilo());
async Task<IOneWayGrain> GetGrainOnOtherSilo()
{
while (true)
{
var candidate = this.GrainFactory.GetGrain<IOneWayGrain>(Guid.NewGuid());
var directorySilo = await candidate.GetPrimaryForGrain();
var thisSilo = await this.GetSiloAddress();
var candidateSilo = await candidate.GetSiloAddress();
if (!directorySilo.Equals(candidateSilo)
&& !directorySilo.Equals(thisSilo)
&& !candidateSilo.Equals(thisSilo))
{
return candidate;
}
}
}
}
public Task<string> GetActivationAddress(IGrain grain)
{
var grainId = ((GrainReference)grain).GrainId;
if (this.catalog.FastLookup(grainId, out var addresses))
{
return Task.FromResult(addresses.Single().ToString());
}
return Task.FromResult<string>(null);
}
public Task NotifyOtherGrain() => this.other.Notify(this.AsReference<ISimpleGrainObserver>());
public Task<int> GetCount() => Task.FromResult(this.count);
public Task Deactivate()
{
this.DeactivateOnIdle();
return Task.CompletedTask;
}
public Task ThrowsOneWay()
{
throw new Exception("GET OUT!");
}
public ValueTask ThrowsOneWayValueTask()
{
throw new Exception("GET OUT (ValueTask)!");
}
public Task<SiloAddress> GetSiloAddress()
{
return Task.FromResult(this.LocalSiloDetails.SiloAddress);
}
public Task<SiloAddress> GetPrimaryForGrain()
{
var grainId = (GrainId)this.GrainId;
var primaryForGrain = this.LocalGrainDirectory.GetPrimaryForGrain(grainId);
return Task.FromResult(primaryForGrain);
}
public void StateChanged(int a, int b)
{
this.tcs.TrySetResult(0);
}
}
public class CanBeOneWayGrain : Grain, ICanBeOneWayGrain
{
private int count;
public Task Notify()
{
this.count++;
return Task.CompletedTask;
}
public Task Notify(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return Task.CompletedTask;
}
public ValueTask NotifyValueTask(ISimpleGrainObserver observer)
{
this.count++;
observer.StateChanged(this.count - 1, this.count);
return default;
}
public Task<int> GetCount() => Task.FromResult(this.count);
public Task Throws()
{
throw new Exception("GET OUT!");
}
public ValueTask ThrowsValueTask()
{
throw new Exception("GET OUT!");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Autofac.Features.Indexed;
using JetBrains.Annotations;
using Reusable.Exceptionize;
using Reusable.Extensions;
using Reusable.OmniLog;
using Reusable.OmniLog.Abstractions;
using Reusable.OmniLog.SemanticExtensions;
namespace Reusable.Commander.Services
{
public interface ICommandExecutor
{
Task ExecuteAsync<TContext>([CanBeNull] string commandLineString, TContext context, CancellationToken cancellationToken = default);
//Task ExecuteAsync<TContext>([NotNull, ItemNotNull] IEnumerable<ICommandLine> commandLines, TContext context, CancellationToken cancellationToken = default);
//Task ExecuteAsync<TBag>([NotNull] Identifier identifier, [CanBeNull] TBag parameter = default, CancellationToken cancellationToken = default) where TBag : ICommandBag, new();
}
public delegate void ExecuteExceptionCallback(Exception exception);
[UsedImplicitly]
public class CommandExecutor : ICommandExecutor
{
private readonly ILogger _logger;
private readonly ICommandLineParser _commandLineParser;
private readonly IIndex<Identifier, IConsoleCommand> _commands;
private readonly ExecuteExceptionCallback _executeExceptionCallback;
public CommandExecutor
(
[NotNull] ILogger<CommandExecutor> logger,
[NotNull] ICommandLineParser commandLineParser,
[NotNull] IIndex<Identifier, IConsoleCommand> commands,
[NotNull] ExecuteExceptionCallback executeExceptionCallback
)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_commandLineParser = commandLineParser ?? throw new ArgumentNullException(nameof(commandLineParser));
_commands = commands ?? throw new ArgumentNullException(nameof(commands));
_executeExceptionCallback = executeExceptionCallback;
}
private async Task ExecuteAsync<TContext>(IEnumerable<ICommandLine> commandLines, TContext context, CancellationToken cancellationToken)
{
var executables =
GetCommands(commandLines)
.Select(t =>
{
var commandLineReader = new CommandLineReader<ICommandParameter>(t.CommandLine);
return new Executable
{
Command = t.Command,
CommandLine = t.CommandLine,
Async = commandLineReader.GetItem(x => x.Async)
};
})
.ToLookup(e => e.ExecutionType());
_logger.Log(Abstraction.Layer.Service().Counter(new
{
CommandCount = executables.Count,
SequentialCommandCount = executables[CommandExecutionType.Sequential].Count(),
AsyncCommandCount = executables[CommandExecutionType.Asynchronous].Count()
}));
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
// Execute sequential commands first.
foreach (var executable in executables[CommandExecutionType.Sequential])
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
await ExecuteAsync(executable, context, cts);
}
// Now execute async commands.
var actionBlock = new ActionBlock<Executable>
(
async executable => await ExecuteAsync(executable, context, cts),
new ExecutionDataflowBlockOptions
{
CancellationToken = cts.Token,
MaxDegreeOfParallelism = Environment.ProcessorCount
}
);
foreach (var executable in executables[CommandExecutionType.Asynchronous])
{
actionBlock.Post(executable);
}
actionBlock.Complete();
await actionBlock.Completion;
}
}
public async Task ExecuteAsync<TContext>(string commandLineString, TContext context, CancellationToken cancellationToken)
{
if (commandLineString.IsNullOrEmpty())
{
throw DynamicException.Create("CommandLineNullOrEmpty", "You need to specify at least one command.");
}
var commandLines = _commandLineParser.Parse(commandLineString);
await ExecuteAsync(commandLines, context, cancellationToken);
}
// public async Task ExecuteAsync<TBag>(Identifier identifier, TBag parameter, CancellationToken cancellationToken = default) where TBag : ICommandBag, new()
// {
// if (identifier == null) throw new ArgumentNullException(nameof(identifier));
//
// await GetCommand(identifier).ExecuteAsync(parameter, default, cancellationToken);
// }
private async Task ExecuteAsync<TContext>(Executable executable, TContext context, CancellationTokenSource cancellationTokenSource)
{
using (_logger.BeginScope().WithCorrelationHandle("Command").AttachElapsed())
{
_logger.Log(Abstraction.Layer.Service().Meta(new { CommandName = executable.Command.Id.Default.ToString() }));
try
{
await executable.Command.ExecuteAsync(executable.CommandLine, context, cancellationTokenSource.Token);
_logger.Log(Abstraction.Layer.Service().Routine(nameof(IConsoleCommand.ExecuteAsync)).Completed());
}
catch (OperationCanceledException)
{
_logger.Log(Abstraction.Layer.Service().Routine(nameof(IConsoleCommand.ExecuteAsync)).Canceled(), "Cancelled by user.");
}
catch (Exception taskEx)
{
_logger.Log(Abstraction.Layer.Service().Routine(nameof(IConsoleCommand.ExecuteAsync)).Faulted(), taskEx);
if (!executable.Async)
{
cancellationTokenSource.Cancel();
}
_executeExceptionCallback(taskEx);
}
}
}
#region Helpers
private IEnumerable<(IConsoleCommand Command, ICommandLine CommandLine)> GetCommands(IEnumerable<ICommandLine> commandLines)
{
return commandLines.Select((commandLine, i) =>
{
try
{
var commandName = commandLine.CommandId();
return (GetCommand(commandName), commandLine);
}
catch (DynamicException inner)
{
throw DynamicException.Create
(
$"CommandLine",
$"Command line at {i} is invalid. See the inner-exception for details.",
inner
);
}
});
}
[NotNull]
private IConsoleCommand GetCommand(Identifier id)
{
return
_commands.TryGetValue(id, out var command)
? command
: throw DynamicException.Create
(
$"CommandNotFound",
$"Could not find command '{id.Default.ToString()}'."
);
}
#endregion
}
internal class Executable
{
public ICommandLine CommandLine { get; set; }
public IConsoleCommand Command { get; set; }
public bool Async { get; set; }
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindAccess
{
/// <summary>
/// Strongly-typed collection for the CustomerCustomerDemo class.
/// </summary>
[Serializable]
public partial class CustomerCustomerDemoCollection : ActiveList<CustomerCustomerDemo, CustomerCustomerDemoCollection>
{
public CustomerCustomerDemoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>CustomerCustomerDemoCollection</returns>
public CustomerCustomerDemoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
CustomerCustomerDemo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CustomerCustomerDemo table.
/// </summary>
[Serializable]
public partial class CustomerCustomerDemo : ActiveRecord<CustomerCustomerDemo>, IActiveRecord
{
#region .ctors and Default Settings
public CustomerCustomerDemo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public CustomerCustomerDemo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public CustomerCustomerDemo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public CustomerCustomerDemo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CustomerCustomerDemo", TableType.Table, DataService.GetInstance("NorthwindAccess"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.String;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = false;
colvarCustomerID.IsPrimaryKey = true;
colvarCustomerID.IsForeignKey = true;
colvarCustomerID.IsReadOnly = false;
colvarCustomerID.DefaultSetting = @"";
colvarCustomerID.ForeignKeyTableName = "Customers";
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarCustomerTypeID = new TableSchema.TableColumn(schema);
colvarCustomerTypeID.ColumnName = "CustomerTypeID";
colvarCustomerTypeID.DataType = DbType.String;
colvarCustomerTypeID.MaxLength = 10;
colvarCustomerTypeID.AutoIncrement = false;
colvarCustomerTypeID.IsNullable = false;
colvarCustomerTypeID.IsPrimaryKey = true;
colvarCustomerTypeID.IsForeignKey = true;
colvarCustomerTypeID.IsReadOnly = false;
colvarCustomerTypeID.DefaultSetting = @"";
colvarCustomerTypeID.ForeignKeyTableName = "CustomerDemographics";
schema.Columns.Add(colvarCustomerTypeID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindAccess"].AddSchema("CustomerCustomerDemo",schema);
}
}
#endregion
#region Props
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get { return GetColumnValue<string>(Columns.CustomerID); }
set { SetColumnValue(Columns.CustomerID, value); }
}
[XmlAttribute("CustomerTypeID")]
[Bindable(true)]
public string CustomerTypeID
{
get { return GetColumnValue<string>(Columns.CustomerTypeID); }
set { SetColumnValue(Columns.CustomerTypeID, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a CustomerDemographic ActiveRecord object related to this CustomerCustomerDemo
///
/// </summary>
public NorthwindAccess.CustomerDemographic CustomerDemographic
{
get { return NorthwindAccess.CustomerDemographic.FetchByID(this.CustomerTypeID); }
set { SetColumnValue("CustomerTypeID", value.CustomerTypeID); }
}
/// <summary>
/// Returns a Customer ActiveRecord object related to this CustomerCustomerDemo
///
/// </summary>
public NorthwindAccess.Customer Customer
{
get { return NorthwindAccess.Customer.FetchByID(this.CustomerID); }
set { SetColumnValue("CustomerID", value.CustomerID); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerID,string varCustomerTypeID)
{
CustomerCustomerDemo item = new CustomerCustomerDemo();
item.CustomerID = varCustomerID;
item.CustomerTypeID = varCustomerTypeID;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varCustomerID,string varCustomerTypeID)
{
CustomerCustomerDemo item = new CustomerCustomerDemo();
item.CustomerID = varCustomerID;
item.CustomerTypeID = varCustomerTypeID;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CustomerIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerTypeIDColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerID = @"CustomerID";
public static string CustomerTypeID = @"CustomerTypeID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* Copyright 2010 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.Text;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// The main class which implements Aztec Code decoding -- as opposed to locating and extracting
/// the Aztec Code from an image.
/// </summary>
/// <author>David Olivier</author>
public sealed class Decoder
{
private enum Table
{
UPPER,
LOWER,
MIXED,
DIGIT,
PUNCT,
BINARY
}
private static readonly String[] UPPER_TABLE =
{
"CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] LOWER_TABLE =
{
"CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] MIXED_TABLE =
{
"CTRL_PS", " ", "\x1", "\x2", "\x3", "\x4", "\x5", "\x6", "\x7", "\b", "\t", "\n",
"\xD", "\f", "\r", "\x21", "\x22", "\x23", "\x24", "\x25", "@", "\\", "^", "_",
"`", "|", "~", "\xB1", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS"
};
private static readonly String[] PUNCT_TABLE =
{
"", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")",
"*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL"
};
private static readonly String[] DIGIT_TABLE =
{
"CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US"
};
private static readonly IDictionary<Table, String[]> codeTables = new Dictionary<Table, String[]>
{
{Table.UPPER, UPPER_TABLE},
{Table.LOWER, LOWER_TABLE},
{Table.MIXED, MIXED_TABLE},
{Table.PUNCT, PUNCT_TABLE},
{Table.DIGIT, DIGIT_TABLE},
{Table.BINARY, null}
};
private static readonly IDictionary<char, Table> codeTableMap = new Dictionary<char, Table>
{
{'U', Table.UPPER},
{'L', Table.LOWER},
{'M', Table.MIXED},
{'P', Table.PUNCT},
{'D', Table.DIGIT},
{'B', Table.BINARY}
};
private AztecDetectorResult ddata;
/// <summary>
/// Decodes the specified detector result.
/// </summary>
/// <param name="detectorResult">The detector result.</param>
/// <returns></returns>
public DecoderResult decode(AztecDetectorResult detectorResult)
{
ddata = detectorResult;
var matrix = detectorResult.Bits;
var rawbits = extractBits(matrix);
if (rawbits == null)
return null;
var correctedBits = correctBits(rawbits);
if (correctedBits == null)
return null;
var result = getEncodedData(correctedBits);
if (result == null)
return null;
var rawBytes = convertBoolArrayToByteArray(correctedBits);
return new DecoderResult(rawBytes, result, null, null);
}
// This method is used for testing the high-level encoder
public static String highLevelDecode(bool[] correctedBits)
{
return getEncodedData(correctedBits);
}
/// <summary>
/// Gets the string encoded in the aztec code bits
/// </summary>
/// <param name="correctedBits">The corrected bits.</param>
/// <returns>the decoded string</returns>
private static String getEncodedData(bool[] correctedBits)
{
var endIndex = correctedBits.Length;
var latchTable = Table.UPPER; // table most recently latched to
var shiftTable = Table.UPPER; // table to use for the next read
var strTable = UPPER_TABLE;
var result = new StringBuilder(20);
var index = 0;
while (index < endIndex)
{
if (shiftTable == Table.BINARY)
{
if (endIndex - index < 5)
{
break;
}
int length = readCode(correctedBits, index, 5);
index += 5;
if (length == 0)
{
if (endIndex - index < 11)
{
break;
}
length = readCode(correctedBits, index, 11) + 31;
index += 11;
}
for (int charCount = 0; charCount < length; charCount++)
{
if (endIndex - index < 8)
{
index = endIndex; // Force outer loop to exit
break;
}
int code = readCode(correctedBits, index, 8);
result.Append((char) code);
index += 8;
}
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
else
{
int size = shiftTable == Table.DIGIT ? 4 : 5;
if (endIndex - index < size)
{
break;
}
int code = readCode(correctedBits, index, size);
index += size;
String str = getCharacter(strTable, code);
if (str.StartsWith("CTRL_"))
{
// Table changes
// ISO/IEC 24778:2008 prescibes ending a shift sequence in the mode from which it was invoked.
// That's including when that mode is a shift.
// Our test case dlusbs.png for issue #642 exercises that.
latchTable = shiftTable; // Latch the current mode, so as to return to Upper after U/S B/S
shiftTable = getTable(str[5]);
strTable = codeTables[shiftTable];
if (str[6] == 'L')
{
latchTable = shiftTable;
}
}
else
{
result.Append(str);
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
}
}
return result.ToString();
}
/// <summary>
/// gets the table corresponding to the char passed
/// </summary>
/// <param name="t">The t.</param>
/// <returns></returns>
private static Table getTable(char t)
{
if (!codeTableMap.ContainsKey(t))
return codeTableMap['U'];
return codeTableMap[t];
}
/// <summary>
/// Gets the character (or string) corresponding to the passed code in the given table
/// </summary>
/// <param name="table">the table used</param>
/// <param name="code">the code of the character</param>
/// <returns></returns>
private static String getCharacter(String[] table, int code)
{
return table[code];
}
/// <summary>
///Performs RS error correction on an array of bits.
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <returns>the corrected array</returns>
private bool[] correctBits(bool[] rawbits)
{
GenericGF gf;
int codewordSize;
if (ddata.NbLayers <= 2)
{
codewordSize = 6;
gf = GenericGF.AZTEC_DATA_6;
}
else if (ddata.NbLayers <= 8)
{
codewordSize = 8;
gf = GenericGF.AZTEC_DATA_8;
}
else if (ddata.NbLayers <= 22)
{
codewordSize = 10;
gf = GenericGF.AZTEC_DATA_10;
}
else
{
codewordSize = 12;
gf = GenericGF.AZTEC_DATA_12;
}
int numDataCodewords = ddata.NbDatablocks;
int numCodewords = rawbits.Length/codewordSize;
if (numCodewords < numDataCodewords)
return null;
int offset = rawbits.Length%codewordSize;
int numECCodewords = numCodewords - numDataCodewords;
int[] dataWords = new int[numCodewords];
for (int i = 0; i < numCodewords; i++, offset += codewordSize)
{
dataWords[i] = readCode(rawbits, offset, codewordSize);
}
var rsDecoder = new ReedSolomonDecoder(gf);
if (!rsDecoder.decode(dataWords, numECCodewords))
return null;
// Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing
int mask = (1 << codewordSize) - 1;
int stuffedBits = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 0 || dataWord == mask)
{
return null;
}
else if (dataWord == 1 || dataWord == mask - 1)
{
stuffedBits++;
}
}
// Now, actually unpack the bits and remove the stuffing
bool[] correctedBits = new bool[numDataCodewords*codewordSize - stuffedBits];
int index = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 1 || dataWord == mask - 1)
{
// next codewordSize-1 bits are all zeros or all ones
SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
index += codewordSize - 1;
}
else
{
for (int bit = codewordSize - 1; bit >= 0; --bit)
{
correctedBits[index++] = (dataWord & (1 << bit)) != 0;
}
}
}
if (index != correctedBits.Length)
return null;
return correctedBits;
}
/// <summary>
/// Gets the array of bits from an Aztec Code matrix
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns>the array of bits</returns>
private bool[] extractBits(BitMatrix matrix)
{
bool compact = ddata.Compact;
int layers = ddata.NbLayers;
int baseMatrixSize = (compact ? 11 : 14) + layers*4; // not including alignment lines
int[] alignmentMap = new int[baseMatrixSize];
bool[] rawbits = new bool[totalBitsInLayer(layers, compact)];
if (compact)
{
for (int i = 0; i < alignmentMap.Length; i++)
{
alignmentMap[i] = i;
}
}
else
{
int matrixSize = baseMatrixSize + 1 + 2*((baseMatrixSize/2 - 1)/15);
int origCenter = baseMatrixSize/2;
int center = matrixSize/2;
for (int i = 0; i < origCenter; i++)
{
int newOffset = i + i/15;
alignmentMap[origCenter - i - 1] = center - newOffset - 1;
alignmentMap[origCenter + i] = center + newOffset + 1;
}
}
for (int i = 0, rowOffset = 0; i < layers; i++)
{
int rowSize = (layers - i)*4 + (compact ? 9 : 12);
// The top-left most point of this layer is <low, low> (not including alignment lines)
int low = i*2;
// The bottom-right most point of this layer is <high, high> (not including alignment lines)
int high = baseMatrixSize - 1 - low;
// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
for (int j = 0; j < rowSize; j++)
{
int columnOffset = j*2;
for (int k = 0; k < 2; k++)
{
// left column
rawbits[rowOffset + columnOffset + k] =
matrix[alignmentMap[low + k], alignmentMap[low + j]];
// bottom row
rawbits[rowOffset + 2*rowSize + columnOffset + k] =
matrix[alignmentMap[low + j], alignmentMap[high - k]];
// right column
rawbits[rowOffset + 4*rowSize + columnOffset + k] =
matrix[alignmentMap[high - k], alignmentMap[high - j]];
// top row
rawbits[rowOffset + 6*rowSize + columnOffset + k] =
matrix[alignmentMap[high - j], alignmentMap[low + k]];
}
}
rowOffset += rowSize*8;
}
return rawbits;
}
/// <summary>
/// Reads a code of given length and at given index in an array of bits
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns></returns>
private static int readCode(bool[] rawbits, int startIndex, int length)
{
int res = 0;
for (int i = startIndex; i < startIndex + length; i++)
{
res <<= 1;
if (rawbits[i])
{
res++;
}
}
return res;
}
/// <summary>
/// Reads a code of length 8 in an array of bits, padding with zeros
/// </summary>
/// <param name="rawbits"></param>
/// <param name="startIndex"></param>
/// <returns></returns>
private static byte readByte(bool[] rawbits, int startIndex)
{
int n = rawbits.Length - startIndex;
if (n >= 8)
{
return (byte) readCode(rawbits, startIndex, 8);
}
return (byte) (readCode(rawbits, startIndex, n) << (8 - n));
}
/// <summary>
/// Packs a bit array into bytes, most significant bit first
/// </summary>
/// <param name="boolArr"></param>
/// <returns></returns>
internal static byte[] convertBoolArrayToByteArray(bool[] boolArr)
{
byte[] byteArr = new byte[(boolArr.Length + 7)/8];
for (int i = 0; i < byteArr.Length; i++)
{
byteArr[i] = readByte(boolArr, 8*i);
}
return byteArr;
}
private static int totalBitsInLayer(int layers, bool compact)
{
return ((compact ? 88 : 112) + 16*layers)*layers;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewButtonCell.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Forms.VisualStyles;
using System.Security.Permissions;
using System.Windows.Forms.ButtonInternal;
using System.Globalization;
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell"]/*' />
/// <devdoc>
/// <para>Identifies a button cell in the dataGridView.</para>
/// </devdoc>
public class DataGridViewButtonCell : DataGridViewCell
{
private static readonly int PropButtonCellFlatStyle = PropertyStore.CreateKey();
private static readonly int PropButtonCellState = PropertyStore.CreateKey();
private static readonly int PropButtonCellUseColumnTextForButtonValue = PropertyStore.CreateKey();
private static readonly VisualStyleElement ButtonElement = VisualStyleElement.Button.PushButton.Normal;
private const byte DATAGRIDVIEWBUTTONCELL_themeMargin = 100; // used to calculate the margins required for XP theming rendering
private const byte DATAGRIDVIEWBUTTONCELL_horizontalTextMargin = 2;
private const byte DATAGRIDVIEWBUTTONCELL_verticalTextMargin = 1;
private const byte DATAGRIDVIEWBUTTONCELL_textPadding = 5;
private static Rectangle rectThemeMargins = new Rectangle(-1, -1, 0, 0);
private static bool mouseInContentBounds = false;
private static Type defaultFormattedValueType = typeof(System.String);
private static Type defaultValueType = typeof(System.Object);
private static Type cellType = typeof(DataGridViewButtonCell);
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.DataGridViewButtonCell"]/*' />
public DataGridViewButtonCell()
{
}
private ButtonState ButtonState
{
get
{
bool found;
int buttonState = this.Properties.GetInteger(PropButtonCellState, out found);
if (found)
{
return (ButtonState)buttonState;
}
return ButtonState.Normal;
}
set
{
// ButtonState.Pushed is used for mouse interaction
// ButtonState.Checked is used for keyboard interaction
Debug.Assert((value & ~(ButtonState.Normal | ButtonState.Pushed | ButtonState.Checked)) == 0);
if (this.ButtonState != value)
{
this.Properties.SetInteger(PropButtonCellState, (int)value);
}
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.EditType"]/*' />
public override Type EditType
{
get
{
// Buttons can't switch to edit mode
return null;
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.FlatStyle"]/*' />
[
DefaultValue(FlatStyle.Standard)
]
public FlatStyle FlatStyle
{
get
{
bool found;
int flatStyle = this.Properties.GetInteger(PropButtonCellFlatStyle, out found);
if (found)
{
return (FlatStyle)flatStyle;
}
return FlatStyle.Standard;
}
set
{
// Sequential enum. Valid values are 0x0 to 0x3
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(FlatStyle));
}
if (value != this.FlatStyle)
{
this.Properties.SetInteger(PropButtonCellFlatStyle, (int)value);
OnCommonChange();
}
}
}
internal FlatStyle FlatStyleInternal
{
set
{
Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System);
if (value != this.FlatStyle)
{
this.Properties.SetInteger(PropButtonCellFlatStyle, (int)value);
}
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.FormattedValueType"]/*' />
public override Type FormattedValueType
{
get
{
// we return string for the formatted type
return defaultFormattedValueType;
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.UseColumnTextForButtonValue"]/*' />
[DefaultValue(false)]
public bool UseColumnTextForButtonValue
{
get
{
bool found;
int useColumnTextForButtonValue = this.Properties.GetInteger(PropButtonCellUseColumnTextForButtonValue, out found);
if (found)
{
return useColumnTextForButtonValue == 0 ? false : true;
}
return false;
}
set
{
if (value != this.UseColumnTextForButtonValue)
{
this.Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0);
OnCommonChange();
}
}
}
internal bool UseColumnTextForButtonValueInternal
{
set
{
if (value != this.UseColumnTextForButtonValue)
{
this.Properties.SetInteger(PropButtonCellUseColumnTextForButtonValue, value ? 1 : 0);
}
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.ValueType"]/*' />
public override Type ValueType
{
get
{
Type valueType = base.ValueType;
if (valueType != null)
{
return valueType;
}
return defaultValueType;
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.Clone"]/*' />
public override object Clone()
{
DataGridViewButtonCell dataGridViewCell;
Type thisType = this.GetType();
if (thisType == cellType) //performance improvement
{
dataGridViewCell = new DataGridViewButtonCell();
}
else
{
// SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info..
//
dataGridViewCell = (DataGridViewButtonCell)System.Activator.CreateInstance(thisType);
}
base.CloneInternal(dataGridViewCell);
dataGridViewCell.FlatStyleInternal = this.FlatStyle;
dataGridViewCell.UseColumnTextForButtonValueInternal = this.UseColumnTextForButtonValue;
return dataGridViewCell;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.CreateAccessibilityInstance"]/*' />
protected override AccessibleObject CreateAccessibilityInstance()
{
return new DataGridViewButtonCellAccessibleObject(this);
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.GetContentBounds"]/*' />
protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null)
{
return Rectangle.Empty;
}
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle contentBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // contentBounds is independent of formattedValue
null /*errorText*/, // contentBounds is independent of errorText
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
Rectangle contentBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting),
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
true /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(contentBoundsDebug.Equals(contentBounds));
#endif
return contentBounds;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.GetErrorIconBounds"]/*' />
protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
if (this.DataGridView == null ||
rowIndex < 0 ||
this.OwningColumn == null ||
!this.DataGridView.ShowCellErrors ||
String.IsNullOrEmpty(GetErrorText(rowIndex)))
{
return Rectangle.Empty;
}
DataGridViewAdvancedBorderStyle dgvabsEffective;
DataGridViewElementStates cellState;
Rectangle cellBounds;
ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds);
Rectangle errorIconBounds = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
null /*formattedValue*/, // errorIconBounds is independent of formattedValue
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
#if DEBUG
object value = GetValue(rowIndex);
Rectangle errorIconBoundsDebug = PaintPrivate(graphics,
cellBounds,
cellBounds,
rowIndex,
cellState,
GetFormattedValue(value, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting),
GetErrorText(rowIndex),
cellStyle,
dgvabsEffective,
DataGridViewPaintParts.ContentForeground,
false /*computeContentBounds*/,
true /*computeErrorIconBounds*/,
false /*paint*/);
Debug.Assert(errorIconBoundsDebug.Equals(errorIconBounds));
#endif
return errorIconBounds;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.GetPreferredSize"]/*' />
protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
{
if (this.DataGridView == null)
{
return new Size(-1, -1);
}
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
Size preferredSize;
Rectangle borderWidthsRect = this.StdBorderWidths;
int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal;
int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical;
DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize);
int marginWidths, marginHeights;
string formattedString = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string;
if (string.IsNullOrEmpty(formattedString))
{
formattedString = " ";
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
// Adding space for text padding.
if (this.DataGridView.ApplyVisualStylesToInnerCells)
{
Rectangle rectThemeMargins = DataGridViewButtonCell.GetThemeMargins(graphics);
marginWidths = rectThemeMargins.X + rectThemeMargins.Width;
marginHeights = rectThemeMargins.Y + rectThemeMargins.Height;
}
else
{
// Hardcoding 5 for the button borders for now.
marginWidths = marginHeights = DATAGRIDVIEWBUTTONCELL_textPadding;
}
switch (freeDimension)
{
case DataGridViewFreeDimension.Width:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 &&
constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin > 0)
{
preferredSize = new Size(DataGridViewCell.MeasureTextWidth(graphics,
formattedString,
cellStyle.Font,
constraintSize.Height - borderAndPaddingHeights - marginHeights - 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin,
flags),
0);
}
else
{
preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags).Width,
0);
}
break;
}
case DataGridViewFreeDimension.Height:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1 &&
constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin > 0)
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextHeight(graphics,
formattedString,
cellStyle.Font,
constraintSize.Width - borderAndPaddingWidths - marginWidths - 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin,
flags));
}
else
{
preferredSize = new Size(0,
DataGridViewCell.MeasureTextSize(graphics,
formattedString,
cellStyle.Font,
flags).Height);
}
break;
}
default:
{
if (cellStyle.WrapMode == DataGridViewTriState.True && formattedString.Length > 1)
{
preferredSize = DataGridViewCell.MeasureTextPreferredSize(graphics, formattedString, cellStyle.Font, 5.0F, flags);
}
else
{
preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedString, cellStyle.Font, flags);
}
break;
}
}
if (freeDimension != DataGridViewFreeDimension.Height)
{
preferredSize.Width += borderAndPaddingWidths + marginWidths + 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin;
if (this.DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth);
}
}
if (freeDimension != DataGridViewFreeDimension.Width)
{
preferredSize.Height += borderAndPaddingHeights + marginHeights + 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin;
if (this.DataGridView.ShowCellErrors)
{
// Making sure that there is enough room for the potential error icon
preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight);
}
}
return preferredSize;
}
private static Rectangle GetThemeMargins(Graphics g)
{
if (rectThemeMargins.X == -1)
{
Rectangle rectCell = new Rectangle(0, 0, DATAGRIDVIEWBUTTONCELL_themeMargin, DATAGRIDVIEWBUTTONCELL_themeMargin);
Rectangle rectContent = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetBackgroundContentRectangle(g, rectCell);
rectThemeMargins.X = rectContent.X;
rectThemeMargins.Y = rectContent.Y;
rectThemeMargins.Width = DATAGRIDVIEWBUTTONCELL_themeMargin - rectContent.Right;
rectThemeMargins.Height = DATAGRIDVIEWBUTTONCELL_themeMargin - rectContent.Bottom;
}
return rectThemeMargins;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.GetValue"]/*' />
protected override object GetValue(int rowIndex)
{
if (this.UseColumnTextForButtonValue &&
this.DataGridView != null &&
this.DataGridView.NewRowIndex != rowIndex &&
this.OwningColumn != null &&
this.OwningColumn is DataGridViewButtonColumn)
{
return ((DataGridViewButtonColumn) this.OwningColumn).Text;
}
return base.GetValue(rowIndex);
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.KeyDownUnsharesRow"]/*' />
protected override bool KeyDownUnsharesRow(KeyEventArgs e, int rowIndex)
{
return e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.KeyUpUnsharesRow"]/*' />
protected override bool KeyUpUnsharesRow(KeyEventArgs e, int rowIndex)
{
return e.KeyCode == Keys.Space;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.MouseDownUnsharesRow"]/*' />
protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.MouseEnterUnsharesRow"]/*' />
protected override bool MouseEnterUnsharesRow(int rowIndex)
{
return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.MouseLeaveUnsharesRow"]/*' />
protected override bool MouseLeaveUnsharesRow(int rowIndex)
{
return (this.ButtonState & ButtonState.Pushed) != 0;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.MouseUpUnsharesRow"]/*' />
protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e)
{
return e.Button == MouseButtons.Left;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnKeyDown"]/*' />
protected override void OnKeyDown(KeyEventArgs e, int rowIndex)
{
if (this.DataGridView == null)
{
return;
}
if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift)
{
UpdateButtonState(this.ButtonState | ButtonState.Checked, rowIndex);
e.Handled = true;
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnKeyUp"]/*' />
protected override void OnKeyUp(KeyEventArgs e, int rowIndex)
{
if (this.DataGridView == null)
{
return;
}
if (e.KeyCode == Keys.Space)
{
UpdateButtonState(this.ButtonState & ~ButtonState.Checked, rowIndex);
if (!e.Alt && !e.Control && !e.Shift)
{
RaiseCellClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex));
if (this.DataGridView != null &&
this.ColumnIndex < this.DataGridView.Columns.Count &&
rowIndex < this.DataGridView.Rows.Count)
{
RaiseCellContentClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex));
}
e.Handled = true;
}
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnLeave"]/*' />
protected override void OnLeave(int rowIndex, bool throughMouseClick)
{
if (this.DataGridView == null)
{
return;
}
if (this.ButtonState != ButtonState.Normal)
{
Debug.Assert(this.RowIndex >= 0); // Cell is not in a shared row.
UpdateButtonState(ButtonState.Normal, rowIndex);
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnMouseDown"]/*' />
protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left && mouseInContentBounds)
{
Debug.Assert(this.DataGridView.CellMouseDownInContentBounds);
UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex);
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnMouseLeave"]/*' />
protected override void OnMouseLeave(int rowIndex)
{
if (this.DataGridView == null)
{
return;
}
if (mouseInContentBounds)
{
mouseInContentBounds = false;
if (this.ColumnIndex >= 0 &&
rowIndex >= 0 &&
(this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup))
{
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}
}
if ((this.ButtonState & ButtonState.Pushed) != 0 &&
this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X &&
rowIndex == this.DataGridView.MouseDownCellAddress.Y)
{
UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, rowIndex);
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnMouseMove"]/*' />
protected override void OnMouseMove(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
bool oldMouseInContentBounds = mouseInContentBounds;
mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y);
if (oldMouseInContentBounds != mouseInContentBounds)
{
if (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup)
{
this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex);
}
if (e.ColumnIndex == this.DataGridView.MouseDownCellAddress.X &&
e.RowIndex == this.DataGridView.MouseDownCellAddress.Y &&
Control.MouseButtons == MouseButtons.Left)
{
if ((this.ButtonState & ButtonState.Pushed) == 0 &&
mouseInContentBounds &&
this.DataGridView.CellMouseDownInContentBounds)
{
UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex);
}
else if ((this.ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds)
{
UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex);
}
}
}
base.OnMouseMove(e);
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.OnMouseUp"]/*' />
protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
{
if (this.DataGridView == null)
{
return;
}
if (e.Button == MouseButtons.Left)
{
UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex);
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.Paint"]/*' />
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates elementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
if (cellStyle == null)
{
throw new ArgumentNullException("cellStyle");
}
PaintPrivate(graphics,
clipBounds,
cellBounds,
rowIndex,
elementState,
formattedValue,
errorText,
cellStyle,
advancedBorderStyle,
paintParts,
false /*computeContentBounds*/,
false /*computeErrorIconBounds*/,
true /*paint*/);
}
// PaintPrivate is used in three places that need to duplicate the paint code:
// 1. DataGridViewCell::Paint method
// 2. DataGridViewCell::GetContentBounds
// 3. DataGridViewCell::GetErrorIconBounds
//
// if computeContentBounds is true then PaintPrivate returns the contentBounds
// else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
// else it returns Rectangle.Empty;
private Rectangle PaintPrivate(Graphics g,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates elementState,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts,
bool computeContentBounds,
bool computeErrorIconBounds,
bool paint)
{
// Parameter checking.
// One bit and one bit only should be turned on
Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
Debug.Assert(cellStyle != null);
Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0;
bool cellCurrent = (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex);
Rectangle resultBounds;
string formattedString = formattedValue as string;
SolidBrush backBrush = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor);
SolidBrush foreBrush = this.DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor);
if (paint && DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
Rectangle valBounds = cellBounds;
Rectangle borderWidths = BorderWidths(advancedBorderStyle);
valBounds.Offset(borderWidths.X, borderWidths.Y);
valBounds.Width -= borderWidths.Right;
valBounds.Height -= borderWidths.Bottom;
if (valBounds.Height > 0 && valBounds.Width > 0)
{
if (paint && DataGridViewCell.PaintBackground(paintParts) && backBrush.Color.A == 255)
{
g.FillRectangle(backBrush, valBounds);
}
if (cellStyle.Padding != Padding.Empty)
{
if (this.DataGridView.RightToLeftInternal)
{
valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
}
else
{
valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
}
valBounds.Width -= cellStyle.Padding.Horizontal;
valBounds.Height -= cellStyle.Padding.Vertical;
}
Rectangle errorBounds = valBounds;
if (valBounds.Height > 0 && valBounds.Width > 0 && (paint || computeContentBounds))
{
if (this.FlatStyle == FlatStyle.Standard || this.FlatStyle == FlatStyle.System)
{
if (this.DataGridView.ApplyVisualStylesToInnerCells)
{
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
VisualStyles.PushButtonState pbState = VisualStyles.PushButtonState.Normal;
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
pbState = VisualStyles.PushButtonState.Pressed;
}
else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex &&
mouseInContentBounds)
{
pbState = VisualStyles.PushButtonState.Hot;
}
if (DataGridViewCell.PaintFocus(paintParts) &&
cellCurrent &&
this.DataGridView.ShowFocusCues &&
this.DataGridView.Focused)
{
pbState |= VisualStyles.PushButtonState.Default;
}
DataGridViewButtonCellRenderer.DrawButton(g, valBounds, (int)pbState);
}
resultBounds = valBounds;
valBounds = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetBackgroundContentRectangle(g, valBounds);
}
else
{
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
ControlPaint.DrawBorder(g, valBounds, SystemColors.Control,
(this.ButtonState == ButtonState.Normal) ? ButtonBorderStyle.Outset : ButtonBorderStyle.Inset);
}
resultBounds = valBounds;
valBounds.Inflate(-SystemInformation.Border3DSize.Width, -SystemInformation.Border3DSize.Height);
}
}
else if (this.FlatStyle == FlatStyle.Flat)
{
// ButtonBase::PaintFlatDown and ButtonBase::PaintFlatUp paint the border in the same way
valBounds.Inflate(-1, -1);
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
ButtonInternal.ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, foreBrush.Color, true /*isDefault == true*/);
if (backBrush.Color.A == 255)
{
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
this.DataGridView.Enabled).Calculate();
IntPtr hdc = g.GetHdc();
try {
using( WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) {
System.Windows.Forms.Internal.WindowsBrush windowsBrush;
if (colors.options.highContrast)
{
windowsBrush = new System.Windows.Forms.Internal.WindowsSolidBrush(wg.DeviceContext, colors.buttonShadow);
}
else
{
windowsBrush = new System.Windows.Forms.Internal.WindowsSolidBrush(wg.DeviceContext, colors.lowHighlight);
}
try
{
ButtonInternal.ButtonBaseAdapter.PaintButtonBackground(wg, valBounds, windowsBrush);
}
finally
{
windowsBrush.Dispose();
}
}
}
finally {
g.ReleaseHdc();
}
}
else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex &&
mouseInContentBounds)
{
IntPtr hdc = g.GetHdc();
try {
using( WindowsGraphics wg = WindowsGraphics.FromHdc(hdc)) {
Color mouseOverBackColor = SystemColors.ControlDark;
using (System.Windows.Forms.Internal.WindowsBrush windowBrush = new System.Windows.Forms.Internal.WindowsSolidBrush(wg.DeviceContext, mouseOverBackColor))
{
ButtonInternal.ButtonBaseAdapter.PaintButtonBackground(wg, valBounds, windowBrush);
}
}
}
finally {
g.ReleaseHdc();
}
}
}
}
resultBounds = valBounds;
}
else
{
Debug.Assert(this.FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
valBounds.Inflate(-1, -1);
if (paint && DataGridViewCell.PaintContentBackground(paintParts))
{
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0)
{
// paint down
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
this.DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.windowFrame,
true /*isDefault*/);
ControlPaint.DrawBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.buttonShadow,
ButtonBorderStyle.Solid);
}
else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex &&
this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex &&
mouseInContentBounds)
{
// paint over
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
this.DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g,
valBounds,
colors.options.highContrast ? colors.windowText : colors.buttonShadow,
false /*isDefault*/);
ButtonBaseAdapter.Draw3DLiteBorder(g, valBounds, colors, true);
}
else
{
// paint up
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
this.DataGridView.Enabled).Calculate();
ButtonBaseAdapter.DrawDefaultBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow, false /*isDefault*/);
ButtonBaseAdapter.DrawFlatBorder(g, valBounds, colors.options.highContrast ? colors.windowText : colors.buttonShadow);
}
}
resultBounds = valBounds;
}
}
else if (computeErrorIconBounds)
{
if (!String.IsNullOrEmpty(errorText))
{
resultBounds = ComputeErrorIconBounds(errorBounds);
}
else
{
resultBounds = Rectangle.Empty;
}
}
else
{
Debug.Assert(valBounds.Height <= 0 || valBounds.Width <= 0);
resultBounds = Rectangle.Empty;
}
if (paint &&
DataGridViewCell.PaintFocus(paintParts) &&
cellCurrent &&
this.DataGridView.ShowFocusCues &&
this.DataGridView.Focused &&
valBounds.Width > 2 * SystemInformation.Border3DSize.Width + 1 &&
valBounds.Height > 2 * SystemInformation.Border3DSize.Height + 1)
{
// Draw focus rectangle
if (this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard)
{
ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(valBounds, -1, -1), Color.Empty, SystemColors.Control);
}
else if (this.FlatStyle == FlatStyle.Flat)
{
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
(this.DataGridView.CurrentCellAddress.Y == rowIndex && this.DataGridView.CurrentCellAddress.X == this.ColumnIndex))
{
ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintFlatRender(g,
cellStyle.ForeColor,
cellStyle.BackColor,
this.DataGridView.Enabled).Calculate();
string text = (formattedString != null) ? formattedString : String.Empty;
ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonFlatAdapter.PaintFlatLayout(g,
true,
SystemInformation.HighContrast,
1,
valBounds,
Padding.Empty,
false,
cellStyle.Font,
text,
this.DataGridView.Enabled,
DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
this.DataGridView.RightToLeft);
options.everettButtonCompat = false;
ButtonBaseAdapter.LayoutData layout = options.Layout();
ButtonInternal.ButtonBaseAdapter.DrawFlatFocus(g,
layout.focus,
colors.options.highContrast ? colors.windowText : colors.constrastButtonShadow);
}
}
else
{
Debug.Assert(this.FlatStyle == FlatStyle.Popup, "FlatStyle.Popup is the last flat style");
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 ||
(this.DataGridView.CurrentCellAddress.Y == rowIndex && this.DataGridView.CurrentCellAddress.X == this.ColumnIndex))
{
// If we are painting the current cell, then paint the text up.
// If we are painting the current cell and the current cell is pressed down, then paint the text down.
bool paintUp = (this.ButtonState == ButtonState.Normal);
string text = (formattedString != null) ? formattedString : String.Empty;
ButtonBaseAdapter.LayoutOptions options = ButtonInternal.ButtonPopupAdapter.PaintPopupLayout(g,
paintUp,
SystemInformation.HighContrast ? 2 : 1,
valBounds,
Padding.Empty,
false,
cellStyle.Font,
text,
this.DataGridView.Enabled,
DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment),
this.DataGridView.RightToLeft);
options.everettButtonCompat = false;
ButtonBaseAdapter.LayoutData layout = options.Layout();
ControlPaint.DrawFocusRectangle(g,
layout.focus,
cellStyle.ForeColor,
cellStyle.BackColor);
}
}
}
if (formattedString != null && paint && DataGridViewCell.PaintContentForeground(paintParts))
{
// Font independent margins
valBounds.Offset(DATAGRIDVIEWBUTTONCELL_horizontalTextMargin, DATAGRIDVIEWBUTTONCELL_verticalTextMargin);
valBounds.Width -= 2 * DATAGRIDVIEWBUTTONCELL_horizontalTextMargin;
valBounds.Height -= 2 * DATAGRIDVIEWBUTTONCELL_verticalTextMargin;
if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0 &&
this.FlatStyle != FlatStyle.Flat && this.FlatStyle != FlatStyle.Popup)
{
valBounds.Offset(1, 1);
valBounds.Width--;
valBounds.Height--;
}
if (valBounds.Width > 0 && valBounds.Height > 0)
{
Color textColor;
if (this.DataGridView.ApplyVisualStylesToInnerCells &&
(this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard))
{
textColor = DataGridViewButtonCellRenderer.DataGridViewButtonRenderer.GetColor(ColorProperty.TextColor);
}
else
{
textColor = foreBrush.Color;
}
TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(this.DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode);
TextRenderer.DrawText(g,
formattedString,
cellStyle.Font,
valBounds,
textColor,
flags);
}
}
if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
{
PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText);
}
}
else
{
resultBounds = Rectangle.Empty;
}
return resultBounds;
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCell.ToString"]/*' />
public override string ToString()
{
return "DataGridViewButtonCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }";
}
private void UpdateButtonState(ButtonState newButtonState, int rowIndex)
{
if (this.ButtonState != newButtonState)
{
this.ButtonState = newButtonState;
this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex);
}
}
private class DataGridViewButtonCellRenderer
{
private static VisualStyleRenderer visualStyleRenderer;
private DataGridViewButtonCellRenderer()
{
}
public static VisualStyleRenderer DataGridViewButtonRenderer
{
get
{
if (visualStyleRenderer == null)
{
visualStyleRenderer = new VisualStyleRenderer(ButtonElement);
}
return visualStyleRenderer;
}
}
public static void DrawButton(Graphics g, Rectangle bounds, int buttonState)
{
DataGridViewButtonRenderer.SetParameters(ButtonElement.ClassName, ButtonElement.Part, buttonState);
DataGridViewButtonRenderer.DrawBackground(g, bounds, Rectangle.Truncate(g.ClipBounds));
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCellAccessibleObject"]/*' />
protected class DataGridViewButtonCellAccessibleObject : DataGridViewCellAccessibleObject
{
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCellAccessibleObject.DataGridViewButtonCellAccessibleObject"]/*' />
public DataGridViewButtonCellAccessibleObject(DataGridViewCell owner) : base (owner)
{
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCellAccessibleObject.DefaultAction"]/*' />
public override string DefaultAction
{
get
{
return SR.GetString(SR.DataGridView_AccButtonCellDefaultAction);
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCellAccessibleObject.DoDefaultAction"]/*' />
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction()
{
DataGridViewButtonCell dataGridViewCell = (DataGridViewButtonCell)this.Owner;
DataGridView dataGridView = dataGridViewCell.DataGridView;
if (dataGridView != null && dataGridViewCell.RowIndex == -1)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidOperationOnSharedCell));
}
if (dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningRow != null)
{
dataGridView.OnCellClickInternal(new DataGridViewCellEventArgs(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex));
dataGridView.OnCellContentClickInternal(new DataGridViewCellEventArgs(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex));
}
}
/// <include file='doc\DataGridViewButtonCell.uex' path='docs/doc[@for="DataGridViewButtonCellAccessibleObject.GetChildCount"]/*' />
public override int GetChildCount()
{
return 0;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
/// <summary>
/// Represents generic type parameters of a method or type.
/// </summary>
public struct GenericParameterHandleCollection : IReadOnlyList<GenericParameterHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
ThrowIndexOutOfRange();
}
return GenericParameterHandle.FromRowId(_firstRowId + index);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterHandle> IEnumerable<GenericParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents constraints of a generic type parameter.
/// </summary>
public struct GenericParameterConstraintHandleCollection : IReadOnlyList<GenericParameterConstraintHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterConstraintHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterConstraintHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
ThrowIndexOutOfRange();
}
return GenericParameterConstraintHandle.FromRowId(_firstRowId + index);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterConstraintHandle> IEnumerable<GenericParameterConstraintHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterConstraintHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterConstraintHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterConstraintHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct CustomAttributeHandleCollection : IReadOnlyCollection<CustomAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal CustomAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.CustomAttributeTable.NumberOfRows;
}
internal CustomAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
Debug.Assert(!handle.IsNil);
_reader = reader;
reader.CustomAttributeTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<CustomAttributeHandle> IEnumerable<CustomAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<CustomAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public CustomAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.CustomAttributeTable.PtrTable != null)
{
return GetCurrentCustomAttributeIndirect();
}
else
{
return CustomAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private CustomAttributeHandle GetCurrentCustomAttributeIndirect()
{
return CustomAttributeHandle.FromRowId(
_reader.CustomAttributeTable.PtrTable[(_currentRowId & (int)TokenTypeIds.RIDMask) - 1]);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct DeclarativeSecurityAttributeHandleCollection : IReadOnlyCollection<DeclarativeSecurityAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.DeclSecurityTable.NumberOfRows;
}
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
Debug.Assert(!handle.IsNil);
_reader = reader;
reader.DeclSecurityTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<DeclarativeSecurityAttributeHandle> IEnumerable<DeclarativeSecurityAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<DeclarativeSecurityAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public DeclarativeSecurityAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return DeclarativeSecurityAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodDefinitionHandleCollection : IReadOnlyCollection<MethodDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.MethodDefTable.NumberOfRows;
}
internal MethodDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetMethodRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<MethodDefinitionHandle> IEnumerable<MethodDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first method rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseMethodPtrTable)
{
return GetCurrentMethodIndirect();
}
else
{
return MethodDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private MethodDefinitionHandle GetCurrentMethodIndirect()
{
return _reader.MethodPtrTable.GetMethodFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct FieldDefinitionHandleCollection : IReadOnlyCollection<FieldDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal FieldDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.FieldTable.NumberOfRows;
}
internal FieldDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetFieldRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<FieldDefinitionHandle> IEnumerable<FieldDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<FieldDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first field rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public FieldDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseFieldPtrTable)
{
return GetCurrentFieldIndirect();
}
else
{
return FieldDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private FieldDefinitionHandle GetCurrentFieldIndirect()
{
return _reader.FieldPtrTable.GetFieldFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyDefinitionHandleCollection : IReadOnlyCollection<PropertyDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal PropertyDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.PropertyTable.NumberOfRows;
}
internal PropertyDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetPropertyRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<PropertyDefinitionHandle> IEnumerable<PropertyDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<PropertyDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Property rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public PropertyDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UsePropertyPtrTable)
{
return GetCurrentPropertyIndirect();
}
else
{
return PropertyDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private PropertyDefinitionHandle GetCurrentPropertyIndirect()
{
return _reader.PropertyPtrTable.GetPropertyFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct EventDefinitionHandleCollection : IReadOnlyCollection<EventDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal EventDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = (int)reader.EventTable.NumberOfRows;
}
internal EventDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetEventRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<EventDefinitionHandle> IEnumerable<EventDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<EventDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId;
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public EventDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseEventPtrTable)
{
return GetCurrentEventIndirect();
}
else
{
return EventDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private EventDefinitionHandle GetCurrentEventIndirect()
{
return _reader.EventPtrTable.GetEventFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodImplementationHandleCollection : IReadOnlyCollection<MethodImplementationHandle>
{
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
if (containingType.IsNil)
{
_firstRowId = 1;
_lastRowId = (int)reader.MethodImplTable.NumberOfRows;
}
else
{
reader.MethodImplTable.GetMethodImplRange(containingType, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _lastRowId);
}
IEnumerator<MethodImplementationHandle> IEnumerable<MethodImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodImplementationHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first impl rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodImplementationHandle Current
{
get
{
return MethodImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Collection of parameters of a specified method.
/// </summary>
public struct ParameterHandleCollection : IReadOnlyCollection<ParameterHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal ParameterHandleCollection(MetadataReader reader, MethodDefinitionHandle containingMethod)
{
Debug.Assert(reader != null);
Debug.Assert(!containingMethod.IsNil);
_reader = reader;
reader.GetParameterRange(containingMethod, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<ParameterHandle> IEnumerable<ParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ParameterHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public ParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseParamPtrTable)
{
return GetCurrentParameterIndirect();
}
else
{
return ParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private ParameterHandle GetCurrentParameterIndirect()
{
return _reader.ParamPtrTable.GetParamFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct InterfaceImplementationHandleCollection : IReadOnlyCollection<InterfaceImplementationHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal InterfaceImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle implementingType)
{
Debug.Assert(reader != null);
Debug.Assert(!implementingType.IsNil);
_reader = reader;
reader.InterfaceImplTable.GetInterfaceImplRange(implementingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<InterfaceImplementationHandle> IEnumerable<InterfaceImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<InterfaceImplementationHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public InterfaceImplementationHandle Current
{
get
{
return InterfaceImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeDefinitionHandle"/>.
/// </summary>
public struct TypeDefinitionHandleCollection : IReadOnlyCollection<TypeDefinitionHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeDef table.
internal TypeDefinitionHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeDefinitionHandle> IEnumerable<TypeDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeDefinitionHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeDefinitionHandle Current
{
get
{
return TypeDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct TypeReferenceHandleCollection : IReadOnlyCollection<TypeReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal TypeReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeReferenceHandle> IEnumerable<TypeReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeReferenceHandle Current
{
get
{
return TypeReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct ExportedTypeHandleCollection : IReadOnlyCollection<ExportedTypeHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal ExportedTypeHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ExportedTypeHandle> IEnumerable<ExportedTypeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ExportedTypeHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ExportedTypeHandle Current
{
get
{
return ExportedTypeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="MemberReferenceHandle"/>.
/// </summary>
public struct MemberReferenceHandleCollection : IReadOnlyCollection<MemberReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal MemberReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<MemberReferenceHandle> IEnumerable<MemberReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MemberReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public MemberReferenceHandle Current
{
get
{
return MemberReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _getterRowId;
private readonly int _setterRowId;
public MethodDefinitionHandle Getter { get { return MethodDefinitionHandle.FromRowId(_getterRowId); } }
public MethodDefinitionHandle Setter { get { return MethodDefinitionHandle.FromRowId(_setterRowId); } }
internal PropertyAccessors(int getterRowId, int setterRowId)
{
_getterRowId = getterRowId;
_setterRowId = setterRowId;
}
}
public struct EventAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _adderRowId;
private readonly int _removerRowId;
private readonly int _raiserRowId;
public MethodDefinitionHandle Adder { get { return MethodDefinitionHandle.FromRowId(_adderRowId); } }
public MethodDefinitionHandle Remover { get { return MethodDefinitionHandle.FromRowId(_removerRowId); } }
public MethodDefinitionHandle Raiser { get { return MethodDefinitionHandle.FromRowId(_raiserRowId); } }
internal EventAccessors(int adderRowId, int removerRowId, int raiserRowId)
{
_adderRowId = adderRowId;
_removerRowId = removerRowId;
_raiserRowId = raiserRowId;
}
}
/// <summary>
/// Collection of assembly references.
/// </summary>
public struct AssemblyReferenceHandleCollection : IReadOnlyCollection<AssemblyReferenceHandle>
{
private readonly MetadataReader _reader;
internal AssemblyReferenceHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
}
public int Count
{
get
{
return _reader.AssemblyRefTable.NumberOfNonVirtualRows + _reader.AssemblyRefTable.NumberOfVirtualRows;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader);
}
IEnumerator<AssemblyReferenceHandle> IEnumerable<AssemblyReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyReferenceHandle>, IEnumerator
{
private readonly MetadataReader _reader;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
private int _virtualRowId;
internal Enumerator(MetadataReader reader)
{
_reader = reader;
_currentRowId = 0;
_virtualRowId = -1;
}
public AssemblyReferenceHandle Current
{
get
{
if (_virtualRowId >= 0)
{
if (_virtualRowId == EnumEnded)
{
return default(AssemblyReferenceHandle);
}
return AssemblyReferenceHandle.FromVirtualIndex((AssemblyReferenceHandle.VirtualIndex)((uint)_virtualRowId));
}
else
{
return AssemblyReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
public bool MoveNext()
{
if (_currentRowId < _reader.AssemblyRefTable.NumberOfNonVirtualRows)
{
_currentRowId++;
return true;
}
if (_virtualRowId < _reader.AssemblyRefTable.NumberOfVirtualRows - 1)
{
_virtualRowId++;
return true;
}
_currentRowId = EnumEnded;
_virtualRowId = EnumEnded;
return false;
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="ManifestResourceHandle"/>.
/// </summary>
public struct ManifestResourceHandleCollection : IReadOnlyCollection<ManifestResourceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire ManifestResource table.
internal ManifestResourceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ManifestResourceHandle> IEnumerable<ManifestResourceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ManifestResourceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ManifestResourceHandle Current
{
get
{
return ManifestResourceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="AssemblyFileHandle"/>.
/// </summary>
public struct AssemblyFileHandleCollection : IReadOnlyCollection<AssemblyFileHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire AssemblyFile table.
internal AssemblyFileHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<AssemblyFileHandle> IEnumerable<AssemblyFileHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyFileHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public AssemblyFileHandle Current
{
get
{
return AssemblyFileHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Provides access to all native methods provided by <c>NativeExtension</c>.
/// An extra level of indirection is added to P/Invoke calls to allow intelligent loading
/// of the right configuration of the native extension based on current platform, architecture etc.
/// </summary>
internal class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create;
public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call;
public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method;
public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host;
public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline;
public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata;
public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_async_delegate grpcsharp_completion_queue_create_async;
public readonly Delegates.grpcsharp_completion_queue_create_sync_delegate grpcsharp_completion_queue_create_sync;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.grpcsharp_call_auth_context_delegate grpcsharp_call_auth_context;
public readonly Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate grpcsharp_auth_context_peer_identity_property_name;
public readonly Delegates.grpcsharp_auth_context_property_iterator_delegate grpcsharp_auth_context_property_iterator;
public readonly Delegates.grpcsharp_auth_property_iterator_next_delegate grpcsharp_auth_property_iterator_next;
public readonly Delegates.grpcsharp_auth_context_release_delegate grpcsharp_auth_context_release;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library);
this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library);
this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library);
this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library);
this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library);
this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library);
this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create_async = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_async_delegate>(library);
this.grpcsharp_completion_queue_create_sync = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_sync_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.grpcsharp_call_auth_context = GetMethodDelegate<Delegates.grpcsharp_call_auth_context_delegate>(library);
this.grpcsharp_auth_context_peer_identity_property_name = GetMethodDelegate<Delegates.grpcsharp_auth_context_peer_identity_property_name_delegate>(library);
this.grpcsharp_auth_context_property_iterator = GetMethodDelegate<Delegates.grpcsharp_auth_context_property_iterator_delegate>(library);
this.grpcsharp_auth_property_iterator_next = GetMethodDelegate<Delegates.grpcsharp_auth_property_iterator_next_delegate>(library);
this.grpcsharp_auth_context_release = GetMethodDelegate<Delegates.grpcsharp_auth_context_release_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
}
/// <summary>
/// Gets singleton instance of this class.
/// </summary>
public static NativeMethods Get()
{
return NativeExtension.Get().NativeMethods;
}
static T GetMethodDelegate<T>(UnmanagedLibrary library)
where T : class
{
var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate");
return library.GetNativeMethodDelegate<T>(methodName);
}
static string RemoveStringSuffix(string str, string toRemove)
{
if (!str.EndsWith(toRemove))
{
return str;
}
return str.Substring(0, str.Length - toRemove.Length);
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate();
public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength);
public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength);
public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx);
public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags,
MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags);
public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata,
byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags);
public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_async_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_sync_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args);
public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate AuthContextSafeHandle grpcsharp_call_auth_context_delegate(CallSafeHandle call);
public delegate IntPtr grpcsharp_auth_context_peer_identity_property_name_delegate(AuthContextSafeHandle authContext); // returns const char*
public delegate AuthContextSafeHandle.NativeAuthPropertyIterator grpcsharp_auth_context_property_iterator_delegate(AuthContextSafeHandle authContext);
public delegate IntPtr grpcsharp_auth_property_iterator_next_delegate(ref AuthContextSafeHandle.NativeAuthPropertyIterator iterator); // returns const auth_property*
public delegate void grpcsharp_auth_context_release_delegate(IntPtr authContext);
public delegate Timespec gprsharp_now_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Plug-Ins
// File : DeploymentPlugIn.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 10/27/2009
// Note : Copyright 2007-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a plug-in that can be used to deploy the resulting help
// file output to a location other than the output folder (i.e. a file share,
// an FTP site, a web server, etc.).
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.2.0 09/09/2007 EFW Created the code
// 1.6.0.5 02/18/2008 EFW Added support for relative deployment paths
// 1.8.0.0 08/13/2008 EFW Updated to support the new project format
// 1.8.0.3 07/06/2009 EFW Added support for Help Viewer deployment
//=============================================================================
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Reflection;
using System.Windows.Forms;
using System.Xml.XPath;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.BuildEngine;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.PlugIns
{
/// <summary>
/// This plug-in class is used to copy the resulting help file output to
/// a location other than the output folder (i.e. a file share, an FTP
/// site, a web server, etc.).
/// </summary>
public class DeploymentPlugIn : IPlugIn
{
#region Private data members
private ExecutionPointCollection executionPoints;
private BuildProcess builder;
// Plug-in configuration options
private DeploymentLocation deployHelp1, deployHelp2, deployHelpViewer,
deployWebsite;
private bool deleteAfterDeploy;
#endregion
#region IPlugIn implementation
//=====================================================================
// IPlugIn implementation
/// <summary>
/// This read-only property returns a friendly name for the plug-in
/// </summary>
public string Name
{
get { return "Output Deployment"; }
}
/// <summary>
/// This read-only property returns the version of the plug-in
/// </summary>
public Version Version
{
get
{
// Use the assembly version
Assembly asm = Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(
asm.Location);
return new Version(fvi.ProductVersion);
}
}
/// <summary>
/// This read-only property returns the copyright information for the
/// plug-in.
/// </summary>
public string Copyright
{
get
{
// Use the assembly copyright
Assembly asm = Assembly.GetExecutingAssembly();
AssemblyCopyrightAttribute copyright =
(AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(
asm, typeof(AssemblyCopyrightAttribute));
return copyright.Copyright;
}
}
/// <summary>
/// This read-only property returns a brief description of the plug-in
/// </summary>
public string Description
{
get
{
return "This plug-in is used to deploy the resulting help " +
"file output to a location other than the output folder " +
"(i.e. a file share, a web server, an FTP site, etc.).";
}
}
/// <summary>
/// This plug-in does not run in partial builds
/// </summary>
public bool RunsInPartialBuild
{
get { return false; }
}
/// <summary>
/// This read-only property returns a collection of execution points
/// that define when the plug-in should be invoked during the build
/// process.
/// </summary>
public ExecutionPointCollection ExecutionPoints
{
get
{
if(executionPoints == null)
{
executionPoints = new ExecutionPointCollection();
// This plug-in has a lower priority as it should execute
// after all other plug-ins in case they add other files
// to the set.
executionPoints.Add(new ExecutionPoint(
BuildStep.CompilingHelpFile,
ExecutionBehaviors.After, 200));
executionPoints.Add(new ExecutionPoint(
BuildStep.CopyingWebsiteFiles,
ExecutionBehaviors.After, 200));
}
return executionPoints;
}
}
/// <summary>
/// This method is used by the Sandcastle Help File Builder to let the
/// plug-in perform its own configuration.
/// </summary>
/// <param name="project">A reference to the active project</param>
/// <param name="currentConfig">The current configuration XML fragment</param>
/// <returns>A string containing the new configuration XML fragment</returns>
/// <remarks>The configuration data will be stored in the help file
/// builder project.</remarks>
public string ConfigurePlugIn(SandcastleProject project,
string currentConfig)
{
using(DeploymentConfigDlg dlg = new DeploymentConfigDlg(
currentConfig))
{
if(dlg.ShowDialog() == DialogResult.OK)
currentConfig = dlg.Configuration;
}
return currentConfig;
}
/// <summary>
/// This method is used to initialize the plug-in at the start of the
/// build process.
/// </summary>
/// <param name="buildProcess">A reference to the current build
/// process.</param>
/// <param name="configuration">The configuration data that the plug-in
/// should use to initialize itself.</param>
/// <exception cref="BuilderException">This is thrown if the plug-in
/// configuration is not valid.</exception>
public void Initialize(BuildProcess buildProcess,
XPathNavigator configuration)
{
XPathNavigator root;
string value;
builder = buildProcess;
builder.ReportProgress("{0} Version {1}\r\n{2}",
this.Name, this.Version, this.Copyright);
root = configuration.SelectSingleNode("configuration");
value = root.GetAttribute("deleteAfterDeploy", String.Empty);
if(!String.IsNullOrEmpty(value))
deleteAfterDeploy = Convert.ToBoolean(value,
CultureInfo.InvariantCulture);
if(root.IsEmptyElement)
throw new BuilderException("ODP0001", "The Output Deployment " +
"plug-in has not been configured yet");
deployHelp1 = DeploymentLocation.FromXPathNavigator(root, "help1x");
deployHelp2 = DeploymentLocation.FromXPathNavigator(root, "help2x");
deployHelpViewer = DeploymentLocation.FromXPathNavigator(root, "helpViewer");
deployWebsite = DeploymentLocation.FromXPathNavigator(root, "website");
// At least one deployment location must be defined
if(deployHelp1.Location == null && deployHelp2.Location == null &&
deployHelpViewer.Location == null && deployWebsite.Location == null)
throw new BuilderException("ODP0002", "The output deployment " +
"plug-in must have at least one configured deployment " +
"location");
// Issue a warning if the deployment location is null and the
// associated help file format is active.
if(deployHelp1.Location == null &&
(builder.CurrentProject.HelpFileFormat & HelpFileFormat.HtmlHelp1) != 0)
builder.ReportWarning("ODP0003", "HTML Help 1 will be generated " +
"but not deployed due to missing deployment location " +
"information");
if(deployHelp2.Location == null &&
(builder.CurrentProject.HelpFileFormat & HelpFileFormat.MSHelp2) != 0)
builder.ReportWarning("ODP0003", "MS Help 2 will be generated " +
"but not deployed due to missing deployment location " +
"information");
if(deployHelpViewer.Location == null &&
(builder.CurrentProject.HelpFileFormat & HelpFileFormat.MSHelpViewer) != 0)
builder.ReportWarning("ODP0003", "MS Help Viewer will be generated " +
"but not deployed due to missing deployment location " +
"information");
if(deployWebsite.Location == null &&
(builder.CurrentProject.HelpFileFormat & HelpFileFormat.Website) != 0)
builder.ReportWarning("ODP0003", "Website will be generated " +
"but not deployed due to missing deployment location " +
"information");
}
/// <summary>
/// This method is used to execute the plug-in during the build process
/// </summary>
/// <param name="context">The current execution context</param>
public void Execute(ExecutionContext context)
{
// Deploy each of the selected help file formats
if(builder.CurrentFormat == HelpFileFormat.HtmlHelp1)
{
builder.ReportProgress("Deploying HTML Help 1 file");
this.DeployOutput(builder.Help1Files, deployHelp1);
}
if(builder.CurrentFormat == HelpFileFormat.MSHelp2)
{
builder.ReportProgress("Deploying MS Help 2 files");
this.DeployOutput(builder.Help2Files, deployHelp2);
}
if(builder.CurrentFormat == HelpFileFormat.MSHelpViewer)
{
builder.ReportProgress("Deploying MS Help Viewer files");
this.DeployOutput(builder.HelpViewerFiles, deployHelpViewer);
}
if(builder.CurrentFormat == HelpFileFormat.Website)
{
builder.ReportProgress("Deploying website files");
this.DeployOutput(builder.WebsiteFiles, deployWebsite);
}
}
#endregion
#region Deploy project output
/// <summary>
/// Deploy the given list of files to the specified location
/// </summary>
/// <param name="files">The list of files to deploy</param>
/// <param name="location">The deployment location</param>
private void DeployOutput(Collection<string> files,
DeploymentLocation location)
{
WebClient webClient = null;
Uri destUri, target = location.Location;
string rootPath, destFile, destPath;
int basePathLength = builder.OutputFolder.Length;
if(files.Count == 0)
{
builder.ReportProgress("No files found to deploy");
return;
}
try
{
// Determine the path type
if(!target.IsAbsoluteUri)
rootPath = Path.GetFullPath(target.OriginalString);
else
if(target.IsFile || target.IsUnc)
rootPath = target.LocalPath;
else
{
// FTP, HTTP, etc.
rootPath = target.ToString();
webClient = new WebClient();
// Initialize the web client
if(!location.UserCredentials.UseDefaultCredentials)
webClient.Credentials = new NetworkCredential(
location.UserCredentials.UserName,
location.UserCredentials.Password);
webClient.CachePolicy = new RequestCachePolicy(
RequestCacheLevel.NoCacheNoStore);
if(location.ProxyCredentials.UseProxyServer)
{
webClient.Proxy = new WebProxy(
location.ProxyCredentials.ProxyServer, true);
if(!location.ProxyCredentials.Credentials.UseDefaultCredentials)
webClient.Proxy.Credentials =
new NetworkCredential(
location.ProxyCredentials.Credentials.UserName,
location.ProxyCredentials.Credentials.Password);
}
}
foreach(string sourceFile in files)
{
destFile = Path.Combine(rootPath,
sourceFile.Substring(basePathLength));
if(webClient == null)
{
builder.ReportProgress(" Deploying {0} to {1}",
sourceFile, destFile);
destPath = Path.GetDirectoryName(destFile);
if(!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
File.Copy(sourceFile, destFile, true);
}
else
{
destUri = new Uri(destFile);
builder.ReportProgress(" Deploying {0} to {1}",
sourceFile, destUri);
webClient.UploadFile(destUri, sourceFile);
}
// If not wanted, remove the source file after deployment
if(deleteAfterDeploy)
File.Delete(sourceFile);
}
}
finally
{
if(webClient != null)
webClient.Dispose();
}
}
#endregion
#region IDisposable implementation
//=====================================================================
// IDisposable implementation
/// <summary>
/// This handles garbage collection to ensure proper disposal of the
/// plug-in if not done explicity with <see cref="Dispose()"/>.
/// </summary>
~DeploymentPlugIn()
{
this.Dispose(false);
}
/// <summary>
/// This implements the Dispose() interface to properly dispose of
/// the plug-in object.
/// </summary>
/// <overloads>There are two overloads for this method.</overloads>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// This can be overridden by derived classes to add their own
/// disposal code if necessary.
/// </summary>
/// <param name="disposing">Pass true to dispose of the managed
/// and unmanaged resources or false to just dispose of the
/// unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// Nothing to dispose of in this one
}
#endregion
}
}
| |
using System.Collections.Generic;
using Lucene.Net.Documents;
namespace Lucene.Net.Search.Spans
{
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using Term = Lucene.Net.Index.Term;
using TFIDFSimilarity = Lucene.Net.Search.Similarities.TFIDFSimilarity;
[TestFixture]
public class TestFieldMaskingSpanQuery : LuceneTestCase
{
protected internal static Document Doc(Field[] fields)
{
Document doc = new Document();
for (int i = 0; i < fields.Length; i++)
{
doc.Add(fields[i]);
}
return doc;
}
protected internal static Field GetField(string name, string value)
{
return NewTextField(name, value, Field.Store.NO);
}
protected internal static IndexSearcher Searcher;
protected internal static Directory Directory;
protected internal static IndexReader Reader;
[TestFixtureSetUp]
public static void BeforeClass()
{
Directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
writer.AddDocument(Doc(new Field[] { GetField("id", "0"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "1"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "2"), GetField("gender", "female"), GetField("first", "greta"), GetField("last", "jones"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "male"), GetField("first", "james"), GetField("last", "jones") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "3"), GetField("gender", "female"), GetField("first", "lisa"), GetField("last", "jones"), GetField("gender", "male"), GetField("first", "bob"), GetField("last", "costas") }));
writer.AddDocument(Doc(new Field[] { GetField("id", "4"), GetField("gender", "female"), GetField("first", "sally"), GetField("last", "smith"), GetField("gender", "female"), GetField("first", "linda"), GetField("last", "dixit"), GetField("gender", "male"), GetField("first", "bubba"), GetField("last", "jones") }));
Reader = writer.Reader;
writer.Dispose();
Searcher = NewSearcher(Reader);
}
[TestFixtureTearDown]
public static void AfterClass()
{
Searcher = null;
Reader.Dispose();
Reader = null;
Directory.Dispose();
Directory = null;
}
protected internal virtual void Check(SpanQuery q, int[] docs)
{
CheckHits.CheckHitCollector(Random(), q, null, Searcher, docs);
}
[Test]
public virtual void TestRewrite0()
{
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
q.Boost = 8.7654321f;
SpanQuery qr = (SpanQuery)Searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
HashSet<Term> terms = new HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(1, terms.Count);
}
[Test]
public virtual void TestRewrite1()
{
// mask an anon SpanQuery class that rewrites to something else.
SpanQuery q = new FieldMaskingSpanQuery(new SpanTermQueryAnonymousInnerClassHelper(this, new Term("last", "sally")), "first");
SpanQuery qr = (SpanQuery)Searcher.Rewrite(q);
QueryUtils.CheckUnequal(q, qr);
HashSet<Term> terms = new HashSet<Term>();
qr.ExtractTerms(terms);
Assert.AreEqual(2, terms.Count);
}
private class SpanTermQueryAnonymousInnerClassHelper : SpanTermQuery
{
private readonly TestFieldMaskingSpanQuery OuterInstance;
public SpanTermQueryAnonymousInnerClassHelper(TestFieldMaskingSpanQuery outerInstance, Term term)
: base(term)
{
this.OuterInstance = outerInstance;
}
public override Query Rewrite(IndexReader reader)
{
return new SpanOrQuery(new SpanTermQuery(new Term("first", "sally")), new SpanTermQuery(new Term("first", "james")));
}
}
[Test]
public virtual void TestRewrite2()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 1, true);
Query qr = Searcher.Rewrite(q);
QueryUtils.CheckEqual(q, qr);
HashSet<Term> set = new HashSet<Term>();
qr.ExtractTerms(set);
Assert.AreEqual(2, set.Count);
}
[Test]
public virtual void TestEquality1()
{
SpanQuery q1 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q2 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
SpanQuery q3 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "XXXXX");
SpanQuery q4 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "XXXXX")), "first");
SpanQuery q5 = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("xXXX", "sally")), "first");
QueryUtils.CheckEqual(q1, q2);
QueryUtils.CheckUnequal(q1, q3);
QueryUtils.CheckUnequal(q1, q4);
QueryUtils.CheckUnequal(q1, q5);
SpanQuery qA = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
qA.Boost = 9f;
SpanQuery qB = new FieldMaskingSpanQuery(new SpanTermQuery(new Term("last", "sally")), "first");
QueryUtils.CheckUnequal(qA, qB);
qB.Boost = 9f;
QueryUtils.CheckEqual(qA, qB);
}
[Test]
public virtual void TestNoop0()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "sally"));
SpanQuery q = new FieldMaskingSpanQuery(q1, "first");
Check(q, new int[] { }); // :EMPTY:
}
[Test]
public virtual void TestNoop1()
{
SpanQuery q1 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), new FieldMaskingSpanQuery(q2, "last") }, 0, true);
Check(q, new int[] { 1, 2 });
}
[Test]
public virtual void TestSimple1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "first") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q2, "first"), q1 }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { q2, new FieldMaskingSpanQuery(q1, "last") }, -1, false);
Check(q, new int[] { 0, 2 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "last"), q2 }, -1, false);
Check(q, new int[] { 0, 2 });
}
[Test]
public virtual void TestSimple2()
{
AssumeTrue("Broken scoring: LUCENE-3723", Searcher.Similarity is TFIDFSimilarity);
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("last", "smith"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { q1, new FieldMaskingSpanQuery(q2, "gender") }, -1, false);
Check(q, new int[] { 2, 4 });
q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(q1, "id"), new FieldMaskingSpanQuery(q2, "id") }, -1, false);
Check(q, new int[] { 2, 4 });
}
[Test]
public virtual void TestSpans0()
{
SpanQuery q1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery q = new SpanOrQuery(q1, new FieldMaskingSpanQuery(q2, "gender"));
Check(q, new int[] { 0, 1, 2, 3, 4 });
Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q);
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(1, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(2, 1, 2), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(4, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(4, 1, 2), s(span));
Assert.AreEqual(false, span.Next());
}
[Test]
public virtual void TestSpans1()
{
SpanQuery q1 = new SpanTermQuery(new Term("first", "sally"));
SpanQuery q2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(q1, q2);
SpanQuery qB = new FieldMaskingSpanQuery(qA, "id");
Check(qA, new int[] { 0, 1, 2, 4 });
Check(qB, new int[] { 0, 1, 2, 4 });
Spans spanA = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, qA);
Spans spanB = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, qB);
while (spanA.Next())
{
Assert.IsTrue(spanB.Next(), "spanB not still going");
Assert.AreEqual(s(spanA), s(spanB), "spanA not equal spanB");
}
Assert.IsTrue(!(spanB.Next()), "spanB still going even tough spanA is done");
}
[Test]
public virtual void TestSpans2()
{
AssumeTrue("Broken scoring: LUCENE-3723", Searcher.Similarity is TFIDFSimilarity);
SpanQuery qA1 = new SpanTermQuery(new Term("gender", "female"));
SpanQuery qA2 = new SpanTermQuery(new Term("first", "james"));
SpanQuery qA = new SpanOrQuery(qA1, new FieldMaskingSpanQuery(qA2, "gender"));
SpanQuery qB = new SpanTermQuery(new Term("last", "jones"));
SpanQuery q = new SpanNearQuery(new SpanQuery[] { new FieldMaskingSpanQuery(qA, "id"), new FieldMaskingSpanQuery(qB, "id") }, -1, false);
Check(q, new int[] { 0, 1, 2, 3 });
Spans span = MultiSpansWrapper.Wrap(Searcher.TopReaderContext, q);
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(0, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(1, 1, 2), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(2, 0, 1), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(2, 2, 3), s(span));
Assert.AreEqual(true, span.Next());
Assert.AreEqual(s(3, 0, 1), s(span));
Assert.AreEqual(false, span.Next());
}
public virtual string s(Spans span)
{
return s(span.Doc(), span.Start(), span.End());
}
public virtual string s(int doc, int start, int end)
{
return "s(" + doc + "," + start + "," + end + ")";
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPut(string index, string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutAsync(string index, string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPut(string index, string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutAsync(string index, string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPutString(string index, string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutStringAsync(string index, string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPost(string index, string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostAsync(string index, string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPost(string index, string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostAsync(string index, string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPostString(string index, string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="index">A comma-separated list of index names the mapping should be added to (supports wildcards); use `_all` or omit to add the mapping on all indices.</param>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostStringAsync(string index, string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/{0}/{1}/_mapping", index, type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPut(string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutAsync(string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPut(string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutAsync(string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPutString(string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPutStringAsync(string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPost(string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostAsync(string type, Stream body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPost(string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostAsync(string type, byte[] body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IndicesPutMappingPostString(string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/indices-put-mapping.html"/></summary>
///<param name="type">The name of the document type</param>
///<param name="body">The mapping definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IndicesPutMappingPostStringAsync(string type, string body, Func<IndicesPutMappingParameters, IndicesPutMappingParameters> options = null)
{
var uri = string.Format("/_mapping/{0}", type);
if (options != null)
{
uri = options.Invoke(new IndicesPutMappingParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// 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.Text;
namespace OpenTK
{
#if NO_SYSDRAWING
/// <summary>
/// Represents a rectangular region on a two-dimensional plane.
/// </summary>
public struct Rectangle : IEquatable<Rectangle>
{
#region Fields
Point location;
Size size;
#endregion
#region Constructors
/// <summary>
/// Constructs a new Rectangle instance.
/// </summary>
/// <param name="location">The top-left corner of the Rectangle.</param>
/// <param name="size">The width and height of the Rectangle.</param>
public Rectangle(Point location, Size size)
: this()
{
Location = location;
Size = size;
}
/// <summary>
/// Constructs a new Rectangle instance.
/// </summary>
/// <param name="x">The x coordinate of the Rectangle.</param>
/// <param name="y">The y coordinate of the Rectangle.</param>
/// <param name="width">The width coordinate of the Rectangle.</param>
/// <param name="height">The height coordinate of the Rectangle.</param>
public Rectangle(int x, int y, int width, int height)
: this(new Point(x, y), new Size(width, height))
{ }
#endregion
#region Public Members
/// <summary>
/// Gets or sets the x coordinate of the Rectangle.
/// </summary>
public int X
{
get { return Location.X; }
set { Location = new Point (value, Y); }
}
/// <summary>
/// Gets or sets the y coordinate of the Rectangle.
/// </summary>
public int Y
{
get { return Location.Y; }
set { Location = new Point (X, value); }
}
/// <summary>
/// Gets or sets the width of the Rectangle.
/// </summary>
public int Width
{
get { return Size.Width; }
set { Size = new Size (value, Height); }
}
/// <summary>
/// Gets or sets the height of the Rectangle.
/// </summary>
public int Height
{
get { return Size.Height; }
set { Size = new Size(Width, value); }
}
/// <summary>
/// Gets or sets a <see cref="Point"/> representing the x and y coordinates
/// of the Rectangle.
/// </summary>
public Point Location
{
get { return location; }
set { location = value; }
}
/// <summary>
/// Gets or sets a <see cref="Size"/> representing the width and height
/// of the Rectangle.
/// </summary>
public Size Size
{
get { return size; }
set { size = value; }
}
/// <summary>
/// Gets the y coordinate of the top edge of this Rectangle.
/// </summary>
public int Top { get { return Y; } }
/// <summary>
/// Gets the x coordinate of the right edge of this Rectangle.
/// </summary>
public int Right { get { return X + Width; } }
/// <summary>
/// Gets the y coordinate of the bottom edge of this Rectangle.
/// </summary>
public int Bottom { get { return Y + Height; } }
/// <summary>
/// Gets the x coordinate of the left edge of this Rectangle.
/// </summary>
public int Left { get { return X; } }
/// <summary>
/// Gets a <see cref="System.Boolean"/> that indicates whether this
/// Rectangle is equal to the empty Rectangle.
/// </summary>
public bool IsEmpty
{
get { return Location.IsEmpty && Size.IsEmpty; }
}
/// <summary>
/// Defines the empty Rectangle.
/// </summary>
public static readonly Rectangle Zero = new Rectangle();
/// <summary>
/// Defines the empty Rectangle.
/// </summary>
public static readonly Rectangle Empty = new Rectangle();
/// <summary>
/// Constructs a new instance with the specified edges.
/// </summary>
/// <param name="left">The left edge of the Rectangle.</param>
/// <param name="top">The top edge of the Rectangle.</param>
/// <param name="right">The right edge of the Rectangle.</param>
/// <param name="bottom">The bottom edge of the Rectangle.</param>
/// <returns>A new Rectangle instance with the specified edges.</returns>
public static Rectangle FromLTRB(int left, int top, int right, int bottom)
{
return new Rectangle(new Point(left, top), new Size(right - left, bottom - top));
}
/// <summary>
/// Tests whether this instance contains the specified Point.
/// </summary>
/// <param name="point">The <see cref="Point"/> to test.</param>
/// <returns>True if this instance contains point; false otherwise.</returns>
/// <remarks>The left and top edges are inclusive. The right and bottom edges
/// are exclusive.</remarks>
public bool Contains(Point point)
{
return point.X >= Left && point.X < Right &&
point.Y >= Top && point.Y < Bottom;
}
/// <summary>
/// Tests whether this instance contains the specified Rectangle.
/// </summary>
/// <param name="rect">The <see cref="Rectangle"/> to test.</param>
/// <returns>True if this instance contains rect; false otherwise.</returns>
/// <remarks>The left and top edges are inclusive. The right and bottom edges
/// are exclusive.</remarks>
public bool Contains(Rectangle rect)
{
return Contains(rect.Location) && Contains(rect.Location + rect.Size);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left is equal to right; false otherwise.</returns>
public static bool operator ==(Rectangle left, Rectangle right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left is not equal to right; false otherwise.</returns>
public static bool operator !=(Rectangle left, Rectangle right)
{
return !left.Equals(right);
}
/// <summary>
/// Converts an OpenTK.Rectangle instance to a System.Drawing.Rectangle.
/// </summary>
/// <param name="rect">
/// The <see cref="Rectangle"/> instance to convert.
/// </param>
/// <returns>
/// A <see cref="System.Drawing.Rectangle"/> instance equivalent to rect.
/// </returns>
public static implicit operator System.Drawing.Rectangle(Rectangle rect)
{
return new System.Drawing.Rectangle(rect.Location, rect.Size);
}
/// <summary>
/// Converts a System.Drawing.Rectangle instance to an OpenTK.Rectangle.
/// </summary>
/// <param name="rect">
/// The <see cref="System.Drawing.Rectangle"/> instance to convert.
/// </param>
/// <returns>
/// A <see cref="Rectangle"/> instance equivalent to point.
/// </returns>
public static implicit operator Rectangle(System.Drawing.Rectangle rect)
{
return new Rectangle(rect.Location, rect.Size);
}
/// <summary>
/// Converts an OpenTK.Rectangle instance to a System.Drawing.RectangleF.
/// </summary>
/// <param name="rect">
/// The <see cref="Rectangle"/> instance to convert.
/// </param>
/// <returns>
/// A <see cref="System.Drawing.RectangleF"/> instance equivalent to rect.
/// </returns>
public static implicit operator System.Drawing.RectangleF(Rectangle rect)
{
return new System.Drawing.RectangleF(rect.Location, rect.Size);
}
/// <summary>
/// Indicates whether this instance is equal to the specified object.
/// </summary>
/// <param name="obj">The object instance to compare to.</param>
/// <returns>True, if both instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (obj is Rectangle)
return Equals((Rectangle)obj);
return false;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A <see cref="System.Int32"/> that represents the hash code for this instance./></returns>
public override int GetHashCode()
{
return Location.GetHashCode() & Size.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that describes this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that describes this instance.</returns>
public override string ToString()
{
return String.Format("{{{0}-{1}}}", Location, Location + Size);
}
#endregion
#region IEquatable<Rectangle> Members
/// <summary>
/// Indicates whether this instance is equal to the specified Rectangle.
/// </summary>
/// <param name="other">The instance to compare to.</param>
/// <returns>True, if both instances are equal; false otherwise.</returns>
public bool Equals(Rectangle other)
{
return Location.Equals(other.Location) &&
Size.Equals(other.Size);
}
#endregion
}
#endif
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using EasyNetQ.Internals;
namespace EasyNetQ;
/// <inheritdoc />
public class DefaultTypeNameSerializer : ITypeNameSerializer
{
private readonly ConcurrentDictionary<Type, string> serializedTypes = new();
private readonly ConcurrentDictionary<string, Type> deSerializedTypes = new();
/// <inheritdoc />
public string Serialize(Type type)
{
Preconditions.CheckNotNull(type, nameof(type));
return serializedTypes.GetOrAdd(type, t =>
{
var typeName = RemoveAssemblyDetails(t.AssemblyQualifiedName);
if (typeName.Length > 255)
{
throw new EasyNetQException($"The serialized name of type '{t.Name}' exceeds the AMQP maximum short string length of 255 characters");
}
return typeName;
});
}
/// <inheritdoc />
public Type DeSerialize(string typeName)
{
Preconditions.CheckNotBlank(typeName, "typeName");
return deSerializedTypes.GetOrAdd(typeName, t =>
{
var typeNameKey = SplitFullyQualifiedTypeName(t);
return GetTypeFromTypeNameKey(typeNameKey);
});
}
private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
var builder = new StringBuilder(fullyQualifiedTypeName.Length);
// loop through the type name and filter out qualified assembly details from nested type names
var writingAssemblyName = false;
var skippingAssemblyDetails = false;
foreach (var character in fullyQualifiedTypeName)
{
switch (character)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(character);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(character);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(character);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
{
builder.Append(character);
}
break;
}
}
return builder.ToString();
}
private static TypeNameKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName)
{
var assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
string typeName;
string assemblyName;
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Trim(0, assemblyDelimiterIndex.GetValueOrDefault());
assemblyName = fullyQualifiedTypeName.Trim(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1);
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
return new TypeNameKey(assemblyName, typeName);
}
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
var assemblyName = typeNameKey.AssemblyName;
var typeName = typeNameKey.TypeName;
if (assemblyName != null)
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
if (assembly == null)
{
throw new EasyNetQException($"Could not load assembly '{assemblyName}'");
}
var type = assembly.GetType(typeName);
if (type == null)
{
// if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies
// example generic typeName format: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
if (typeName.IndexOf('`') >= 0)
{
try
{
type = GetGenericTypeFromTypeName(typeName, assembly);
}
catch (Exception ex)
{
throw new EasyNetQException($"Could not find type '{typeName}' in assembly '{assembly.FullName}'", ex);
}
}
if (type == null)
{
throw new EasyNetQException($"Could not find type '{typeName}' in assembly '{assembly.FullName}'");
}
}
return type;
}
return Type.GetType(typeName);
}
private static Type GetGenericTypeFromTypeName(string typeName, Assembly assembly)
{
Type type = null;
var openBracketIndex = typeName.IndexOf('[');
if (openBracketIndex >= 0)
{
var genericTypeDefName = typeName.Substring(0, openBracketIndex);
var genericTypeDef = assembly.GetType(genericTypeDefName);
if (genericTypeDef != null)
{
var genericTypeArguments = new List<Type>();
var scope = 0;
var typeArgStartIndex = 0;
var endIndex = typeName.Length - 1;
for (var i = openBracketIndex + 1; i < endIndex; ++i)
{
var current = typeName[i];
switch (current)
{
case '[':
if (scope == 0)
{
typeArgStartIndex = i + 1;
}
++scope;
break;
case ']':
--scope;
if (scope == 0)
{
var typeArgAssemblyQualifiedName = typeName.Substring(typeArgStartIndex, i - typeArgStartIndex);
var typeNameKey = SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName);
genericTypeArguments.Add(GetTypeFromTypeNameKey(typeNameKey));
}
break;
}
}
type = genericTypeDef.MakeGenericType(genericTypeArguments.ToArray());
}
}
return type;
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
// we need to get the first comma following all surrounded in brackets because of generic types
// e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
var scope = 0;
for (var i = 0; i < fullyQualifiedTypeName.Length; i++)
{
var current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
{
return i;
}
break;
}
}
return null;
}
private readonly struct TypeNameKey
{
public string AssemblyName { get; }
public string TypeName { get; }
public TypeNameKey(string assemblyName, string typeName)
{
AssemblyName = assemblyName;
TypeName = typeName;
}
}
}
| |
namespace Files.ViewModels.FileStats
{
using System;
using System.IO;
using Edi.Core.Interfaces;
using Edi.Core.Interfaces.Enums;
using Edi.Core.ViewModels;
/// <summary>
/// This class can be used to present file based information, such as,
/// Size, Path etc to the user.
/// </summary>
internal class FileStatsViewModel : Edi.Core.ViewModels.ToolViewModel, IRegisterableToolWindow
{
#region fields
public const string ToolContentId = "<FileStatsTool>";
public const string ToolName = "File Info";
private string _FilePathName;
private DateTime _lastModified;
private string _FilePath;
private long _FileSize;
private IDocumentParent mParent = null;
#endregion fields
#region constructor
/// <summary>
/// Class constructor
/// </summary>
public FileStatsViewModel()
: base(FileStatsViewModel.ToolName)
{
ContentId = FileStatsViewModel.ToolContentId;
this.OnActiveDocumentChanged(null, null);
_FilePath = string.Empty;
}
#endregion constructor
#region properties
/// <summary>
/// Gets the size of the file in bytes.
/// </summary>
public long FileSize
{
get { return _FileSize; }
private set
{
if (_FileSize != value)
{
_FileSize = value;
RaisePropertyChanged("FileSize");
}
}
}
/// <summary>
/// Gets the date and time of the time when the displayed
/// file was modified on storage space.
/// </summary>
public DateTime LastModified
{
get { return _lastModified; }
private set
{
if (_lastModified != value)
{
_lastModified = value;
RaisePropertyChanged("LastModified");
}
}
}
/// <summary>
/// Gets the file name for the currently displayed file infornation.
/// </summary>
public string FileName
{
get
{
if (string.IsNullOrEmpty(_FilePathName) == true)
return string.Empty;
try
{
return System.IO.Path.GetFileName(_FilePathName);
}
catch (Exception)
{
return string.Empty;
}
}
}
/// <summary>
/// Gets the full directory for the currently displayed file infornation.
/// </summary>
public string FilePath
{
get { return _FilePath; }
private set
{
if (_FilePath != value)
{
_FilePath = value;
RaisePropertyChanged(() => FilePath);
}
}
}
/// <summary>
/// Gets the Uri of the Icon Resource for this tool window.
/// </summary>
public override Uri IconSource
{
get
{
return new Uri("pack://application:,,,/Edi.Themes;component/Images/property-blue.png", UriKind.RelativeOrAbsolute);
}
}
/// <summary>
/// Gets the preferred location of the tool window
/// (for positioning it for the very first time).
/// </summary>
public override PaneLocation PreferredLocation
{
get { return PaneLocation.Right; }
}
#endregion properties
#region methods
/// <summary>
/// Set the document parent handling object to deactivation and activation
/// of documents with content relevant to this tool window viewmodel.
/// </summary>
/// <param name="parent"></param>
public void SetDocumentParent(IDocumentParent parent)
{
if (parent != null)
parent.ActiveDocumentChanged -= this.OnActiveDocumentChanged;
this.mParent = parent;
// Check if active document is a log4net document to display data for...
if (this.mParent != null)
parent.ActiveDocumentChanged += new DocumentChangedEventHandler(this.OnActiveDocumentChanged);
else
this.OnActiveDocumentChanged(null, null);
}
/// <summary>
/// Set the document parent handling object and visibility
/// to enable tool window to react on deactivation and activation
/// of documents with content relevant to this tool window viewmodel.
/// </summary>
/// <param name="parent"></param>
/// <param name="isVisible"></param>
public void SetToolWindowVisibility(IDocumentParent parent,
bool isVisible = true)
{
if (IsVisible == true)
this.SetDocumentParent(parent);
else
this.SetDocumentParent(null);
base.SetToolWindowVisibility(isVisible);
}
/// <summary>
/// Method executes when (user in) AvalonDock has (loaded) selected another document.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnActiveDocumentChanged(object sender, DocumentChangedEventArgs e)
{
_FilePathName = string.Empty;
FileSize = 0;
LastModified = DateTime.MinValue;
if (e != null)
{
if (e.ActiveDocument != null)
{
if (e.ActiveDocument is IFileBaseViewModel)
{
IFileBaseViewModel f = e.ActiveDocument as IFileBaseViewModel;
if (f.IsFilePathReal == false) // Start page or somethin...
return;
try
{
if (File.Exists(f.FilePath) == true)
{
var fi = new FileInfo(f.FilePath);
_FilePathName = f.FilePath;
this.RaisePropertyChanged(() => this.FileName);
FileSize = fi.Length;
LastModified = fi.LastWriteTime;
FilePath = fi.DirectoryName;
}
}
catch { }
}
}
}
}
#endregion methods
}
}
| |
using System;
using System.Globalization;
using System.Reflection;
using Cake.Core.IO;
using System.Collections.Generic;
using Cake.Core;
using System.Linq;
using System.Runtime.Versioning;
namespace CodeCake
{
/// <summary>
/// Represents the environment Cake operates in. This mutable implementation allows the PATH environment variable
/// to be dynamically modified. Except this new <see cref="EnvironmentPaths"/> this is the same as the <see cref="CakeEnvironment"/>
/// provided by Cake.
/// </summary>
public class MutableCakeEnvironment : ICakeEnvironment
{
readonly ICakePlatform _platform;
readonly ICakeRuntime _runtime;
readonly DirectoryPath _applicationRoot;
readonly List<string> _paths;
readonly List<string> _addedPaths;
readonly List<string> _dynamicPaths;
IGlobber _globber;
/// <summary>
/// Gets or sets the working directory.
/// </summary>
/// <value>The working directory.</value>
public DirectoryPath WorkingDirectory
{
get { return Environment.CurrentDirectory; }
set { SetWorkingDirectory( value ); }
}
/// <summary>
/// Initializes a new instance of the <see cref="MutableCakeEnvironment" /> class.
/// </summary>
/// <param name="platform">The platform.</param>
/// <param name="runtime">The runtime.</param>
/// <param name="appRoot">App root path</param>
public MutableCakeEnvironment( ICakePlatform platform, ICakeRuntime runtime, string appRoot = null )
{
_platform = platform;
_runtime = runtime;
var rootPath = string.IsNullOrEmpty( appRoot ) ? Assembly.GetExecutingAssembly().Location : appRoot;
_applicationRoot = System.IO.Path.GetDirectoryName( rootPath );
WorkingDirectory = new DirectoryPath( Environment.CurrentDirectory );
var pathEnv = Environment.GetEnvironmentVariable( "PATH" );
if( !string.IsNullOrEmpty( pathEnv ) )
{
_paths = pathEnv.Split( new char[] { _platform.IsUnix() ? ':' : ';' }, StringSplitOptions.RemoveEmptyEntries )
.Select( s => s.Trim() )
.Where( s => s.Length > 0 )
.ToList();
}
else
{
_paths = new List<string>();
}
_addedPaths = new List<string>();
_dynamicPaths = new List<string>();
}
internal void Initialize( IGlobber globber )
{
_globber = globber;
}
/// <summary>
/// Gets whether or not the current operative system is 64 bit.
/// </summary>
/// <returns>
/// Whether or not the current operative system is 64 bit.
/// </returns>
[Obsolete( "Please use CakeEnvironment.Platform.Is64Bit instead." )]
public bool Is64BitOperativeSystem() => _platform.Is64Bit;
public bool IsUnix() => _platform.IsUnix();
/// <summary>
/// Gets a special path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>
/// A <see cref="DirectoryPath" /> to the special path.
/// </returns>
public DirectoryPath GetSpecialPath( SpecialPath path )
{
switch( path )
{
case SpecialPath.ApplicationData:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ) );
case SpecialPath.CommonApplicationData:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.CommonApplicationData ) );
case SpecialPath.LocalApplicationData:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ) );
case SpecialPath.ProgramFiles:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.ProgramFiles ) );
case SpecialPath.ProgramFilesX86:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.ProgramFilesX86 ) );
case SpecialPath.Windows:
return new DirectoryPath( Environment.GetFolderPath( Environment.SpecialFolder.Windows ) );
case SpecialPath.LocalTemp:
return new DirectoryPath( System.IO.Path.GetTempPath() );
}
const string format = "The special path '{0}' is not supported.";
throw new NotSupportedException( string.Format( CultureInfo.InvariantCulture, format, path ) );
}
/// <summary>
/// Gets the application root path.
/// </summary>
/// <value>The application root path.</value>
public DirectoryPath ApplicationRoot => _applicationRoot;
[Obsolete( "Please use CakeEnvironment.ApplicationRoot instead." )]
public DirectoryPath GetApplicationRoot()
{
var path = System.IO.Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
return new DirectoryPath( path );
}
/// <summary>
/// Gets an environment variable.
/// </summary>
/// <param name="variable">The variable.</param>
/// <returns>
/// The value of the environment variable.
/// </returns>
public string GetEnvironmentVariable( string variable )
{
if( StringComparer.OrdinalIgnoreCase.Equals( variable, "PATH" ) ) return string.Join( _platform.IsUnix() ? ":" : ";", FinalEnvironmentPaths );
return Environment.GetEnvironmentVariable( variable );
}
/// <summary>
/// Gets a list of paths in PATH environement variable.
/// When getting the PATH variable with <see cref="GetEnvironmentVariable"/>, the <see cref="FinalEnvironmentPaths"/> is returned as a joined string.
/// </summary>
public IReadOnlyList<string> EnvironmentPaths
{
get { return _paths; }
}
/// <summary>
/// Gets a list of paths added via <see cref="AddPath(EnvironmentAddedPath)"/>.
/// When getting the PATH variable with <see cref="GetEnvironmentVariable"/>, the <see cref="FinalEnvironmentPaths"/> is returned as a joined string.
/// </summary>
public IList<string> EnvironmentAddedPaths
{
get { return _addedPaths; }
}
/// <summary>
/// Gets a list of dynamic paths added via <see cref="AddPath"/>.
/// When getting the PATH variable with <see cref="GetEnvironmentVariable"/>, the <see cref="FinalEnvironmentPaths"/> is returned as a joined string.
/// </summary>
public IReadOnlyList<string> EnvironmentDynamicPaths
{
get { return _dynamicPaths; }
}
/// <summary>
/// Get the final environment paths: it is the <see cref="EnvironmentPaths"/>, the <see cref="EnvironmentAddedPaths"/>
/// and the <see cref="ExistingPathsFromDynamicPaths"/>.
/// </summary>
public IEnumerable<string> FinalEnvironmentPaths => _paths.Concat(_addedPaths ).Concat( ExistingPathsFromDynamicPaths );
/// <summary>
/// Adds a path to <see cref="EnvironmentAddedPaths"/> or <see cref="EnvironmentDynamicPaths"/>.
/// </summary>
/// <param name="p">The path to add.</param>
public void AddPath( EnvironmentAddedPath p )
{
if( p.IsDynamicPattern )
{
if( !_dynamicPaths.Contains( p.Path ) ) _dynamicPaths.Add( p.Path );
}
else
{
string expansed = Environment.ExpandEnvironmentVariables( p.Path );
foreach( var final in _globber.GetDirectories( expansed ).Select( d => d.FullPath ) )
{
if( !_addedPaths.Contains( final ) ) _addedPaths.Add( final );
}
}
}
/// <summary>
/// Gets the existing paths defined by <see cref="EnvironmentDynamicPaths"/>.
/// </summary>
public IEnumerable<string> ExistingPathsFromDynamicPaths => _dynamicPaths.SelectMany( p => _globber.GetDirectories( Environment.ExpandEnvironmentVariables( p ) ).Select( d => d.FullPath ) );
/// <summary>
/// Gets the platform Cake is running on.
/// </summary>
/// <value>The platform Cake is running on.</value>
public ICakePlatform Platform => _platform;
/// <summary>
/// Gets the runtime Cake is running in.
/// </summary>
/// <value>The runtime Cake is running in.</value>
public ICakeRuntime Runtime => _runtime;
private static void SetWorkingDirectory( DirectoryPath path )
{
if( path.IsRelative )
{
throw new CakeException( "Working directory can not be set to a relative path." );
}
Environment.CurrentDirectory = path.FullPath;
}
/// <summary>
/// Gets all environment variables.
/// </summary>
/// <returns>The environment variables as IDictionary<string, string> </returns>
public IDictionary<string, string> GetEnvironmentVariables()
{
return Environment.GetEnvironmentVariables()
.Cast<System.Collections.DictionaryEntry>()
.Select( e => StringComparer.OrdinalIgnoreCase.Equals( e.Key, "PATH" )
? new System.Collections.DictionaryEntry( e.Key, GetEnvironmentVariable( "PATH" ) )
: e )
.ToDictionary(
key => (string)key.Key,
value => value.Value as string,
StringComparer.OrdinalIgnoreCase );
}
}
}
| |
// 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 Microsoft.Azure.Management.Relay
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NamespacesOperations operations.
/// </summary>
public partial interface INamespacesOperations
{
/// <summary>
/// Check the give namespace name availability.
/// </summary>
/// <param name='parameters'>
/// Parameters to check availability of the given namespace name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<CheckNameAvailabilityResult>> CheckNameAvailabilityMethodWithHttpMessagesAsync(CheckNameAvailability parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the available namespaces within the subscription
/// irrespective of the resourceGroups.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the available namespaces within the ResourceGroup.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create Azure Relay namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, RelayNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated resources under the namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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 namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the description for the specified namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='parameters'>
/// Parameters for updating a namespace resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, RelayUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates an authorization rule for a namespace
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// The authorization rule parameters
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rule for a namespace by name.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Primary and Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the Primary or Secondary ConnectionStrings to the
/// namespace
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create Azure Relay namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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<RelayNamespace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, RelayNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing namespace. This operation also removes all
/// associated resources under the namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The Namespace Name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// 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 namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the available namespaces within the subscription
/// irrespective of the resourceGroups.
/// </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="ErrorResponseException">
/// 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<RelayNamespace>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the available namespaces within the ResourceGroup.
/// </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="ErrorResponseException">
/// 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<RelayNamespace>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a namespace.
/// </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="ErrorResponseException">
/// 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<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ProtectionPoliciesOperations operations.
/// </summary>
internal partial class ProtectionPoliciesOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectionPoliciesOperations
{
/// <summary>
/// Initializes a new instance of the ProtectionPoliciesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ProtectionPoliciesOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides the details of the backup policies associated to Recovery
/// Services Vault. This is an asynchronous operation. Status of the
/// operation can be fetched using GetPolicyOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='policyName'>
/// Backup policy information to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ProtectionPolicyResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (policyName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyName");
}
string apiVersion = "2016-06-01";
// 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("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("policyName", policyName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{policyName}", System.Uri.EscapeDataString(policyName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ProtectionPolicyResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectionPolicyResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or modifies a backup policy. This is an asynchronous operation.
/// Status of the operation can be fetched using GetPolicyOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='policyName'>
/// Backup policy to be created.
/// </param>
/// <param name='resourceProtectionPolicy'>
/// resource backup policy
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ProtectionPolicyResource>> CreateOrUpdateWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, ProtectionPolicyResource resourceProtectionPolicy, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (policyName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyName");
}
if (resourceProtectionPolicy == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceProtectionPolicy");
}
string apiVersion = "2016-06-01";
// 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("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("policyName", policyName);
tracingParameters.Add("resourceProtectionPolicy", resourceProtectionPolicy);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{policyName}", System.Uri.EscapeDataString(policyName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceProtectionPolicy != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceProtectionPolicy, 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");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ProtectionPolicyResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectionPolicyResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes specified backup policy from your Recovery Services Vault. This is
/// an asynchronous operation. Status of the operation can be fetched using
/// GetPolicyOperationResult API.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='policyName'>
/// Backup policy to be deleted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string vaultName, string resourceGroupName, string policyName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (policyName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "policyName");
}
string apiVersion = "2016-06-01";
// 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("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("policyName", policyName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies/{policyName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{policyName}", System.Uri.EscapeDataString(policyName));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ProtectionPolicyResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<ProtectionPolicyQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ProtectionPolicyQueryObject>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-06-01";
// 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("odataQuery", odataQuery);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupPolicies").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_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>
/// Lists of backup policies associated with Recovery Services Vault. API
/// provides pagination parameters to fetch scoped results.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ProtectionPolicyResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<ProtectionPolicyResource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ProtectionPolicyResource>>(_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 file="CriteriaBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Base type from which Criteria classes can be</summary>
//-----------------------------------------------------------------------
using System;
using Csla.Serialization.Mobile;
using Csla.Core;
using System.ComponentModel;
using System.Linq.Expressions;
using Csla.Reflection;
using System.Reflection;
namespace Csla
{
/// <summary>
/// Base type from which Criteria classes can be
/// derived in a business class.
/// </summary>
[Serializable]
public abstract class CriteriaBase<T> : ManagedObjectBase
where T : CriteriaBase<T>
{
/// <summary>
/// Initializes empty CriteriaBase. The type of
/// business object to be created by the DataPortal
/// MUST be supplied by the subclass.
/// </summary>
protected CriteriaBase()
{ }
#region Register Properties
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">
/// Type of property.
/// </typeparam>
/// <param name="info">
/// PropertyInfo object for the property.
/// </param>
/// <returns>
/// The provided IPropertyInfo object.
/// </returns>
protected static PropertyInfo<P> RegisterProperty<P>(PropertyInfo<P> info)
{
return Core.FieldManager.PropertyInfoManager.RegisterProperty<P>(typeof(T), info);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
[Obsolete]
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, P defaultValue)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, reflectedPropertyInfo.Name, defaultValue));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="relationship">Relationship with
/// referenced object.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, RelationshipTypes relationship)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, string.Empty, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="relationship">Relationship with
/// referenced object.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name, relationship);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="relationship">Relationship with
/// referenced object.</param>
/// <returns></returns>
[Obsolete]
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, friendlyName, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue);
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyName">Property name from nameof()</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <param name="relationship">Relationship with
/// referenced object.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue, RelationshipTypes relationship)
{
return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue, relationship));
}
/// <summary>
/// Indicates that the specified property belongs
/// to the business object type.
/// </summary>
/// <typeparam name="P">Type of property</typeparam>
/// <param name="propertyLambdaExpression">Property Expression</param>
/// <param name="friendlyName">Friendly description for a property to be used in databinding</param>
/// <param name="defaultValue">Default Value for the property</param>
/// <param name="relationship">Relationship with
/// referenced object.</param>
/// <returns></returns>
protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue, RelationshipTypes relationship)
{
PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression);
return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue, relationship);
}
#endregion
}
}
| |
// [Twin] Copyright eBay Inc., Twin authors, and other contributors.
// This file is provided to you under the terms of the Apache License, Version 2.0.
// See LICENSE.txt and NOTICE.txt for license and copyright information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Automation;
using System.Windows;
using System.Windows.Forms;
using Twin.Proxy;
namespace Twin.Model {
class Element : IDisposable, IJSONProperties {
AutomationElement element;
int processId; // needed for scoping children
public AutomationElement AutomationElement {
get {
return element;
}
}
private object Pattern(AutomationPattern pattern) {
try {
return element.GetCurrentPattern(pattern);
} catch (InvalidOperationException e) {
ControlType type = (ControlType)element.GetCurrentPropertyValue(AutomationElement.ControlTypeProperty);
throw new InvalidOperationException(type.ProgrammaticName + " does not support " + pattern.ProgrammaticName, e);
}
}
private TransformPattern TransformPattern {
get { return (TransformPattern)Pattern(TransformPattern.Pattern); }
}
private SelectionItemPattern SelectionItemPattern {
get { return (SelectionItemPattern)Pattern(SelectionItemPattern.Pattern); }
}
private WindowPattern WindowPattern {
get { return (WindowPattern)Pattern(WindowPattern.Pattern); }
}
private InvokePattern InvokePattern {
get { return (InvokePattern)Pattern(InvokePattern.Pattern); }
}
private ExpandCollapsePattern ExpandCollapsePattern {
get { return (ExpandCollapsePattern)Pattern(ExpandCollapsePattern.Pattern); }
}
private TogglePattern TogglePattern {
get { return (TogglePattern)Pattern(TogglePattern.Pattern); }
}
private ValuePattern ValuePattern {
get { return (ValuePattern)Pattern(ValuePattern.Pattern); }
}
private ScrollPattern ScrollPattern {
get { return (ScrollPattern)Pattern(ScrollPattern.Pattern); }
}
public static Element Create(AutomationElement element, int processId) {
AutomationElement.AutomationElementInformation current = element.Current;
if (current.NativeWindowHandle != 0 && current.ControlType == ControlType.Window)
return new NativeElement(element, processId);
return new Element(element, processId);
}
protected Element(AutomationElement element, int processId) {
this.processId = processId;
this.element = element;
}
// threadsafe
private object this[AutomationProperty property] {
get {
return STAHelper.Invoke(
delegate() {
return element.GetCurrentPropertyValue(property);
}
);
}
}
public string Id {
get {
string id = (string)this[AutomationElement.AutomationIdProperty];
return (id.Length == 0) ? null : id;
}
}
public string Class {
get {
string className = (string)this[AutomationElement.ClassNameProperty];
return (className.Length == 0) ? null : className;
}
}
public bool Enabled {
get {
return (bool)this[AutomationElement.IsEnabledProperty];
}
}
public bool Expanded {
get {
ExpandCollapseState state = (ExpandCollapseState)this[ExpandCollapsePattern.ExpandCollapseStateProperty];
return (state == ExpandCollapseState.Expanded || state == ExpandCollapseState.PartiallyExpanded);
}
set {
STAHelper.Invoke(
delegate() {
if (value) {
ExpandCollapseState state = (ExpandCollapseState)element.GetCurrentPropertyValue(ExpandCollapsePattern.ExpandCollapseStateProperty);
if (state == ExpandCollapseState.LeafNode) { // Expand() will throw, but some poorly-coded apps use 'fake' internal nodes - actually leaves with a graphic
this.Focus();
SendKeys.SendWait("{RIGHT}");
state = (ExpandCollapseState)element.GetCurrentPropertyValue(ExpandCollapsePattern.ExpandCollapseStateProperty);
if (state == ExpandCollapseState.LeafNode) {
throw new InvalidOperationException("Cannot expand a leaf node (tried to focus it and type {RIGHT}, but no effect)");
}
} else {
ExpandCollapsePattern.Expand();
}
} else {
if (Expanded)
ExpandCollapsePattern.Collapse();
}
}
);
}
}
public string Name {
get {
string name = (string)this[AutomationElement.NameProperty];
return (name.Length == 0) ? null : name;
}
}
public string Value {
get {
return (string)this[ValuePattern.ValueProperty];
}
set {
STAHelper.Invoke(
delegate() {
ValuePattern.SetValue(value);
}
);
}
}
public bool IsValueReadOnly() {
return (bool)this[ValuePattern.IsReadOnlyProperty];
}
public ControlType ControlType {
get {
return (ControlType)this[AutomationElement.ControlTypeProperty];
}
}
public virtual string ControlTypeName {
get {
return NameMappings.GetName(ControlType);
}
}
public virtual Rect Bounds {
get {
return (Rect)this[AutomationElement.BoundingRectangleProperty];
}
set {
Location = value.Location;
Size = value.Size;
}
}
public Point Location {
get {
return Bounds.Location;
}
set {
STAHelper.Invoke(
delegate() {
TransformPattern.Move(value.X, value.Y);
}
);
}
}
public Size Size {
get {
return Bounds.Size;
}
set {
STAHelper.Invoke(
delegate() {
TransformPattern.Resize(value.Width, value.Height);
}
);
}
}
public void Close() {
STAHelper.Invoke(
delegate() {
WindowPattern.Close();
}
);
}
public void Focus() {
// run all in same thread for speed
bool focused = (bool)STAHelper.Invoke(
delegate() {
// make sure parent window is focused
if (ControlType != ControlType.Window) {
Element window = Parent;
while (window != null && window.ControlType != ControlType.Window)
window = window.Parent;
if (window != null)
window.element.SetFocus();
}
element.SetFocus();
return (bool)AutomationElement.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty);
}
);
if(!focused) {
// we can't actually fail here because some elements respond to SetFocus
// but don't accept keyboard focus.
// on the other hand sometimes the focus is async and not done yet.
// so if we're not sure we're done, sleep a little and hope it finishes
System.Threading.Thread.Sleep(100);
}
}
public Element Parent {
get {
return (Element) STAHelper.Invoke(
delegate() {
TreeWalker tWalker = TreeWalker.RawViewWalker;
AutomationElement parent = tWalker.GetParent(element);
if (parent == null || parent == element)
return null;
if (parent == AutomationElement.RootElement)
return Desktop.GetInstance(processId);
return Element.Create(parent, processId);
}
);
}
}
public List<Element> Children {
get {
return (List<Element>) STAHelper.Invoke(
delegate() {
List<AutomationElement> searchResults = AutomationExtensions.FindAllRaw(element, TreeScope.Children, new PropertyCondition2(AutomationElement.ProcessIdProperty, processId));
List<Element> result = new List<Element>();
foreach (AutomationElement e in searchResults)
result.Add(Element.Create(e, processId));
return result;
}
);
}
}
public List<Element> Selection {
get {
return (List<Element>) STAHelper.Invoke(
delegate() {
List<Element> result = new List<Element>();
AutomationElement[] elts = (AutomationElement[])this[SelectionPattern.SelectionProperty];
foreach(AutomationElement elt in elts)
result.Add(Element.Create(elt, processId));
return result;
}
);
}
}
public bool SelectionIsRequired {
get {
return (bool)this[SelectionPattern.IsSelectionRequiredProperty];
}
}
public bool SelectionAllowsMultiple {
get {
return (bool)this[SelectionPattern.CanSelectMultipleProperty];
}
}
public Element SelectionContainer {
get {
return (Element)STAHelper.Invoke(
delegate() {
AutomationElement container = (AutomationElement)this[SelectionItemPattern.SelectionContainerProperty];
return Element.Create(container, processId);
}
);
}
}
private Dictionary<OrientationType, ScrollAxis> scrollAxes = new Dictionary<OrientationType, ScrollAxis>();
public ScrollAxis GetScrollAxis(OrientationType orientation) {
return (ScrollAxis)STAHelper.Invoke(
delegate() {
if(!scrollAxes.ContainsKey(orientation)) {
object pattern;
if(AutomationElement.TryGetCurrentPattern(ScrollPattern.Pattern, out pattern)) {
scrollAxes[orientation] = new ScrollPatternAxis((ScrollPattern)pattern, orientation);
} else if(ControlType == ControlType.ScrollBar) {
if(orientation == (OrientationType)this[AutomationElement.OrientationProperty])
scrollAxes[orientation] = new ScrollBarAxis(AutomationElement);
else
throw new ArgumentException("Cannot get "+orientation+" scroll-axis for a scrollbar that is not "+orientation);
} else if (ControlType == ControlType.Pane && Class == "ScrollBar") {
scrollAxes[orientation] = new PaneScrollAxis(AutomationElement);
} else {
Condition scrollBarCondition =
new AndCondition(
new PropertyCondition2(AutomationElement.OrientationProperty, orientation),
new PropertyCondition2(AutomationElement.ControlTypeProperty, ControlType.ScrollBar)
);
Condition scrollPaneCondition =
new AndCondition(
new PropertyCondition2(AutomationElement.ControlTypeProperty, ControlType.Pane),
new PropertyCondition2(AutomationElement.ClassNameProperty, "ScrollBar")
);
Condition scrollPatternCondition = new PropertyCondition2(AutomationElement.IsScrollPatternAvailableProperty, true);
Condition condition = new OrCondition(scrollBarCondition, scrollPaneCondition, scrollPatternCondition);
List<AutomationElement> matches = Twin.View.Search.FindAll(AutomationElement, TreeScope.Descendants, 1 ,condition, (int)AutomationElement.GetCurrentPropertyValue(AutomationElement.ProcessIdProperty));
for(int i=0; i<matches.Count; i++) {
if(matches[i].GetCurrentPropertyValue(AutomationElement.ControlTypeProperty) != ControlType.Pane)
continue;
if((bool)matches[i].GetCurrentPropertyValue(AutomationElement.IsScrollPatternAvailableProperty))
continue;
Rect bounds = (Rect)matches[i].GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
if(orientation == OrientationType.Horizontal && bounds.Height > bounds.Width)
matches.RemoveAt(i--);
if(orientation == OrientationType.Vertical && bounds.Width > bounds.Height)
matches.RemoveAt(i--);
}
if (matches.Count == 0)
return null;
if (matches.Count > 1)
throw new ArgumentException("Scrollable Axis for element ambiguous");
return Element.Create(matches[0], processId).GetScrollAxis(orientation);
}
}
return scrollAxes[orientation];
}
);
}
public NativeElement EnclosingNativeElement {
get {
if (this is NativeElement)
return (NativeElement)this;
return Parent.EnclosingNativeElement;
}
}
public System.Drawing.Bitmap CaptureScreenshot() {
Size size = this.Size;
return CaptureScreenshot(new Rect(0,0,size.Width, size.Height));
}
// overridden for native elements
public virtual System.Drawing.Bitmap CaptureScreenshot(Rect bounds) {
Element nativeParent = EnclosingNativeElement;
bounds.Location += this.Location - nativeParent.Location;
return nativeParent.CaptureScreenshot(bounds);
}
public void Click() {
try {
Invoke();
return;
} catch (InvalidOperationException) {}
try {
Toggle();
return;
} catch (InvalidOperationException) {}
try {
SelectionItemPattern.Select();
return;
} catch (InvalidOperationException) {}
try {
ExpandCollapse();
return;
} catch (InvalidOperationException) {}
Click(1);
}
public void Click(int button) {
STAHelper.Invoke(
delegate() {
Point clickable = element.GetClickablePoint(); // absolute coords
Desktop.GetInstance(processId).Click(button, clickable.X, clickable.Y);
}
);
}
public virtual void Click(int button, double x, double y) {
Point point = Location;
point.X += x;
point.Y += y;
// TODO make sure window is in front?
Desktop.GetInstance(processId).Click(button, (int)point.X, (int)point.Y);
}
public void Toggle() {
STAHelper.Invoke(
delegate() {
TogglePattern.Toggle();
}
);
}
public bool ToggleState {
get {
ToggleState state = (ToggleState)this[TogglePattern.ToggleStateProperty];
if (state == System.Windows.Automation.ToggleState.Off)
return false;
return true;
}
set {
if (ToggleState != value)
STAHelper.Invoke(delegate() { TogglePattern.Toggle(); });
}
}
public WindowVisualState WindowState {
get {
return (WindowVisualState)this[WindowPattern.WindowVisualStateProperty];
}
set {
STAHelper.Invoke(delegate() { WindowPattern.SetWindowVisualState(value); });
}
}
public bool Selected {
get {
return (bool) this[SelectionItemPattern.IsSelectedProperty];
}
set {
STAHelper.Invoke(
delegate() {
if (value) {
AutomationElement container = (AutomationElement)this[SelectionItemPattern.SelectionContainerProperty];
if ((bool)container.GetCurrentPropertyValue(SelectionPattern.CanSelectMultipleProperty))
SelectionItemPattern.AddToSelection();
else
SelectionItemPattern.Select();
} else {
SelectionItemPattern.RemoveFromSelection();
}
}
);
}
}
public void Deselect() {
STAHelper.Invoke(delegate() { SelectionItemPattern.RemoveFromSelection(); });
}
public void ExpandCollapse() {
STAHelper.Invoke(
delegate() {
ExpandCollapsePattern expandCollapse = ExpandCollapsePattern;
if (expandCollapse.Current.ExpandCollapseState == ExpandCollapseState.Collapsed)
expandCollapse.Expand();
else
expandCollapse.Collapse();
}
);
}
public void Invoke() {
STAHelper.Invoke(delegate() { InvokePattern.Invoke(); });
}
public bool Exists {
get {
try {
STAHelper.Invoke(
delegate() {
Rect rect = (Rect)element.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
if(Double.IsInfinity(rect.Top) || Double.IsNaN(rect.Top))
throw new ElementNotAvailableException();
}
);
return true;
} catch (ElementNotAvailableException) {
return false;
}
}
}
public void Dispose() {
// STAHelper.Invoke(delegate() { element.Dispose(); });
}
public void AddExtraJSONProperties(IDictionary<string,object> values) {
values["name"] = Name;
values["id"] = Id;
values["controlType"] = ControlTypeName;
values["className"] = Class;
values["controlPatterns"] = STAHelper.Invoke(
delegate() {
List<object> controlPatterns = new List<object>();
foreach (AutomationPattern pattern in element.GetSupportedPatterns()) {
string name = NameMappings.GetName(pattern);
if(name != null)
controlPatterns.Add(name);
}
return controlPatterns;
}
);
}
// don't think equality/hashcode need to be run in STA thread...
public override int GetHashCode() {
return element.GetHashCode();
}
public override bool Equals(object other) {
return (other is Element) && (element == ((Element)other).element);
}
public static bool operator ==(Element first, Element second) {
return first.Equals(second);
}
public static bool operator !=(Element first, Element second) {
return !first.Equals(second);
}
}
}
| |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#pragma warning disable 0219
namespace nanoFramework.Tools.VisualStudio.Extension.Serialization.PdbxFile
{
public class XmlSerializationWriterPdbxFile : System.Xml.Serialization.XmlSerializationWriter
{
public void Write12_PdbxFile(object o)
{
WriteStartDocument();
if (o == null)
{
WriteNullTagLiteral(@"PdbxFile", @"");
return;
}
TopLevelElement();
Write11_PdbxFile(@"PdbxFile", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)o), true, false);
}
void Write11_PdbxFile(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"PdbxFile", @"");
Write10_Assembly(@"Assembly", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly)o.@Assembly), false, false);
WriteEndElement(o);
}
void Write10_Assembly(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"Assembly", @"");
WriteElementString(@"FileName", @"", ((global::System.String)o.@FileName));
Write2_VersionStruct(@"Version", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct)o.@Version), false);
Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false);
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])o.@Classes);
if (a != null)
{
WriteStartElement(@"Classes", @"", null, false);
for (int ia = 0; ia < a.Length; ia++)
{
Write9_Class(@"Class", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class)a[ia]), true, false);
}
WriteEndElement();
}
}
WriteEndElement(o);
}
void Write9_Class(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"Class", @"");
Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false);
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])o.@Fields);
if (a != null)
{
WriteStartElement(@"Fields", @"", null, false);
for (int ia = 0; ia < a.Length; ia++)
{
Write6_Field(@"Field", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field)a[ia]), true, false);
}
WriteEndElement();
}
}
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])o.@Methods);
if (a != null)
{
WriteStartElement(@"Methods", @"", null, false);
for (int ia = 0; ia < a.Length; ia++)
{
Write8_Method(@"Method", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method)a[ia]), true, false);
}
WriteEndElement();
}
}
WriteEndElement(o);
}
void Write8_Method(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"Method", @"");
Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false);
WriteElementStringRaw(@"HasByteCode", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@HasByteCode)));
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])o.@ILMap);
if (a != null)
{
WriteStartElement(@"ILMap", @"", null, false);
for (int ia = 0; ia < a.Length; ia++)
{
Write7_IL(@"IL", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL)a[ia]), true, false);
}
WriteEndElement();
}
}
WriteEndElement(o);
}
void Write7_IL(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"IL", @"");
WriteElementString(@"CLR", @"", ((global::System.String)o.@CLR_String));
WriteElementString(@"nanoCLR", @"", ((global::System.String)o.@nanoCLR_String));
WriteEndElement(o);
}
void Write4_Token(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"Token", @"");
WriteElementString(@"CLR", @"", ((global::System.String)o.@CLR_String));
WriteElementString(@"nanoCLR", @"", ((global::System.String)o.@nanoCLR_String));
WriteEndElement(o);
}
void Write6_Field(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field o, bool isNullable, bool needType)
{
if ((object)o == null)
{
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"Field", @"");
Write4_Token(@"Token", @"", ((global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token)o.@Token), false, false);
WriteEndElement(o);
}
void Write2_VersionStruct(string n, string ns, global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct o, bool needType)
{
if (!needType)
{
System.Type t = o.GetType();
if (t == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct))
{
}
else
{
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"VersionStruct", @"");
WriteElementStringRaw(@"Major", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Major)));
WriteElementStringRaw(@"Minor", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Minor)));
WriteElementStringRaw(@"Build", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Build)));
WriteElementStringRaw(@"Revision", @"", System.Xml.XmlConvert.ToString((global::System.UInt16)((global::System.UInt16)o.@Revision)));
WriteEndElement(o);
}
protected override void InitCallbacks()
{
}
}
public class XmlSerializationReaderPdbxFile : System.Xml.Serialization.XmlSerializationReader
{
public object Read12_PdbxFile()
{
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)id1_PdbxFile && (object)Reader.NamespaceURI == (object)id2_Item))
{
o = Read11_PdbxFile(true, true);
}
else
{
throw CreateUnknownNodeException();
}
}
else
{
UnknownNode(null, @":PdbxFile");
}
return (object)o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile Read11_PdbxFile(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id1_PdbxFile && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile();
bool[] paramsRead = new bool[1];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations0 = 0;
int readerCount0 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id3_Assembly && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Assembly = Read10_Assembly(false, true);
paramsRead[0] = true;
}
else
{
UnknownNode((object)o, @":Assembly");
}
}
else
{
UnknownNode((object)o, @":Assembly");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations0, ref readerCount0);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly Read10_Assembly(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id3_Assembly && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly();
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a_3 = null;
int ca_3 = 0;
bool[] paramsRead = new bool[4];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations1 = 0;
int readerCount1 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id4_FileName && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@FileName = Reader.ReadElementString();
}
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id5_Version && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Version = Read2_VersionStruct(true);
paramsRead[1] = true;
}
else if (!paramsRead[2] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Token = Read4_Token(false, true);
paramsRead[2] = true;
}
else if (((object)Reader.LocalName == (object)id7_Classes && (object)Reader.NamespaceURI == (object)id2_Item))
{
if (!ReadNull())
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[] a_3_0 = null;
int ca_3_0 = 0;
if ((Reader.IsEmptyElement))
{
Reader.Skip();
}
else
{
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations2 = 0;
int readerCount2 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)id8_Class && (object)Reader.NamespaceURI == (object)id2_Item))
{
a_3_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])EnsureArrayIndex(a_3_0, ca_3_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class)); a_3_0[ca_3_0++] = Read9_Class(true, true);
}
else
{
UnknownNode(null, @":Class");
}
}
else
{
UnknownNode(null, @":Class");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations2, ref readerCount2);
}
ReadEndElement();
}
o.@Classes = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class[])ShrinkArray(a_3_0, ca_3_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class), false);
}
}
else
{
UnknownNode((object)o, @":FileName, :Version, :Token, :Classes");
}
}
else
{
UnknownNode((object)o, @":FileName, :Version, :Token, :Classes");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations1, ref readerCount1);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class Read9_Class(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id8_Class && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Class();
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a_1 = null;
int ca_1 = 0;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a_2 = null;
int ca_2 = 0;
bool[] paramsRead = new bool[3];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations3 = 0;
int readerCount3 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Token = Read4_Token(false, true);
paramsRead[0] = true;
}
else if (((object)Reader.LocalName == (object)id9_Fields && (object)Reader.NamespaceURI == (object)id2_Item))
{
if (!ReadNull())
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[] a_1_0 = null;
int ca_1_0 = 0;
if ((Reader.IsEmptyElement))
{
Reader.Skip();
}
else
{
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations4 = 0;
int readerCount4 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)id10_Field && (object)Reader.NamespaceURI == (object)id2_Item))
{
a_1_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field)); a_1_0[ca_1_0++] = Read6_Field(true, true);
}
else
{
UnknownNode(null, @":Field");
}
}
else
{
UnknownNode(null, @":Field");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations4, ref readerCount4);
}
ReadEndElement();
}
o.@Fields = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field[])ShrinkArray(a_1_0, ca_1_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field), false);
}
}
else if (((object)Reader.LocalName == (object)id11_Methods && (object)Reader.NamespaceURI == (object)id2_Item))
{
if (!ReadNull())
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[] a_2_0 = null;
int ca_2_0 = 0;
if ((Reader.IsEmptyElement))
{
Reader.Skip();
}
else
{
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations5 = 0;
int readerCount5 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)id12_Method && (object)Reader.NamespaceURI == (object)id2_Item))
{
a_2_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method)); a_2_0[ca_2_0++] = Read8_Method(true, true);
}
else
{
UnknownNode(null, @":Method");
}
}
else
{
UnknownNode(null, @":Method");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations5, ref readerCount5);
}
ReadEndElement();
}
o.@Methods = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method[])ShrinkArray(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method), false);
}
}
else
{
UnknownNode((object)o, @":Token, :Fields, :Methods");
}
}
else
{
UnknownNode((object)o, @":Token, :Fields, :Methods");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations3, ref readerCount3);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method Read8_Method(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id12_Method && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Method();
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a_2 = null;
int ca_2 = 0;
bool[] paramsRead = new bool[3];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations6 = 0;
int readerCount6 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Token = Read4_Token(false, true);
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id13_HasByteCode && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@HasByteCode = System.Xml.XmlConvert.ToBoolean(Reader.ReadElementString());
}
paramsRead[1] = true;
}
else if (((object)Reader.LocalName == (object)id14_ILMap && (object)Reader.NamespaceURI == (object)id2_Item))
{
if (!ReadNull())
{
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[] a_2_0 = null;
int ca_2_0 = 0;
if ((Reader.IsEmptyElement))
{
Reader.Skip();
}
else
{
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations7 = 0;
int readerCount7 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (((object)Reader.LocalName == (object)id15_IL && (object)Reader.NamespaceURI == (object)id2_Item))
{
a_2_0 = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL)); a_2_0[ca_2_0++] = Read7_IL(true, true);
}
else
{
UnknownNode(null, @":IL");
}
}
else
{
UnknownNode(null, @":IL");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations7, ref readerCount7);
}
ReadEndElement();
}
o.@ILMap = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL[])ShrinkArray(a_2_0, ca_2_0, typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL), false);
}
}
else
{
UnknownNode((object)o, @":Token, :HasByteCode, :ILMap");
}
}
else
{
UnknownNode((object)o, @":Token, :HasByteCode, :ILMap");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations6, ref readerCount6);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL Read7_IL(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id15_IL && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.IL();
bool[] paramsRead = new bool[2];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations8 = 0;
int readerCount8 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id16_CLR && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@CLR_String = Reader.ReadElementString();
}
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id17_nanoCLR && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@nanoCLR_String = Reader.ReadElementString();
}
paramsRead[1] = true;
}
else
{
UnknownNode((object)o, @":CLR, :nanoCLR");
}
}
else
{
UnknownNode((object)o, @":CLR, :nanoCLR");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations8, ref readerCount8);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token Read4_Token(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id6_Token && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Token();
bool[] paramsRead = new bool[2];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations9 = 0;
int readerCount9 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id16_CLR && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@CLR_String = Reader.ReadElementString();
}
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id17_nanoCLR && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@nanoCLR_String = Reader.ReadElementString();
}
paramsRead[1] = true;
}
else
{
UnknownNode((object)o, @":CLR, :nanoCLR");
}
}
else
{
UnknownNode((object)o, @":CLR, :nanoCLR");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations9, ref readerCount9);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field Read6_Field(bool isNullable, bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id10_Field && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field o;
o = new global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Field();
bool[] paramsRead = new bool[1];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations10 = 0;
int readerCount10 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id6_Token && (object)Reader.NamespaceURI == (object)id2_Item))
{
o.@Token = Read4_Token(false, true);
paramsRead[0] = true;
}
else
{
UnknownNode((object)o, @":Token");
}
}
else
{
UnknownNode((object)o, @":Token");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations10, ref readerCount10);
}
ReadEndElement();
return o;
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct Read2_VersionStruct(bool checkType)
{
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (checkType)
{
if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)id18_VersionStruct && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item))
{
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct o;
try
{
o = (global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct)System.Activator.CreateInstance(typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct), System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.NonPublic, null, new object[0], null);
}
catch (System.MissingMethodException)
{
throw CreateInaccessibleConstructorException(@"global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct");
}
catch (System.Security.SecurityException)
{
throw CreateCtorHasSecurityException(@"global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.Assembly.VersionStruct");
}
bool[] paramsRead = new bool[4];
while (Reader.MoveToNextAttribute())
{
if (!IsXmlnsAttribute(Reader.Name))
{
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement)
{
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations11 = 0;
int readerCount11 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None)
{
if (Reader.NodeType == System.Xml.XmlNodeType.Element)
{
if (!paramsRead[0] && ((object)Reader.LocalName == (object)id19_Major && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@Major = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object)Reader.LocalName == (object)id20_Minor && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@Minor = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
paramsRead[1] = true;
}
else if (!paramsRead[2] && ((object)Reader.LocalName == (object)id21_Build && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@Build = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
paramsRead[2] = true;
}
else if (!paramsRead[3] && ((object)Reader.LocalName == (object)id22_Revision && (object)Reader.NamespaceURI == (object)id2_Item))
{
{
o.@Revision = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString());
}
paramsRead[3] = true;
}
else
{
UnknownNode((object)o, @":Major, :Minor, :Build, :Revision");
}
}
else
{
UnknownNode((object)o, @":Major, :Minor, :Build, :Revision");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations11, ref readerCount11);
}
ReadEndElement();
return o;
}
protected override void InitCallbacks()
{
}
string id17_nanoCLR;
string id9_Fields;
string id13_HasByteCode;
string id18_VersionStruct;
string id14_ILMap;
string id5_Version;
string id22_Revision;
string id10_Field;
string id8_Class;
string id19_Major;
string id12_Method;
string id6_Token;
string id2_Item;
string id20_Minor;
string id1_PdbxFile;
string id15_IL;
string id21_Build;
string id7_Classes;
string id3_Assembly;
string id16_CLR;
string id11_Methods;
string id4_FileName;
protected override void InitIDs()
{
id17_nanoCLR = Reader.NameTable.Add(@"nanoCLR");
id9_Fields = Reader.NameTable.Add(@"Fields");
id13_HasByteCode = Reader.NameTable.Add(@"HasByteCode");
id18_VersionStruct = Reader.NameTable.Add(@"VersionStruct");
id14_ILMap = Reader.NameTable.Add(@"ILMap");
id5_Version = Reader.NameTable.Add(@"Version");
id22_Revision = Reader.NameTable.Add(@"Revision");
id10_Field = Reader.NameTable.Add(@"Field");
id8_Class = Reader.NameTable.Add(@"Class");
id19_Major = Reader.NameTable.Add(@"Major");
id12_Method = Reader.NameTable.Add(@"Method");
id6_Token = Reader.NameTable.Add(@"Token");
id2_Item = Reader.NameTable.Add(@"");
id20_Minor = Reader.NameTable.Add(@"Minor");
id1_PdbxFile = Reader.NameTable.Add(@"PdbxFile");
id15_IL = Reader.NameTable.Add(@"IL");
id21_Build = Reader.NameTable.Add(@"Build");
id7_Classes = Reader.NameTable.Add(@"Classes");
id3_Assembly = Reader.NameTable.Add(@"Assembly");
id16_CLR = Reader.NameTable.Add(@"CLR");
id11_Methods = Reader.NameTable.Add(@"Methods");
id4_FileName = Reader.NameTable.Add(@"FileName");
}
}
public abstract class XmlSerializer1 : System.Xml.Serialization.XmlSerializer
{
protected override System.Xml.Serialization.XmlSerializationReader CreateReader()
{
return new XmlSerializationReaderPdbxFile();
}
protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter()
{
return new XmlSerializationWriterPdbxFile();
}
}
public sealed class PdbxFileSerializer : XmlSerializer1
{
public override System.Boolean CanDeserialize(System.Xml.XmlReader xmlReader)
{
return xmlReader.IsStartElement(@"PdbxFile", @"");
}
protected override void Serialize(object o, System.Xml.Serialization.XmlSerializationWriter writer)
{
((XmlSerializationWriterPdbxFile)writer).Write12_PdbxFile(o);
}
protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader)
{
return ((XmlSerializationReaderPdbxFile)reader).Read12_PdbxFile();
}
}
public class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation
{
public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReaderPdbxFile(); } }
public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriterPdbxFile(); } }
System.Collections.Hashtable readMethods = null;
public override System.Collections.Hashtable ReadMethods
{
get
{
if (readMethods == null)
{
System.Collections.Hashtable _tmp = new System.Collections.Hashtable();
_tmp[@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::"] = @"Read12_PdbxFile";
if (readMethods == null) readMethods = _tmp;
}
return readMethods;
}
}
System.Collections.Hashtable writeMethods = null;
public override System.Collections.Hashtable WriteMethods
{
get
{
if (writeMethods == null)
{
System.Collections.Hashtable _tmp = new System.Collections.Hashtable();
_tmp[@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::"] = @"Write12_PdbxFile";
if (writeMethods == null) writeMethods = _tmp;
}
return writeMethods;
}
}
System.Collections.Hashtable typedSerializers = null;
public override System.Collections.Hashtable TypedSerializers
{
get
{
if (typedSerializers == null)
{
System.Collections.Hashtable _tmp = new System.Collections.Hashtable();
_tmp.Add(@"nanoFramework.Tools.VisualStudio.Extension.Pdbx+PdbxFile::", new PdbxFileSerializer());
if (typedSerializers == null) typedSerializers = _tmp;
}
return typedSerializers;
}
}
public override System.Boolean CanSerialize(System.Type type)
{
if (type == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)) return true;
return false;
}
public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type)
{
if (type == typeof(global::nanoFramework.Tools.VisualStudio.Extension.Pdbx.PdbxFile)) return new PdbxFileSerializer();
return null;
}
}
}
#pragma warning restore 0219
| |
//
// thread6.cs: Thread abort tests
//
using System;
using System.Threading;
public class Tests {
public static int result = 0;
public static object started = new object ();
public static void ThreadStart1 () {
Console.WriteLine("{0} started",
Thread.CurrentThread.Name);
try {
try {
try {
lock (started) {
Monitor.Pulse (started);
}
int i = 0;
try {
while (true) {
Console.WriteLine ("Count: " + i++);
Thread.Sleep (100);
}
}
catch (ThreadAbortException e) {
Console.WriteLine ("cought exception level 3 ");
// Check that the exception is only rethrown in
// the appropriate catch clauses
// This doesn't work currently, see
// http://bugzilla.ximian.com/show_bug.cgi?id=68552
/*
try {
}
catch {}
try {
throw new DivideByZeroException ();
}
catch (Exception) {
}
*/
result |= 32;
// Check that the exception is properly rethrown
}
result = 255;
} catch (ThreadAbortException e) {
Console.WriteLine ("cought exception level 2 " + e.ExceptionState);
Console.WriteLine (e);
if ((string)e.ExceptionState == "STATETEST")
result |= 1;
Thread.ResetAbort ();
throw e;
}
} catch (ThreadAbortException e) {
Console.WriteLine ("cought exception level 1 " + e.ExceptionState);
Console.WriteLine (e);
if (e.ExceptionState == null)
result |= 2;
}
} catch (Exception e) {
Console.WriteLine ("cought exception level 0")
; Console.WriteLine (e);
Console.WriteLine (e.StackTrace);
result |= 4;
}
try {
Thread.ResetAbort ();
} catch (System.Threading.ThreadStateException e) {
result |= 8;
}
Console.WriteLine ("end");
result |= 16;
}
static string regress_78024 ()
{
try {
Thread.CurrentThread.Abort ();
} catch (Exception e) {
return "Got exception: " + e.Message;
} finally {
}
return "";
}
public static int Main() {
return TestDriver.RunTests (typeof (Tests));
}
public static int test_0_abort_current () {
// Check aborting the current thread
bool aborted = false;
try {
Thread.CurrentThread.Abort ();
}
catch {
aborted = true;
Thread.ResetAbort ();
}
if (!aborted)
return 2;
return 0;
}
public static int test_0_test_1 () {
Thread t1 = null;
lock (started) {
t1 = new Thread(new ThreadStart
(Tests.ThreadStart1));
t1.Name = "Thread 1";
Thread.Sleep (100);
t1.Start();
Monitor.Wait (started);
}
Thread.Sleep (100);
t1.Abort ("STATETEST");
t1.Join ();
if (result != 59) {
Console.WriteLine ("Result: " + result);
return 1;
}
return 0;
}
public static int test_0_regress_68552 () {
try {
try {
Run ();
} catch (Exception ex) {
}
return 2;
}
catch (ThreadAbortException ex) {
Thread.ResetAbort ();
}
return 0;
}
public static int test_0_regress_78024 () {
try {
regress_78024 ();
return 3;
}
catch (ThreadAbortException ex) {
Thread.ResetAbort ();
}
return 0;
}
public class CBO : ContextBoundObject {
public void Run () {
Thread.CurrentThread.Abort ("FOO");
}
}
public static int test_0_regress_539394 () {
// Check that a ThreadAbortException thrown through remoting retains its
// abort state
AppDomain d = AppDomain.CreateDomain ("test");
CBO obj = (CBO)d.CreateInstanceFromAndUnwrap (typeof (Tests).Assembly.Location, "Tests/CBO");
bool success = false;
Thread t = new Thread (delegate () {
try {
obj.Run ();
} catch (ThreadAbortException ex) {
if ((string)ex.ExceptionState == "FOO")
success = true;
}
});
t.Start ();
t.Join ();
return success ? 0 : 1;
}
public static int test_0_regress_4413 () {
// Check that thread abort exceptions originating in another thread are not automatically rethrown
object o = new object ();
Thread t = null;
bool waiting = false;
Action a = delegate () {
t = Thread.CurrentThread;
while (true) {
lock (o) {
if (waiting) {
Monitor.Pulse (o);
break;
}
}
Thread.Sleep (10);
}
while (true) {
Thread.Sleep (1000);
}
};
var ar = a.BeginInvoke (null, null);
lock (o) {
waiting = true;
Monitor.Wait (o);
}
t.Abort ();
try {
try {
a.EndInvoke (ar);
} catch (ThreadAbortException) {
}
} catch (ThreadAbortException) {
// This will fail
Thread.ResetAbort ();
return 1;
}
return 0;
}
public static void Run ()
{
try {
Thread.CurrentThread.Abort ();
} catch (Exception ex) {
throw new Exception ("other");
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/13/2009 3:27:36 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace DotSpatial.Projections
{
public class Datum : ProjDescriptor, IEsriString
{
#region Private Variables
private const double SEC_TO_RAD = 4.84813681109535993589914102357e-6;
private DatumType _datumtype;
private string _description;
private string[] _nadGrids;
private string _name;
private Spheroid _spheroid;
private double[] _toWgs84;
private static readonly Lazy<DatumsHandler> _datumsHandler = new Lazy<DatumsHandler>(delegate
{
var dh = new DatumsHandler();
dh.Initialize();
return dh;
}, true);
#endregion Private Variables
#region Constructors
/// <summary>
/// Creates a new instance of Datum
/// </summary>
public Datum()
{
_spheroid = new Spheroid();
DatumType = DatumType.Unknown;
}
/// <summary>
/// uses a string name of a standard datum to create a new instance of the Datum class
/// </summary>
/// <param name="standardDatum">The string name of the datum to use</param>
public Datum(string standardDatum)
: this()
{
Proj4DatumName = standardDatum;
}
/// <summary>
/// Uses a Proj4Datums enumeration in order to specify a known datum to
/// define the spheroid and to WGS calculation method and parameters
/// </summary>
/// <param name="standardDatum">The Proj4Datums enumeration specifying the known datum</param>
public Datum(Proj4Datum standardDatum)
: this(standardDatum.ToString())
{
}
#endregion Constructors
#region Methods
/// <summary>
/// Returns a representation of this object as a Proj4 string.
/// </summary>
/// <returns></returns>
public string ToProj4String()
{
// if you have a datum name you don't need to say anything about the Spheroid
string str = Proj4DatumName;
if (str == null)
{
switch (DatumType)
{
case DatumType.Unknown:
case DatumType.WGS84:
break;
case DatumType.Param3:
Debug.Assert(_toWgs84.Length >= 3);
str = String.Format(CultureInfo.InvariantCulture, " +towgs84={0},{1},{2}", _toWgs84[0], _toWgs84[1], _toWgs84[2]);
break;
case DatumType.Param7:
Debug.Assert(_toWgs84.Length >= 7);
str = String.Format(CultureInfo.InvariantCulture, " +towgs84={0},{1},{2},{3},{4},{5},{6}",
_toWgs84[0],
_toWgs84[1],
_toWgs84[2],
_toWgs84[3] / SEC_TO_RAD,
_toWgs84[4] / SEC_TO_RAD,
_toWgs84[5] / SEC_TO_RAD,
(_toWgs84[6] - 1) * 1000000.0);
break;
case DatumType.GridShift:
str = String.Format(" +nadgrids={0}", String.Join(",", NadGrids));
break;
default:
throw new ArgumentOutOfRangeException("DatumType");
}
return str + Spheroid.ToProj4String();
}
else
{
return String.Format(" +datum={0}", Proj4DatumName);
}
}
/// <summary>
/// Compares two datums to see if they are actually describing the same thing and
/// therefore don't need to be transformed.
/// </summary>
/// <param name="otherDatum">The other datum to compare against</param>
/// <returns>The boolean result of the operation.</returns>
public bool Matches(Datum otherDatum)
{
if (_datumtype != otherDatum.DatumType) return false;
if (_datumtype == DatumType.WGS84) return true;
if (_spheroid.EquatorialRadius != otherDatum.Spheroid.EquatorialRadius) return false;
if (_spheroid.PolarRadius != otherDatum.Spheroid.PolarRadius) return false;
if (_datumtype == DatumType.Param3)
{
if (_toWgs84[0] != otherDatum.ToWGS84[0]) return false;
if (_toWgs84[1] != otherDatum.ToWGS84[1]) return false;
if (_toWgs84[2] != otherDatum.ToWGS84[2]) return false;
return true;
}
if (_datumtype == DatumType.Param7)
{
if (_toWgs84[0] != otherDatum.ToWGS84[0]) return false;
if (_toWgs84[1] != otherDatum.ToWGS84[1]) return false;
if (_toWgs84[2] != otherDatum.ToWGS84[2]) return false;
if (_toWgs84[3] != otherDatum.ToWGS84[3]) return false;
if (_toWgs84[4] != otherDatum.ToWGS84[4]) return false;
if (_toWgs84[5] != otherDatum.ToWGS84[5]) return false;
if (_toWgs84[6] != otherDatum.ToWGS84[6]) return false;
return true;
}
if (_datumtype == DatumType.GridShift)
{
if (_nadGrids.Length != otherDatum.NadGrids.Length) return false;
return !_nadGrids.Where((t, i) => t != otherDatum.NadGrids[i]).Any();
}
return false;
}
#endregion Methods
#region Properties
/// <summary>
/// Gets or sets the name of the datum defining the spherical characteristics of the model of the earth
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// The spheroid of the earth, defining the maximal radius and the flattening factor
/// </summary>
public Spheroid Spheroid
{
get { return _spheroid; }
set { _spheroid = value; }
}
/// <summary>
/// Gets or sets the set of double parameters, (this can either be 3 or 7 parameters)
/// used to transform this
/// </summary>
public double[] ToWGS84
{
get { return _toWgs84; }
set { _toWgs84 = value; }
}
/// <summary>
/// Gets or sets the datum type, which clarifies how to perform transforms to WGS84
/// </summary>
public DatumType DatumType
{
get { return _datumtype; }
set { _datumtype = value; }
}
/// <summary>
/// Gets or sets an english description for this datum
/// </summary>
public string Description
{
get { return _description; }
set { _description = value; }
}
/// <summary>
/// Gets or sets the array of string nadGrid
/// </summary>
public string[] NadGrids
{
get { return _nadGrids; }
set { _nadGrids = value; }
}
#endregion Properties
/// <summary>
/// Lookups the proj4 datum based on the stored name.
/// </summary>
public string Proj4DatumName
{
get
{
if (Name == null)
return null;
switch (Name)
{
case "D_WGS_1984":
return "WGS84";
case "D_Greek":
return "GGRS87";
case "D_North_American_1983":
return "NAD83";
case "D_North_American_1927":
return "NAD27";
default:
// not sure where to lookup the remaining, missing values.
// also we could include this information in the datum.xml file where much of this information resides.
return null;
}
}
set
{
string id = value.ToLower();
switch (id)
{
case "wgs84":
_toWgs84 = new double[] { 0, 0, 0 };
_spheroid = new Spheroid(Proj4Ellipsoid.WGS_1984);
_description = "WGS 1984";
_name = "D_WGS_1984";
_datumtype = DatumType.WGS84;
break;
case "ggrs87":
_toWgs84 = new[] { -199.87, 74.79, 246.62 };
_spheroid = new Spheroid(Proj4Ellipsoid.GRS_1980);
_description = "Greek Geodetic Reference System 1987";
_datumtype = DatumType.Param3;
_name = "D_Greek";
break;
case "nad83":
_toWgs84 = new double[] { 0, 0, 0 };
_spheroid = new Spheroid(Proj4Ellipsoid.GRS_1980);
_description = "North American Datum 1983";
_datumtype = DatumType.WGS84;
_name = "D_North_American_1983";
break;
case "nad27":
_nadGrids = new[] { "@conus", "@ntv1_can", "@ntv2_0", "@alaska" };
_spheroid = new Spheroid(Proj4Ellipsoid.Clarke_1866);
_description = "North American Datum 1927";
_name = "D_North_American_1927";
_datumtype = DatumType.GridShift;
break;
case "potsdam":
_toWgs84 = new[] { 606.0, 23.0, 413.0 };
_spheroid = new Spheroid(Proj4Ellipsoid.Bessel_1841);
_description = "Potsdam Rauenberg 1950 DHDN";
_datumtype = DatumType.Param3;
break;
case "carthage":
_toWgs84 = new[] { -263.0, 6, 413 };
_spheroid = new Spheroid(Proj4Ellipsoid.ClarkeModified_1880);
_description = "Carthage 1934 Tunisia";
_datumtype = DatumType.Param3;
break;
case "hermannskogel":
_toWgs84 = new[] { 653.0, -212.0, 449 };
_spheroid = new Spheroid(Proj4Ellipsoid.Bessel_1841);
_description = "Hermannskogel";
_datumtype = DatumType.Param3;
break;
case "ire65":
InitializeToWgs84(new[] { "482.530", "-130.569", "564.557", "-1.042", "-0.214", "-0.631", "8.15" });
_spheroid = new Spheroid(Proj4Ellipsoid.AiryModified);
_description = "Ireland 1965";
break;
case "nzgd49":
InitializeToWgs84(new[] { "59.47", "-5.04", "187.44", "0.47", "-0.1", "1.024", "-4.5993" });
_spheroid = new Spheroid(Proj4Ellipsoid.International_1909);
_description = "New Zealand";
break;
case "osgb36":
InitializeToWgs84(new[] { "446.448", "-125.157", "542.060", "0.1502", "0.2470", "0.8421", "-20.4894" });
_spheroid = new Spheroid(Proj4Ellipsoid.Airy_1830);
_description = "Airy 1830";
break;
}
}
}
#region IEsriString Members
/// <summary>
/// Creates an esri well known text string for the datum part of the string
/// </summary>
/// <returns>The datum portion of the esri well known text</returns>
public string ToEsriString()
{
return @"DATUM[""" + _name + @"""," + Spheroid.ToEsriString() + "]";
}
/// <summary>
/// Parses the datum from the esri string
/// </summary>
/// <param name="esriString">The string to parse values from</param>
public void ParseEsriString(string esriString)
{
if (string.IsNullOrEmpty(esriString))
return;
if (esriString.Contains("DATUM") == false) return;
int iStart = esriString.IndexOf("DATUM") + 7;
int iEnd = esriString.IndexOf(@""",", iStart) - 1;
if (iEnd < iStart) return;
_name = esriString.Substring(iStart, iEnd - iStart + 1);
var datumEntry = _datumsHandler.Value[_name];
if (datumEntry != null)
{
DatumType = datumEntry.Type;
switch (DatumType)
{
case DatumType.Param3:
{
var transform = new double[3];
transform[0] = ParseDouble(datumEntry.P1);
transform[1] = ParseDouble(datumEntry.P2);
transform[2] = ParseDouble(datumEntry.P3);
ToWGS84 = transform;
}
break;
case DatumType.Param7:
{
double[] transform = new double[7];
transform[0] = ParseDouble(datumEntry.P1);
transform[1] = ParseDouble(datumEntry.P2);
transform[2] = ParseDouble(datumEntry.P3);
transform[3] = ParseDouble(datumEntry.P4);
transform[4] = ParseDouble(datumEntry.P5);
transform[5] = ParseDouble(datumEntry.P6);
transform[6] = ParseDouble(datumEntry.P7);
ToWGS84 = transform;
break;
}
case DatumType.GridShift:
if (!string.IsNullOrEmpty(datumEntry.Shift))
{
NadGrids = datumEntry.Shift.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries);
}
break;
}
}
_spheroid.ParseEsriString(esriString);
}
private static double ParseDouble(string str)
{
if (string.IsNullOrEmpty(str)) return 0;
return double.Parse(str, CultureInfo.InvariantCulture);
}
#endregion
/// <summary>
/// Initializes to WGS84.
/// </summary>
/// <param name="values">The values.</param>
/// <exception cref="ArgumentNullException">Throws if <paramref name="values"/> is null</exception>
/// <exception cref="ArgumentOutOfRangeException">Throws if <paramref name="values"/> has length not 3 or 7.</exception>
public void InitializeToWgs84(string[] values)
{
if (values == null) throw new ArgumentNullException("values");
if (values.Length != 3 && values.Length != 7)
throw new ArgumentOutOfRangeException("values", "Unrecognized ToWgs84 array length. The number of elements in the array should be 3 or 7");
_toWgs84 = new double[values.Length];
for (int i = 0; i < values.Length; i++)
{
_toWgs84[i] = double.Parse(values[i], CultureInfo.InvariantCulture);
}
if (_toWgs84.Length == 3)
{
_datumtype = DatumType.Param3;
}
else
{
// checking to see if several blank values were included.
if (_toWgs84[3] == 0.0 && _toWgs84[4] == 0.0 && _toWgs84[5] == 0.0 && _toWgs84[6] == 0.0)
{
_datumtype = DatumType.Param3;
}
else
{
_datumtype = DatumType.Param7;
// Transform from arc seconds to radians
_toWgs84[3] *= SEC_TO_RAD;
_toWgs84[4] *= SEC_TO_RAD;
_toWgs84[5] *= SEC_TO_RAD;
// transform from parts per millon to scaling factor
_toWgs84[6] = (_toWgs84[6] / 1000000.0) + 1;
}
}
}
}
}
| |
namespace WYZTracker
{
partial class frmDockedMain
{
/// <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();
}
if (disposing)
{
//p.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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmDockedMain));
this.mainMenu = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportarAWAVToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteAsDelay = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.instrumentosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.importarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.customizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editorDeFrecuenciasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editorDeArpegiosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sfd = new System.Windows.Forms.SaveFileDialog();
this.ofd = new System.Windows.Forms.OpenFileDialog();
this.lstInstruments = new System.Windows.Forms.ListBox();
this.instrumentsContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.exportInstrumentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.instrumentsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.instrumentStrip = new System.Windows.Forms.ToolStrip();
this.newInstrument = new System.Windows.Forms.ToolStripButton();
this.deleteInstrument = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.importInstruments = new System.Windows.Forms.ToolStripButton();
this.exportInstruments = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.instrumentProperties = new System.Windows.Forms.ToolStripButton();
this.txtInstrumentName = new System.Windows.Forms.ToolStripTextBox();
this.gboxSongProperties = new System.Windows.Forms.GroupBox();
this.songProperties = new WYZTracker.SongProperties();
this.tabInstrumentsFX = new System.Windows.Forms.TabControl();
this.tabInstrumentos = new System.Windows.Forms.TabPage();
this.tabFX = new System.Windows.Forms.TabPage();
this.lstFX = new System.Windows.Forms.ListBox();
this.fxContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.exportarEfectoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.effectsBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.fxStrip = new System.Windows.Forms.ToolStrip();
this.newFX = new System.Windows.Forms.ToolStripButton();
this.deleteFX = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.importFX = new System.Windows.Forms.ToolStripButton();
this.exportFX = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.fxProperties = new System.Windows.Forms.ToolStripButton();
this.txtFXName = new System.Windows.Forms.ToolStripTextBox();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton5 = new System.Windows.Forms.ToolStripButton();
this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.nuevoToolStrip = new System.Windows.Forms.ToolStripButton();
this.abrirToolStrip = new System.Windows.Forms.ToolStripButton();
this.guardarToolStrip = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.playAllClick = new System.Windows.Forms.ToolStripButton();
this.playToolStrip = new System.Windows.Forms.ToolStripButton();
this.playPattern = new System.Windows.Forms.ToolStripButton();
this.stopToolStrip = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator();
this.addPatronToolStrip = new System.Windows.Forms.ToolStripButton();
this.removePatronToolStrip = new System.Windows.Forms.ToolStripButton();
this.clonePattern = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator();
this.importarMUS = new System.Windows.Forms.ToolStripButton();
this.exportarWYZToolStrip = new System.Windows.Forms.ToolStripButton();
this.gboxPatterns = new System.Windows.Forms.GroupBox();
this.patLength = new System.Windows.Forms.NumericUpDown();
this.patternBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.label1 = new System.Windows.Forms.Label();
this.cmdBajarPatron = new System.Windows.Forms.Button();
this.cmdSubirPatron = new System.Windows.Forms.Button();
this.cmdPreviousPattern = new System.Windows.Forms.Button();
this.cmdNextPattern = new System.Windows.Forms.Button();
this.lboxPatterns = new System.Windows.Forms.ListBox();
this.patEditor = new WYZTracker.PatternEditor();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cboEnvRatio = new System.Windows.Forms.ComboBox();
this.envelopeDataBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.cboEnvShape = new System.Windows.Forms.ComboBox();
this.chkActiveFreqs = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.toolStrip2 = new System.Windows.Forms.ToolStrip();
this.lblOctavaBase = new System.Windows.Forms.ToolStripLabel();
this.cmbOctavaBase = new System.Windows.Forms.ToolStripComboBox();
this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.incrementoAutomatico = new System.Windows.Forms.ToolStripTextBox();
this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.txtResalte = new System.Windows.Forms.ToolStripTextBox();
this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel();
this.cboStereo = new System.Windows.Forms.ToolStripComboBox();
this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel();
this.txtDecrementoDelay = new System.Windows.Forms.ToolStripTextBox();
this.mainMenu.SuspendLayout();
this.instrumentsContextMenu.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.instrumentsBindingSource)).BeginInit();
this.instrumentStrip.SuspendLayout();
this.gboxSongProperties.SuspendLayout();
this.tabInstrumentsFX.SuspendLayout();
this.tabInstrumentos.SuspendLayout();
this.tabFX.SuspendLayout();
this.fxContextMenu.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.effectsBindingSource)).BeginInit();
this.fxStrip.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.gboxPatterns.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.patLength)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.patternBindingSource)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.envelopeDataBindingSource)).BeginInit();
this.toolStrip2.SuspendLayout();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.instrumentosToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
resources.ApplyResources(this.mainMenu, "mainMenu");
this.mainMenu.Name = "mainMenu";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.exportToolStripMenuItem,
this.exportarAWAVToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// newToolStripMenuItem
//
resources.ApplyResources(this.newToolStripMenuItem, "newToolStripMenuItem");
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// openToolStripMenuItem
//
resources.ApplyResources(this.openToolStripMenuItem, "openToolStripMenuItem");
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
resources.ApplyResources(this.toolStripSeparator, "toolStripSeparator");
//
// saveToolStripMenuItem
//
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
resources.ApplyResources(this.saveAsToolStripMenuItem, "saveAsToolStripMenuItem");
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem");
this.exportToolStripMenuItem.Click += new System.EventHandler(this.exportToolStripMenuItem_Click);
//
// exportarAWAVToolStripMenuItem
//
this.exportarAWAVToolStripMenuItem.Name = "exportarAWAVToolStripMenuItem";
resources.ApplyResources(this.exportarAWAVToolStripMenuItem, "exportarAWAVToolStripMenuItem");
this.exportarAWAVToolStripMenuItem.Click += new System.EventHandler(this.exportarAWAVToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator3,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.pasteAsDelay,
this.toolStripSeparator4,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
resources.ApplyResources(this.editToolStripMenuItem, "editToolStripMenuItem");
//
// undoToolStripMenuItem
//
resources.ApplyResources(this.undoToolStripMenuItem, "undoToolStripMenuItem");
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click);
//
// redoToolStripMenuItem
//
resources.ApplyResources(this.redoToolStripMenuItem, "redoToolStripMenuItem");
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// cutToolStripMenuItem
//
resources.ApplyResources(this.cutToolStripMenuItem, "cutToolStripMenuItem");
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem");
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
resources.ApplyResources(this.pasteToolStripMenuItem, "pasteToolStripMenuItem");
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click);
//
// pasteAsDelay
//
resources.ApplyResources(this.pasteAsDelay, "pasteAsDelay");
this.pasteAsDelay.Name = "pasteAsDelay";
this.pasteAsDelay.Click += new System.EventHandler(this.pasteAsDelay_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
resources.ApplyResources(this.selectAllToolStripMenuItem, "selectAllToolStripMenuItem");
//
// instrumentosToolStripMenuItem
//
this.instrumentosToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.importarToolStripMenuItem,
this.exportarToolStripMenuItem});
this.instrumentosToolStripMenuItem.Name = "instrumentosToolStripMenuItem";
resources.ApplyResources(this.instrumentosToolStripMenuItem, "instrumentosToolStripMenuItem");
//
// importarToolStripMenuItem
//
this.importarToolStripMenuItem.Name = "importarToolStripMenuItem";
resources.ApplyResources(this.importarToolStripMenuItem, "importarToolStripMenuItem");
this.importarToolStripMenuItem.Click += new System.EventHandler(this.importarToolStripMenuItem_Click);
//
// exportarToolStripMenuItem
//
this.exportarToolStripMenuItem.Name = "exportarToolStripMenuItem";
resources.ApplyResources(this.exportarToolStripMenuItem, "exportarToolStripMenuItem");
this.exportarToolStripMenuItem.Click += new System.EventHandler(this.exportarToolStripMenuItem_Click);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.customizeToolStripMenuItem,
this.optionsToolStripMenuItem,
this.editorDeFrecuenciasToolStripMenuItem,
this.editorDeArpegiosToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// customizeToolStripMenuItem
//
resources.ApplyResources(this.customizeToolStripMenuItem, "customizeToolStripMenuItem");
this.customizeToolStripMenuItem.Name = "customizeToolStripMenuItem";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
resources.ApplyResources(this.optionsToolStripMenuItem, "optionsToolStripMenuItem");
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click);
//
// editorDeFrecuenciasToolStripMenuItem
//
this.editorDeFrecuenciasToolStripMenuItem.Name = "editorDeFrecuenciasToolStripMenuItem";
resources.ApplyResources(this.editorDeFrecuenciasToolStripMenuItem, "editorDeFrecuenciasToolStripMenuItem");
this.editorDeFrecuenciasToolStripMenuItem.Click += new System.EventHandler(this.editorDeFrecuenciasToolStripMenuItem_Click);
//
// editorDeArpegiosToolStripMenuItem
//
this.editorDeArpegiosToolStripMenuItem.Name = "editorDeArpegiosToolStripMenuItem";
resources.ApplyResources(this.editorDeArpegiosToolStripMenuItem, "editorDeArpegiosToolStripMenuItem");
this.editorDeArpegiosToolStripMenuItem.Click += new System.EventHandler(this.editorDeArpegiosToolStripMenuItem_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.indexToolStripMenuItem,
this.toolStripSeparator5,
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
resources.ApplyResources(this.indexToolStripMenuItem, "indexToolStripMenuItem");
this.indexToolStripMenuItem.Click += new System.EventHandler(this.indexToolStripMenuItem_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
resources.ApplyResources(this.aboutToolStripMenuItem, "aboutToolStripMenuItem");
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
//
// lstInstruments
//
this.lstInstruments.ContextMenuStrip = this.instrumentsContextMenu;
this.lstInstruments.DataSource = this.instrumentsBindingSource;
this.lstInstruments.DisplayMember = "Name";
resources.ApplyResources(this.lstInstruments, "lstInstruments");
this.lstInstruments.FormattingEnabled = true;
this.lstInstruments.Name = "lstInstruments";
this.lstInstruments.SelectedIndexChanged += new System.EventHandler(this.lstInstruments_SelectedIndexChanged);
this.lstInstruments.DoubleClick += new System.EventHandler(this.lstInstruments_DoubleClick);
//
// instrumentsContextMenu
//
this.instrumentsContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exportInstrumentToolStripMenuItem});
this.instrumentsContextMenu.Name = "instrumentsContextMenu";
resources.ApplyResources(this.instrumentsContextMenu, "instrumentsContextMenu");
//
// exportInstrumentToolStripMenuItem
//
this.exportInstrumentToolStripMenuItem.Name = "exportInstrumentToolStripMenuItem";
resources.ApplyResources(this.exportInstrumentToolStripMenuItem, "exportInstrumentToolStripMenuItem");
this.exportInstrumentToolStripMenuItem.Click += new System.EventHandler(this.exportInstrumentToolStripMenuItem_Click);
//
// instrumentsBindingSource
//
this.instrumentsBindingSource.DataSource = typeof(WYZTracker.Instruments);
//
// instrumentStrip
//
resources.ApplyResources(this.instrumentStrip, "instrumentStrip");
this.instrumentStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newInstrument,
this.deleteInstrument,
this.toolStripSeparator1,
this.importInstruments,
this.exportInstruments,
this.toolStripSeparator6,
this.instrumentProperties,
this.txtInstrumentName});
this.instrumentStrip.Name = "instrumentStrip";
//
// newInstrument
//
this.newInstrument.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newInstrument.Image = global::WYZTracker.Properties.Resources.filenew;
resources.ApplyResources(this.newInstrument, "newInstrument");
this.newInstrument.Name = "newInstrument";
this.newInstrument.Click += new System.EventHandler(this.newInstrument_Click);
//
// deleteInstrument
//
this.deleteInstrument.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.deleteInstrument.Image = global::WYZTracker.Properties.Resources.button_cancel;
resources.ApplyResources(this.deleteInstrument, "deleteInstrument");
this.deleteInstrument.Name = "deleteInstrument";
this.deleteInstrument.Click += new System.EventHandler(this.deleteInstrument_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// importInstruments
//
this.importInstruments.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.importInstruments.Image = global::WYZTracker.Properties.Resources.fileopen;
resources.ApplyResources(this.importInstruments, "importInstruments");
this.importInstruments.Name = "importInstruments";
this.importInstruments.Click += new System.EventHandler(this.importInstruments_Click);
//
// exportInstruments
//
this.exportInstruments.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.exportInstruments.Image = global::WYZTracker.Properties.Resources.filesave;
resources.ApplyResources(this.exportInstruments, "exportInstruments");
this.exportInstruments.Name = "exportInstruments";
this.exportInstruments.Click += new System.EventHandler(this.exportInstruments_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// instrumentProperties
//
this.instrumentProperties.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.instrumentProperties, "instrumentProperties");
this.instrumentProperties.Name = "instrumentProperties";
this.instrumentProperties.Click += new System.EventHandler(this.instrumentProperties_Click);
//
// txtInstrumentName
//
this.txtInstrumentName.Name = "txtInstrumentName";
resources.ApplyResources(this.txtInstrumentName, "txtInstrumentName");
this.txtInstrumentName.Validating += new System.ComponentModel.CancelEventHandler(this.txtInstrumentName_Validating);
this.txtInstrumentName.Validated += new System.EventHandler(this.txtInstrumentName_Validated);
//
// gboxSongProperties
//
this.gboxSongProperties.Controls.Add(this.songProperties);
resources.ApplyResources(this.gboxSongProperties, "gboxSongProperties");
this.gboxSongProperties.Name = "gboxSongProperties";
this.gboxSongProperties.TabStop = false;
//
// songProperties
//
this.songProperties.CurrentPattern = null;
this.songProperties.CurrentSong = null;
resources.ApplyResources(this.songProperties, "songProperties");
this.songProperties.Name = "songProperties";
this.songProperties.SongChannelsChanged += new System.EventHandler<WYZTracker.SongChannelsChangedEventArgs>(this.songProperties_SongChannelsChanged);
//
// tabInstrumentsFX
//
resources.ApplyResources(this.tabInstrumentsFX, "tabInstrumentsFX");
this.tabInstrumentsFX.Controls.Add(this.tabInstrumentos);
this.tabInstrumentsFX.Controls.Add(this.tabFX);
this.tabInstrumentsFX.Name = "tabInstrumentsFX";
this.tabInstrumentsFX.SelectedIndex = 0;
//
// tabInstrumentos
//
this.tabInstrumentos.Controls.Add(this.lstInstruments);
this.tabInstrumentos.Controls.Add(this.instrumentStrip);
resources.ApplyResources(this.tabInstrumentos, "tabInstrumentos");
this.tabInstrumentos.Name = "tabInstrumentos";
this.tabInstrumentos.UseVisualStyleBackColor = true;
//
// tabFX
//
this.tabFX.Controls.Add(this.lstFX);
this.tabFX.Controls.Add(this.fxStrip);
resources.ApplyResources(this.tabFX, "tabFX");
this.tabFX.Name = "tabFX";
this.tabFX.UseVisualStyleBackColor = true;
//
// lstFX
//
this.lstFX.ContextMenuStrip = this.fxContextMenu;
this.lstFX.DataSource = this.effectsBindingSource;
this.lstFX.DisplayMember = "Name";
resources.ApplyResources(this.lstFX, "lstFX");
this.lstFX.FormattingEnabled = true;
this.lstFX.Name = "lstFX";
this.lstFX.SelectedIndexChanged += new System.EventHandler(this.lstFX_SelectedIndexChanged);
this.lstFX.DoubleClick += new System.EventHandler(this.lstFX_DoubleClick);
//
// fxContextMenu
//
this.fxContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exportarEfectoToolStripMenuItem});
this.fxContextMenu.Name = "fxContextMenu";
resources.ApplyResources(this.fxContextMenu, "fxContextMenu");
//
// exportarEfectoToolStripMenuItem
//
this.exportarEfectoToolStripMenuItem.Name = "exportarEfectoToolStripMenuItem";
resources.ApplyResources(this.exportarEfectoToolStripMenuItem, "exportarEfectoToolStripMenuItem");
this.exportarEfectoToolStripMenuItem.Click += new System.EventHandler(this.exportarEfectoToolStripMenuItem_Click);
//
// effectsBindingSource
//
this.effectsBindingSource.DataSource = typeof(WYZTracker.Effects);
//
// fxStrip
//
resources.ApplyResources(this.fxStrip, "fxStrip");
this.fxStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newFX,
this.deleteFX,
this.toolStripSeparator9,
this.importFX,
this.exportFX,
this.toolStripSeparator10,
this.fxProperties,
this.txtFXName});
this.fxStrip.Name = "fxStrip";
//
// newFX
//
this.newFX.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.newFX, "newFX");
this.newFX.Name = "newFX";
this.newFX.Click += new System.EventHandler(this.newFX_Click);
//
// deleteFX
//
this.deleteFX.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.deleteFX, "deleteFX");
this.deleteFX.Name = "deleteFX";
this.deleteFX.Click += new System.EventHandler(this.deleteFX_Click);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9");
//
// importFX
//
this.importFX.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.importFX, "importFX");
this.importFX.Name = "importFX";
this.importFX.Click += new System.EventHandler(this.importFX_Click);
//
// exportFX
//
this.exportFX.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.exportFX, "exportFX");
this.exportFX.Name = "exportFX";
this.exportFX.Click += new System.EventHandler(this.exportFX_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10");
//
// fxProperties
//
this.fxProperties.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.fxProperties, "fxProperties");
this.fxProperties.Name = "fxProperties";
this.fxProperties.Click += new System.EventHandler(this.fxProperties_Click);
//
// txtFXName
//
this.txtFXName.Name = "txtFXName";
resources.ApplyResources(this.txtFXName, "txtFXName");
this.txtFXName.Validating += new System.ComponentModel.CancelEventHandler(this.txtFXName_Validating);
this.txtFXName.Validated += new System.EventHandler(this.txtFXName_Validated);
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripButton1, "toolStripButton1");
this.toolStripButton1.Name = "toolStripButton1";
//
// toolStripButton2
//
this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripButton2, "toolStripButton2");
this.toolStripButton2.Name = "toolStripButton2";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
//
// toolStripButton3
//
this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripButton3, "toolStripButton3");
this.toolStripButton3.Name = "toolStripButton3";
//
// toolStripButton4
//
this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripButton4, "toolStripButton4");
this.toolStripButton4.Name = "toolStripButton4";
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8");
//
// toolStripButton5
//
this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.toolStripButton5, "toolStripButton5");
this.toolStripButton5.Name = "toolStripButton5";
//
// toolStripTextBox1
//
this.toolStripTextBox1.Name = "toolStripTextBox1";
resources.ApplyResources(this.toolStripTextBox1, "toolStripTextBox1");
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nuevoToolStrip,
this.abrirToolStrip,
this.guardarToolStrip,
this.toolStripSeparator11,
this.playAllClick,
this.playToolStrip,
this.playPattern,
this.stopToolStrip,
this.toolStripSeparator12,
this.addPatronToolStrip,
this.removePatronToolStrip,
this.clonePattern,
this.toolStripSeparator13,
this.importarMUS,
this.exportarWYZToolStrip});
resources.ApplyResources(this.toolStrip1, "toolStrip1");
this.toolStrip1.Name = "toolStrip1";
//
// nuevoToolStrip
//
this.nuevoToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.nuevoToolStrip.Image = global::WYZTracker.Properties.Resources.filenew;
resources.ApplyResources(this.nuevoToolStrip, "nuevoToolStrip");
this.nuevoToolStrip.Name = "nuevoToolStrip";
this.nuevoToolStrip.Click += new System.EventHandler(this.nuevoToolStrip_Click);
//
// abrirToolStrip
//
this.abrirToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.abrirToolStrip.Image = global::WYZTracker.Properties.Resources.fileopen;
resources.ApplyResources(this.abrirToolStrip, "abrirToolStrip");
this.abrirToolStrip.Name = "abrirToolStrip";
this.abrirToolStrip.Click += new System.EventHandler(this.abrirToolStrip_Click);
//
// guardarToolStrip
//
this.guardarToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.guardarToolStrip.Image = global::WYZTracker.Properties.Resources.filesave;
resources.ApplyResources(this.guardarToolStrip, "guardarToolStrip");
this.guardarToolStrip.Name = "guardarToolStrip";
this.guardarToolStrip.Click += new System.EventHandler(this.guardarToolStrip_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11");
//
// playAllClick
//
this.playAllClick.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.playAllClick.Image = global::WYZTracker.Properties.Resources.player_end;
resources.ApplyResources(this.playAllClick, "playAllClick");
this.playAllClick.Name = "playAllClick";
this.playAllClick.Click += new System.EventHandler(this.playAllClick_Click);
//
// playToolStrip
//
this.playToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.playToolStrip.Image = global::WYZTracker.Properties.Resources.player_play;
resources.ApplyResources(this.playToolStrip, "playToolStrip");
this.playToolStrip.Name = "playToolStrip";
this.playToolStrip.Click += new System.EventHandler(this.playToolStrip_Click);
//
// playPattern
//
this.playPattern.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.playPattern.Image = global::WYZTracker.Properties.Resources.switchuser;
resources.ApplyResources(this.playPattern, "playPattern");
this.playPattern.Name = "playPattern";
this.playPattern.Click += new System.EventHandler(this.playPattern_Click);
//
// stopToolStrip
//
this.stopToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.stopToolStrip.Image = global::WYZTracker.Properties.Resources.player_stop;
resources.ApplyResources(this.stopToolStrip, "stopToolStrip");
this.stopToolStrip.Name = "stopToolStrip";
this.stopToolStrip.Click += new System.EventHandler(this.stopToolStrip_Click);
//
// toolStripSeparator12
//
this.toolStripSeparator12.Name = "toolStripSeparator12";
resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12");
//
// addPatronToolStrip
//
this.addPatronToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.addPatronToolStrip.Image = global::WYZTracker.Properties.Resources.addPattern;
resources.ApplyResources(this.addPatronToolStrip, "addPatronToolStrip");
this.addPatronToolStrip.Name = "addPatronToolStrip";
this.addPatronToolStrip.Click += new System.EventHandler(this.addPatronToolStrip_Click);
//
// removePatronToolStrip
//
this.removePatronToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.removePatronToolStrip.Image = global::WYZTracker.Properties.Resources.removePattern;
resources.ApplyResources(this.removePatronToolStrip, "removePatronToolStrip");
this.removePatronToolStrip.Name = "removePatronToolStrip";
this.removePatronToolStrip.Click += new System.EventHandler(this.removePatronToolStrip_Click);
//
// clonePattern
//
this.clonePattern.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.clonePattern.Image = global::WYZTracker.Properties.Resources.clonePattern;
resources.ApplyResources(this.clonePattern, "clonePattern");
this.clonePattern.Name = "clonePattern";
this.clonePattern.Click += new System.EventHandler(this.clonePattern_Click);
//
// toolStripSeparator13
//
this.toolStripSeparator13.Name = "toolStripSeparator13";
resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13");
//
// importarMUS
//
this.importarMUS.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.importarMUS, "importarMUS");
this.importarMUS.Image = global::WYZTracker.Properties.Resources.importarMus;
this.importarMUS.Name = "importarMUS";
this.importarMUS.Click += new System.EventHandler(this.importarMUS_Click);
//
// exportarWYZToolStrip
//
this.exportarWYZToolStrip.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.exportarWYZToolStrip.Image = global::WYZTracker.Properties.Resources.exportarWYZ;
resources.ApplyResources(this.exportarWYZToolStrip, "exportarWYZToolStrip");
this.exportarWYZToolStrip.Name = "exportarWYZToolStrip";
this.exportarWYZToolStrip.Click += new System.EventHandler(this.exportarWYZToolStrip_Click);
//
// gboxPatterns
//
this.gboxPatterns.Controls.Add(this.patLength);
this.gboxPatterns.Controls.Add(this.label1);
this.gboxPatterns.Controls.Add(this.cmdBajarPatron);
this.gboxPatterns.Controls.Add(this.cmdSubirPatron);
this.gboxPatterns.Controls.Add(this.cmdPreviousPattern);
this.gboxPatterns.Controls.Add(this.cmdNextPattern);
this.gboxPatterns.Controls.Add(this.lboxPatterns);
resources.ApplyResources(this.gboxPatterns, "gboxPatterns");
this.gboxPatterns.Name = "gboxPatterns";
this.gboxPatterns.TabStop = false;
//
// patLength
//
this.patLength.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.patternBindingSource, "Length", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
resources.ApplyResources(this.patLength, "patLength");
this.patLength.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.patLength.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.patLength.Name = "patLength";
this.patLength.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// patternBindingSource
//
this.patternBindingSource.DataSource = typeof(WYZTracker.Pattern);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// cmdBajarPatron
//
this.cmdBajarPatron.Image = global::WYZTracker.Properties.Resources.move_task_down;
resources.ApplyResources(this.cmdBajarPatron, "cmdBajarPatron");
this.cmdBajarPatron.Name = "cmdBajarPatron";
this.cmdBajarPatron.UseVisualStyleBackColor = true;
this.cmdBajarPatron.Click += new System.EventHandler(this.cmdBajarPatron_Click);
//
// cmdSubirPatron
//
this.cmdSubirPatron.Image = global::WYZTracker.Properties.Resources.move_task_up;
resources.ApplyResources(this.cmdSubirPatron, "cmdSubirPatron");
this.cmdSubirPatron.Name = "cmdSubirPatron";
this.cmdSubirPatron.UseVisualStyleBackColor = true;
this.cmdSubirPatron.Click += new System.EventHandler(this.cmdSubirPatron_Click);
//
// cmdPreviousPattern
//
this.cmdPreviousPattern.Image = global::WYZTracker.Properties.Resources.edit_remove;
resources.ApplyResources(this.cmdPreviousPattern, "cmdPreviousPattern");
this.cmdPreviousPattern.Name = "cmdPreviousPattern";
this.cmdPreviousPattern.UseVisualStyleBackColor = true;
this.cmdPreviousPattern.Click += new System.EventHandler(this.cmdPreviousPattern_Click);
//
// cmdNextPattern
//
this.cmdNextPattern.Image = global::WYZTracker.Properties.Resources.edit_add;
resources.ApplyResources(this.cmdNextPattern, "cmdNextPattern");
this.cmdNextPattern.Name = "cmdNextPattern";
this.cmdNextPattern.UseVisualStyleBackColor = true;
this.cmdNextPattern.Click += new System.EventHandler(this.cmdNextPattern_Click);
//
// lboxPatterns
//
this.lboxPatterns.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.lboxPatterns.FormattingEnabled = true;
resources.ApplyResources(this.lboxPatterns, "lboxPatterns");
this.lboxPatterns.Name = "lboxPatterns";
this.lboxPatterns.Click += new System.EventHandler(this.lboxPatterns_Click);
this.lboxPatterns.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.lboxPatterns_DrawItem);
this.lboxPatterns.SelectedIndexChanged += new System.EventHandler(this.lboxPatterns_SelectedIndexChanged);
this.lboxPatterns.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lboxPatterns_MouseDown);
//
// patEditor
//
resources.ApplyResources(this.patEditor, "patEditor");
this.patEditor.BackColor = System.Drawing.Color.Black;
this.patEditor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.patEditor.CurrentChannel = ((byte)(0));
this.patEditor.CurrentInstrument = null;
this.patEditor.CurrentPattern = null;
this.patEditor.CurrentSong = null;
this.patEditor.DelayDecrement = 0;
this.patEditor.EditionIncrement = 0;
this.patEditor.HighlightRange = 4;
this.patEditor.Name = "patEditor";
this.patEditor.SelectedIndex = 0;
this.patEditor.Play += new System.EventHandler<WYZTracker.PlayEventArgs>(this.patEditor_Play);
this.patEditor.Stop += new System.EventHandler(this.patEditor_Stop);
this.patEditor.IncreaseOctave += new System.EventHandler(this.patEditor_IncreaseOctave);
this.patEditor.DecreaseOctave += new System.EventHandler(this.patEditor_DecreaseOctave);
this.patEditor.IncreaseInstrument += new System.EventHandler(this.patEditor_IncreaseInstrument);
this.patEditor.DecreaseInstrument += new System.EventHandler(this.patEditor_DecreaseInstrument);
this.patEditor.EditionIncrementChanged += new System.EventHandler(this.patEditor_EditionIncrementChanged);
this.patEditor.HighlightRangeChanged += new System.EventHandler(this.patEditor_HighlightRangeChanged);
this.patEditor.NextPattern += new System.EventHandler(this.patEditor_NextPattern);
this.patEditor.PreviousPattern += new System.EventHandler(this.patEditor_PreviousPattern);
this.patEditor.FileDropped += new System.EventHandler<WYZTracker.FileDroppedEventArgs>(this.patEditor_FileDropped);
this.patEditor.FxChannelChanged += new System.EventHandler<WYZTracker.FxChannelChangedEventArgs>(this.patEditor_FxChannelChanged);
this.patEditor.SetActiveFx += new System.EventHandler<WYZTracker.ActiveFxEventArgs>(this.patEditor_SetActiveFx);
this.patEditor.SetActiveInstrument += new System.EventHandler<WYZTracker.ActiveInstrumentEventArgs>(this.patEditor_SetActiveInstrument);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.cboEnvRatio);
this.groupBox1.Controls.Add(this.cboEnvShape);
this.groupBox1.Controls.Add(this.chkActiveFreqs);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// cboEnvRatio
//
this.cboEnvRatio.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.envelopeDataBindingSource, "FrequencyRatio", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "X"));
this.cboEnvRatio.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboEnvRatio.FormattingEnabled = true;
resources.ApplyResources(this.cboEnvRatio, "cboEnvRatio");
this.cboEnvRatio.Name = "cboEnvRatio";
this.cboEnvRatio.SelectedIndexChanged += new System.EventHandler(this.cboEnvRatio_SelectedIndexChanged);
//
// envelopeDataBindingSource
//
this.envelopeDataBindingSource.DataSource = typeof(WYZTracker.EnvelopeData);
//
// cboEnvShape
//
this.cboEnvShape.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.envelopeDataBindingSource, "Style", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "X"));
this.cboEnvShape.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboEnvShape.FormattingEnabled = true;
resources.ApplyResources(this.cboEnvShape, "cboEnvShape");
this.cboEnvShape.Name = "cboEnvShape";
this.cboEnvShape.SelectedIndexChanged += new System.EventHandler(this.cboEnvShape_SelectedIndexChanged);
//
// chkActiveFreqs
//
resources.ApplyResources(this.chkActiveFreqs, "chkActiveFreqs");
this.chkActiveFreqs.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.envelopeDataBindingSource, "ActiveFrequencies", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.chkActiveFreqs.Name = "chkActiveFreqs";
this.chkActiveFreqs.UseVisualStyleBackColor = true;
this.chkActiveFreqs.CheckedChanged += new System.EventHandler(this.chkActiveFreqs_CheckedChanged);
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// toolStrip2
//
this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblOctavaBase,
this.cmbOctavaBase,
this.toolStripSeparator15,
this.toolStripLabel1,
this.incrementoAutomatico,
this.toolStripSeparator16,
this.toolStripLabel2,
this.txtResalte,
this.toolStripSeparator17,
this.toolStripLabel3,
this.cboStereo,
this.toolStripSeparator18,
this.toolStripLabel4,
this.txtDecrementoDelay});
resources.ApplyResources(this.toolStrip2, "toolStrip2");
this.toolStrip2.Name = "toolStrip2";
//
// lblOctavaBase
//
this.lblOctavaBase.Name = "lblOctavaBase";
resources.ApplyResources(this.lblOctavaBase, "lblOctavaBase");
//
// cmbOctavaBase
//
this.cmbOctavaBase.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbOctavaBase.Items.AddRange(new object[] {
resources.GetString("cmbOctavaBase.Items"),
resources.GetString("cmbOctavaBase.Items1"),
resources.GetString("cmbOctavaBase.Items2"),
resources.GetString("cmbOctavaBase.Items3"),
resources.GetString("cmbOctavaBase.Items4")});
this.cmbOctavaBase.Name = "cmbOctavaBase";
resources.ApplyResources(this.cmbOctavaBase, "cmbOctavaBase");
this.cmbOctavaBase.SelectedIndexChanged += new System.EventHandler(this.cmbOctavaBase_SelectedIndexChanged);
//
// toolStripSeparator15
//
this.toolStripSeparator15.Name = "toolStripSeparator15";
resources.ApplyResources(this.toolStripSeparator15, "toolStripSeparator15");
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
resources.ApplyResources(this.toolStripLabel1, "toolStripLabel1");
//
// incrementoAutomatico
//
this.incrementoAutomatico.Name = "incrementoAutomatico";
resources.ApplyResources(this.incrementoAutomatico, "incrementoAutomatico");
this.incrementoAutomatico.TextChanged += new System.EventHandler(this.incrementoAutomatico_TextChanged);
//
// toolStripSeparator16
//
this.toolStripSeparator16.Name = "toolStripSeparator16";
resources.ApplyResources(this.toolStripSeparator16, "toolStripSeparator16");
//
// toolStripLabel2
//
this.toolStripLabel2.Name = "toolStripLabel2";
resources.ApplyResources(this.toolStripLabel2, "toolStripLabel2");
//
// txtResalte
//
this.txtResalte.Name = "txtResalte";
resources.ApplyResources(this.txtResalte, "txtResalte");
this.txtResalte.TextChanged += new System.EventHandler(this.txtResalte_TextChanged);
//
// toolStripSeparator17
//
this.toolStripSeparator17.Name = "toolStripSeparator17";
resources.ApplyResources(this.toolStripSeparator17, "toolStripSeparator17");
//
// toolStripLabel3
//
this.toolStripLabel3.Name = "toolStripLabel3";
resources.ApplyResources(this.toolStripLabel3, "toolStripLabel3");
//
// cboStereo
//
this.cboStereo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboStereo.DropDownWidth = 125;
this.cboStereo.Name = "cboStereo";
resources.ApplyResources(this.cboStereo, "cboStereo");
this.cboStereo.SelectedIndexChanged += new System.EventHandler(this.cboStereo_SelectedIndexChanged);
//
// toolStripSeparator18
//
this.toolStripSeparator18.Name = "toolStripSeparator18";
resources.ApplyResources(this.toolStripSeparator18, "toolStripSeparator18");
//
// toolStripLabel4
//
this.toolStripLabel4.Name = "toolStripLabel4";
resources.ApplyResources(this.toolStripLabel4, "toolStripLabel4");
//
// txtDecrementoDelay
//
this.txtDecrementoDelay.Name = "txtDecrementoDelay";
resources.ApplyResources(this.txtDecrementoDelay, "txtDecrementoDelay");
this.txtDecrementoDelay.TextChanged += new System.EventHandler(this.txtDecrementoDelay_TextChanged);
//
// frmDockedMain
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.toolStrip2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.gboxPatterns);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.tabInstrumentsFX);
this.Controls.Add(this.gboxSongProperties);
this.Controls.Add(this.patEditor);
this.Controls.Add(this.mainMenu);
this.Name = "frmDockedMain";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmDockedMain_FormClosed);
this.mainMenu.ResumeLayout(false);
this.mainMenu.PerformLayout();
this.instrumentsContextMenu.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.instrumentsBindingSource)).EndInit();
this.instrumentStrip.ResumeLayout(false);
this.instrumentStrip.PerformLayout();
this.gboxSongProperties.ResumeLayout(false);
this.tabInstrumentsFX.ResumeLayout(false);
this.tabInstrumentos.ResumeLayout(false);
this.tabInstrumentos.PerformLayout();
this.tabFX.ResumeLayout(false);
this.tabFX.PerformLayout();
this.fxContextMenu.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.effectsBindingSource)).EndInit();
this.fxStrip.ResumeLayout(false);
this.fxStrip.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.gboxPatterns.ResumeLayout(false);
this.gboxPatterns.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.patLength)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.patternBindingSource)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.envelopeDataBindingSource)).EndInit();
this.toolStrip2.ResumeLayout(false);
this.toolStrip2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mainMenu;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem customizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog sfd;
private System.Windows.Forms.ToolStripMenuItem instrumentosToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem importarToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportarToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog ofd;
private PatternEditor patEditor;
private System.Windows.Forms.ListBox lstInstruments;
private System.Windows.Forms.BindingSource instrumentsBindingSource;
private System.Windows.Forms.ToolStrip instrumentStrip;
private System.Windows.Forms.ToolStripButton newInstrument;
private System.Windows.Forms.ToolStripButton deleteInstrument;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton importInstruments;
private System.Windows.Forms.ToolStripButton exportInstruments;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton instrumentProperties;
private System.Windows.Forms.ToolStripTextBox txtInstrumentName;
private SongProperties songProperties;
private System.Windows.Forms.GroupBox gboxSongProperties;
private System.Windows.Forms.TabControl tabInstrumentsFX;
private System.Windows.Forms.TabPage tabInstrumentos;
private System.Windows.Forms.TabPage tabFX;
private System.Windows.Forms.ListBox lstFX;
private System.Windows.Forms.ToolStrip fxStrip;
private System.Windows.Forms.ToolStripButton newFX;
private System.Windows.Forms.ToolStripButton deleteFX;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripButton importFX;
private System.Windows.Forms.ToolStripButton exportFX;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripButton fxProperties;
private System.Windows.Forms.ToolStripTextBox txtFXName;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripButton toolStripButton3;
private System.Windows.Forms.ToolStripButton toolStripButton4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripButton toolStripButton5;
private System.Windows.Forms.ToolStripTextBox toolStripTextBox1;
private System.Windows.Forms.BindingSource effectsBindingSource;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.GroupBox gboxPatterns;
private System.Windows.Forms.Button cmdNextPattern;
private System.Windows.Forms.ListBox lboxPatterns;
private System.Windows.Forms.Button cmdBajarPatron;
private System.Windows.Forms.Button cmdSubirPatron;
private System.Windows.Forms.Button cmdPreviousPattern;
private System.Windows.Forms.ToolStripButton nuevoToolStrip;
private System.Windows.Forms.ToolStripButton abrirToolStrip;
private System.Windows.Forms.ToolStripButton guardarToolStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripButton playToolStrip;
private System.Windows.Forms.ToolStripButton stopToolStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator12;
private System.Windows.Forms.ToolStripButton addPatronToolStrip;
private System.Windows.Forms.ToolStripButton removePatronToolStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator13;
private System.Windows.Forms.ToolStripButton exportarWYZToolStrip;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown patLength;
private System.Windows.Forms.BindingSource patternBindingSource;
private System.Windows.Forms.ToolStripButton clonePattern;
private System.Windows.Forms.ToolStripButton importarMUS;
private System.Windows.Forms.ToolStripButton playAllClick;
private System.Windows.Forms.ToolStripButton playPattern;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.BindingSource envelopeDataBindingSource;
private System.Windows.Forms.CheckBox chkActiveFreqs;
private System.Windows.Forms.ComboBox cboEnvShape;
private System.Windows.Forms.ComboBox cboEnvRatio;
private System.Windows.Forms.ToolStripMenuItem editorDeFrecuenciasToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip instrumentsContextMenu;
private System.Windows.Forms.ToolStripMenuItem exportInstrumentToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip fxContextMenu;
private System.Windows.Forms.ToolStripMenuItem exportarEfectoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editorDeArpegiosToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportarAWAVToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip2;
private System.Windows.Forms.ToolStripLabel lblOctavaBase;
private System.Windows.Forms.ToolStripComboBox cmbOctavaBase;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator15;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripTextBox incrementoAutomatico;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator16;
private System.Windows.Forms.ToolStripLabel toolStripLabel2;
private System.Windows.Forms.ToolStripTextBox txtResalte;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator17;
private System.Windows.Forms.ToolStripLabel toolStripLabel3;
private System.Windows.Forms.ToolStripComboBox cboStereo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator18;
private System.Windows.Forms.ToolStripLabel toolStripLabel4;
private System.Windows.Forms.ToolStripTextBox txtDecrementoDelay;
private System.Windows.Forms.ToolStripMenuItem pasteAsDelay;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib
{
/// <summary>
/// Specify the account type of cName
/// </summary>
public enum KerberosAccountType : byte
{
/// <summary>
/// User account
/// </summary>
User = 0,
/// <summary>
/// Computer account
/// </summary>
Device = 1,
}
/// <summary>
/// The padata type represent which padata value will be contained in request.
/// </summary>
public enum PaDataType : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// DER encoding of AP-REQ
/// </summary>
PA_TGS_REQ = 1,
/// <summary>
/// DER encoding of PA-ENC-TIMESTAMP
/// </summary>
PA_ENC_TIMESTAMP = 2,
/// <summary>
/// salt (not ASN.1 encoded)
/// </summary>
PA_PW_SALT = 3,
/// <summary>
/// DER encoding of ETYPE-INFO
/// </summary>
PA_ETYPE_INFO = 11,
/// <summary>
/// DER encoding of PA_PK_AS_REQ_OLD
/// </summary>
PA_PK_AS_REQ_OLD = 14,
/// <summary>
/// DER encoding of PA_PK_AS_REP_OLD
/// </summary>
PA_PK_AS_REP_OLD = 15,
/// <summary>
/// DER encoding of PA_PK_AS_REQ
/// </summary>
PA_PK_AS_REQ = 16,
/// <summary>
/// DER encoding of PA_PK_AS_REP
/// </summary>
PA_PK_AS_REP = 17,
/// <summary>
/// DER encoding of ETYPE-INFO2
/// </summary>
PA_ETYPE_INFO2 = 19,
/// <summary>
/// DER encoding of PA_SVR_REFERRAL_DATA
/// </summary>
PA_SVR_REFERRAL_INFO = 20,
/// <summary>
/// DER encoding of PA_PAC_REQUEST
/// </summary>
PA_PAC_REQUEST = 128,
/// <summary>
/// PA_FOR_USER of SFU
/// </summary>
PA_SFU_PA_FOR_USER = 129,
/// <summary>
/// PA_S4U_X509_USER of SFU
/// </summary>
PA_SFU_PA_S4U_X509_USER = 130,
/// <summary>
/// PA_DATA_CHEKSUM in as-request
/// </summary>
PA_DATA_CHEKSUM = 132,
/// <summary>
/// PA-FX-COOKIE Stateless cookie that is not tied to a specific KDC.
/// </summary>
PA_FX_COOKIE = 133,
/// <summary>
/// Fast
/// </summary>
PA_FX_FAST = 136,
/// <summary>
/// PA_FX_ERROR
/// </summary>
PA_FX_ERROR = 137,
/// <summary>
/// Encrypted PA-ENC-TS-ENC
/// </summary>
PA_ENCRYPTED_CHALLENGE = 138,
/// <summary>
/// supported encryption types
/// </summary>
PA_SUPPORTED_ENCTYPES = 165,
/// <summary>
/// Pac option
/// </summary>
PA_PAC_OPTION = 167,
/// <summary>
/// Invalid padata type
/// </summary>
UnKnow = 10000,
/// <summary>
/// DER encoding of PA_PK_AS_REQ_OLD
/// </summary>
PA_PK_AS_REQ_WINDOWS_OLD = 15,
/// <summary>
/// DER encoding of PA_PK_AS_REP_OLD
/// </summary>
PA_PK_AS_REP_WINDOWS_OLD = 15,
}
/// <summary>
/// Key usage number from rfc 4120,in
/// http://www.apps.ietf.org/rfc/rfc4120.html#sec-7.5.1
/// </summary>
public enum KeyUsageNumber : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// AS-REQ PA-ENC-TIMESTAMP padata timestamp, encrypted with the client key (Section 5.2.7.2)
/// </summary>
PA_ENC_TIMESTAMP = 1,
/// <summary>
/// AS-REP Ticket and TGS-REP Ticket (includes TGS session
/// key or application session key), encrypted with the service key (Section 5.3)
/// </summary>
AS_REP_TicketAndTGS_REP_Ticket = 2,
/// <summary>
/// AS-REP encrypted part (includes TGS session key or
/// application session key), encrypted with the client key (Section 5.4.2)
/// </summary>
AS_REP_ENCRYPTEDPART = 3,
/// <summary>
/// TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with
/// the TGS session key (Section 5.4.1)
/// </summary>
TGS_REQ_KDC_REQ_BODY_AuthorizationData = 4,
/// <summary>
/// TGS-REQ KDC-REQ-BODY AuthorizationData, encrypted with
/// the TGS authenticator subkey (Section 5.4.1)
/// </summary>
TGS_REQ_KDC_REQ_BODY_AuthorizatorData = 5,
/// <summary>
/// TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator cksum,
/// keyed with the TGS session key (Section 5.5.1) 7. TGS-REQ PA-TGS-REQ padata
/// AP-REQ Authenticator (includes TGS authenticator subkey), encrypted with
/// the TGS session key (Section 5.5.1)
/// </summary>
TGS_REQ_PA_TGS_REQ_adataOR_AP_REQ_Authenticator_cksum = 6,
/// <summary>
/// TGS-REQ PA-TGS-REQ padata AP-REQ Authenticator (includes TGS authenticator subkey),
/// encrypted with the TGS session key (Section 5.5.1)
/// </summary>
TG_REQ_PA_TGS_REQ_padataOR_AP_REQ_Authenticator = 7,
/// <summary>
/// TGS-REP encrypted part (includes application sessionkey),
/// encrypted with the TGS session key (Section 5.4.2)
/// </summary>
TGS_REP_encrypted_part = 8,
/// <summary>
/// TGS-REP encrypted part (includes application session key),
/// encrypted with the TGS authenticator subkey(Section 5.4.2)
/// </summary>
TGS_REP_encrypted_part_subkey = 9,
/// <summary>
/// AP-REQ Authenticator checksum in TGS request.
/// </summary>
AP_REQ_Authenticator_Checksum = 10,
/// <summary>
/// AP-REQ Authenticator.
/// </summary>
AP_REQ_Authenticator = 11,
/// <summary>
/// AP-REP encrypted part.
/// </summary>
AP_REP_EncAPRepPart = 12,
/// <summary>
/// KRB-PRIV encrypted part.
/// </summary>
KRB_PRIV_EncPart = 13,
/// <summary>
/// KRB-CRED encrypted part.
/// </summary>
KRB_CRED_EncPart = 14,
/// <summary>
/// KRB-SAFE cksum, keyed with a key chosen by the application (Section 5.6.1)
/// </summary>
KRB_SAFE_Checksum = 15,
/// <summary>
/// KrbFastArmoredReq Checksum.([RFC6113] Section 5.4.2)
/// </summary>
FAST_REQ_CHECKSUM = 50,
/// <summary>
/// KrbFastArmoredReq encrypted part.([RFC6113] Section 5.4.2)
/// </summary>
FAST_ENC = 51,
/// <summary>
/// KrbFastArmoredRep encrypted part.([RFC6113] Section 5.4.2)
/// </summary>
FAST_REP = 52,
/// <summary>
/// KrbFastFinished ticket-checksum part.([RFC6113] Section 5.4.3)
/// </summary>
FAST_FINISHED = 53,
/// <summary>
/// EncryptedChallenge encrypted part.([RFC6113] Section 5.4.6)
/// </summary>
ENC_CHALLENGE_CLIENT = 54
}
/// <summary>
/// usage number for token.
/// </summary>
public enum TokenKeyUsage : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// usage number for wrap token for [rfc4757].
/// </summary>
USAGE_WRAP = 13,
/// <summary>
/// usage number for mic token for [rfc4757].
/// </summary>
USAGE_MIC = 15,
/// <summary>
/// usage number for wrap and mic token for [rfc4121].
/// </summary>
KG_USAGE_ACCEPTOR_SEAL = 22,
/// <summary>
/// usage number for wrap and mic token for [rfc4121].
/// </summary>
KG_USAGE_ACCEPTOR_SIGN = 23,
/// <summary>
/// usage number for wrap and mic token for [rfc4121].
/// </summary>
KG_USAGE_INITIATOR_SEAL = 24,
/// <summary>
/// usage number for wrap and mic token for [rfc4121].
/// </summary>
KG_USAGE_INITIATOR_SIGN = 25,
}
/// <summary>
/// KILE Message Type
/// </summary>
public enum MsgType : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// This signifies KRB_AS_REQ message Type
/// </summary>
KRB_AS_REQ = 10,
/// <summary>
/// This signifies KRB_AS_RESP message Type
/// </summary>
KRB_AS_RESP = 11,
/// <summary>
/// This signifies KRB_TGS_REQ message Type
/// </summary>
KRB_TGS_REQ = 12,
/// <summary>
/// This signifies KRB_TGS_RESP message Type
/// </summary>
KRB_TGS_RESP = 13,
/// <summary>
/// This signifies KRB_AP_REQ message Type
/// </summary>
KRB_AP_REQ = 14,
/// <summary>
/// This signifies KRB_AP_RESP message Type
/// </summary>
KRB_AP_RESP = 15,
/// <summary>
/// This signifies KRB_SAFE message Type
/// </summary>
KRB_SAFE = 20,
/// <summary>
/// This signifies KRB_PRIV message Type
/// </summary>
KRB_PRIV = 21,
/// <summary>
/// This signifies KRB_CRED message Type
/// </summary>
KRB_CRED = 22,
/// <summary>
/// This signifies KRB_ERROR message Type
/// </summary>
KRB_ERROR = 30
}
/// <summary>
/// EncTicket Flags, can be found in rfc 4120. Section 5.3 Tickets
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
[Flags]
public enum EncTicketFlags : uint
{
/// <summary>
/// Reserved for future expansion of this field.
/// </summary>
RESERVED = (uint)1 << 31,
/// <summary>
/// The FORWARDABLE flag is normally only interpreted by the TGS, and can be ignored by end servers.
/// When set, this flag tells the ticket-granting server that it is OK to issue a new TGT
/// with a different network address based on the presented ticket.
/// </summary>
FORWARDABLE = (uint)1 << 30,
/// <summary>
/// When set, this flag indicates that the ticket has either been forwarded TGT.
/// </summary>
FORWARDED = (uint)1 << 29,
/// <summary>
/// The PROXIABLE flag is normally only interpreted by the TGS, and can be ignored by end servers.
/// The PROXIABLE flag has an interpretation identical to that of the FORWARDABLE flag,
/// except that the PROXIABLE flag tells the ticket-granting server that only non-TGTs may be issued with different network addresses.
/// </summary>
PROXIABLE = (uint)1 << 28,
/// <summary>
/// When set, this flag indicates that a ticket is a proxy.
/// </summary>
PROXY = (uint)1 << 27,
/// <summary>
/// The MAY-POSTDATE flag is normally only interpreted by the TGS, and can be ignored by end servers.
/// This flag tells the ticket-granting server that a post-dated ticket MAY be issued based on this TGT.
/// </summary>
MAY_POSTDATE = (uint)1 << 26,
/// <summary>
/// This flag indicates that this ticket has been postdated.
/// The end-service can check the authtime field to see when the original authentication occurred.
/// </summary>
POSTDATED = (uint)1 << 25,
/// <summary>
/// This flag indicates that a ticket is invalid, and it must be validated by the KDC before use.
/// Application servers must reject tickets which have this flag set.
/// </summary>
INVALID = (uint)1 << 24,
/// <summary>
/// The RENEWABLE flag is normally only interpreted by the TGS, and can usually be ignored by end servers
/// (some particularly careful servers MAY disallow renewable tickets). A renewable ticket can be used
/// to obtain a replacement ticket that expires at a later date.
/// </summary>
RENEWABLE = (uint)1 << 23,
/// <summary>
/// This flag indicates that this ticket was issued using the AS protocol, and not issued based on a TGT.
/// </summary>
INITIAL = (uint)1 << 22,
/// <summary>
/// This flag indicates that during initial authentication, the client was authenticated by the KDC before a ticket was issued.
/// The strength of the pre-authentication method is not indicated, but is acceptable to the KDC.
/// </summary>
PRE_AUTHENT = (uint)1 << 21,
/// <summary>
/// This flag indicates that the protocol employed for initial authentication required the use of hardware expected to
/// be possessed solely by the named client. The hardware authentication method is and the strength of the method is not indicated.
/// </summary>
HW_AUTHENT = (uint)1 << 20,
/// <summary>
/// This flag indicates that the KDC for policy-checked the realm has checked the transited field against a realm-defined policy for trusted certifiers.
/// If this flag is reset (0), then the application server must check the transited field itself, and if unable to do so, it must reject the authentication.
/// If the flag is set (1), then the application server MAY skip its own validation of the transited field, relying on the validation performed by the KDC.
/// At its option the application server MAY still apply its own validation based on a separate policy for acceptance.
/// This flag is new since RFC 1510.
/// </summary>
TRANSITED_POLICY_CHECKED = (uint)1 << 19,
/// <summary>
/// This flag indicates that the server (not the client) specified in the ticket has been determined by policy of the realm to be a suitable recipient of delegation.
/// A client can use the presence of this flag to help it decide whether to delegate credentials (either grant a proxy or a forwarded TGT) to this server.
/// The client is free to ignore the value of this flag. When setting this flag, an administrator should consider the security and placement of the server
/// on which the service will run, as well as whether the service requires the use of delegated credentials.
/// This flag is new since RFC 1510.
/// </summary>
OK_AS_DELEGATE = (uint)1 << 18
}
/// <summary>
/// KRB FLAGS, can find in rfc 4120
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
[Flags]
public enum KdcOptions : uint
{
/// <summary>
/// This signifies Validate KRB Flag
/// </summary>
VALIDATE = 0x00000001,
/// <summary>
/// This signifies RENEW KRB Flag
/// </summary>
RENEW = 0x00000002,
/// <summary>
/// This signifies UNUSED29 KRB Flag
/// </summary>
UNUSED29 = 0x00000004,
/// <summary>
/// This signifies ENCTKTINSKEY KRB Flag
/// </summary>
ENCTKTINSKEY = 0x00000008,
/// <summary>
/// This signifies RENEWABLEOK KRB Flag
/// </summary>
RENEWABLEOK = 0x00000010,
/// <summary>
/// This signifies DISABLETRANSITEDCHECK Flag
/// </summary>
DISABLETRANSITEDCHECK = 0x00000020,
/// <summary>
/// This signifies UNUSED16 Flag
/// </summary>
UNUSED16 = 0x0000FFC0,
/// <summary>
/// This signifies CANONICALIZE Flag
/// </summary>
CANONICALIZE = 0x00010000,
/// <summary>
/// This signifies CNAMEINADDLTKT Flag
/// </summary>
CNAMEINADDLTKT = 0x00020000,
/// <summary>
/// This signifies OK_AS_DELEGATE KRB Flag
/// </summary>
OK_AS_DELEGATE = 0x00040000,
/// <summary>
/// This signifies UNUSED12 KRB Flag
/// </summary>
UNUSED12 = 0x00080000,
/// <summary>
/// This signifies OPTHARDWAREAUTH KRB Flag
/// </summary>
OPTHARDWAREAUTH = 0x00100000,
/// <summary>
/// This signifies UNUSED10 KRB Flag
/// </summary>
PREAUTHENT = 0x00200000,
/// <summary>
/// This signifies UNUSED9 KRB Flag
/// </summary>
INITIAL = 0x00400000,
/// <summary>
/// This signifies RENEWABLE KRB Flag
/// </summary>
RENEWABLE = 0x00800000,
/// <summary>
/// This signifies UNUSED7 KRB Flag
/// </summary>
UNUSED7 = 0x01000000,
/// <summary>
/// This signifies POSTDATED KRB Flag
/// </summary>
POSTDATED = 0x02000000,
/// <summary>
/// This signifies ALLOWPOSTDATE KRB Flag
/// </summary>
ALLOWPOSTDATE = 0x04000000,
/// <summary>
/// This signifies PROXY KRB Flag
/// </summary>
PROXY = 0x08000000,
/// <summary>
/// This signifies PROXIABLE KRB Flag
/// </summary>
PROXIABLE = 0x10000000,
/// <summary>
/// This signifies FORWARDED KRB Flag
/// </summary>
FORWARDED = 0x20000000,
/// <summary>
/// This signifies FORWARDABLE KRB Flag
/// </summary>
FORWARDABLE = 0x40000000,
/// <summary>
/// This signifies RESERVED KRB Flag
/// </summary>
RESERVED = 0x80000000,
}
/// <summary>
/// Represents the valid error messages associated with KILE.
/// Reference rfc 4120 section 7.5.9. Error Codes
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
public enum KRB_ERROR_CODE : int
{
/// <summary>
/// No error
/// </summary>
NONE = 0,
/// <summary>
/// Client's entry in database has expired
/// </summary>
KDC_ERR_NAME_EXP = 1,
/// <summary>
/// Server's entry in database has expired
/// </summary>
KDC_ERR_SERVICE_EXP = 2,
/// <summary>
/// Requested protocol version number not supported
/// </summary>
KDC_ERR_BAD_PVNO = 3,
/// <summary>
/// Client's key encrypted in old master key
/// </summary>
KDC_ERR_C_OLD_MAST_KVNO = 4,
/// <summary>
/// Server's key encrypted in old master key
/// </summary>
KDC_ERR_S_OLD_MAST_KVNO = 5,
/// <summary>
/// Client not found in Kerberos database
/// </summary>
KDC_ERR_C_PRINCIPAL_UNKNOWN = 6,
/// <summary>
/// Server not found in Kerberos database
/// </summary>
KDC_ERR_S_PRINCIPAL_UNKNOWN = 7,
/// <summary>
/// Multiple principal entries in database
/// </summary>
KDC_ERR_PRINCIPAL_NOT_UNIQUE = 8,
/// <summary>
/// The client or server has a null key
/// </summary>
KDC_ERR_NULL_KEY = 9,
/// <summary>
/// Ticket not eligible for postdating
/// </summary>
KDC_ERR_CANNOT_POSTDATE = 10,
/// <summary>
/// Requested starttime is later than endtime
/// </summary>
KDC_ERR_NEVER_VALID = 11,
/// <summary>
/// KDC policy rejects request
/// </summary>
KDC_ERR_POLICY = 12,
/// <summary>
/// KDC cannot accommodate requested option
/// </summary>
KDC_ERR_BADOPTION = 13,
/// <summary>
/// KDC has no support for encryption type
/// </summary>
KDC_ERR_ETYPE_NOTSUPP = 14,
/// <summary>
/// KDC has no support for checksum type
/// </summary>
KDC_ERR_SUMTYPE_NOSUPP = 15,
/// <summary>
/// KDC has no support for padata type
/// </summary>
KDC_ERR_PADATA_TYPE_NOSUPP = 16,
/// <summary>
/// KDC has no support for transited type
/// </summary>
KDC_ERR_TRTYPE_NOSUPP = 17,
/// <summary>
/// Clients credentials have been revoked
/// </summary>
KDC_ERR_CLIENT_REVOKED = 18,
/// <summary>
/// Credentials for server have been revoked
/// </summary>
KDC_ERR_SERVICE_REVOKED = 19,
/// <summary>
/// TGT has been revoked
/// </summary>
KDC_ERR_TGT_REVOKED = 20,
/// <summary>
/// Client not yet valid; try again later
/// </summary>
KDC_ERR_CLIENT_NOTYET = 21,
/// <summary>
/// Server not yet valid; try again later
/// </summary>
KDC_ERR_SERVICE_NOTYET = 22,
/// <summary>
/// Password has expired;change password to reset
/// </summary>
KDC_ERR_KEY_EXPIRED = 23,
/// <summary>
/// Pre-authentication information was invalid
/// </summary>
KDC_ERR_PREAUTH_FAILED = 24,
/// <summary>
/// Additional pre-authentication required
/// </summary>
KDC_ERR_PREAUTH_REQUIRED = 25,
/// <summary>
/// Requested server and ticket don't match
/// </summary>
KDC_ERR_SERVER_NOMATCH = 26,
/// <summary>
/// Server principal valid for user2user only
/// </summary>
KDC_ERR_MUST_USE_USER2USER = 27,
/// <summary>
/// KDC Policy rejects transited path
/// </summary>
KDC_ERR_PATH_NOT_ACCEPTED = 28,
/// <summary>
/// A service is not available
/// </summary>
KDC_ERR_SVC_UNAVAILABLE = 29,
/// <summary>
/// Integrity check on decrypted field failed
/// </summary>
KRB_AP_ERR_BAD_INTEGRITY = 31,
/// <summary>
/// Ticket expired
/// </summary>
KRB_AP_ERR_TKT_EXPIRED = 32,
/// <summary>
/// Ticket not yet valid
/// </summary>
KRB_AP_ERR_TKT_NYV = 33,
/// <summary>
/// Request is a replay
/// </summary>
KRB_AP_ERR_REPEAT = 34,
/// <summary>
/// The ticket isn't for us
/// </summary>
KRB_AP_ERR_NOT_US = 35,
/// <summary>
/// Ticket and authenticator don't match
/// </summary>
KRB_AP_ERR_BADMATCH = 36,
/// <summary>
/// Clock skew too great
/// </summary>
KRB_AP_ERR_SKEW = 37,
/// <summary>
/// Incorrect net address
/// </summary>
KRB_AP_ERR_BADADDR = 38,
/// <summary>
/// Protocol version mismatch
/// </summary>
KRB_AP_ERR_BADVERSION = 39,
/// <summary>
/// Invalid msg type
/// </summary>
KRB_AP_ERR_MSG_TYPE = 40,
/// <summary>
/// Message stream modified
/// </summary>
KRB_AP_ERR_MODIFIED = 41,
/// <summary>
/// Message out of order
/// </summary>
KRB_AP_ERR_BADORDER = 42,
/// <summary>
/// Specified version of key is not available
/// </summary>
KRB_AP_ERR_BADKEYVER = 44,
/// <summary>
/// Service key not available
/// </summary>
KRB_AP_ERR_NOKEY = 45,
/// <summary>
/// Mutual authentication failed
/// </summary>
KRB_AP_ERR_MUT_FAIL = 46,
/// <summary>
/// Incorrect message direction
/// </summary>
KRB_AP_ERR_BADDIRECTION = 47,
/// <summary>
/// Alternative authentication method required
/// </summary>
KRB_AP_ERR_METHOD = 48,
/// <summary>
/// Incorrect sequence number in message
/// </summary>
KRB_AP_ERR_BADSEQ = 49,
/// <summary>
/// Inappropriate type of checksum in message
/// </summary>
KRB_AP_ERR_INAPP_CKSUM = 50,
/// <summary>
/// Policy rejects transited path
/// </summary>
KRB_AP_PATH_NOT_ACCEPTED = 51,
/// <summary>
/// Response too big for UDP retry with TCP
/// </summary>
KRB_ERR_RESPONSE_TOO_BIG = 52,
/// <summary>
/// Generic error (description in e-text)
/// </summary>
KRB_ERR_GENERIC = 60,
/// <summary>
/// Field is too long for this implementation
/// </summary>
KRB_ERR_FIELD_TOOLONG = 61,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERROR_CLIENT_NOT_TRUSTED = 62,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERROR_KDC_NOT_TRUSTED = 63,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERROR_INVALID_SIG = 64,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERR_KEY_TOO_WEAK = 65,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERR_CERTIFICATE_MISMATCH = 66,
/// <summary>
/// No TGT available to validate USER-TO-USER
/// </summary>
KRB_AP_ERR_NO_TGT = 67,
/// <summary>
/// Reserved for future use
/// </summary>
KDC_ERR_WRONG_REALM = 68,
/// <summary>
/// Ticket must be for USER-TO-USER
/// </summary>
KRB_AP_ERR_USER_TO_USER_REQUIRED = 69,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERR_CANT_VERIFY_CERTIFICATE = 70,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERR_INVALID_CERTIFICATE = 71,
/// <summary>
/// Reserved for PKINIT
/// </summary>
KDC_ERR_REVOKED_CERTIFICATE = 72,
/// <summary>
/// KILE will return a zero-length message whenever it receives a message that is either not well-formed or not supported.
/// </summary>
ZERO_LENGTH_MESSAGE
}
/// <summary>
/// Represents different modes associated with the KRB_PRIV message.
/// </summary>
public enum KRB_PRIV_REQUEST
{
/// <summary>
/// Represents a KRB_PRIV message with timestamp
/// </summary>
KrbPrivWithTimeStamp,
/// <summary>
/// Represents a KRB_PRIV message with sequencenumber
/// </summary>
KrbPrivWithSequenceNumber,
}
/// <summary>
/// Checksum algorithm type for Wrap and GetMic token.
/// </summary>
public enum SGN_ALG : ushort
{
/// <summary>
/// DES MAC MD5 algorithm in rfc[1964].
/// </summary>
DES_MAC_MD5 = 0x0000,
/// <summary>
/// MD2.5 algorithm in rfc[1964].
/// </summary>
MD2_5 = 0x0100,
/// <summary>
/// DES-MAC algorithm in rfc[1964].
/// </summary>
DES_MAC = 0x0200,
/// <summary>
/// HMAC algorithm in rfc[4757].
/// </summary>
HMAC = 0x1100,
}
/// <summary>
/// Seal flag in Wrap and GetMic token.
/// </summary>
public enum SEAL_ALG : ushort
{
/// <summary>
/// DES encryption.
/// </summary>
DES = 0x0000,
/// <summary>
/// RC4 encryption.
/// </summary>
RC4 = 0x1000,
/// <summary>
/// No encryption.
/// </summary>
NONE = 0xffff,
}
/// <summary>
/// AuthorizationData_element type
/// this type value can be find in rfc 4120
/// </summary>
public enum AuthorizationData_elementType : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// AD-IF-RELEVANT is (1).
/// </summary>
AD_IF_RELEVANT = 1,
/// <summary>
/// The ad-type for AD-KDC-ISSUED is (4).
/// </summary>
AD_KDC_ISSUED = 4,
/// <summary>
/// The ad-type for AD-AND-OR is (5).
/// </summary>
AD_AND_OR = 5,
/// <summary>
/// The ad-type for AD-MANDATORY-FOR-KDC is (8).
/// </summary>
AD_MANDATORY_FOR_KDC = 8,
/// <summary>
/// The ad-type of AD-WIN2K-PAC
/// </summary>
AD_WIN2K_PAC = 128,
/// <summary>
/// type KERB_AUTH_DATA_TOKEN_RESTRICTIONS (141), containing the KERB-AD-RESTRICTION-ENTRY structure (
/// </summary>
KERB_AUTH_DATA_TOKEN_RESTRICTIONS = 141,
/// <summary>
/// The Authorization Data Type AD-AUTH-DATA-AP-OPTIONS has an ad-type
/// of 143 and ad-data of KERB_AP_OPTIONS_CBT (0x4000)
/// </summary>
AD_AUTH_DATA_AP_OPTIONS = 143,
/// <summary>
/// The Authorization Data Type AD-fx-fast-armor has an ad-type
/// of 71 and null ad-data.
/// </summary>
AD_FX_FAST_ARMOR = 71,
/// <summary>
/// The Authorization Data Type AD-fx-fast-used has an ad-type
/// of 72 and null ad-data.
/// </summary>
AD_FX_FAST_USED = 72
}
/// <summary>
/// The principal type of Principal, can be found in rfc 4120
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
public enum PrincipalType : int
{
/// <summary>
/// Name type not known
/// </summary>
NT_UNKNOWN = 0,
/// <summary>
/// Just the name of the principal as in DCE,or for users
/// </summary>
NT_PRINCIPAL = 1,
/// <summary>
/// Service and other unique instance (krbtgt)
/// </summary>
NT_SRV_INST = 2,
/// <summary>
/// Service with host name as instance (telnet, rcommands)
/// </summary>
NT_SRV_HST = 3,
/// <summary>
/// Service with host as remaining components
/// </summary>
NT_SRV_XHST = 4,
/// <summary>
/// Unique ID
/// </summary>
NT_UID = 5,
/// <summary>
/// Encoded X.509 Distinguished name [RFC2253]
/// </summary>
NT_X500_PRINCIPAL = 6,
/// <summary>
/// Name in form of SMTP email name(e.g., user@example.com)
/// </summary>
NT_SMTP_NAME = 7,
/// <summary>
/// Enterprise name - may be mapped to principal name
/// </summary>
NT_ENTERPRISE = 10
}
/// <summary>
/// The APOptions,can find in rfc 4120.
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
[Flags]
public enum ApOptions : uint
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// Reserved for future expansion of this field.
/// </summary>
Reserved = 0x80000000,
/// <summary>
/// The USE-SESSION-KEY option indicates that the ticket the client is presenting to a
/// server is encrypted in the session key from the server's TGT. When this option is not
/// specified, the ticket is encrypted in the server's secret key.
/// </summary>
UseSessionKey = 0x40000000,
/// <summary>
/// The MUTUAL-REQUIRED option tells the server that the client requires mutual
/// authentication, and that it must respond with a KRB_AP_REP message.
/// </summary>
MutualRequired = 0x20000000,
}
/// <summary>
/// The PA PAC Options
/// </summary>
[Flags]
public enum PacOptions : uint
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// Reserved for future expansion of this field.
/// </summary>
Claims = 0x80000000,
/// <summary>
/// The USE-SESSION-KEY option indicates that the ticket the client is presenting to a
/// server is encrypted in the session key from the server's TGT. When this option is not
/// specified, the ticket is encrypted in the server's secret key.
/// </summary>
BranchAware = 0x40000000,
/// <summary>
/// The MUTUAL-REQUIRED option tells the server that the client requires mutual
/// authentication, and that it must respond with a KRB_AP_REP message.
/// </summary>
ForwardToFullDc = 0x20000000,
}
/// <summary>
/// The transport type.
/// </summary>
public enum TransportType
{
TCP,
UDP,
}
/// <summary>
/// The ip type.
/// </summary>
public enum IpType
{
Ipv4,
Ipv6,
}
/// <summary>
/// The checksum "Flags" field is used to convey service options or extension negotiation information.
/// It is defined in [RFC 4121] section 4.1.1.1.
/// </summary>
[Flags]
public enum ChecksumFlags : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// When GSS_C_DELEG_FLAG is set, the DlgOpt, Dlgth, and Deleg fields of the checksum data MUST
/// immediately follow the Flags field.
/// </summary>
GSS_C_DELEG_FLAG = 0x00000001,
/// <summary>
/// MutualAuthentication.
/// </summary>
GSS_C_MUTUAL_FLAG = 0x00000002,
/// <summary>
/// ReplayDetect.
/// </summary>
GSS_C_REPLAY_FLAG = 0x00000004,
/// <summary>
/// SequenceDetect.
/// </summary>
GSS_C_SEQUENCE_FLAG = 0x00000008,
/// <summary>
/// Confidentiality.
/// </summary>
GSS_C_CONF_FLAG = 0x00000010,
/// <summary>
/// Integrity.
/// </summary>
GSS_C_INTEG_FLAG = 0x00000020,
/// <summary>
/// This flag was added for use with Microsoft's implementation of Distributed Computing Environment
/// Remote Procedure Call (DCE RPC), which initially expected three legs of authentication.
/// </summary>
GSS_C_DCE_STYLE = 0x00001000,
/// <summary>
/// This flag allows the client to indicate to the server that it should only allow the server application
/// to identify the client by name and ID, but not to impersonate the client.
/// </summary>
GSS_C_IDENTIFY_FLAG = 0x00002000,
/// <summary>
/// Setting this flag indicates that the client wants to be informed of extended error information.
/// </summary>
GSS_C_EXTENDED_ERROR_FLAG = 0x00004000,
}
/// <summary>
/// The address type ,can find in
/// http://www.ietf.org/rfc/rfc4120.txt
/// </summary>
public enum AddressType : int
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// ipv4
/// </summary>
IPv4 = 2,
/// <summary>
/// Directional
/// </summary>
Directional = 3,
/// <summary>
///CHAOSnet addresses
/// </summary>
ChaosNet = 5,
/// <summary>
/// Xerox Network Services (XNS) addresses
/// </summary>
XNS = 6,
/// <summary>
/// ISO addresses
/// </summary>
ISO = 7,
/// <summary>
/// DECnet Phase IV addresses
/// </summary>
DECNET_Phase_IV = 12,
/// <summary>
/// AppleTalk Datagram Delivery Protocol (DDP) addresses
/// </summary>
AppleTalk_DDP = 16,
/// <summary>
/// net bios address
/// </summary>
NetBios = 20,
/// <summary>
/// ipv6
/// </summary>
IPv6 = 24,
}
/// <summary>
/// Token ID in GSSAPI.
/// </summary>
public enum TOK_ID : ushort
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// Mic token ID in [rfc1964] and [rfc4757].
/// </summary>
Mic1964_4757 = 0x0101,
/// <summary>
/// Wrap token ID in [rfc1964] and [rfc4757].
/// </summary>
Wrap1964_4757 = 0x0201,
/// <summary>
/// Mic token ID in [rfc4121].
/// </summary>
Mic4121 = 0x0404,
/// <summary>
/// Wrap token ID in [rfc4121].
/// </summary>
Wrap4121 = 0x0504,
/// <summary>
/// KRB_AP_REQ token ID.
/// </summary>
KRB_AP_REQ = 0x0100,
/// <summary>
/// KRB_AP_REP token ID.
/// </summary>
KRB_AP_REP = 0x0200,
/// <summary>
/// KRB_ERROR token ID.
/// </summary>
KRB_ERROR = 0x0300,
}
/// <summary>
/// A 32-bit unsigned integer indicating the token information type.
/// </summary>
public enum LSAP_TOKEN_INFO_INTEGRITY_Flags : uint
{
/// <summary>
/// Full token.
/// </summary>
FULL_TOKEN = 0x00000000,
/// <summary>
/// User Account Control (UAC) restricted token.
/// </summary>
UAC_TOKEN = 0x00000001,
}
/// <summary>
/// A 32-bit unsigned integer indicating the integrity level of the calling process.
/// </summary>
public enum LSAP_TOKEN_INFO_INTEGRITY_TokenIL : uint
{
/// <summary>
/// Untrusted.
/// </summary>
Untrusted = 0x00000000,
/// <summary>
/// Low.
/// </summary>
Low = 0x00001000,
/// <summary>
/// Medium.
/// </summary>
Medium = 0x00002000,
/// <summary>
/// High.
/// </summary>
High = 0x00003000,
/// <summary>
/// System.
/// </summary>
System = 0x00004000,
/// <summary>
/// Protected process.
/// </summary>
Protected = 0x00005000,
}
public enum KrbFastArmorType
{
FX_FAST_ARMOR_AP_REQUEST = 1
}
/// <summary>
/// The data in the msDS-SupportedEncryptionTypes attribute([MS-ADA2] section 2.402).
/// </summary>
[Flags]
public enum SupportedEncryptionTypes : uint
{
DES_CBC_CRC = 0x00000001,
DES_CBC_MD5 = 0x00000002,
RC4_HMAC = 0x00000004,
AES128_CTS_HMAC_SHA1_96 = 0x00000008,
AES256_CTS_HMAC_SHA1_96 = 0x00000010,
FAST_Supported = 0x00010000,
CompoundIdentity_Supported = 0x00020000,
Claims_Supported = 0x00040000,
ResSIDCompression_Disabled = 0x00080000
}
[Flags]
public enum FastOptionFlags : uint
{
None = 0x00000000,
Hide_Client_Names = 0x40000000
}
/// <summary>
/// AP request authenticator checksum structure.
/// </summary>
public struct AuthCheckSum
{
public int Lgth;
public byte[] Bnd; // 16 bytes
public int Flags;
public short DlgOpt;
public short Dlgth;
public byte[] Deleg;
public byte[] Exts;
}
/// <summary>
/// Principal
/// </summary>
public class Principal
{
/// <summary>
/// Type of Principal
/// </summary>
public KerberosAccountType Type
{
get;
set;
}
/// <summary>
/// Realm of this principal
/// </summary>
public Realm Realm
{
get;
set;
}
/// <summary>
/// Principal name
/// </summary>
public PrincipalName Name
{
get;
set;
}
/// <summary>
/// Password of principal
/// </summary>
public string Password
{
get;
set;
}
/// <summary>
/// Salt of principal
/// </summary>
public string Salt
{
get;
set;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Type of Principal</param>
/// <param name="name">Principal name</param>
/// <param name="password">Password of principal</param>
public Principal(KerberosAccountType type, Realm realm, PrincipalName name, string password, string salt)
{
Type = type;
Realm = realm;
Name = name;
Password = password;
Salt = salt;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Type of Principal</param>
/// <param name="name">Principal name</param>
/// <param name="password">Password of principal</param>
/// <param name="salt">Salt of principal</param>
public Principal(KerberosAccountType type, string realm, string name, string password, string salt)
{
Type = type;
Realm = new Realm(realm);
Name = new PrincipalName(new KerbInt32((int)PrincipalType.NT_PRINCIPAL), KerberosUtility.String2SeqKerbString(name));
Password = password;
Salt = salt;
}
}
/// <summary>
/// Kerberos ticket
/// </summary>
public class KerberosTicket
{
/// <summary>
/// Ticket
/// </summary>
public Ticket Ticket
{
get;
set;
}
/// <summary>
/// Owner of ticket
/// </summary>
public PrincipalName TicketOwner
{
get;
set;
}
/// <summary>
/// Session key in ticket
/// </summary>
public EncryptionKey SessionKey
{
get;
set;
}
/// <summary>
/// Create a Kerberos ticket
/// </summary>
/// <param name="ticket">Ticket</param>
/// <param name="ticketOwner">Owner of ticket</param>
/// <param name="sessionKey">Session key in ticket</param>
public KerberosTicket(Ticket ticket, PrincipalName ticketOwner, EncryptionKey sessionKey)
{
this.Ticket = ticket;
this.TicketOwner = ticketOwner;
this.SessionKey = sessionKey;
}
}
/// <summary>
/// Error types in KKDCP
/// </summary>
public enum KKDCPError
{
STATUS_SUCCESS,
STATUS_AUTHENTICATION_FIREWALL_FAILED,
STATUS_NO_LOGON_SERVERS
}
/// <summary>
/// Error types for Kpassword
/// </summary>
public enum KpasswdError : ushort
{
/// <summary>
/// request succeeds
/// </summary>
KRB5_KPASSWD_SUCCESS,
/// <summary>
/// request fails due to being malformed
/// </summary>
KRB5_KPASSWD_MALFORMED,
/// <summary>
/// request fails due to "hard" error in processing the request
/// </summary>
KRB5_KPASSWD_HARDERROR,
/// <summary>
/// request fails due to an error in authentication processing
/// </summary>
KRB5_KPASSWD_AUTHERROR,
/// <summary>
/// request fails due to a "soft" error in processing the request
/// </summary>
KRB5_KPASSWD_SOFTERROR,
/// <summary>
/// requestor not authorized
/// </summary>
KRB5_KPASSWD_ACCESSDENIED,
/// <summary>
/// protocol version unsupported, not used in windows
/// </summary>
KRB5_KPASSWD_BAD_VERSION,
/// <summary>
/// initial flag required, not used in windows
/// </summary>
KRB5_KPASSWD_INITIAL_FLAG_NEEDED,
/// <summary>
/// request fails for some other reason
/// </summary>
KRB5_KPASSWD_OTHER_ERRORS = 0xFFFF
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace System.Resources
{
public sealed class ResourceReader : IDisposable
{
private const int ResSetVersion = 2;
private const int ResourceTypeCodeString = 1;
private const int ResourceManagerMagicNumber = unchecked((int)0xBEEFCACE);
private const int ResourceManagerHeaderVersionNumber = 1;
private Stream _stream; // backing store we're reading from.
private long _nameSectionOffset; // Offset to name section of file.
private long _dataSectionOffset; // Offset to Data section of file.
private long _resourceStreamStart; // beginning of the resource stream, which could be part of a longer file stream
private int[] _namePositions; // relative locations of names
private int _stringTypeIndex;
private int _numOfTypes;
private int _numResources; // Num of resources files, in case arrays aren't allocated.
private int _version;
// "System.String, mscorlib" representation in resources stream
private readonly static byte[] s_SystemStringName = EncodeStringName();
public ResourceReader(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
if (!stream.CanSeek)
throw new ArgumentException(SR.Argument_StreamNotSeekable);
_stream = stream;
ReadResources();
}
public void Dispose()
{
Dispose(true);
}
[System.Security.SecuritySafeCritical] // auto-generated
private unsafe void Dispose(bool disposing)
{
if (_stream != null) {
if (disposing) {
Stream stream = _stream;
_stream = null;
if (stream != null) {
stream.Dispose();
}
_namePositions = null;
}
}
}
private void SkipString()
{
int stringLength;
if (!_stream.TryReadInt327BitEncoded(out stringLength) || stringLength < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_stream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNamePosition(int index)
{
Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
int r;
r = _namePositions[index];
if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesNameInvalidOffset + ":" + r);
}
return r;
}
public IDictionaryEnumerator GetEnumerator()
{
if (_stream == null)
throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
private void SuccessElseEosException(bool condition)
{
if (!condition) {
throw new EndOfStreamException();
}
}
private string GetKeyForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(_resourceStreamStart + nameVA + _nameSectionOffset, SeekOrigin.Begin);
var result = _stream.ReadString(utf16: true);
int dataOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataOffset));
if (dataOffset < 0 || dataOffset >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + " offset :" + dataOffset);
}
return result;
}
}
private string GetValueForNameIndex(int index)
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
lock (this)
{
_stream.Seek(_resourceStreamStart + nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
int dataPos;
SuccessElseEosException(_stream.TryReadInt32(out dataPos));
if (dataPos < 0 || dataPos >= _stream.Length - _dataSectionOffset)
{
throw new FormatException(SR.BadImageFormat_ResourcesDataInvalidOffset + dataPos);
}
try
{
return ReadStringElseNull(dataPos);
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
catch (ArgumentOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
}
//returns null if the resource is not a string
private string ReadStringElseNull(int pos)
{
_stream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex;
if(!_stream.TryReadInt327BitEncoded(out typeIndex)) {
throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
if (_version == 1) {
if (typeIndex == -1 || !IsString(typeIndex)) {
return null;
}
}
else
{
if (ResourceTypeCodeString != typeIndex) {
return null;
}
}
return _stream.ReadString(utf16 : false);
}
private void ReadResources()
{
Debug.Assert(_stream != null, "ResourceReader is closed!");
try
{
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
catch (EndOfStreamException eof)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
catch (IndexOutOfRangeException e)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
private void _ReadResources()
{
_resourceStreamStart = _stream.Position;
// Read out the ResourceManager header
// Read out magic number
int magicNum;
SuccessElseEosException(_stream.TryReadInt32(out magicNum));
if (magicNum != ResourceManagerMagicNumber)
throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion;
SuccessElseEosException(_stream.TryReadInt32(out resMgrHeaderVersion));
//number of bytes to skip over to get past ResMgr header
int numBytesToSkip;
SuccessElseEosException(_stream.TryReadInt32(out numBytesToSkip));
if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
if (resMgrHeaderVersion > 1) {
_stream.Seek(numBytesToSkip, SeekOrigin.Current);
}
else {
// We don't care about numBytesToSkip; read the rest of the header
//Due to legacy : this field is always a variant of System.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
//So we Skip the type name for resourcereader unlike Desktop
SkipString();
// Skip over type name for a suitable ResourceSet
SkipString();
}
// Read RuntimeResourceSet header
// Do file version check
SuccessElseEosException(_stream.TryReadInt32(out _version));
if (_version != ResSetVersion && _version != 1) {
throw new ArgumentException(SR.Arg_ResourceFileUnsupportedVersion + "Expected:" + ResSetVersion + "but got:" + _version);
}
// number of resources
SuccessElseEosException(_stream.TryReadInt32(out _numResources));
if (_numResources < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
SuccessElseEosException(_stream.TryReadInt32(out _numOfTypes));
if (_numOfTypes < 0) {
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// find index of System.String
for (int i = 0; i < _numOfTypes; i++)
{
if(_stream.StartsWith(s_SystemStringName, advance : true)){
_stringTypeIndex = i;
}
}
// Prepare to read in the array of name hashes
// Note that the name hashes array is aligned to 8 bytes so
// we can use pointers into it on 64 bit machines. (4 bytes
// may be sufficient, but let's plan for the future)
// Skip over alignment stuff. All public .resources files
// should be aligned No need to verify the byte values.
long pos = _stream.Position;
int alignBytes = ((int)pos) & 7;
if (alignBytes != 0)
{
for (int i = 0; i < 8 - alignBytes; i++)
{
_stream.ReadByte();
}
}
//Skip over the array of name hashes
for (int i = 0; i < _numResources; i++)
{
int hash;
SuccessElseEosException(_stream.TryReadInt32(out hash));
}
// Read in the array of relative positions for all the names.
_namePositions = new int[_numResources];
for (int i = 0; i < _numResources; i++)
{
int namePosition;
SuccessElseEosException(_stream.TryReadInt32(out namePosition));
if (namePosition < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
// Read location of data section.
int dataSectionOffset;
SuccessElseEosException(_stream.TryReadInt32(out dataSectionOffset));
if (dataSectionOffset < 0)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_dataSectionOffset = dataSectionOffset;
// Store current location as start of name section
_nameSectionOffset = _stream.Position - _resourceStreamStart;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
if (_dataSectionOffset < _nameSectionOffset)
{
throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
}
private bool IsString(int typeIndex)
{
if (typeIndex < 0 || typeIndex >= _numOfTypes)
{
throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
return typeIndex == _stringTypeIndex;
}
private static byte[] EncodeStringName()
{
var type = typeof(string);
var name = type.AssemblyQualifiedName;
int length = name.IndexOf(", Version=");
var buffer = new byte[length + 1];
var encoded = Encoding.UTF8.GetBytes(name, 0, length, buffer, 1);
// all characters should be single byte encoded and the type name shorter than 128 bytes
// this restriction is needed to encode without multiple allocations of the buffer
if (encoded > 127 || encoded != length)
{
throw new NotSupportedException();
}
checked { buffer[0] = (byte)encoded; }
return buffer;
}
internal sealed class ResourceEnumerator : IDictionaryEnumerator
{
private const int ENUM_DONE = int.MinValue;
private const int ENUM_NOT_STARTED = -1;
private ResourceReader _reader;
private bool _currentIsValid;
private int _currentName;
internal ResourceEnumerator(ResourceReader reader)
{
_currentName = ENUM_NOT_STARTED;
_reader = reader;
}
public bool MoveNext()
{
if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
{
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
}
_currentIsValid = true;
_currentName++;
return true;
}
public Object Key
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetKeyForNameIndex(_currentName);
}
}
public Object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
string key = _reader.GetKeyForNameIndex(_currentName);
string value = _reader.GetValueForNameIndex(_currentName);
return new DictionaryEntry(key, value);
}
}
public Object Value
{
get
{
if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
if (!_currentIsValid) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
return _reader.GetValueForNameIndex(_currentName);
}
}
public void Reset()
{
if (_reader._stream == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
}
}
}
| |
using Cosmos.Build.Common;
using IL2CPU.API.Attribs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
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;
}
}
}
| |
namespace Obscur.Core.Cryptography.Ciphers.Block.Primitives
{
/**
* An RC6 engine.
*/
public class Rc6Engine
: BlockCipherBase
{
private const int wordSize = 32;
private const int bytesPerWord = wordSize/8;
private const int BLOCK_SIZE = 4 * bytesPerWord;
/*
* the number of rounds to perform
*/
private const int _noRounds = 20;
/*
* the expanded key array of size 2*(rounds + 1)
*/
private int [] _S;
/*
* our "magic constants" for wordSize 32
*
* Pw = Odd((e-2) * 2^wordsize)
* Qw = Odd((o-2) * 2^wordsize)
*
* where e is the base of natural logarithms (2.718281828...)
* and o is the golden ratio (1.61803398...)
*/
private const int P32 = unchecked((int) 0xb7e15163);
private const int Q32 = unchecked((int) 0x9e3779b9);
private const int LGW = 5; // log2(32)
public Rc6Engine() : base(BlockCipher.Rc6, BLOCK_SIZE) { }
/// <inheritdoc />
protected override void InitState()
{
SetKey(Key);
}
/// <inheritdoc />
internal override int ProcessBlockInternal(byte[] input, int inOff, byte[] output, int outOff)
{
return (Encrypting)
? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
/// <inheritdoc />
public override void Reset()
{
}
/**
* Re-key the cipher.
*
* @param inKey the key to be used
*/
private void SetKey(
byte[] key)
{
//
// KEY EXPANSION:
//
// There are 3 phases to the key expansion.
//
// Phase 1:
// Copy the secret key K[0...b-1] into an array L[0..c-1] of
// c = ceil(b/u), where u = wordSize/8 in little-endian order.
// In other words, we fill up L using u consecutive key bytes
// of K. Any unfilled byte positions in L are zeroed. In the
// case that b = c = 0, set c = 1 and L[0] = 0.
//
// compute number of dwords
int c = (key.Length + (bytesPerWord - 1)) / bytesPerWord;
if (c == 0)
{
c = 1;
}
int[] L = new int[(key.Length + bytesPerWord - 1) / bytesPerWord];
// load all key bytes into array of key dwords
for (int i = key.Length - 1; i >= 0; i--)
{
L[i / bytesPerWord] = (L[i / bytesPerWord] << 8) + (key[i] & 0xff);
}
//
// Phase 2:
// Key schedule is placed in a array of 2+2*ROUNDS+2 = 44 dwords.
// Initialize S to a particular fixed pseudo-random bit pattern
// using an arithmetic progression modulo 2^wordsize determined
// by the magic numbers, Pw & Qw.
//
_S = new int[2+2*_noRounds+2];
_S[0] = P32;
for (int i=1; i < _S.Length; i++)
{
_S[i] = (_S[i-1] + Q32);
}
//
// Phase 3:
// Mix in the user's secret key in 3 passes over the arrays S & L.
// The max of the arrays sizes is used as the loop control
//
int iter;
if (L.Length > _S.Length)
{
iter = 3 * L.Length;
}
else
{
iter = 3 * _S.Length;
}
int A = 0;
int B = 0;
int ii = 0, jj = 0;
for (int k = 0; k < iter; k++)
{
A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
ii = (ii+1) % _S.Length;
jj = (jj+1) % L.Length;
}
}
private int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
// load A,B,C and D registers from in.
int A = BytesToWord(input, inOff);
int B = BytesToWord(input, inOff + bytesPerWord);
int C = BytesToWord(input, inOff + bytesPerWord*2);
int D = BytesToWord(input, inOff + bytesPerWord*3);
// Do pseudo-round #0: pre-whitening of B and D
B += _S[0];
D += _S[1];
// perform round #1,#2 ... #ROUNDS of encryption
for (int i = 1; i <= _noRounds; i++)
{
int t = 0,u = 0;
t = B*(2*B+1);
t = RotateLeft(t,5);
u = D*(2*D+1);
u = RotateLeft(u,5);
A ^= t;
A = RotateLeft(A,u);
A += _S[2*i];
C ^= u;
C = RotateLeft(C,t);
C += _S[2*i+1];
int temp = A;
A = B;
B = C;
C = D;
D = temp;
}
// do pseudo-round #(ROUNDS+1) : post-whitening of A and C
A += _S[2*_noRounds+2];
C += _S[2*_noRounds+3];
// store A, B, C and D registers to out
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + bytesPerWord);
WordToBytes(C, outBytes, outOff + bytesPerWord*2);
WordToBytes(D, outBytes, outOff + bytesPerWord*3);
return 4 * bytesPerWord;
}
private int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
// load A,B,C and D registers from out.
int A = BytesToWord(input, inOff);
int B = BytesToWord(input, inOff + bytesPerWord);
int C = BytesToWord(input, inOff + bytesPerWord*2);
int D = BytesToWord(input, inOff + bytesPerWord*3);
// Undo pseudo-round #(ROUNDS+1) : post whitening of A and C
C -= _S[2*_noRounds+3];
A -= _S[2*_noRounds+2];
// Undo round #ROUNDS, .., #2,#1 of encryption
for (int i = _noRounds; i >= 1; i--)
{
int t=0,u = 0;
int temp = D;
D = C;
C = B;
B = A;
A = temp;
t = B*(2*B+1);
t = RotateLeft(t, LGW);
u = D*(2*D+1);
u = RotateLeft(u, LGW);
C -= _S[2*i+1];
C = RotateRight(C,t);
C ^= u;
A -= _S[2*i];
A = RotateRight(A,u);
A ^= t;
}
// Undo pseudo-round #0: pre-whitening of B and D
D -= _S[1];
B -= _S[0];
WordToBytes(A, outBytes, outOff);
WordToBytes(B, outBytes, outOff + bytesPerWord);
WordToBytes(C, outBytes, outOff + bytesPerWord*2);
WordToBytes(D, outBytes, outOff + bytesPerWord*3);
return 4 * bytesPerWord;
}
//////////////////////////////////////////////////////////////
//
// PRIVATE Helper Methods
//
//////////////////////////////////////////////////////////////
/**
* Perform a left "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private static int RotateLeft(int x, int y)
{
return ((int)((uint)(x << (y & (wordSize-1)))
| ((uint) x >> (wordSize - (y & (wordSize-1))))));
}
/**
* Perform a right "spin" of the word. The rotation of the given
* word <em>x</em> is rotated left by <em>y</em> bits.
* Only the <em>lg(wordSize)</em> low-order bits of <em>y</em>
* are used to determine the rotation amount. Here it is
* assumed that the wordsize used is a power of 2.
*
* @param x word to rotate
* @param y number of bits to rotate % wordSize
*/
private static int RotateRight(int x, int y)
{
return ((int)(((uint) x >> (y & (wordSize-1)))
| (uint)(x << (wordSize - (y & (wordSize-1))))));
}
private static int BytesToWord(
byte[] src,
int srcOff)
{
int word = 0;
for (int i = bytesPerWord - 1; i >= 0; i--)
{
word = (word << 8) + (src[i + srcOff] & 0xff);
}
return word;
}
private static void WordToBytes(
int word,
byte[] dst,
int dstOff)
{
for (int i = 0; i < bytesPerWord; i++)
{
dst[i + dstOff] = (byte)word;
word = (int) ((uint) word >> 8);
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ResourceManager.V3.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Iam.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedTagValuesClientSnippets
{
/// <summary>Snippet for ListTagValues</summary>
public void ListTagValuesRequestObject()
{
// Snippet: ListTagValues(ListTagValuesRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
ListTagValuesRequest request = new ListTagValuesRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
};
// Make the request
PagedEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValues(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagValue item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagValuesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagValuesAsync</summary>
public async Task ListTagValuesRequestObjectAsync()
{
// Snippet: ListTagValuesAsync(ListTagValuesRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
ListTagValuesRequest request = new ListTagValuesRequest
{
ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
};
// Make the request
PagedAsyncEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValuesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagValue item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagValuesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagValues</summary>
public void ListTagValues()
{
// Snippet: ListTagValues(string, string, int?, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValues(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagValue item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagValuesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagValuesAsync</summary>
public async Task ListTagValuesAsync()
{
// Snippet: ListTagValuesAsync(string, string, int?, CallSettings)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string parent = "a/wildcard/resource";
// Make the request
PagedAsyncEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValuesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagValue item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagValuesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagValues</summary>
public void ListTagValuesResourceNames()
{
// Snippet: ListTagValues(IResourceName, string, int?, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValues(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (TagValue item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTagValuesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTagValuesAsync</summary>
public async Task ListTagValuesResourceNamesAsync()
{
// Snippet: ListTagValuesAsync(IResourceName, string, int?, CallSettings)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValuesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagValue item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagValuesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetTagValue</summary>
public void GetTagValueRequestObject()
{
// Snippet: GetTagValue(GetTagValueRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
GetTagValueRequest request = new GetTagValueRequest
{
TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"),
};
// Make the request
TagValue response = tagValuesClient.GetTagValue(request);
// End snippet
}
/// <summary>Snippet for GetTagValueAsync</summary>
public async Task GetTagValueRequestObjectAsync()
{
// Snippet: GetTagValueAsync(GetTagValueRequest, CallSettings)
// Additional: GetTagValueAsync(GetTagValueRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
GetTagValueRequest request = new GetTagValueRequest
{
TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"),
};
// Make the request
TagValue response = await tagValuesClient.GetTagValueAsync(request);
// End snippet
}
/// <summary>Snippet for GetTagValue</summary>
public void GetTagValue()
{
// Snippet: GetTagValue(string, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string name = "tagValues/[TAG_VALUE]";
// Make the request
TagValue response = tagValuesClient.GetTagValue(name);
// End snippet
}
/// <summary>Snippet for GetTagValueAsync</summary>
public async Task GetTagValueAsync()
{
// Snippet: GetTagValueAsync(string, CallSettings)
// Additional: GetTagValueAsync(string, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string name = "tagValues/[TAG_VALUE]";
// Make the request
TagValue response = await tagValuesClient.GetTagValueAsync(name);
// End snippet
}
/// <summary>Snippet for GetTagValue</summary>
public void GetTagValueResourceNames()
{
// Snippet: GetTagValue(TagValueName, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
TagValueName name = TagValueName.FromTagValue("[TAG_VALUE]");
// Make the request
TagValue response = tagValuesClient.GetTagValue(name);
// End snippet
}
/// <summary>Snippet for GetTagValueAsync</summary>
public async Task GetTagValueResourceNamesAsync()
{
// Snippet: GetTagValueAsync(TagValueName, CallSettings)
// Additional: GetTagValueAsync(TagValueName, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
TagValueName name = TagValueName.FromTagValue("[TAG_VALUE]");
// Make the request
TagValue response = await tagValuesClient.GetTagValueAsync(name);
// End snippet
}
/// <summary>Snippet for CreateTagValue</summary>
public void CreateTagValueRequestObject()
{
// Snippet: CreateTagValue(CreateTagValueRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
CreateTagValueRequest request = new CreateTagValueRequest
{
TagValue = new TagValue(),
ValidateOnly = false,
};
// Make the request
Operation<TagValue, CreateTagValueMetadata> response = tagValuesClient.CreateTagValue(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, CreateTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, CreateTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceCreateTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagValueAsync</summary>
public async Task CreateTagValueRequestObjectAsync()
{
// Snippet: CreateTagValueAsync(CreateTagValueRequest, CallSettings)
// Additional: CreateTagValueAsync(CreateTagValueRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
CreateTagValueRequest request = new CreateTagValueRequest
{
TagValue = new TagValue(),
ValidateOnly = false,
};
// Make the request
Operation<TagValue, CreateTagValueMetadata> response = await tagValuesClient.CreateTagValueAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, CreateTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, CreateTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceCreateTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagValue</summary>
public void CreateTagValue()
{
// Snippet: CreateTagValue(TagValue, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
TagValue tagValue = new TagValue();
// Make the request
Operation<TagValue, CreateTagValueMetadata> response = tagValuesClient.CreateTagValue(tagValue);
// Poll until the returned long-running operation is complete
Operation<TagValue, CreateTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, CreateTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceCreateTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateTagValueAsync</summary>
public async Task CreateTagValueAsync()
{
// Snippet: CreateTagValueAsync(TagValue, CallSettings)
// Additional: CreateTagValueAsync(TagValue, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
TagValue tagValue = new TagValue();
// Make the request
Operation<TagValue, CreateTagValueMetadata> response = await tagValuesClient.CreateTagValueAsync(tagValue);
// Poll until the returned long-running operation is complete
Operation<TagValue, CreateTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, CreateTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceCreateTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagValue</summary>
public void UpdateTagValueRequestObject()
{
// Snippet: UpdateTagValue(UpdateTagValueRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
UpdateTagValueRequest request = new UpdateTagValueRequest
{
TagValue = new TagValue(),
UpdateMask = new FieldMask(),
ValidateOnly = false,
};
// Make the request
Operation<TagValue, UpdateTagValueMetadata> response = tagValuesClient.UpdateTagValue(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, UpdateTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, UpdateTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceUpdateTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagValueAsync</summary>
public async Task UpdateTagValueRequestObjectAsync()
{
// Snippet: UpdateTagValueAsync(UpdateTagValueRequest, CallSettings)
// Additional: UpdateTagValueAsync(UpdateTagValueRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
UpdateTagValueRequest request = new UpdateTagValueRequest
{
TagValue = new TagValue(),
UpdateMask = new FieldMask(),
ValidateOnly = false,
};
// Make the request
Operation<TagValue, UpdateTagValueMetadata> response = await tagValuesClient.UpdateTagValueAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, UpdateTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, UpdateTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceUpdateTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagValue</summary>
public void UpdateTagValue()
{
// Snippet: UpdateTagValue(TagValue, FieldMask, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
TagValue tagValue = new TagValue();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<TagValue, UpdateTagValueMetadata> response = tagValuesClient.UpdateTagValue(tagValue, updateMask);
// Poll until the returned long-running operation is complete
Operation<TagValue, UpdateTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, UpdateTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceUpdateTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateTagValueAsync</summary>
public async Task UpdateTagValueAsync()
{
// Snippet: UpdateTagValueAsync(TagValue, FieldMask, CallSettings)
// Additional: UpdateTagValueAsync(TagValue, FieldMask, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
TagValue tagValue = new TagValue();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<TagValue, UpdateTagValueMetadata> response = await tagValuesClient.UpdateTagValueAsync(tagValue, updateMask);
// Poll until the returned long-running operation is complete
Operation<TagValue, UpdateTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, UpdateTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceUpdateTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValue</summary>
public void DeleteTagValueRequestObject()
{
// Snippet: DeleteTagValue(DeleteTagValueRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
DeleteTagValueRequest request = new DeleteTagValueRequest
{
TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"),
ValidateOnly = false,
Etag = "",
};
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = tagValuesClient.DeleteTagValue(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceDeleteTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValueAsync</summary>
public async Task DeleteTagValueRequestObjectAsync()
{
// Snippet: DeleteTagValueAsync(DeleteTagValueRequest, CallSettings)
// Additional: DeleteTagValueAsync(DeleteTagValueRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
DeleteTagValueRequest request = new DeleteTagValueRequest
{
TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"),
ValidateOnly = false,
Etag = "",
};
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = await tagValuesClient.DeleteTagValueAsync(request);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceDeleteTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValue</summary>
public void DeleteTagValue()
{
// Snippet: DeleteTagValue(string, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string name = "tagValues/[TAG_VALUE]";
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = tagValuesClient.DeleteTagValue(name);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceDeleteTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValueAsync</summary>
public async Task DeleteTagValueAsync()
{
// Snippet: DeleteTagValueAsync(string, CallSettings)
// Additional: DeleteTagValueAsync(string, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string name = "tagValues/[TAG_VALUE]";
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = await tagValuesClient.DeleteTagValueAsync(name);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceDeleteTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValue</summary>
public void DeleteTagValueResourceNames()
{
// Snippet: DeleteTagValue(TagValueName, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
TagValueName name = TagValueName.FromTagValue("[TAG_VALUE]");
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = tagValuesClient.DeleteTagValue(name);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceDeleteTagValue(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteTagValueAsync</summary>
public async Task DeleteTagValueResourceNamesAsync()
{
// Snippet: DeleteTagValueAsync(TagValueName, CallSettings)
// Additional: DeleteTagValueAsync(TagValueName, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
TagValueName name = TagValueName.FromTagValue("[TAG_VALUE]");
// Make the request
Operation<TagValue, DeleteTagValueMetadata> response = await tagValuesClient.DeleteTagValueAsync(name);
// Poll until the returned long-running operation is complete
Operation<TagValue, DeleteTagValueMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
TagValue result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<TagValue, DeleteTagValueMetadata> retrievedResponse = await tagValuesClient.PollOnceDeleteTagValueAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
TagValue retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyRequestObject()
{
// Snippet: GetIamPolicy(GetIamPolicyRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Options = new GetPolicyOptions(),
};
// Make the request
Policy response = tagValuesClient.GetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyRequestObjectAsync()
{
// Snippet: GetIamPolicyAsync(GetIamPolicyRequest, CallSettings)
// Additional: GetIamPolicyAsync(GetIamPolicyRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
GetIamPolicyRequest request = new GetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Options = new GetPolicyOptions(),
};
// Make the request
Policy response = await tagValuesClient.GetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicy()
{
// Snippet: GetIamPolicy(string, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
// Make the request
Policy response = tagValuesClient.GetIamPolicy(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyAsync()
{
// Snippet: GetIamPolicyAsync(string, CallSettings)
// Additional: GetIamPolicyAsync(string, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
// Make the request
Policy response = await tagValuesClient.GetIamPolicyAsync(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicy</summary>
public void GetIamPolicyResourceNames()
{
// Snippet: GetIamPolicy(IResourceName, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
// Make the request
Policy response = tagValuesClient.GetIamPolicy(resource);
// End snippet
}
/// <summary>Snippet for GetIamPolicyAsync</summary>
public async Task GetIamPolicyResourceNamesAsync()
{
// Snippet: GetIamPolicyAsync(IResourceName, CallSettings)
// Additional: GetIamPolicyAsync(IResourceName, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
// Make the request
Policy response = await tagValuesClient.GetIamPolicyAsync(resource);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyRequestObject()
{
// Snippet: SetIamPolicy(SetIamPolicyRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Policy = new Policy(),
};
// Make the request
Policy response = tagValuesClient.SetIamPolicy(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyRequestObjectAsync()
{
// Snippet: SetIamPolicyAsync(SetIamPolicyRequest, CallSettings)
// Additional: SetIamPolicyAsync(SetIamPolicyRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
SetIamPolicyRequest request = new SetIamPolicyRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Policy = new Policy(),
};
// Make the request
Policy response = await tagValuesClient.SetIamPolicyAsync(request);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicy()
{
// Snippet: SetIamPolicy(string, Policy, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
Policy policy = new Policy();
// Make the request
Policy response = tagValuesClient.SetIamPolicy(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyAsync()
{
// Snippet: SetIamPolicyAsync(string, Policy, CallSettings)
// Additional: SetIamPolicyAsync(string, Policy, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
Policy policy = new Policy();
// Make the request
Policy response = await tagValuesClient.SetIamPolicyAsync(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicy</summary>
public void SetIamPolicyResourceNames()
{
// Snippet: SetIamPolicy(IResourceName, Policy, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
Policy policy = new Policy();
// Make the request
Policy response = tagValuesClient.SetIamPolicy(resource, policy);
// End snippet
}
/// <summary>Snippet for SetIamPolicyAsync</summary>
public async Task SetIamPolicyResourceNamesAsync()
{
// Snippet: SetIamPolicyAsync(IResourceName, Policy, CallSettings)
// Additional: SetIamPolicyAsync(IResourceName, Policy, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
Policy policy = new Policy();
// Make the request
Policy response = await tagValuesClient.SetIamPolicyAsync(resource, policy);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsRequestObject()
{
// Snippet: TestIamPermissions(TestIamPermissionsRequest, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Permissions = { "", },
};
// Make the request
TestIamPermissionsResponse response = tagValuesClient.TestIamPermissions(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsRequestObjectAsync()
{
// Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest, CallSettings)
// Additional: TestIamPermissionsAsync(TestIamPermissionsRequest, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"),
Permissions = { "", },
};
// Make the request
TestIamPermissionsResponse response = await tagValuesClient.TestIamPermissionsAsync(request);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissions()
{
// Snippet: TestIamPermissions(string, IEnumerable<string>, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = tagValuesClient.TestIamPermissions(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsAsync()
{
// Snippet: TestIamPermissionsAsync(string, IEnumerable<string>, CallSettings)
// Additional: TestIamPermissionsAsync(string, IEnumerable<string>, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
string resource = "a/wildcard/resource";
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = await tagValuesClient.TestIamPermissionsAsync(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissions</summary>
public void TestIamPermissionsResourceNames()
{
// Snippet: TestIamPermissions(IResourceName, IEnumerable<string>, CallSettings)
// Create client
TagValuesClient tagValuesClient = TagValuesClient.Create();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = tagValuesClient.TestIamPermissions(resource, permissions);
// End snippet
}
/// <summary>Snippet for TestIamPermissionsAsync</summary>
public async Task TestIamPermissionsResourceNamesAsync()
{
// Snippet: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CallSettings)
// Additional: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CancellationToken)
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
IResourceName resource = new UnparsedResourceName("a/wildcard/resource");
IEnumerable<string> permissions = new string[] { "", };
// Make the request
TestIamPermissionsResponse response = await tagValuesClient.TestIamPermissionsAsync(resource, permissions);
// End snippet
}
}
}
| |
//
// ZipExtraData.cs
//
// Copyright 2004-2007 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
// TODO: Sort out wether tagged data is useful and what a good implementation might look like.
// Its just a sketch of an idea at the moment.
/// <summary>
/// ExtraData tagged value interface.
/// </summary>
public interface ITaggedData
{
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
short TagID { get; }
/// <summary>
/// Set the contents of this instance from the data passed.
/// </summary>
/// <param name="data">The data to extract contents from.</param>
/// <param name="offset">The offset to begin extracting data from.</param>
/// <param name="count">The number of bytes to extract.</param>
void SetData(byte[] data, int offset, int count);
/// <summary>
/// Get the data representing this instance.
/// </summary>
/// <returns>Returns the data for this instance.</returns>
byte[] GetData();
}
/// <summary>
/// A raw binary tagged value
/// </summary>
public class RawTaggedData : ITaggedData
{
/// <summary>
/// Initialise a new instance.
/// </summary>
/// <param name="tag">The tag ID.</param>
public RawTaggedData(short tag)
{
_tag = tag;
}
#region ITaggedData Members
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
public short TagID
{
get { return _tag; }
set { _tag = value; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="offset">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int offset, int count)
{
if( data==null )
{
throw new ArgumentNullException("data");
}
_data=new byte[count];
Array.Copy(data, offset, _data, 0, count);
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
return _data;
}
#endregion
/// <summary>
/// Get /set the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] Data
{
get { return _data; }
set { _data=value; }
}
#region Instance Fields
/// <summary>
/// The tag ID for this instance.
/// </summary>
short _tag;
byte[] _data;
#endregion
}
/// <summary>
/// Class representing extended unix date time values.
/// </summary>
public class ExtendedUnixData : ITaggedData
{
/// <summary>
/// Flags indicate which values are included in this instance.
/// </summary>
[Flags]
public enum Flags : byte
{
/// <summary>
/// The modification time is included
/// </summary>
ModificationTime = 0x01,
/// <summary>
/// The access time is included
/// </summary>
AccessTime = 0x02,
/// <summary>
/// The create time is included.
/// </summary>
CreateTime = 0x04,
}
#region ITaggedData Members
/// <summary>
/// Get the ID
/// </summary>
public short TagID
{
get { return 0x5455; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="index">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int index, int count)
{
using (MemoryStream ms = new MemoryStream(data, index, count, false))
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
// bit 0 if set, modification time is present
// bit 1 if set, access time is present
// bit 2 if set, creation time is present
_flags = (Flags)helperStream.ReadByte();
if (((_flags & Flags.ModificationTime) != 0) && (count >= 5))
{
int iTime = helperStream.ReadLEInt();
_modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.AccessTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.CreateTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
}
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
using (MemoryStream ms = new MemoryStream())
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.IsStreamOwner = false;
helperStream.WriteByte((byte)_flags); // Flags
if ( (_flags & Flags.ModificationTime) != 0) {
TimeSpan span = _modificationTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
if ( (_flags & Flags.AccessTime) != 0) {
TimeSpan span = _lastAccessTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
if ( (_flags & Flags.CreateTime) != 0) {
TimeSpan span = _createTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
return ms.ToArray();
}
}
#endregion
/// <summary>
/// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see>
/// </summary>
/// <param name="value">The <see cref="DateTime">value</see> to test.</param>
/// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
/// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number,
/// which is the number of seconds since 1970-01-01.
/// Being 32 bits means the values here cover a range of about 136 years.
/// The minimum representable time is 1901-12-13 20:45:52,
/// and the maximum representable time is 2038-01-19 03:14:07.
/// </remarks>
public static bool IsValidValue(DateTime value)
{
return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
( value <= new DateTime(2038, 1, 19, 03, 14, 07) ));
}
/// <summary>
/// Get /set the Modification Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime ModificationTime
{
get { return _modificationTime; }
set
{
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.ModificationTime;
_modificationTime=value;
}
}
/// <summary>
/// Get / set the Access Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime AccessTime
{
get { return _lastAccessTime; }
set {
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.AccessTime;
_lastAccessTime=value;
}
}
/// <summary>
/// Get / Set the Create Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime CreateTime
{
get { return _createTime; }
set {
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.CreateTime;
_createTime=value;
}
}
/// <summary>
/// Get/set the <see cref="Flags">values</see> to include.
/// </summary>
Flags Include
{
get { return _flags; }
set { _flags = value; }
}
#region Instance Fields
Flags _flags;
DateTime _modificationTime = new DateTime(1970,1,1);
DateTime _lastAccessTime = new DateTime(1970, 1, 1);
DateTime _createTime = new DateTime(1970, 1, 1);
#endregion
}
/// <summary>
/// Class handling NT date time values.
/// </summary>
public class NTTaggedData : ITaggedData
{
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
public short TagID
{
get { return 10; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="index">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int index, int count)
{
using (MemoryStream ms = new MemoryStream(data, index, count, false))
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.ReadLEInt(); // Reserved
while (helperStream.Position < helperStream.Length)
{
int ntfsTag = helperStream.ReadLEShort();
int ntfsLength = helperStream.ReadLEShort();
if (ntfsTag == 1)
{
if (ntfsLength >= 24)
{
long lastModificationTicks = helperStream.ReadLELong();
_lastModificationTime = DateTime.FromFileTime(lastModificationTicks);
long lastAccessTicks = helperStream.ReadLELong();
_lastAccessTime = DateTime.FromFileTime(lastAccessTicks);
long createTimeTicks = helperStream.ReadLELong();
_createTime = DateTime.FromFileTime(createTimeTicks);
}
break;
}
else
{
// An unknown NTFS tag so simply skip it.
helperStream.Seek(ntfsLength, SeekOrigin.Current);
}
}
}
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
using (MemoryStream ms = new MemoryStream())
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.IsStreamOwner = false;
helperStream.WriteLEInt(0); // Reserved
helperStream.WriteLEShort(1); // Tag
helperStream.WriteLEShort(24); // Length = 3 x 8.
helperStream.WriteLELong(_lastModificationTime.ToFileTime());
helperStream.WriteLELong(_lastAccessTime.ToFileTime());
helperStream.WriteLELong(_createTime.ToFileTime());
return ms.ToArray();
}
}
/// <summary>
/// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see>
/// </summary>
/// <param name="value">The <see cref="DateTime">value</see> to test.</param>
/// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
/// <remarks>
/// NTFS filetimes are 64-bit unsigned integers, stored in Intel
/// (least significant byte first) byte order. They determine the
/// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
/// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
/// </remarks>
public static bool IsValidValue(DateTime value)
{
bool result = true;
try
{
value.ToFileTimeUtc();
}
catch
{
result = false;
}
return result;
}
/// <summary>
/// Get/set the <see cref="DateTime">last modification time</see>.
/// </summary>
public DateTime LastModificationTime
{
get { return _lastModificationTime; }
set {
if (! IsValidValue(value))
{
throw new ArgumentOutOfRangeException("value");
}
_lastModificationTime = value;
}
}
/// <summary>
/// Get /set the <see cref="DateTime">create time</see>
/// </summary>
public DateTime CreateTime
{
get { return _createTime; }
set {
if ( !IsValidValue(value)) {
throw new ArgumentOutOfRangeException("value");
}
_createTime = value;
}
}
/// <summary>
/// Get /set the <see cref="DateTime">last access time</see>.
/// </summary>
public DateTime LastAccessTime
{
get { return _lastAccessTime; }
set {
if (!IsValidValue(value)) {
throw new ArgumentOutOfRangeException("value");
}
_lastAccessTime = value;
}
}
#region Instance Fields
DateTime _lastAccessTime = DateTime.FromFileTime(0);
DateTime _lastModificationTime = DateTime.FromFileTime(0);
DateTime _createTime = DateTime.FromFileTime(0);
#endregion
}
/// <summary>
/// A factory that creates <see cref="ITaggedData">tagged data</see> instances.
/// </summary>
interface ITaggedDataFactory
{
/// <summary>
/// Get data for a specific tag value.
/// </summary>
/// <param name="tag">The tag ID to find.</param>
/// <param name="data">The data to search.</param>
/// <param name="offset">The offset to begin extracting data from.</param>
/// <param name="count">The number of bytes to extract.</param>
/// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns>
ITaggedData Create(short tag, byte[] data, int offset, int count);
}
///
/// <summary>
/// A class to handle the extra data field for Zip entries
/// </summary>
/// <remarks>
/// Extra data contains 0 or more values each prefixed by a header tag and length.
/// They contain zero or more bytes of actual data.
/// The data is held internally using a copy on write strategy. This is more efficient but
/// means that for extra data created by passing in data can have the values modified by the caller
/// in some circumstances.
/// </remarks>
sealed public class ZipExtraData : IDisposable
{
#region Constructors
/// <summary>
/// Initialise a default instance.
/// </summary>
public ZipExtraData()
{
Clear();
}
/// <summary>
/// Initialise with known extra data.
/// </summary>
/// <param name="data">The extra data.</param>
public ZipExtraData(byte[] data)
{
if ( data == null )
{
_data = new byte[0];
}
else
{
_data = data;
}
}
#endregion
/// <summary>
/// Get the raw extra data value
/// </summary>
/// <returns>Returns the raw byte[] extra data this instance represents.</returns>
public byte[] GetEntryData()
{
if ( Length > ushort.MaxValue ) {
throw new ZipException("Data exceeds maximum length");
}
return (byte[])_data.Clone();
}
/// <summary>
/// Clear the stored data.
/// </summary>
public void Clear()
{
if ( (_data == null) || (_data.Length != 0) ) {
_data = new byte[0];
}
}
/// <summary>
/// Gets the current extra data length.
/// </summary>
public int Length
{
get { return _data.Length; }
}
/// <summary>
/// Get a read-only <see cref="Stream"/> for the associated tag.
/// </summary>
/// <param name="tag">The tag to locate data for.</param>
/// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns>
public Stream GetStreamForTag(int tag)
{
Stream result = null;
if ( Find(tag) ) {
result = new MemoryStream(_data, _index, _readValueLength, false);
}
return result;
}
/// <summary>
/// Get the <see cref="ITaggedData">tagged data</see> for a tag.
/// </summary>
/// <param name="tag">The tag to search for.</param>
/// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns>
private ITaggedData GetData(short tag)
{
ITaggedData result = null;
if (Find(tag))
{
result = Create(tag, _data, _readValueStart, _readValueLength);
}
return result;
}
static ITaggedData Create(short tag, byte[] data, int offset, int count)
{
ITaggedData result = null;
switch ( tag )
{
case 0x000A:
result = new NTTaggedData();
break;
case 0x5455:
result = new ExtendedUnixData();
break;
default:
result = new RawTaggedData(tag);
break;
}
result.SetData(data, offset, count);
return result;
}
/// <summary>
/// Get the length of the last value found by <see cref="Find"/>
/// </summary>
/// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks>
public int ValueLength
{
get { return _readValueLength; }
}
/// <summary>
/// Get the index for the current read value.
/// </summary>
/// <remarks>This is only valid if <see cref="Find"/> has previously returned true.
/// Initially the result will be the index of the first byte of actual data. The value is updated after calls to
/// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks>
public int CurrentReadIndex
{
get { return _index; }
}
/// <summary>
/// Get the number of bytes remaining to be read for the current value;
/// </summary>
public int UnreadCount
{
get
{
if ((_readValueStart > _data.Length) ||
(_readValueStart < 4) ) {
throw new ZipException("Find must be called before calling a Read method");
}
return _readValueStart + _readValueLength - _index;
}
}
/// <summary>
/// Find an extra data value
/// </summary>
/// <param name="headerID">The identifier for the value to find.</param>
/// <returns>Returns true if the value was found; false otherwise.</returns>
public bool Find(int headerID)
{
_readValueStart = _data.Length;
_readValueLength = 0;
_index = 0;
int localLength = _readValueStart;
int localTag = headerID - 1;
// Trailing bytes that cant make up an entry (as there arent enough
// bytes for a tag and length) are ignored!
while ( (localTag != headerID) && (_index < _data.Length - 3) ) {
localTag = ReadShortInternal();
localLength = ReadShortInternal();
if ( localTag != headerID ) {
_index += localLength;
}
}
bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length);
if ( result ) {
_readValueStart = _index;
_readValueLength = localLength;
}
return result;
}
/// <summary>
/// Add a new entry to extra data.
/// </summary>
/// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param>
public void AddEntry(ITaggedData taggedData)
{
if (taggedData == null)
{
throw new ArgumentNullException("taggedData");
}
AddEntry(taggedData.TagID, taggedData.GetData());
}
/// <summary>
/// Add a new entry to extra data
/// </summary>
/// <param name="headerID">The ID for this entry.</param>
/// <param name="fieldData">The data to add.</param>
/// <remarks>If the ID already exists its contents are replaced.</remarks>
public void AddEntry(int headerID, byte[] fieldData)
{
if ( (headerID > ushort.MaxValue) || (headerID < 0)) {
throw new ArgumentOutOfRangeException("headerID");
}
int addLength = (fieldData == null) ? 0 : fieldData.Length;
if ( addLength > ushort.MaxValue ) {
#if NETCF_1_0 || UNITY_WINRT
throw new ArgumentOutOfRangeException("fieldData");
#else
throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length");
#endif
}
// Test for new length before adjusting data.
int newLength = _data.Length + addLength + 4;
if ( Find(headerID) )
{
newLength -= (ValueLength + 4);
}
if ( newLength > ushort.MaxValue ) {
throw new ZipException("Data exceeds maximum length");
}
Delete(headerID);
byte[] newData = new byte[newLength];
_data.CopyTo(newData, 0);
int index = _data.Length;
_data = newData;
SetShort(ref index, headerID);
SetShort(ref index, addLength);
if ( fieldData != null ) {
fieldData.CopyTo(newData, index);
}
}
/// <summary>
/// Start adding a new entry.
/// </summary>
/// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>.
/// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks>
/// <seealso cref="AddEntry(ITaggedData)"/>
public void StartNewEntry()
{
_newEntry = new MemoryStream();
}
/// <summary>
/// Add entry data added since <see cref="StartNewEntry"/> using the ID passed.
/// </summary>
/// <param name="headerID">The identifier to use for this entry.</param>
public void AddNewEntry(int headerID)
{
byte[] newData = _newEntry.ToArray();
_newEntry = null;
AddEntry(headerID, newData);
}
/// <summary>
/// Add a byte of data to the pending new entry.
/// </summary>
/// <param name="data">The byte to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddData(byte data)
{
_newEntry.WriteByte(data);
}
/// <summary>
/// Add data to a pending new entry.
/// </summary>
/// <param name="data">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddData(byte[] data)
{
if ( data == null ) {
throw new ArgumentNullException("data");
}
_newEntry.Write(data, 0, data.Length);
}
/// <summary>
/// Add a short value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeShort(int toAdd)
{
unchecked {
_newEntry.WriteByte(( byte )toAdd);
_newEntry.WriteByte(( byte )(toAdd >> 8));
}
}
/// <summary>
/// Add an integer value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeInt(int toAdd)
{
unchecked {
AddLeShort(( short )toAdd);
AddLeShort(( short )(toAdd >> 16));
}
}
/// <summary>
/// Add a long value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeLong(long toAdd)
{
unchecked {
AddLeInt(( int )(toAdd & 0xffffffff));
AddLeInt(( int )(toAdd >> 32));
}
}
/// <summary>
/// Delete an extra data field.
/// </summary>
/// <param name="headerID">The identifier of the field to delete.</param>
/// <returns>Returns true if the field was found and deleted.</returns>
public bool Delete(int headerID)
{
bool result = false;
if ( Find(headerID) ) {
result = true;
int trueStart = _readValueStart - 4;
byte[] newData = new byte[_data.Length - (ValueLength + 4)];
Array.Copy(_data, 0, newData, 0, trueStart);
int trueEnd = trueStart + ValueLength + 4;
Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd);
_data = newData;
}
return result;
}
#region Reading Support
/// <summary>
/// Read a long in little endian form from the last <see cref="Find">found</see> data value
/// </summary>
/// <returns>Returns the long value read.</returns>
public long ReadLong()
{
ReadCheck(8);
return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32);
}
/// <summary>
/// Read an integer in little endian form from the last <see cref="Find">found</see> data value.
/// </summary>
/// <returns>Returns the integer read.</returns>
public int ReadInt()
{
ReadCheck(4);
int result = _data[_index] + (_data[_index + 1] << 8) +
(_data[_index + 2] << 16) + (_data[_index + 3] << 24);
_index += 4;
return result;
}
/// <summary>
/// Read a short value in little endian form from the last <see cref="Find">found</see> data value.
/// </summary>
/// <returns>Returns the short value read.</returns>
public int ReadShort()
{
ReadCheck(2);
int result = _data[_index] + (_data[_index + 1] << 8);
_index += 2;
return result;
}
/// <summary>
/// Read a byte from an extra data
/// </summary>
/// <returns>The byte value read or -1 if the end of data has been reached.</returns>
public int ReadByte()
{
int result = -1;
if ( (_index < _data.Length) && (_readValueStart + _readValueLength > _index) ) {
result = _data[_index];
_index += 1;
}
return result;
}
/// <summary>
/// Skip data during reading.
/// </summary>
/// <param name="amount">The number of bytes to skip.</param>
public void Skip(int amount)
{
ReadCheck(amount);
_index += amount;
}
void ReadCheck(int length)
{
if ((_readValueStart > _data.Length) ||
(_readValueStart < 4) ) {
throw new ZipException("Find must be called before calling a Read method");
}
if (_index > _readValueStart + _readValueLength - length ) {
throw new ZipException("End of extra data");
}
if ( _index + length < 4 ) {
throw new ZipException("Cannot read before start of tag");
}
}
/// <summary>
/// Internal form of <see cref="ReadShort"/> that reads data at any location.
/// </summary>
/// <returns>Returns the short value read.</returns>
int ReadShortInternal()
{
if ( _index > _data.Length - 2) {
throw new ZipException("End of extra data");
}
int result = _data[_index] + (_data[_index + 1] << 8);
_index += 2;
return result;
}
void SetShort(ref int index, int source)
{
_data[index] = (byte)source;
_data[index + 1] = (byte)(source >> 8);
index += 2;
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose of this instance.
/// </summary>
public void Dispose()
{
if ( _newEntry != null ) {
_newEntry.Dispose();
}
}
#endregion
#region Instance Fields
int _index;
int _readValueStart;
int _readValueLength;
MemoryStream _newEntry;
byte[] _data;
#endregion
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using OpenTK.Graphics.OpenGL;
using SharpFlame.Collections;
using SharpFlame.Core.Collections;
using SharpFlame.Core.Domain;
using SharpFlame.Core.Extensions;
using SharpFlame.Domain.ObjData;
using SharpFlame.Maths;
using SharpFlame.Util;
namespace SharpFlame.Domain
{
public abstract class UnitTypeBase
{
public readonly ConnectedListItem<UnitTypeBase, ObjectData> UnitType_ObjectDataLink;
public readonly ConnectedListItem<UnitTypeBase, frmMain> UnitType_frmMainSelectedLink;
public bool IsUnknown = false;
public UnitType Type;
protected UnitTypeBase()
{
UnitType_frmMainSelectedLink = new ConnectedListItem<UnitTypeBase, frmMain>(this);
UnitType_ObjectDataLink = new ConnectedListItem<UnitTypeBase, ObjectData>(this);
}
public XYInt GetFootprintOld
{
get
{
switch ( Type )
{
case UnitType.Feature:
return ((FeatureTypeBase)this).Footprint;
case UnitType.PlayerStructure:
return ((StructureTypeBase)this).Footprint;
default:
var XY_int = new XYInt(1, 1);
return XY_int;
}
}
}
public void GLDraw(float RotationDegrees)
{
switch ( App.Draw_Lighting )
{
case DrawLighting.Off:
GL.Color3(1.0F, 1.0F, 1.0F);
break;
case DrawLighting.Half:
GL.Color3(0.875F, 0.875F, 0.875F);
break;
case DrawLighting.Normal:
GL.Color3(0.75F, 0.75F, 0.75F);
break;
}
//GL.Rotate(x, 1.0F, 0.0F, 0.0F)
GL.Rotate(RotationDegrees, 0.0F, 1.0F, 0.0F);
//GL.Rotate(z, 0.0F, 0.0F, -1.0F)
TypeGLDraw();
}
protected virtual void TypeGLDraw()
{
}
public XYInt GetGetFootprintNew(int Rotation)
{
//get initial footprint
XYInt result;
switch ( Type )
{
case UnitType.Feature:
result = ((FeatureTypeBase)this).Footprint;
break;
case UnitType.PlayerStructure:
result = ((StructureTypeBase)this).Footprint;
break;
default:
//return droid footprint
result = new XYInt(1, 1);
return result;
}
//switch footprint axes if not a droid
var Remainder = Convert.ToDouble((Rotation / 90.0D + 0.5D) % 2.0D);
if ( Remainder < 0.0D )
{
Remainder += 2.0D;
}
if ( Remainder >= 1.0D )
{
var X = result.X;
result.X = result.Y;
result.Y = X;
}
return result;
}
public XYInt GetGetFootprintSelected(int rotation)
{
// if ( Program.frmMainInstance.cbxFootprintRotate.Checked )
// {
// return GetGetFootprintNew(rotation);
// }
return GetFootprintOld;
}
public bool GetCode(ref string Result)
{
switch ( Type )
{
case UnitType.Feature:
Result = ((FeatureTypeBase)this).Code;
return true;
case UnitType.PlayerStructure:
Result = ((StructureTypeBase)this).Code;
return true;
case UnitType.PlayerDroid:
var Droid = (DroidDesign)this;
if ( Droid.IsTemplate )
{
Result = ((DroidTemplate)this).Code;
return true;
}
Result = null;
return false;
default:
Result = null;
return false;
}
}
public string GetDisplayTextCode()
{
switch ( Type )
{
case UnitType.Feature:
var featureTypeBase = (FeatureTypeBase)this;
return featureTypeBase.Code + " (" + featureTypeBase.Name + ")";
case UnitType.PlayerStructure:
var structureTypeBase = (StructureTypeBase)this;
return structureTypeBase.Code + " (" + structureTypeBase.Name + ")";
case UnitType.PlayerDroid:
var DroidType = (DroidDesign)this;
if ( DroidType.IsTemplate )
{
var Template = (DroidTemplate)this;
return Template.Code + " (" + Template.Name + ")";
}
return "<droid> (" + DroidType.GenerateName() + ")";
default:
return "";
}
}
public string GetDisplayTextName()
{
switch ( Type )
{
case UnitType.Feature:
var featureTypeBase = (FeatureTypeBase)this;
return featureTypeBase.Name + " (" + featureTypeBase.Code + ")";
case UnitType.PlayerStructure:
var structureTypeBase = (StructureTypeBase)this;
return structureTypeBase.Name + " (" + structureTypeBase.Code + ")";
case UnitType.PlayerDroid:
var DroidType = (DroidDesign)this;
if ( DroidType.IsTemplate )
{
var Template = (DroidTemplate)this;
return Template.Name + " (" + Template.Code + ")";
}
return DroidType.GenerateName() + " (<droid>)";
default:
return "";
}
}
public virtual string GetName()
{
return "";
}
}
public class clsAttachment
{
public Matrix3DMath.Matrix3D AngleOffsetMatrix = new Matrix3DMath.Matrix3D();
public ObservableCollection<clsAttachment> Attachments = new ObservableCollection<clsAttachment>();
public ObservableCollection<clsModel> Models = new ObservableCollection<clsModel>();
public XYZDouble PosOffset;
public clsAttachment()
{
Matrix3DMath.MatrixSetToIdentity(AngleOffsetMatrix);
this.Models.CollectionChanged += (sender, args) =>
{
if( args.Action == NotifyCollectionChangedAction.Add &&
args.NewItems.Contains(null) )
{
this.Models.Remove(null);
}
};
}
public void GLDraw()
{
var angleRpy = default(Angles.AngleRPY);
var matrixA = new Matrix3DMath.Matrix3D();
foreach ( var model in Models )
{
model.GLDraw();
}
foreach ( var attachment in Attachments )
{
GL.PushMatrix();
Matrix3DMath.MatrixInvert(attachment.AngleOffsetMatrix, matrixA);
Matrix3DMath.MatrixToRPY(matrixA, ref angleRpy);
GL.Translate(attachment.PosOffset.X, attachment.PosOffset.Y, Convert.ToDouble(- attachment.PosOffset.Z));
GL.Rotate((float)(angleRpy.Roll / MathUtil.RadOf1Deg), 0.0F, 0.0F, -1.0F);
GL.Rotate((float)(angleRpy.Pitch / MathUtil.RadOf1Deg), 1.0F, 0.0F, 0.0F);
GL.Rotate((float)(angleRpy.Yaw / MathUtil.RadOf1Deg), 0.0F, 1.0F, 0.0F);
attachment.GLDraw();
GL.PopMatrix();
}
}
public clsAttachment CreateAttachment()
{
var result = new clsAttachment();
Attachments.Add(result);
return result;
}
public clsAttachment CopyAttachment(clsAttachment Other)
{
var result = new clsAttachment
{
PosOffset = Other.PosOffset
};
Attachments.Add(result);
Matrix3DMath.MatrixCopy(Other.AngleOffsetMatrix, result.AngleOffsetMatrix);
result.Models.AddRange(Other.Models);
result.Attachments.AddRange(Other.Attachments);
return result;
}
public clsAttachment AddCopyOfAttachment(clsAttachment AttachmentToCopy)
{
var ResultAttachment = new clsAttachment();
var Attachment = default(clsAttachment);
Attachments.Add(ResultAttachment);
Matrix3DMath.MatrixCopy(AttachmentToCopy.AngleOffsetMatrix, ResultAttachment.AngleOffsetMatrix);
ResultAttachment.Models.AddRange(AttachmentToCopy.Models);
foreach ( var tempLoopVar_Attachment in AttachmentToCopy.Attachments )
{
Attachment = tempLoopVar_Attachment;
ResultAttachment.AddCopyOfAttachment(Attachment);
}
return ResultAttachment;
}
}
public enum UnitType
{
Unspecified,
Feature,
PlayerStructure,
PlayerDroid
}
public class FeatureTypeBase : UnitTypeBase
{
public clsAttachment BaseAttachment;
public string Code = "";
public FeatureType FeatureType = FeatureType.Unknown;
public ConnectedListItem<FeatureTypeBase, ObjectData> FeatureType_ObjectDataLink;
public XYInt Footprint;
public string Name = "Unknown";
public FeatureTypeBase()
{
Footprint = new XYInt(0, 0);
FeatureType_ObjectDataLink = new ConnectedListItem<FeatureTypeBase, ObjectData>(this);
Type = UnitType.Feature;
}
protected override void TypeGLDraw()
{
if ( BaseAttachment != null )
{
BaseAttachment.GLDraw();
}
}
public override string GetName()
{
return Name;
}
}
public enum FeatureType
{
Unknown,
OilResource
}
public class StructureTypeBase : UnitTypeBase
{
public clsAttachment BaseAttachment = new clsAttachment();
public string Code = "";
public XYInt Footprint;
public string Name = "Unknown";
public clsModel StructureBasePlate;
public StructureType StructureType = StructureType.Unknown;
public ConnectedListItem<StructureTypeBase, ObjectData> StructureType_ObjectDataLink;
public ConnectedListItem<StructureTypeBase, clsWallType> WallLink;
public StructureTypeBase()
{
StructureType_ObjectDataLink = new ConnectedListItem<StructureTypeBase, ObjectData>(this);
WallLink = new ConnectedListItem<StructureTypeBase, clsWallType>(this);
Type = UnitType.PlayerStructure;
}
protected override void TypeGLDraw()
{
if ( BaseAttachment != null )
{
BaseAttachment.GLDraw();
}
if ( StructureBasePlate != null )
{
StructureBasePlate.GLDraw();
}
}
public bool IsModule()
{
return StructureType == StructureType.FactoryModule
| StructureType == StructureType.PowerModule
| StructureType == StructureType.ResearchModule;
}
public override string GetName()
{
return Name;
}
}
public class DroidDesign : UnitTypeBase
{
public bool AlwaysDrawTextLabel;
public clsAttachment BaseAttachment = new clsAttachment();
public Body Body;
public bool IsTemplate;
public string Name = "";
public Propulsion Propulsion;
public clsTemplateDroidType TemplateDroidType;
public Turret Turret1;
public Turret Turret2;
public Turret Turret3;
public byte TurretCount;
public DroidDesign()
{
Type = UnitType.PlayerDroid;
}
public void CopyDesign(DroidDesign droidTypeToCopy)
{
TemplateDroidType = droidTypeToCopy.TemplateDroidType;
Body = droidTypeToCopy.Body;
Propulsion = droidTypeToCopy.Propulsion;
TurretCount = droidTypeToCopy.TurretCount;
Turret1 = droidTypeToCopy.Turret1;
Turret2 = droidTypeToCopy.Turret2;
Turret3 = droidTypeToCopy.Turret3;
}
protected override void TypeGLDraw()
{
if ( BaseAttachment != null )
{
BaseAttachment.GLDraw();
}
}
public void UpdateAttachments()
{
BaseAttachment = new clsAttachment();
if ( Body == null )
{
AlwaysDrawTextLabel = true;
return;
}
var NewBody = BaseAttachment.AddCopyOfAttachment(Body.Attachment);
AlwaysDrawTextLabel = NewBody.Models.Count == 0;
if ( Propulsion != null )
{
if ( Body.ObjectDataLink.IsConnected )
{
BaseAttachment.AddCopyOfAttachment(Propulsion.Bodies[Body.ObjectDataLink.Position].LeftAttachment);
BaseAttachment.AddCopyOfAttachment(Propulsion.Bodies[Body.ObjectDataLink.Position].RightAttachment);
}
}
if ( NewBody.Models.Count == 0 )
{
return;
}
if ( NewBody.Models[0].ConnectorCount <= 0 )
{
return;
}
var turretConnector = Body.Attachment.Models[0].Connectors[0];
if ( TurretCount >= 1 )
{
if ( Turret1 != null )
{
var newTurret = NewBody.AddCopyOfAttachment(Turret1.Attachment);
newTurret.PosOffset = turretConnector;
}
}
if ( Body.Attachment.Models[0].ConnectorCount <= 1 )
{
return;
}
turretConnector = Body.Attachment.Models[0].Connectors[1];
if ( TurretCount >= 2 )
{
if ( Turret2 != null )
{
var newTurret = NewBody.AddCopyOfAttachment(Turret2.Attachment);
newTurret.PosOffset = turretConnector;
}
}
}
public int GetMaxHitPoints()
{
var result = 0;
//this is inaccurate
if ( Body == null )
{
return 0;
}
result = Body.Hitpoints;
if ( Propulsion == null )
{
return result;
}
result += (Body.Hitpoints * Propulsion.HitPoints / 100.0D).ToInt();
if ( Turret1 == null )
{
return result;
}
result += Body.Hitpoints + Turret1.HitPoints;
if ( TurretCount < 2 || Turret2 == null )
{
return result;
}
if ( Turret2.TurretType != TurretType.Weapon )
{
return result;
}
result += Body.Hitpoints + Turret2.HitPoints;
if ( TurretCount < 3 || Turret3 == null )
{
return result;
}
if ( Turret3.TurretType != TurretType.Weapon )
{
return result;
}
result += Body.Hitpoints + Turret3.HitPoints;
return result;
}
public bool LoadParts(sLoadPartsArgs Args)
{
var TurretConflict = default(bool);
Body = Args.Body;
Propulsion = Args.Propulsion;
TurretConflict = false;
if ( Args.Construct != null )
{
if ( Args.Construct.Code != "ZNULLCONSTRUCT" )
{
if ( Turret1 != null )
{
TurretConflict = true;
}
TurretCount = 1;
Turret1 = Args.Construct;
}
}
if ( Args.Repair != null )
{
if ( Args.Repair.Code != "ZNULLREPAIR" )
{
if ( Turret1 != null )
{
TurretConflict = true;
}
TurretCount = 1;
Turret1 = Args.Repair;
}
}
if ( Args.Brain != null )
{
if ( Args.Brain.Code != "ZNULLBRAIN" )
{
if ( Turret1 != null )
{
TurretConflict = true;
}
TurretCount = 1;
Turret1 = Args.Brain;
}
}
if ( Args.Weapon1 != null )
{
var UseWeapon = default(bool);
if ( Turret1 != null )
{
if ( Turret1.TurretType == TurretType.Brain )
{
UseWeapon = false;
}
else
{
UseWeapon = true;
TurretConflict = true;
}
}
else
{
UseWeapon = true;
}
if ( UseWeapon )
{
TurretCount = 1;
Turret1 = Args.Weapon1;
if ( Args.Weapon2 != null )
{
Turret2 = Args.Weapon2;
TurretCount += 1;
if ( Args.Weapon3 != null )
{
Turret3 = Args.Weapon3;
TurretCount += 1;
}
}
}
}
if ( Args.Sensor != null )
{
if ( Args.Sensor.Location == SensorLocationType.Turret )
{
if ( Turret1 != null )
{
TurretConflict = true;
}
TurretCount = 1;
Turret1 = Args.Sensor;
}
}
UpdateAttachments();
return !TurretConflict; //return if all is ok
}
public string GenerateName()
{
var Result = "";
if ( Propulsion != null )
{
if ( Result.Length > 0 )
{
Result = ' ' + Result;
}
Result = Propulsion.Name + Result;
}
if ( Body != null )
{
if ( Result.Length > 0 )
{
Result = ' ' + Result;
}
Result = Body.Name + Result;
}
if ( TurretCount >= 3 )
{
if ( Turret3 != null )
{
if ( Result.Length > 0 )
{
Result = ' ' + Result;
}
Result = Turret3.Name + Result;
}
}
if ( TurretCount >= 2 )
{
if ( Turret2 != null )
{
if ( Result.Length > 0 )
{
Result = ' ' + Result;
}
Result = Turret2.Name + Result;
}
}
if ( TurretCount >= 1 )
{
if ( Turret1 != null )
{
if ( Result.Length > 0 )
{
Result = ' ' + Result;
}
Result = Turret1.Name + Result;
}
}
return Result;
}
public DroidType GetDroidType()
{
var Result = default(DroidType);
if ( TemplateDroidType == App.TemplateDroidType_Null )
{
Result = DroidType.Default;
}
else if ( TemplateDroidType == App.TemplateDroidType_Person )
{
Result = DroidType.Person;
}
else if ( TemplateDroidType == App.TemplateDroidType_Cyborg )
{
Result = DroidType.Cyborg;
}
else if ( TemplateDroidType == App.TemplateDroidType_CyborgSuper )
{
Result = DroidType.CyborgSuper;
}
else if ( TemplateDroidType == App.TemplateDroidType_CyborgConstruct )
{
Result = DroidType.CyborgConstruct;
}
else if ( TemplateDroidType == App.TemplateDroidType_CyborgRepair )
{
Result = DroidType.CyborgRepair;
}
else if ( TemplateDroidType == App.TemplateDroidType_Transporter )
{
Result = DroidType.Transporter;
}
else if ( Turret1 == null )
{
Result = DroidType.Default;
}
else if ( Turret1.TurretType == TurretType.Brain )
{
Result = DroidType.Command;
}
else if ( Turret1.TurretType == TurretType.Sensor )
{
Result = DroidType.Sensor;
}
else if ( Turret1.TurretType == TurretType.ECM )
{
Result = DroidType.ECM;
}
else if ( Turret1.TurretType == TurretType.Construct )
{
Result = DroidType.Construct;
}
else if ( Turret1.TurretType == TurretType.Repair )
{
Result = DroidType.Repair;
}
else if ( Turret1.TurretType == TurretType.Weapon )
{
Result = DroidType.Weapon;
}
else
{
Result = DroidType.Default;
}
return Result;
}
public bool SetDroidType(DroidType DroidType)
{
switch ( DroidType )
{
case DroidType.Weapon:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.Sensor:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.ECM:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.Construct:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.Person:
TemplateDroidType = App.TemplateDroidType_Person;
break;
case DroidType.Cyborg:
TemplateDroidType = App.TemplateDroidType_Cyborg;
break;
case DroidType.Transporter:
TemplateDroidType = App.TemplateDroidType_Transporter;
break;
case DroidType.Command:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.Repair:
TemplateDroidType = App.TemplateDroidType_Droid;
break;
case DroidType.Default:
TemplateDroidType = App.TemplateDroidType_Null;
break;
case DroidType.CyborgConstruct:
TemplateDroidType = App.TemplateDroidType_CyborgConstruct;
break;
case DroidType.CyborgRepair:
TemplateDroidType = App.TemplateDroidType_CyborgRepair;
break;
case DroidType.CyborgSuper:
TemplateDroidType = App.TemplateDroidType_CyborgSuper;
break;
default:
TemplateDroidType = null;
return false;
}
return true;
}
public string GetConstructCode()
{
var NotThis = default(bool);
if ( TurretCount >= 1 )
{
if ( Turret1 == null )
{
NotThis = true;
}
else if ( Turret1.TurretType != TurretType.Construct )
{
NotThis = true;
}
else
{
NotThis = false;
}
}
else
{
NotThis = true;
}
if ( NotThis )
{
return "ZNULLCONSTRUCT";
}
return Turret1.Code;
}
public string GetRepairCode()
{
var NotThis = default(bool);
if ( TurretCount >= 1 )
{
if ( Turret1 == null )
{
NotThis = true;
}
else if ( Turret1.TurretType != TurretType.Repair )
{
NotThis = true;
}
else
{
NotThis = false;
}
}
else
{
NotThis = true;
}
if ( NotThis )
{
return "ZNULLREPAIR";
}
return Turret1.Code;
}
public string GetSensorCode()
{
var NotThis = default(bool);
if ( TurretCount >= 1 )
{
if ( Turret1 == null )
{
NotThis = true;
}
else if ( Turret1.TurretType != TurretType.Sensor )
{
NotThis = true;
}
else
{
NotThis = false;
}
}
else
{
NotThis = true;
}
if ( NotThis )
{
return "ZNULLSENSOR";
}
return Turret1.Code;
}
public string GetBrainCode()
{
var NotThis = default(bool);
if ( TurretCount >= 1 )
{
if ( Turret1 == null )
{
NotThis = true;
}
else if ( Turret1.TurretType != TurretType.Brain )
{
NotThis = true;
}
else
{
NotThis = false;
}
}
else
{
NotThis = true;
}
if ( NotThis )
{
return "ZNULLBRAIN";
}
return Turret1.Code;
}
public string GetECMCode()
{
var NotThis = default(bool);
if ( TurretCount >= 1 )
{
if ( Turret1 == null )
{
NotThis = true;
}
else if ( Turret1.TurretType != TurretType.ECM )
{
NotThis = true;
}
else
{
NotThis = false;
}
}
else
{
NotThis = true;
}
if ( NotThis )
{
return "ZNULLECM";
}
return Turret1.Code;
}
public override string GetName()
{
return Name;
}
public class clsTemplateDroidType
{
public string Name;
public int Num = -1;
public string TemplateCode;
public clsTemplateDroidType(string NewName, string NewTemplateCode)
{
Name = NewName;
TemplateCode = NewTemplateCode;
}
}
public struct sLoadPartsArgs
{
public Body Body;
public Brain Brain;
public Construct Construct;
public Ecm ECM;
public Propulsion Propulsion;
public Repair Repair;
public Sensor Sensor;
public Weapon Weapon1;
public Weapon Weapon2;
public Weapon Weapon3;
}
}
public class DroidTemplate : DroidDesign
{
public string Code = "";
public ConnectedListItem<DroidTemplate, ObjectData> DroidTemplate_ObjectDataLink;
public DroidTemplate()
{
DroidTemplate_ObjectDataLink = new ConnectedListItem<DroidTemplate, ObjectData>(this);
IsTemplate = true;
Name = "Unknown";
}
}
public class clsWallType
{
private const int d0 = 0;
private const int d1 = 90;
private const int d2 = 180;
private const int d3 = 270;
public string Code = "";
public string Name = "Unknown";
public ConnectedList<StructureTypeBase, clsWallType> Segments;
public int[] TileWalls_Direction = {d0, d0, d2, d0, d3, d0, d3, d0, d1, d1, d2, d2, d3, d1, d3, d0};
public int[] TileWalls_Segment = {0, 0, 0, 0, 0, 3, 3, 2, 0, 3, 3, 2, 0, 2, 2, 1};
public ConnectedListItem<clsWallType, ObjectData> WallType_ObjectDataLink;
public clsWallType()
{
WallType_ObjectDataLink = new ConnectedListItem<clsWallType, ObjectData>(this);
Segments = new ConnectedList<StructureTypeBase, clsWallType>(this);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2010-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The TestResult class represents the result of a test.
/// </summary>
public abstract class TestResult : LongLivedMarshalByRefObject, ITestResult
{
#region Fields
/// <summary>
/// Error message for when child tests have errors
/// </summary>
internal static readonly string CHILD_ERRORS_MESSAGE = "One or more child tests had errors";
/// <summary>
/// Error message for when child tests have warnings
/// </summary>
internal static readonly string CHILD_WARNINGS_MESSAGE = "One or more child tests had warnings";
/// <summary>
/// Error message for when child tests are ignored
/// </summary>
internal static readonly string CHILD_IGNORE_MESSAGE = "One or more child tests were ignored";
/// <summary>
/// The minimum duration for tests
/// </summary>
internal const double MIN_DURATION = 0.000001d;
// static Logger log = InternalTrace.GetLogger("TestResult");
private readonly StringBuilder _output = new StringBuilder();
private double _duration;
/// <summary>
/// Aggregate assertion count
/// </summary>
protected int InternalAssertCount;
private ResultState _resultState;
private string _message;
private string _stackTrace;
private readonly List<AssertionResult> _assertionResults = new List<AssertionResult>();
private readonly List<TestAttachment> _testAttachments = new List<TestAttachment>();
#if PARALLEL
/// <summary>
/// ReaderWriterLock
/// </summary>
#if NET20
protected ReaderWriterLock RwLock = new ReaderWriterLock();
#else
protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
#endif
#endif
#endregion
#region Constructor
/// <summary>
/// Construct a test result given a Test
/// </summary>
/// <param name="test">The test to be used</param>
public TestResult(ITest test)
{
Test = test;
ResultState = ResultState.Inconclusive;
#if NETSTANDARD1_4
OutWriter = new StringWriter(_output);
#else
OutWriter = TextWriter.Synchronized(new StringWriter(_output));
#endif
}
#endregion
#region ITestResult Members
/// <summary>
/// Gets the test with which this result is associated.
/// </summary>
public ITest Test { get; }
/// <summary>
/// Gets the ResultState of the test result, which
/// indicates the success or failure of the test.
/// </summary>
public ResultState ResultState
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _resultState;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
private set { _resultState = value; }
}
/// <summary>
/// Gets the name of the test result
/// </summary>
public virtual string Name
{
get { return Test.Name; }
}
/// <summary>
/// Gets the full name of the test result
/// </summary>
public virtual string FullName
{
get { return Test.FullName; }
}
/// <summary>
/// Gets or sets the elapsed time for running the test in seconds
/// </summary>
public double Duration
{
get { return _duration; }
set { _duration = value >= MIN_DURATION ? value : MIN_DURATION; }
}
/// <summary>
/// Gets or sets the time the test started running.
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// Gets or sets the time the test finished running.
/// </summary>
public DateTime EndTime { get; set; }
/// <summary>
/// Adds a test attachment to the test result
/// </summary>
/// <param name="attachment">The TestAttachment object to attach</param>
internal void AddTestAttachment(TestAttachment attachment)
{
_testAttachments.Add(attachment);
}
/// <summary>
/// Gets the collection of files attached to the test
/// </summary>
public ICollection<TestAttachment> TestAttachments => new ReadOnlyCollection<TestAttachment>(_testAttachments);
/// <summary>
/// Gets the message associated with a test
/// failure or with not running the test
/// </summary>
public string Message
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _message;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
private set
{
_message = value;
}
}
/// <summary>
/// Gets any stack trace associated with an
/// error or failure.
/// </summary>
public virtual string StackTrace
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _stackTrace;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
private set
{
_stackTrace = value;
}
}
/// <summary>
/// Gets or sets the count of asserts executed
/// when running the test.
/// </summary>
public int AssertCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return InternalAssertCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock ();
#endif
}
}
internal set
{
InternalAssertCount = value;
}
}
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public abstract int FailCount { get; }
/// <summary>
/// Gets the number of test cases that had warnings
/// when running the test and all its children.
/// </summary>
public abstract int WarningCount { get; }
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public abstract int PassCount { get; }
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public abstract int SkipCount { get; }
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public abstract int InconclusiveCount { get; }
/// <summary>
/// Indicates whether this result has any child results.
/// </summary>
public abstract bool HasChildren { get; }
/// <summary>
/// Gets the collection of child results.
/// </summary>
public abstract IEnumerable<ITestResult> Children { get; }
/// <summary>
/// Gets a TextWriter, which will write output to be included in the result.
/// </summary>
public TextWriter OutWriter { get; }
/// <summary>
/// Gets any text output written to this result.
/// </summary>
public string Output
{
get { return _output.ToString(); }
}
/// <summary>
/// Gets a list of assertion results associated with the test.
/// </summary>
public IList<AssertionResult> AssertionResults
{
get { return _assertionResults; }
}
#endregion
#region IXmlNodeBuilder Members
/// <summary>
/// Returns the XML representation of the result.
/// </summary>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns>An XmlNode representing the result</returns>
public TNode ToXml(bool recursive)
{
return AddToXml(new TNode("dummy"), recursive);
}
/// <summary>
/// Adds the XML representation of the result as a child of the
/// supplied parent node..
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public virtual TNode AddToXml(TNode parentNode, bool recursive)
{
// A result node looks like a test node with extra info added
TNode thisNode = Test.AddToXml(parentNode, false);
thisNode.AddAttribute("result", ResultState.Status.ToString());
if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString())
thisNode.AddAttribute("label", ResultState.Label);
if (ResultState.Site != FailureSite.Test)
thisNode.AddAttribute("site", ResultState.Site.ToString());
thisNode.AddAttribute("start-time", StartTime.ToString("u"));
thisNode.AddAttribute("end-time", EndTime.ToString("u"));
thisNode.AddAttribute("duration", Duration.ToString("0.000000", NumberFormatInfo.InvariantInfo));
if (Test is TestSuite)
{
thisNode.AddAttribute("total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString());
thisNode.AddAttribute("passed", PassCount.ToString());
thisNode.AddAttribute("failed", FailCount.ToString());
thisNode.AddAttribute("warnings", WarningCount.ToString());
thisNode.AddAttribute("inconclusive", InconclusiveCount.ToString());
thisNode.AddAttribute("skipped", SkipCount.ToString());
}
thisNode.AddAttribute("asserts", AssertCount.ToString());
switch (ResultState.Status)
{
case TestStatus.Failed:
AddFailureElement(thisNode);
break;
case TestStatus.Skipped:
case TestStatus.Passed:
case TestStatus.Inconclusive:
case TestStatus.Warning:
if (Message != null && Message.Trim().Length > 0)
AddReasonElement(thisNode);
break;
}
if (Output.Length > 0)
AddOutputElement(thisNode);
if (AssertionResults.Count > 0)
AddAssertionsElement(thisNode);
if (_testAttachments.Count > 0)
AddAttachmentsElement(thisNode);
if (recursive && HasChildren)
foreach (TestResult child in Children)
child.AddToXml(thisNode, recursive);
return thisNode;
}
#endregion
#region Other Public Properties
/// <summary>
/// Gets a count of pending failures (from Multiple Assert)
/// </summary>
public int PendingFailures
{
get { return AssertionResults.Count(ar => ar.Status == AssertionStatus.Failed); }
}
/// <summary>
/// Gets the worst assertion status (highest enum) in all the assertion results
/// </summary>
public AssertionStatus WorstAssertionStatus
{
get { return AssertionResults.Aggregate((ar1, ar2) => ar1.Status > ar2.Status ? ar1 : ar2).Status; }
}
#endregion
#region Other Public Methods
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
public void SetResult(ResultState resultState)
{
SetResult(resultState, null, null);
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="message">A message associated with the result state</param>
public void SetResult(ResultState resultState, string message)
{
SetResult(resultState, message, null);
}
/// <summary>
/// Set the result of the test
/// </summary>
/// <param name="resultState">The ResultState to use in the result</param>
/// <param name="message">A message associated with the result state</param>
/// <param name="stackTrace">Stack trace giving the location of the command</param>
public void SetResult(ResultState resultState, string message, string stackTrace)
{
#if PARALLEL
RwLock.EnterWriteLock();
#endif
try
{
ResultState = resultState;
Message = message;
StackTrace = stackTrace;
}
finally
{
#if PARALLEL
RwLock.ExitWriteLock();
#endif
}
}
/// <summary>
/// Set the test result based on the type of exception thrown
/// </summary>
/// <param name="ex">The exception that was thrown</param>
public void RecordException(Exception ex)
{
var result = new ExceptionResult(ex, FailureSite.Test);
SetResult(result.ResultState, result.Message, result.StackTrace);
if (AssertionResults.Count > 0 && result.ResultState == ResultState.Error)
{
// Add pending failures to the legacy result message
Message += CreateLegacyFailureMessage();
// Add to the list of assertion errors, so that newer runners will see it
AssertionResults.Add(new AssertionResult(AssertionStatus.Error, result.Message, result.StackTrace));
}
}
/// <summary>
/// Set the test result based on the type of exception thrown
/// </summary>
/// <param name="ex">The exception that was thrown</param>
/// <param name="site">The FailureSite to use in the result</param>
public void RecordException(Exception ex, FailureSite site)
{
var result = new ExceptionResult(ex, site);
SetResult(result.ResultState, result.Message, result.StackTrace);
}
/// <summary>
/// RecordTearDownException appends the message and stack trace
/// from an exception arising during teardown of the test
/// to any previously recorded information, so that any
/// earlier failure information is not lost. Note that
/// calling Assert.Ignore, Assert.Inconclusive, etc. during
/// teardown is treated as an error. If the current result
/// represents a suite, it may show a teardown error even
/// though all contained tests passed.
/// </summary>
/// <param name="ex">The Exception to be recorded</param>
public void RecordTearDownException(Exception ex)
{
ex = ValidateAndUnwrap(ex);
ResultState resultState = ResultState == ResultState.Cancelled
? ResultState.Cancelled
: ResultState.Error;
if (Test.IsSuite)
resultState = resultState.WithSite(FailureSite.TearDown);
string message = "TearDown : " + ExceptionHelper.BuildMessage(ex);
if (Message != null)
message = Message + Environment.NewLine + message;
string stackTrace = "--TearDown" + Environment.NewLine + ExceptionHelper.BuildStackTrace(ex);
if (StackTrace != null)
stackTrace = StackTrace + Environment.NewLine + stackTrace;
SetResult(resultState, message, stackTrace);
}
private static Exception ValidateAndUnwrap(Exception ex)
{
Guard.ArgumentNotNull(ex, nameof(ex));
if ((ex is NUnitException || ex is TargetInvocationException) && ex.InnerException != null)
return ex.InnerException;
return ex;
}
private struct ExceptionResult
{
public ResultState ResultState { get; }
public string Message { get; }
public string StackTrace { get; }
public ExceptionResult(Exception ex, FailureSite site)
{
ex = ValidateAndUnwrap(ex);
if (ex is ResultStateException)
{
ResultState = ((ResultStateException)ex).ResultState.WithSite(site);
Message = ex.Message;
StackTrace = StackFilter.DefaultFilter.Filter(ex.StackTrace);
}
#if THREAD_ABORT
else if (ex is ThreadAbortException)
{
ResultState = ResultState.Cancelled.WithSite(site);
Message = "Test cancelled by user";
StackTrace = ex.StackTrace;
}
#endif
else
{
ResultState = ResultState.Error.WithSite(site);
Message = ExceptionHelper.BuildMessage(ex);
StackTrace = ExceptionHelper.BuildStackTrace(ex);
}
}
}
/// <summary>
/// Update overall test result, including legacy Message, based
/// on AssertionResults that have been saved to this point.
/// </summary>
public void RecordTestCompletion()
{
switch (AssertionResults.Count)
{
case 0:
SetResult(ResultState.Success);
break;
case 1:
SetResult(
AssertionStatusToResultState(AssertionResults[0].Status),
AssertionResults[0].Message,
AssertionResults[0].StackTrace);
break;
default:
SetResult(
AssertionStatusToResultState(WorstAssertionStatus),
CreateLegacyFailureMessage());
break;
}
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionResult assertion)
{
_assertionResults.Add(assertion);
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionStatus status, string message, string stackTrace)
{
RecordAssertion(new AssertionResult(status, message, stackTrace));
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionStatus status, string message)
{
RecordAssertion(status, message, null);
}
/// <summary>
/// Creates a failure message incorporating failures
/// from a Multiple Assert block for use by runners
/// that don't know about AssertionResults.
/// </summary>
/// <returns>Message as a string</returns>
private string CreateLegacyFailureMessage()
{
var writer = new StringWriter();
if (AssertionResults.Count > 1)
writer.WriteLine("Multiple failures or warnings in test:");
int counter = 0;
foreach (var assertion in AssertionResults)
writer.WriteLine(string.Format(" {0}) {1}", ++counter, assertion.Message));
return writer.ToString();
}
#endregion
#region Helper Methods
/// <summary>
/// Adds a reason element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new reason element.</returns>
private TNode AddReasonElement(TNode targetNode)
{
TNode reasonNode = targetNode.AddElement("reason");
return reasonNode.AddElementWithCDATA("message", Message);
}
/// <summary>
/// Adds a failure element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new failure element.</returns>
private TNode AddFailureElement(TNode targetNode)
{
TNode failureNode = targetNode.AddElement("failure");
if (Message != null && Message.Trim().Length > 0)
failureNode.AddElementWithCDATA("message", Message);
if (StackTrace != null && StackTrace.Trim().Length > 0)
failureNode.AddElementWithCDATA("stack-trace", StackTrace);
return failureNode;
}
private TNode AddOutputElement(TNode targetNode)
{
return targetNode.AddElementWithCDATA("output", Output);
}
private TNode AddAssertionsElement(TNode targetNode)
{
var assertionsNode = targetNode.AddElement("assertions");
foreach (var assertion in AssertionResults)
{
TNode assertionNode = assertionsNode.AddElement("assertion");
assertionNode.AddAttribute("result", assertion.Status.ToString());
if (assertion.Message != null)
assertionNode.AddElementWithCDATA("message", assertion.Message);
if (assertion.StackTrace != null)
assertionNode.AddElementWithCDATA("stack-trace", assertion.StackTrace);
}
return assertionsNode;
}
private ResultState AssertionStatusToResultState(AssertionStatus status)
{
switch (status)
{
case AssertionStatus.Inconclusive:
return ResultState.Inconclusive;
default:
case AssertionStatus.Passed:
return ResultState.Success;
case AssertionStatus.Warning:
return ResultState.Warning;
case AssertionStatus.Failed:
return ResultState.Failure;
case AssertionStatus.Error:
return ResultState.Error;
}
}
/// <summary>
/// Adds an attachments element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new attachments element.</returns>
private TNode AddAttachmentsElement(TNode targetNode)
{
TNode attachmentsNode = targetNode.AddElement("attachments");
foreach (var attachment in _testAttachments)
{
var attachmentNode = attachmentsNode.AddElement("attachment");
attachmentNode.AddElement("filePath", attachment.FilePath);
if (attachment.Description != null)
attachmentNode.AddElementWithCDATA("description", attachment.Description);
}
return attachmentsNode;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Windows.ApplicationModel.Resources;
namespace Prism.Windows.Validation
{
/// <summary>
/// The BindableValidator class run validation rules of an entity, and stores a collection of errors of the properties that did not pass validation.
/// The validation is run on each property change or whenever the ValidateProperties method is called.
/// It also provides an indexer property, that uses the property names as keys and return the error list for the specified property.
/// </summary>
public class BindableValidator : INotifyPropertyChanged
{
private readonly INotifyPropertyChanged _entityToValidate;
private IDictionary<string, ReadOnlyCollection<string>> _errors = new Dictionary<string, ReadOnlyCollection<string>>();
/// <summary>
/// Represents a collection of empty error values.
/// </summary>
public static readonly ReadOnlyCollection<string> EmptyErrorsCollection = new ReadOnlyCollection<string>(new List<string>());
private Func<string, string, string> _getResourceDelegate;
/// <summary>
/// Initializes a new instance of the BindableValidator class with the entity to validate.
/// </summary>
/// <param name="entityToValidate">The entity to validate</param>
/// <param name="getResourceDelegate">A delegate that returns a string resource given a resource map Id and resource Id</param>
/// <exception cref="ArgumentNullException">When <paramref name="entityToValidate"/> is <see langword="null" />.</exception>
public BindableValidator(INotifyPropertyChanged entityToValidate, Func<string, string, string> getResourceDelegate)
: this(entityToValidate)
{
_getResourceDelegate = getResourceDelegate;
}
/// <summary>
/// Initializes a new instance of the BindableValidator class with the entity to validate.
/// </summary>
/// <param name="entityToValidate">The entity to validate</param>
/// <exception cref="ArgumentNullException">When <paramref name="entityToValidate"/> is <see langword="null" />.</exception>
public BindableValidator(INotifyPropertyChanged entityToValidate)
{
if (entityToValidate == null)
{
throw new ArgumentNullException("entityToValidate");
}
_entityToValidate = entityToValidate;
IsValidationEnabled = true;
_getResourceDelegate = (mapId, key) =>
{
var resourceLoader = ResourceLoader.GetForCurrentView(mapId);
return resourceLoader.GetString(key);
};
}
/// <summary>
/// Multicast event for errors change notifications.
/// </summary>
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
/// <summary>
/// Multicast event for property change notifications.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Returns the errors of the property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <returns>The errors of the property, if it has errors. Otherwise, the BindableValidator.EmptyErrorsCollection.</returns>
public ReadOnlyCollection<string> this[string propertyName]
{
get
{
return _errors.ContainsKey(propertyName) ? _errors[propertyName] : EmptyErrorsCollection;
}
}
/// <summary>
/// Gets the list of errors per property.
/// </summary>
/// <value>
/// The dictionary of property names and errors collection pairs.
/// </value>
public IDictionary<string, ReadOnlyCollection<string>> Errors
{
get { return _errors; }
}
/// <summary>
/// Returns true if the Validation functionality is enabled. Otherwise, false.
/// </summary>
public bool IsValidationEnabled { get; set; }
/// <summary>
/// Returns a new ReadOnlyDictionary containing all the errors of the Entity, separated by property.
/// </summary>
/// <returns>
/// A ReadOnlyDictionary that contains a KeyValuePair for each property with errors.
/// Each KeyValuePair has a property name as the key, and the value is the collection of errors of that property.
/// </returns>
public ReadOnlyDictionary<string, ReadOnlyCollection<string>> GetAllErrors()
{
return new ReadOnlyDictionary<string, ReadOnlyCollection<string>>(_errors);
}
/// <summary>
/// Updates the errors collection of the entity, notifying if the errors collection has changed.
/// </summary>
/// <param name="entityErrors">The collection of errors for the entity.</param>
public void SetAllErrors(IDictionary<string, ReadOnlyCollection<string>> entityErrors)
{
if (entityErrors == null)
{
throw new ArgumentNullException("entityErrors");
}
_errors.Clear();
foreach (var item in entityErrors)
{
SetPropertyErrors(item.Key, item.Value);
}
OnPropertyChanged("Item[]");
OnErrorsChanged(string.Empty);
}
/// <summary>
/// Validates the property, based on the rules set in the property ValidationAttributes attributes.
/// It updates the errors collection with the new validation results (notifying if necessary).
/// </summary>
/// <param name="propertyName">The name of the property to validate.</param>
/// <returns>True if the property is valid. Otherwise, false.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="propertyName"/> is <see langword="null" /> or an empty string value.</exception>
/// <exception cref="ArgumentException">When the <paramref name="propertyName"/> parameter does not match any property name.</exception>
public bool ValidateProperty(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException("propertyName");
}
var propertyInfo = _entityToValidate.GetType().GetRuntimeProperty(propertyName);
if (propertyInfo == null)
{
var errorString = _getResourceDelegate(Constants.InfrastructureResourceMapId, "InvalidPropertyNameException");
throw new ArgumentException(errorString, propertyName);
}
var propertyErrors = new List<string>();
bool isValid = TryValidateProperty(propertyInfo, propertyErrors);
bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors);
if (errorsChanged)
{
OnErrorsChanged(propertyName);
OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName));
}
return isValid;
}
/// <summary>
/// Validates all the properties decorated with the ValidationAttribute attribute.
/// It updates each property errors collection with the new validation results (notifying if necessary).
/// </summary>
/// <returns>True if the property is valid. Otherwise, false.</returns>
public bool ValidateProperties()
{
var propertiesWithChangedErrors = new List<string>();
// Get all the properties decorated with the ValidationAttribute attribute.
var propertiesToValidate = _entityToValidate.GetType()
.GetRuntimeProperties()
.Where(c => c.GetCustomAttributes(typeof(ValidationAttribute)).Any());
foreach (PropertyInfo propertyInfo in propertiesToValidate)
{
var propertyErrors = new List<string>();
TryValidateProperty(propertyInfo, propertyErrors);
// If the errors have changed, save the property name to notify the update at the end of this method.
bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors);
if (errorsChanged && !propertiesWithChangedErrors.Contains(propertyInfo.Name))
{
propertiesWithChangedErrors.Add(propertyInfo.Name);
}
}
// Notify each property whose set of errors has changed since the last validation.
foreach (string propertyName in propertiesWithChangedErrors)
{
OnErrorsChanged(propertyName);
OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName));
}
return _errors.Values.Count == 0;
}
/// <summary>
/// Performs a validation of a property, adding the results in the propertyErrors list.
/// </summary>
/// <param name="propertyInfo">The PropertyInfo of the property to validate</param>
/// <param name="propertyErrors">A list containing the current error messages of the property.</param>
/// <returns>True if the property is valid. Otherwise, false.</returns>
private bool TryValidateProperty(PropertyInfo propertyInfo, List<string> propertyErrors)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(_entityToValidate) { MemberName = propertyInfo.Name };
var propertyValue = propertyInfo.GetValue(_entityToValidate);
// Validate the property
bool isValid = Validator.TryValidateProperty(propertyValue, context, results);
if (results.Any())
{
propertyErrors.AddRange(results.Select(c => c.ErrorMessage));
}
return isValid;
}
/// <summary>
/// Updates the errors collection of the property.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="propertyNewErrors">The new collection of property errors.</param>
/// <returns>True if the property errors have changed. Otherwise, false.</returns>
private bool SetPropertyErrors(string propertyName, IList<string> propertyNewErrors)
{
bool errorsChanged = false;
// If the property does not have errors, simply add them
if (!_errors.ContainsKey(propertyName))
{
if (propertyNewErrors.Count > 0)
{
_errors.Add(propertyName, new ReadOnlyCollection<string>(propertyNewErrors));
errorsChanged = true;
}
}
else
{
// If the property has errors, check if the number of errors are different.
// If the number of errors is the same, check if there are new ones
if (propertyNewErrors.Count != _errors[propertyName].Count || _errors[propertyName].Intersect(propertyNewErrors).Count() != propertyNewErrors.Count())
{
if (propertyNewErrors.Count > 0)
{
_errors[propertyName] = new ReadOnlyCollection<string>(propertyNewErrors);
}
else
{
_errors.Remove(propertyName);
}
errorsChanged = true;
}
}
return errorsChanged;
}
/// <summary>
/// Notifies listeners that a property value has changed.
/// </summary>
/// <param name="propertyName">Name of the property used to notify listeners.</param>
private void OnPropertyChanged(string propertyName)
{
var eventHandler = PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Notifies listeners that the errors of a property have changed.
/// </summary>
/// <param name="propertyName">Name of the property used to notify listeners.</param>
private void OnErrorsChanged(string propertyName)
{
var eventHandler = ErrorsChanged;
if (eventHandler != null)
{
eventHandler(this, new DataErrorsChangedEventArgs(propertyName));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Util;
using Android.Views;
using Android.Views.Animations;
namespace Explosions
{
/// <summary>
/// Represents the overlay that controls <see cref="View" /> explosions.
/// </summary>
public class ExplosionView : View
{
private readonly IList<ExplosionAnimator> explosions = new List<ExplosionAnimator>();
/// <summary>
/// Initializes a new instance of the <see cref="ExplosionView"/> class.
/// </summary>
/// <param name="context">The context.</param>
public ExplosionView(Context context)
: base(context)
{
Init();
}
/// <summary>
/// Initializes a new instance of the <see cref="ExplosionView"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="attrs">The attributes.</param>
public ExplosionView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
Init();
}
/// <summary>
/// Initializes a new instance of the <see cref="ExplosionView"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="attrs">The attributes.</param>
/// <param name="defStyleAttr">The default style attribute.</param>
public ExplosionView(Context context, IAttributeSet attrs, int defStyleAttr)
: base(context, attrs, defStyleAttr)
{
Init();
}
private void Init()
{
ExpansionLimit = Utils.Dp2Px(32);
}
/// <summary>
/// Gets or sets the expansion limit when exploding.
/// </summary>
/// <value>The expansion limit.</value>
public int ExpansionLimit { get; set; }
/// <summary>
/// Called when the view is being drawn.
/// </summary>
/// <param name="canvas">The canvas on which the background will be drawn.</param>
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
foreach (ExplosionAnimator explosion in explosions.ToArray())
{
explosion.Draw(canvas);
}
}
/// <summary>
/// Explodes the specified bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="bounds">The bounds.</param>
/// <param name="startDelay">The start delay.</param>
/// <param name="duration">The duration.</param>
public void Explode(Bitmap bitmap, Rect bounds, long startDelay, long duration)
{
var explosion = new ExplosionAnimator(this, bitmap, bounds);
explosion.AnimationEnd += delegate
{
explosions.Remove(explosion);
};
explosion.StartDelay = startDelay;
explosion.Duration = duration;
explosions.Add(explosion);
explosion.Start();
}
/// <summary>
/// Explodes the specified view.
/// </summary>
/// <param name="view">The view.</param>
public void Explode(View view)
{
Explode(view, ExplosionAnimator.DefaultDuration, null);
}
/// <summary>
/// Explodes the specified view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="duration">The duration of the explosion.</param>
public void Explode(View view, long duration)
{
Explode(view, duration, null);
}
/// <summary>
/// Explodes the specified view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="onHidden">The callback that is invoked when the view is no longer visible.</param>
public void Explode(View view, Action onHidden)
{
Explode(view, ExplosionAnimator.DefaultDuration, onHidden);
}
/// <summary>
/// Explodes the specified view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="duration">The duration of the explosion.</param>
/// <param name="onHidden">The callback that is invoked when the view is no longer visible.</param>
public void Explode(View view, long duration, Action onHidden)
{
const float vibrateAmount = 0.05f;
var preDuration = (long)(duration * 0.25f);
var explosionDuration = (long)(duration * 0.75f);
var startDelay = (long)(duration * 0.15f);
// get the bounds
var r = new Rect();
view.GetGlobalVisibleRect(r);
var location = new int[2];
GetLocationOnScreen(location);
r.Offset(-location[0], -location[1]);
r.Inset(-ExpansionLimit, -ExpansionLimit);
var set = new AnimationSet(true);
// vibrate
var vibrate = new VibrateAnimation(view.Width * vibrateAmount, view.Height * vibrateAmount);
vibrate.Duration = preDuration;
set.AddAnimation(vibrate);
// implode
var alpha = new AlphaAnimation(1.0f, 0.0f);
alpha.Duration = preDuration;
alpha.StartOffset = startDelay;
set.AddAnimation(alpha);
var scale = new ScaleAnimation(
1.0f, 0.0f,
1.0f, 0.0f,
Dimension.RelativeToSelf, 0.5f,
Dimension.RelativeToSelf, 0.5f);
scale.Duration = preDuration;
scale.StartOffset = startDelay;
set.AddAnimation(scale);
// apply on complete
set.AnimationEnd += delegate
{
view.Visibility = ViewStates.Invisible;
if (onHidden != null)
{
onHidden();
}
};
view.StartAnimation(set);
// explode
Explode(Utils.CreateBitmapFromView(view), r, startDelay, explosionDuration);
}
/// <summary>
/// Resets the specified view.
/// </summary>
/// <param name="view">The view.</param>
public void Reset(View view)
{
view.Visibility = ViewStates.Visible;
}
/// <summary>
/// Attaches the explosion overlay to the specified activity.
/// </summary>
/// <param name="activity">The activity.</param>
/// <returns>The ExplosionView that was attached.</returns>
public static ExplosionView Attach(Activity activity)
{
var rootView = (ViewGroup)activity.Window.DecorView;
var explosionField = new ExplosionView(activity);
var layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent);
rootView.AddView(explosionField, layoutParams);
return explosionField;
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.AspNet.Razor.Generator;
using Microsoft.AspNet.Razor.Parser.SyntaxTree;
namespace Microsoft.AspNet.Razor.Test.Framework
{
// The product code doesn't need this, but having subclasses for the block types makes tests much cleaner :)
public class StatementBlock : Block
{
private const BlockType ThisBlockType = BlockType.Statement;
public StatementBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public StatementBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public StatementBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public StatementBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class DirectiveBlock : Block
{
private const BlockType ThisBlockType = BlockType.Directive;
public DirectiveBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public DirectiveBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public DirectiveBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public DirectiveBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class FunctionsBlock : Block
{
private const BlockType ThisBlockType = BlockType.Functions;
public FunctionsBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public FunctionsBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public FunctionsBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public FunctionsBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class ExpressionBlock : Block
{
private const BlockType ThisBlockType = BlockType.Expression;
public ExpressionBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public ExpressionBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public ExpressionBlock(params SyntaxTreeNode[] children)
: this(new ExpressionCodeGenerator(), children)
{
}
public ExpressionBlock(IEnumerable<SyntaxTreeNode> children)
: this(new ExpressionCodeGenerator(), children)
{
}
}
public class HelperBlock : Block
{
private const BlockType ThisBlockType = BlockType.Helper;
public HelperBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public HelperBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public HelperBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public HelperBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class MarkupBlock : Block
{
private const BlockType ThisBlockType = BlockType.Markup;
public MarkupBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public MarkupBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public MarkupBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public MarkupBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class SectionBlock : Block
{
private const BlockType ThisBlockType = BlockType.Section;
public SectionBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public SectionBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public SectionBlock(params SyntaxTreeNode[] children)
: this(BlockCodeGenerator.Null, children)
{
}
public SectionBlock(IEnumerable<SyntaxTreeNode> children)
: this(BlockCodeGenerator.Null, children)
{
}
}
public class TemplateBlock : Block
{
private const BlockType ThisBlockType = BlockType.Template;
public TemplateBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public TemplateBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public TemplateBlock(params SyntaxTreeNode[] children)
: this(new TemplateBlockCodeGenerator(), children)
{
}
public TemplateBlock(IEnumerable<SyntaxTreeNode> children)
: this(new TemplateBlockCodeGenerator(), children)
{
}
}
public class CommentBlock : Block
{
private const BlockType ThisBlockType = BlockType.Comment;
public CommentBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)
: base(ThisBlockType, children, codeGenerator)
{
}
public CommentBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)
: this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)
{
}
public CommentBlock(params SyntaxTreeNode[] children)
: this(new RazorCommentCodeGenerator(), children)
{
}
public CommentBlock(IEnumerable<SyntaxTreeNode> children)
: this(new RazorCommentCodeGenerator(), children)
{
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.TestHost
{
public class TestClientTests
{
[Fact]
public async Task GetAsyncWorks()
{
// Arrange
var expected = "GET Response";
RequestDelegate appDelegate = ctx =>
ctx.Response.WriteAsync(expected);
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act
var actual = await client.GetStringAsync("http://localhost:12345");
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public async Task NoTrailingSlash_NoPathBase()
{
// Arrange
var expected = "GET Response";
RequestDelegate appDelegate = ctx =>
{
Assert.Equal("", ctx.Request.PathBase.Value);
Assert.Equal("/", ctx.Request.Path.Value);
return ctx.Response.WriteAsync(expected);
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act
var actual = await client.GetStringAsync("http://localhost:12345");
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public async Task SingleTrailingSlash_NoPathBase()
{
// Arrange
var expected = "GET Response";
RequestDelegate appDelegate = ctx =>
{
Assert.Equal("", ctx.Request.PathBase.Value);
Assert.Equal("/", ctx.Request.Path.Value);
return ctx.Response.WriteAsync(expected);
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act
var actual = await client.GetStringAsync("http://localhost:12345/");
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public async Task PutAsyncWorks()
{
// Arrange
RequestDelegate appDelegate = async ctx =>
{
var content = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
await ctx.Response.WriteAsync(content + " PUT Response");
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act
var content = new StringContent("Hello world");
var response = await client.PutAsync("http://localhost:12345", content).DefaultTimeout();
// Assert
Assert.Equal("Hello world PUT Response", await response.Content.ReadAsStringAsync().DefaultTimeout());
}
[Fact]
public async Task PostAsyncWorks()
{
// Arrange
RequestDelegate appDelegate = async ctx =>
await ctx.Response.WriteAsync(await new StreamReader(ctx.Request.Body).ReadToEndAsync() + " POST Response");
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act
var content = new StringContent("Hello world");
var response = await client.PostAsync("http://localhost:12345", content).DefaultTimeout();
// Assert
Assert.Equal("Hello world POST Response", await response.Content.ReadAsStringAsync().DefaultTimeout());
}
[Fact]
public async Task LargePayload_DisposesRequest_AfterResponseIsCompleted()
{
// Arrange
var data = new byte[2048];
var character = Encoding.ASCII.GetBytes("a");
for (var i = 0; i < data.Length; i++)
{
data[i] = character[0];
}
var builder = new WebHostBuilder();
RequestDelegate app = async ctx =>
{
var disposable = new TestDisposable();
ctx.Response.RegisterForDispose(disposable);
await ctx.Response.Body.WriteAsync(data, 0, 1024);
Assert.False(disposable.IsDisposed);
await ctx.Response.Body.WriteAsync(data, 1024, 1024);
};
builder.Configure(appBuilder => appBuilder.Run(app));
var server = new TestServer(builder);
var client = server.CreateClient();
// Act & Assert
var response = await client.GetAsync("http://localhost:12345");
}
private class TestDisposable : IDisposable
{
public bool IsDisposed { get; private set; }
public void Dispose()
{
IsDisposed = true;
}
}
[Fact]
public async Task ClientStreamingWorks()
{
// Arrange
var responseStartedSyncPoint = new SyncPoint();
var requestEndingSyncPoint = new SyncPoint();
var requestStreamSyncPoint = new SyncPoint();
RequestDelegate appDelegate = async ctx =>
{
// Send headers
await ctx.Response.BodyWriter.FlushAsync();
// Ensure headers received by client
await responseStartedSyncPoint.WaitToContinue();
await ctx.Response.WriteAsync("STARTED");
// ReadToEndAsync will wait until request body is complete
var requestString = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
await ctx.Response.WriteAsync(requestString + " POST Response");
await requestEndingSyncPoint.WaitToContinue();
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamSyncPoint.WaitToContinue();
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
await responseStartedSyncPoint.WaitForSyncPoint().DefaultTimeout();
responseStartedSyncPoint.Continue();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
// Ensure request stream has started
await requestStreamSyncPoint.WaitForSyncPoint();
byte[] buffer = new byte[1024];
var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal("STARTED", Encoding.UTF8.GetString(buffer, 0, length));
// Send content and finish request body
await requestStream.WriteAsync(Encoding.UTF8.GetBytes("Hello world")).AsTask().DefaultTimeout();
await requestStream.FlushAsync().DefaultTimeout();
requestStreamSyncPoint.Continue();
// Ensure content is received while request is in progress
length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal("Hello world POST Response", Encoding.UTF8.GetString(buffer, 0, length));
// Request is ending
await requestEndingSyncPoint.WaitForSyncPoint().DefaultTimeout();
requestEndingSyncPoint.Continue();
// No more response content
length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal(0, length);
}
[Fact]
public async Task ClientStreaming_Cancellation()
{
// Arrange
var responseStartedSyncPoint = new SyncPoint();
var responseReadSyncPoint = new SyncPoint();
var responseEndingSyncPoint = new SyncPoint();
var requestStreamSyncPoint = new SyncPoint();
var readCanceled = false;
RequestDelegate appDelegate = async ctx =>
{
// Send headers
await ctx.Response.BodyWriter.FlushAsync();
// Ensure headers received by client
await responseStartedSyncPoint.WaitToContinue();
var serverBuffer = new byte[1024];
var serverLength = await ctx.Request.Body.ReadAsync(serverBuffer);
Assert.Equal("SENT", Encoding.UTF8.GetString(serverBuffer, 0, serverLength));
await responseReadSyncPoint.WaitToContinue();
try
{
await ctx.Request.Body.ReadAsync(serverBuffer);
}
catch (OperationCanceledException)
{
readCanceled = true;
}
await responseEndingSyncPoint.WaitToContinue();
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamSyncPoint.WaitToContinue();
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
await responseStartedSyncPoint.WaitForSyncPoint().DefaultTimeout();
responseStartedSyncPoint.Continue();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
// Ensure request stream has started
await requestStreamSyncPoint.WaitForSyncPoint();
// Write to request
await requestStream.WriteAsync(Encoding.UTF8.GetBytes("SENT")).AsTask().DefaultTimeout();
await requestStream.FlushAsync().DefaultTimeout();
await responseReadSyncPoint.WaitForSyncPoint().DefaultTimeout();
// Cancel request. Disposing response must be used because SendAsync has finished.
response.Dispose();
responseReadSyncPoint.Continue();
await responseEndingSyncPoint.WaitForSyncPoint().DefaultTimeout();
responseEndingSyncPoint.Continue();
Assert.True(readCanceled);
requestStreamSyncPoint.Continue();
}
[Fact]
public async Task ClientStreaming_ResponseCompletesWithoutReadingRequest()
{
// Arrange
var requestStreamTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
var responseEndingSyncPoint = new SyncPoint();
RequestDelegate appDelegate = async ctx =>
{
await ctx.Response.WriteAsync("POST Response");
await responseEndingSyncPoint.WaitToContinue();
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamTcs.Task;
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
// Read response
byte[] buffer = new byte[1024];
var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal("POST Response", Encoding.UTF8.GetString(buffer, 0, length));
// Send large content and block on back pressure
var writeTask = Task.Run(async () =>
{
try
{
await requestStream.WriteAsync(Encoding.UTF8.GetBytes(new string('!', 1024 * 1024 * 50))).AsTask().DefaultTimeout();
requestStreamTcs.SetResult(null);
}
catch (Exception ex)
{
requestStreamTcs.SetException(ex);
}
});
responseEndingSyncPoint.Continue();
// No more response content
length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal(0, length);
await writeTask;
}
[Fact]
public async Task ClientStreaming_ResponseCompletesWithPendingRead_ThrowError()
{
// Arrange
var requestStreamTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
RequestDelegate appDelegate = async ctx =>
{
var pendingReadTask = ctx.Request.Body.ReadAsync(new byte[1024], 0, 1024);
ctx.Response.Headers["test-header"] = "true";
await ctx.Response.Body.FlushAsync();
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamTcs.Task;
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal("true", response.Headers.GetValues("test-header").Single());
// Read response
var ex = await Assert.ThrowsAsync<IOException>(async () =>
{
byte[] buffer = new byte[1024];
var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
});
Assert.Equal("An error occurred when completing the request. Request delegate may have finished while there is a pending read of the request body.", ex.InnerException.Message);
// Unblock request
requestStreamTcs.TrySetResult(null);
}
[Fact]
public async Task ClientStreaming_ResponseCompletesWithoutResponseBodyWrite()
{
// Arrange
var requestStreamTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
RequestDelegate appDelegate = ctx =>
{
ctx.Response.Headers["test-header"] = "true";
return Task.CompletedTask;
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamTcs.Task;
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal("true", response.Headers.GetValues("test-header").Single());
// Read response
byte[] buffer = new byte[1024];
var length = await responseContent.ReadAsync(buffer).AsTask().DefaultTimeout();
Assert.Equal(0, length);
// Writing to request stream will fail because server is complete
await Assert.ThrowsAnyAsync<Exception>(() => requestStream.WriteAsync(buffer).AsTask());
// Unblock request
requestStreamTcs.TrySetResult(null);
}
[Fact]
public async Task ClientStreaming_ServerAbort()
{
// Arrange
var requestStreamSyncPoint = new SyncPoint();
var responseEndingSyncPoint = new SyncPoint();
RequestDelegate appDelegate = async ctx =>
{
// Send headers
await ctx.Response.BodyWriter.FlushAsync();
ctx.Abort();
await responseEndingSyncPoint.WaitToContinue();
};
Stream requestStream = null;
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:12345");
httpRequest.Version = new Version(2, 0);
httpRequest.Content = new PushContent(async stream =>
{
requestStream = stream;
await requestStreamSyncPoint.WaitToContinue();
});
// Act
var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
var responseContent = await response.Content.ReadAsStreamAsync().DefaultTimeout();
// Assert
// Ensure server has aborted
await responseEndingSyncPoint.WaitForSyncPoint();
// Ensure request stream has started
await requestStreamSyncPoint.WaitForSyncPoint();
// Send content and finish request body
await ExceptionAssert.ThrowsAsync<OperationCanceledException>(
() => requestStream.WriteAsync(Encoding.UTF8.GetBytes("Hello world")).AsTask(),
"Flush was canceled on underlying PipeWriter.").DefaultTimeout();
responseEndingSyncPoint.Continue();
requestStreamSyncPoint.Continue();
}
private class PushContent : HttpContent
{
private readonly Func<Stream, Task> _sendContent;
public PushContent(Func<Stream, Task> sendContent)
{
_sendContent = sendContent;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _sendContent(stream);
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
[Fact]
public async Task WebSocketWorks()
{
// Arrange
// This logger will attempt to access information from HttpRequest once the HttpContext is created
var logger = new VerifierLogger();
RequestDelegate appDelegate = async ctx =>
{
if (ctx.WebSockets.IsWebSocketRequest)
{
Assert.False(ctx.Request.Headers.ContainsKey(HeaderNames.SecWebSocketProtocol));
var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
var receiveArray = new byte[1024];
while (true)
{
var receiveResult = await websocket.ReceiveAsync(new System.ArraySegment<byte>(receiveArray), CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);
break;
}
else
{
var sendBuffer = new System.ArraySegment<byte>(receiveArray, 0, receiveResult.Count);
await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
}
}
}
};
var builder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddSingleton<ILogger<IWebHost>>(logger);
})
.Configure(app =>
{
app.Run(appDelegate);
});
var server = new TestServer(builder);
// Act
var client = server.CreateWebSocketClient();
// The HttpContext will be created and the logger will make sure that the HttpRequest exists and contains reasonable values
var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);
var hello = Encoding.UTF8.GetBytes("hello");
await clientSocket.SendAsync(new System.ArraySegment<byte>(hello), WebSocketMessageType.Text, true, CancellationToken.None);
var world = Encoding.UTF8.GetBytes("world!");
await clientSocket.SendAsync(new System.ArraySegment<byte>(world), WebSocketMessageType.Binary, true, CancellationToken.None);
await clientSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);
// Assert
Assert.Equal(WebSocketState.CloseSent, clientSocket.State);
var buffer = new byte[1024];
var result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
Assert.Equal(hello.Length, result.Count);
Assert.True(hello.SequenceEqual(buffer.Take(hello.Length)));
Assert.Equal(WebSocketMessageType.Text, result.MessageType);
result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
Assert.Equal(world.Length, result.Count);
Assert.True(world.SequenceEqual(buffer.Take(world.Length)));
Assert.Equal(WebSocketMessageType.Binary, result.MessageType);
result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
Assert.Equal(WebSocketMessageType.Close, result.MessageType);
Assert.Equal(WebSocketState.Closed, clientSocket.State);
clientSocket.Dispose();
}
[Fact]
public async Task WebSocketSubProtocolsWorks()
{
// Arrange
RequestDelegate appDelegate = async ctx =>
{
if (ctx.WebSockets.IsWebSocketRequest)
{
if (ctx.WebSockets.WebSocketRequestedProtocols.Contains("alpha") &&
ctx.WebSockets.WebSocketRequestedProtocols.Contains("bravo"))
{
// according to rfc6455, the "server needs to include the same field and one of the selected subprotocol values"
// however, this isn't enforced by either our server or client so it's possible to accept an arbitrary protocol.
// Done here to demonstrate not "correct" behaviour, simply to show it's possible. Other clients may not allow this.
var websocket = await ctx.WebSockets.AcceptWebSocketAsync("charlie");
await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);
}
else
{
var subprotocols = ctx.WebSockets.WebSocketRequestedProtocols.Any()
? string.Join(", ", ctx.WebSockets.WebSocketRequestedProtocols)
: "<none>";
var closeReason = "Unexpected subprotocols: " + subprotocols;
var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
await websocket.CloseAsync(WebSocketCloseStatus.InternalServerError, closeReason, CancellationToken.None);
}
}
};
var builder = new WebHostBuilder()
.Configure(app =>
{
app.Run(appDelegate);
});
var server = new TestServer(builder);
// Act
var client = server.CreateWebSocketClient();
client.SubProtocols.Add("alpha");
client.SubProtocols.Add("bravo");
var clientSocket = await client.ConnectAsync(new Uri("wss://localhost"), CancellationToken.None);
var buffer = new byte[1024];
var result = await clientSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// Assert
Assert.Equal(WebSocketMessageType.Close, result.MessageType);
Assert.Equal("Normal Closure", result.CloseStatusDescription);
Assert.Equal(WebSocketState.CloseReceived, clientSocket.State);
Assert.Equal("charlie", clientSocket.SubProtocol);
clientSocket.Dispose();
}
[ConditionalFact]
public async Task WebSocketAcceptThrowsWhenCancelled()
{
// Arrange
// This logger will attempt to access information from HttpRequest once the HttpContext is created
var logger = new VerifierLogger();
RequestDelegate appDelegate = async ctx =>
{
if (ctx.WebSockets.IsWebSocketRequest)
{
var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
var receiveArray = new byte[1024];
while (true)
{
var receiveResult = await websocket.ReceiveAsync(new ArraySegment<byte>(receiveArray), CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal Closure", CancellationToken.None);
break;
}
else
{
var sendBuffer = new System.ArraySegment<byte>(receiveArray, 0, receiveResult.Count);
await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
}
}
}
};
var builder = new WebHostBuilder()
.ConfigureServices(services => services.AddSingleton<ILogger<IWebHost>>(logger))
.Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
// Act
var client = server.CreateWebSocketClient();
var tokenSource = new CancellationTokenSource();
tokenSource.Cancel();
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await client.ConnectAsync(new Uri("http://localhost"), tokenSource.Token));
}
private class VerifierLogger : ILogger<IWebHost>
{
public IDisposable BeginScope<TState>(TState state) => new NoopDispoasble();
public bool IsEnabled(LogLevel logLevel) => true;
// This call verifies that fields of HttpRequest are accessed and valid
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) => formatter(state, exception);
class NoopDispoasble : IDisposable
{
public void Dispose()
{
}
}
}
[Fact]
public async Task WebSocketDisposalThrowsOnPeer()
{
// Arrange
RequestDelegate appDelegate = async ctx =>
{
if (ctx.WebSockets.IsWebSocketRequest)
{
var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
websocket.Dispose();
}
};
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(appDelegate);
});
var server = new TestServer(builder);
// Act
var client = server.CreateWebSocketClient();
var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);
var buffer = new byte[1024];
await Assert.ThrowsAsync<IOException>(async () => await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None));
clientSocket.Dispose();
}
[Fact]
public async Task WebSocketTinyReceiveGeneratesEndOfMessage()
{
// Arrange
RequestDelegate appDelegate = async ctx =>
{
if (ctx.WebSockets.IsWebSocketRequest)
{
var websocket = await ctx.WebSockets.AcceptWebSocketAsync();
var receiveArray = new byte[1024];
while (true)
{
var receiveResult = await websocket.ReceiveAsync(new System.ArraySegment<byte>(receiveArray), CancellationToken.None);
var sendBuffer = new System.ArraySegment<byte>(receiveArray, 0, receiveResult.Count);
await websocket.SendAsync(sendBuffer, receiveResult.MessageType, receiveResult.EndOfMessage, CancellationToken.None);
}
}
};
var builder = new WebHostBuilder().Configure(app =>
{
app.Run(appDelegate);
});
var server = new TestServer(builder);
// Act
var client = server.CreateWebSocketClient();
var clientSocket = await client.ConnectAsync(new System.Uri("http://localhost"), CancellationToken.None);
var hello = Encoding.UTF8.GetBytes("hello");
await clientSocket.SendAsync(new System.ArraySegment<byte>(hello), WebSocketMessageType.Text, true, CancellationToken.None);
// Assert
var buffer = new byte[1];
for (var i = 0; i < hello.Length; i++)
{
bool last = i == (hello.Length - 1);
var result = await clientSocket.ReceiveAsync(new System.ArraySegment<byte>(buffer), CancellationToken.None);
Assert.Equal(buffer.Length, result.Count);
Assert.Equal(buffer[0], hello[i]);
Assert.Equal(last, result.EndOfMessage);
}
clientSocket.Dispose();
}
[Fact]
public async Task ClientDisposalAbortsRequest()
{
// Arrange
var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
RequestDelegate appDelegate = async ctx =>
{
// Write Headers
await ctx.Response.Body.FlushAsync();
var sem = new SemaphoreSlim(0);
try
{
await sem.WaitAsync(ctx.RequestAborted);
}
catch (Exception e)
{
tcs.SetException(e);
}
};
// Act
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345");
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
// Abort Request
response.Dispose();
// Assert
var exception = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await tcs.Task);
}
[Fact]
public async Task ClientCancellationAbortsRequest()
{
var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var builder = new WebHostBuilder().Configure(app => app.Run(async ctx =>
{
try
{
await Task.Delay(TimeSpan.FromSeconds(30), ctx.RequestAborted);
tcs.SetResult(0);
}
catch (Exception e)
{
tcs.SetException(e);
return;
}
throw new InvalidOperationException("The request was not aborted");
}));
using var server = new TestServer(builder);
using var client = server.CreateClient();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
var response = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.GetAsync("http://localhost:12345", cts.Token));
var exception = await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await tcs.Task);
}
[Fact]
public async Task AsyncLocalValueOnClientIsNotPreserved()
{
var asyncLocal = new AsyncLocal<object>();
var value = new object();
asyncLocal.Value = value;
object capturedValue = null;
var builder = new WebHostBuilder()
.Configure(app =>
{
app.Run((context) =>
{
capturedValue = asyncLocal.Value;
return context.Response.WriteAsync("Done");
});
});
var server = new TestServer(builder);
var client = server.CreateClient();
var resp = await client.GetAsync("/");
Assert.NotSame(value, capturedValue);
}
[Fact]
public async Task AsyncLocalValueOnClientIsPreservedIfPreserveExecutionContextIsTrue()
{
var asyncLocal = new AsyncLocal<object>();
var value = new object();
asyncLocal.Value = value;
object capturedValue = null;
var builder = new WebHostBuilder()
.Configure(app =>
{
app.Run((context) =>
{
capturedValue = asyncLocal.Value;
return context.Response.WriteAsync("Done");
});
});
var server = new TestServer(builder)
{
PreserveExecutionContext = true
};
var client = server.CreateClient();
var resp = await client.GetAsync("/");
Assert.Same(value, capturedValue);
}
[Fact]
public async Task SendAsync_Default_Protocol11()
{
// Arrange
string protocol = null;
var expected = "GET Response";
RequestDelegate appDelegate = async ctx =>
{
protocol = ctx.Request.Protocol;
await ctx.Response.WriteAsync(expected);
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345");
// Act
var message = await client.SendAsync(request);
var actual = await message.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, actual);
Assert.Equal(new Version(1, 1), message.Version);
Assert.Equal(protocol, HttpProtocol.Http11);
}
[Fact]
public async Task SendAsync_ExplicitlySet_Protocol20()
{
// Arrange
string protocol = null;
var expected = "GET Response";
RequestDelegate appDelegate = async ctx =>
{
protocol = ctx.Request.Protocol;
await ctx.Response.WriteAsync(expected);
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345");
request.Version = new Version(2, 0);
// Act
var message = await client.SendAsync(request);
var actual = await message.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, actual);
Assert.Equal(new Version(2, 0), message.Version);
Assert.Equal(protocol, HttpProtocol.Http2);
}
[Fact]
public async Task SendAsync_ExplicitlySet_Protocol30()
{
// Arrange
string protocol = null;
var expected = "GET Response";
RequestDelegate appDelegate = async ctx =>
{
protocol = ctx.Request.Protocol;
await ctx.Response.WriteAsync(expected);
};
var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate));
var server = new TestServer(builder);
var client = server.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345");
request.Version = new Version(3, 0);
// Act
var message = await client.SendAsync(request);
var actual = await message.Content.ReadAsStringAsync();
// Assert
Assert.Equal(expected, actual);
Assert.Equal(new Version(3, 0), message.Version);
Assert.Equal(protocol, HttpProtocol.Http3);
}
[Fact]
public async Task VerifyWebSocketAndUpgradeFeaturesForNonWebSocket()
{
using (var testServer = new TestServer(new WebHostBuilder()
.Configure(app =>
{
app.UseWebSockets();
app.Run(async c =>
{
var upgradeFeature = c.Features.Get<IHttpUpgradeFeature>();
// Feature needs to exist for SignalR to verify that the server supports WebSockets
Assert.NotNull(upgradeFeature);
Assert.False(upgradeFeature.IsUpgradableRequest);
await Assert.ThrowsAsync<NotSupportedException>(() => upgradeFeature.UpgradeAsync());
var webSocketFeature = c.Features.Get<IHttpWebSocketFeature>();
Assert.NotNull(webSocketFeature);
Assert.False(webSocketFeature.IsWebSocketRequest);
await c.Response.WriteAsync("test");
});
})))
{
var client = testServer.CreateClient();
var actual = await client.GetStringAsync("http://localhost:12345/");
Assert.Equal("test", actual);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")]
public partial class HttpClientHandler_SslProtocols_Test : HttpClientTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(~SslProtocols.None)]
#pragma warning disable 0618 // obsolete warning
[InlineData(SslProtocols.Ssl2)]
[InlineData(SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
[InlineData(SslProtocols.Tls11, true)]
[InlineData(SslProtocols.Tls12, false)]
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (UseManagedHandler)
{
// TODO #26186: The managed handler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
public static readonly object[][] SupportedSSLVersionServers =
{
new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer},
new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer},
new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer},
};
// This test is logically the same as the above test, albeit using remote servers
// instead of local ones. We're keeping it for now (as outerloop) because it helps
// to validate against another SSL implementation that what we mean by a particular
// TLS version matches that other implementation.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
if (UseManagedHandler)
{
// TODO #26186: The managed handler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
{
if (PlatformDetection.IsRedHatFamily7)
{
// Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0
// Hence, set the specific protocol on HttpClient that is required by test
handler.SslProtocols = sslProtocols;
}
using (var client = new HttpClient(handler))
{
(await RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)).Dispose();
}
}
}
public Func<Exception, bool> remoteServerExceptionWrapper = (exception) =>
{
Type exceptionType = exception.GetType();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// On linux, taskcanceledexception is thrown.
return exceptionType.Equals(typeof(TaskCanceledException));
}
else
{
// The internal exceptions return operation timed out.
return exceptionType.Equals(typeof(HttpRequestException)) && exception.InnerException.Message.Contains("timed out");
}
};
public static readonly object[][] NotSupportedSSLVersionServers =
{
new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer},
new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer},
};
// It would be easy to remove the dependency on these remote servers if we didn't
// explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
if (!SSLv3DisabledByDefault)
{
return;
}
if (UseManagedHandler && !PlatformDetection.IsWindows10Version1607OrGreater)
{
// On Windows, https://github.com/dotnet/corefx/issues/21925#issuecomment-313408314
// On Linux, an older version of OpenSSL may permit negotiating SSLv3.
return;
}
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
if (!BackendSupportsSslConfiguration)
return;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol);
await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
return null;
}, options));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
if (!BackendSupportsSslConfiguration)
return;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = allowedProtocol;
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(8538, TestPlatforms.Windows)]
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
options.SslProtocols = SslProtocols.Tls;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 })
{
options.SslProtocols = prot;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
}, options);
}
}
else
{
await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/"));
}
}
}
private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7;
// TLS 1.2 may not be enabled on Win7
// https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using System.Data.Common;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
namespace System.Data.SqlTypes
{
[Serializable, XmlSchemaProvider("GetXsdType")]
public sealed class SqlChars : INullable, IXmlSerializable, ISerializable
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
// SqlChars has five possible states
// 1) SqlChars is Null
// - m_stream must be null, m_lCuLen must be x_lNull
// 2) SqlChars contains a valid buffer,
// - m_rgchBuf must not be null, and m_stream must be null
// 3) SqlChars contains a valid pointer
// - m_rgchBuf could be null or not,
// if not null, content is garbage, should never look into it.
// - m_stream must be null.
// 4) SqlChars contains a SqlStreamChars
// - m_stream must not be null
// - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it.
// - m_lCurLen must be x_lNull.
// 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed)
//
internal char[] _rgchBuf; // Data buffer
private long _lCurLen; // Current data length
internal SqlStreamChars _stream;
private SqlBytesCharsState _state;
private char[] _rgchWorkBuf; // A 1-char work buffer.
// The max data length that we support at this time.
private const long x_lMaxLen = System.Int32.MaxValue;
private const long x_lNull = -1L;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
// Public default constructor used for XML serialization
public SqlChars()
{
SetNull();
}
// Create a SqlChars with an in-memory buffer
public SqlChars(char[] buffer)
{
_rgchBuf = buffer;
_stream = null;
if (_rgchBuf == null)
{
_state = SqlBytesCharsState.Null;
_lCurLen = x_lNull;
}
else
{
_state = SqlBytesCharsState.Buffer;
_lCurLen = _rgchBuf.Length;
}
_rgchWorkBuf = null;
AssertValid();
}
// Create a SqlChars from a SqlString
public SqlChars(SqlString value) : this(value.IsNull ? null : value.Value.ToCharArray())
{
}
// Create a SqlChars from a SqlStreamChars
internal SqlChars(SqlStreamChars s)
{
_rgchBuf = null;
_lCurLen = x_lNull;
_stream = s;
_state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
_rgchWorkBuf = null;
AssertValid();
}
// Constructor required for serialization. Deserializes as a Buffer. If the bits have been tampered with
// then this will throw a SerializationException or a InvalidCastException.
private SqlChars(SerializationInfo info, StreamingContext context)
{
_stream = null;
_rgchWorkBuf = null;
if (info.GetBoolean("IsNull"))
{
_state = SqlBytesCharsState.Null;
_rgchBuf = null;
}
else
{
_state = SqlBytesCharsState.Buffer;
_rgchBuf = (char[])info.GetValue("data", typeof(char[]));
_lCurLen = _rgchBuf.Length;
}
AssertValid();
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// INullable
public bool IsNull
{
get
{
return _state == SqlBytesCharsState.Null;
}
}
// Property: the in-memory buffer of SqlChars
// Return Buffer even if SqlChars is Null.
public char[] Buffer
{
get
{
if (FStream())
{
CopyStreamToBuffer();
}
return _rgchBuf;
}
}
// Property: the actual length of the data
public long Length
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return _stream.Length;
default:
return _lCurLen;
}
}
}
// Property: the max length of the data
// Return MaxLength even if SqlChars is Null.
// When the buffer is also null, return -1.
// If containing a Stream, return -1.
public long MaxLength
{
get
{
switch (_state)
{
case SqlBytesCharsState.Stream:
return -1L;
default:
return (_rgchBuf == null) ? -1L : _rgchBuf.Length;
}
}
}
// Property: get a copy of the data in a new char[] array.
public char[] Value
{
get
{
char[] buffer;
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
if (_stream.Length > x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
buffer = new char[_stream.Length];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(buffer, 0, checked((int)_stream.Length));
break;
default:
buffer = new char[_lCurLen];
Array.Copy(_rgchBuf, 0, buffer, 0, (int)_lCurLen);
break;
}
return buffer;
}
}
// class indexer
public char this[long offset]
{
get
{
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (_rgchWorkBuf == null)
_rgchWorkBuf = new char[1];
Read(offset, _rgchWorkBuf, 0, 1);
return _rgchWorkBuf[0];
}
set
{
if (_rgchWorkBuf == null)
_rgchWorkBuf = new char[1];
_rgchWorkBuf[0] = value;
Write(offset, _rgchWorkBuf, 0, 1);
}
}
internal SqlStreamChars Stream
{
get
{
return FStream() ? _stream : new StreamOnSqlChars(this);
}
set
{
_lCurLen = x_lNull;
_stream = value;
_state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
AssertValid();
}
}
public StorageState Storage
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return StorageState.Stream;
case SqlBytesCharsState.Buffer:
return StorageState.Buffer;
default:
return StorageState.UnmanagedBuffer;
}
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public void SetNull()
{
_lCurLen = x_lNull;
_stream = null;
_state = SqlBytesCharsState.Null;
AssertValid();
}
// Set the current length of the data
// If the SqlChars is Null, setLength will make it non-Null.
public void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
if (FStream())
{
_stream.SetLength(value);
}
else
{
// If there is a buffer, even the value of SqlChars is Null,
// still allow setting length to zero, which will make it not Null.
// If the buffer is null, raise exception
//
if (null == _rgchBuf)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (value > _rgchBuf.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else if (IsNull)
// At this point we know that value is small enough
// Go back in buffer mode
_state = SqlBytesCharsState.Buffer;
_lCurLen = value;
}
AssertValid();
}
// Read data of specified length from specified offset into a buffer
public long Read(long offset, char[] buffer, int offsetInBuffer, int count)
{
if (IsNull)
throw new SqlNullValueException();
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offsetInBuffer > buffer.Length || offsetInBuffer < 0)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
// Adjust count based on data length
if (count > Length - offset)
count = (int)(Length - offset);
if (count != 0)
{
switch (_state)
{
case SqlBytesCharsState.Stream:
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Read(buffer, offsetInBuffer, count);
break;
default:
Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count);
break;
}
}
return count;
}
// Write data of specified length into the SqlChars from specified offset
public void Write(long offset, char[] buffer, int offsetInBuffer, int count)
{
if (FStream())
{
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Write(buffer, offsetInBuffer, count);
}
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (_rgchBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset > _rgchBuf.Length)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
if (count > _rgchBuf.Length - offset)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (IsNull)
{
// If NULL and there is buffer inside, we only allow writing from
// offset zero.
//
if (offset != 0)
throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage);
// treat as if our current length is zero.
// Note this has to be done after all inputs are validated, so that
// we won't throw exception after this point.
//
_lCurLen = 0;
_state = SqlBytesCharsState.Buffer;
}
else if (offset > _lCurLen)
{
// Don't allow writing from an offset that this larger than current length.
// It would leave uninitialized data in the buffer.
//
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
}
if (count != 0)
{
Array.Copy(buffer, offsetInBuffer, _rgchBuf, offset, count);
// If the last position that has been written is after
// the current data length, reset the length
if (_lCurLen < offset + count)
_lCurLen = offset + count;
}
}
AssertValid();
}
public SqlString ToSqlString()
{
return IsNull ? SqlString.Null : new string(Value);
}
// --------------------------------------------------------------
// Conversion operators
// --------------------------------------------------------------
// Alternative method: ToSqlString()
public static explicit operator SqlString(SqlChars value)
{
return value.ToSqlString();
}
// Alternative method: constructor SqlChars(SqlString)
public static explicit operator SqlChars(SqlString value)
{
return new SqlChars(value);
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
[Conditional("DEBUG")]
private void AssertValid()
{
Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream);
if (IsNull)
{
}
else
{
Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream());
Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length));
Debug.Assert(!FStream() || (_lCurLen == x_lNull));
}
Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1);
}
// whether the SqlChars contains a Stream
internal bool FStream()
{
return _state == SqlBytesCharsState.Stream;
}
// Copy the data from the Stream to the array buffer.
// If the SqlChars doesn't hold a buffer or the buffer
// is not big enough, allocate new char array.
private void CopyStreamToBuffer()
{
Debug.Assert(FStream());
long lStreamLen = _stream.Length;
if (lStreamLen >= x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (_rgchBuf == null || _rgchBuf.Length < lStreamLen)
_rgchBuf = new char[lStreamLen];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(_rgchBuf, 0, (int)lStreamLen);
_stream = null;
_lCurLen = lStreamLen;
_state = SqlBytesCharsState.Buffer;
AssertValid();
}
private void SetBuffer(char[] buffer)
{
_rgchBuf = buffer;
_lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length;
_stream = null;
_state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer;
AssertValid();
}
// --------------------------------------------------------------
// XML Serialization
// --------------------------------------------------------------
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(XmlReader r)
{
char[] value = null;
string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
r.ReadElementString();
SetNull();
}
else
{
value = r.ReadElementString().ToCharArray();
SetBuffer(value);
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
char[] value = Buffer;
writer.WriteString(new string(value, 0, (int)(Length)));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("string", XmlSchema.Namespace);
}
// --------------------------------------------------------------
// Serialization using ISerializable
// --------------------------------------------------------------
// State information is not saved. The current state is converted to Buffer and only the underlying
// array is serialized, except for Null, in which case this state is kept.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
switch (_state)
{
case SqlBytesCharsState.Null:
info.AddValue("IsNull", true);
break;
case SqlBytesCharsState.Buffer:
info.AddValue("IsNull", false);
info.AddValue("data", _rgchBuf);
break;
case SqlBytesCharsState.Stream:
CopyStreamToBuffer();
goto case SqlBytesCharsState.Buffer;
default:
Debug.Assert(false);
goto case SqlBytesCharsState.Null;
}
}
// --------------------------------------------------------------
// Static fields, properties
// --------------------------------------------------------------
// Get a Null instance.
// Since SqlChars is mutable, have to be property and create a new one each time.
public static SqlChars Null
{
get
{
return new SqlChars((char[])null);
}
}
} // class SqlChars
// StreamOnSqlChars is a stream build on top of SqlChars, and
// provides the Stream interface. The purpose is to help users
// to read/write SqlChars object.
internal sealed class StreamOnSqlChars : SqlStreamChars
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
private SqlChars _sqlchars; // the SqlChars object
private long _lPosition;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
internal StreamOnSqlChars(SqlChars s)
{
_sqlchars = s;
_lPosition = 0;
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
public override bool IsNull
{
get
{
return _sqlchars == null || _sqlchars.IsNull;
}
}
// Always can read/write/seek, unless sb is null,
// which means the stream has been closed.
public override bool CanRead
{
get
{
return _sqlchars != null && !_sqlchars.IsNull;
}
}
public override bool CanSeek
{
get
{
return _sqlchars != null;
}
}
public override bool CanWrite
{
get
{
return _sqlchars != null && (!_sqlchars.IsNull || _sqlchars._rgchBuf != null);
}
}
public override long Length
{
get
{
CheckIfStreamClosed("get_Length");
return _sqlchars.Length;
}
}
public override long Position
{
get
{
CheckIfStreamClosed("get_Position");
return _lPosition;
}
set
{
CheckIfStreamClosed("set_Position");
if (value < 0 || value > _sqlchars.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else
_lPosition = value;
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public override long Seek(long offset, SeekOrigin origin)
{
CheckIfStreamClosed();
long lPosition = 0;
switch (origin)
{
case SeekOrigin.Begin:
if (offset < 0 || offset > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = offset;
break;
case SeekOrigin.Current:
lPosition = _lPosition + offset;
if (lPosition < 0 || lPosition > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = lPosition;
break;
case SeekOrigin.End:
lPosition = _sqlchars.Length + offset;
if (lPosition < 0 || lPosition > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = lPosition;
break;
default:
throw ADP.ArgumentOutOfRange(nameof(offset));
}
return _lPosition;
}
// The Read/Write/Readchar/Writechar simply delegates to SqlChars
public override int Read(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count);
_lPosition += icharsRead;
return icharsRead;
}
public override void Write(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
_sqlchars.Write(_lPosition, buffer, offset, count);
_lPosition += count;
}
public override int ReadChar()
{
CheckIfStreamClosed();
// If at the end of stream, return -1, rather than call SqlChars.Readchar,
// which will throw exception. This is the behavior for Stream.
//
if (_lPosition >= _sqlchars.Length)
return -1;
int ret = _sqlchars[_lPosition];
_lPosition++;
return ret;
}
public override void WriteChar(char value)
{
CheckIfStreamClosed();
_sqlchars[_lPosition] = value;
_lPosition++;
}
public override void SetLength(long value)
{
CheckIfStreamClosed();
_sqlchars.SetLength(value);
if (_lPosition > value)
_lPosition = value;
}
// Flush is a no-op if underlying SqlChars is not a stream on SqlChars
public override void Flush()
{
if (_sqlchars.FStream())
_sqlchars._stream.Flush();
}
protected override void Dispose(bool disposing)
{
// When m_sqlchars is null, it means the stream has been closed, and
// any opearation in the future should fail.
// This is the only case that m_sqlchars is null.
_sqlchars = null;
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
private bool FClosed()
{
return _sqlchars == null;
}
private void CheckIfStreamClosed([CallerMemberName] string methodname = "")
{
if (FClosed())
throw ADP.StreamClosed(methodname);
}
} // class StreamOnSqlChars
} // namespace System.Data.SqlTypes
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.ScrollContentPresenter.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
sealed public partial class ScrollContentPresenter : ContentPresenter, System.Windows.Controls.Primitives.IScrollInfo
{
#region Methods and constructors
protected override System.Windows.Size ArrangeOverride(System.Windows.Size arrangeSize)
{
return default(System.Windows.Size);
}
protected override System.Windows.Media.Geometry GetLayoutClip(System.Windows.Size layoutSlotSize)
{
return default(System.Windows.Media.Geometry);
}
protected override System.Windows.Media.Visual GetVisualChild(int index)
{
return default(System.Windows.Media.Visual);
}
public void LineDown()
{
}
public void LineLeft()
{
}
public void LineRight()
{
}
public void LineUp()
{
}
public System.Windows.Rect MakeVisible(System.Windows.Media.Visual visual, System.Windows.Rect rectangle)
{
return default(System.Windows.Rect);
}
protected override System.Windows.Size MeasureOverride(System.Windows.Size constraint)
{
return default(System.Windows.Size);
}
public void MouseWheelDown()
{
}
public void MouseWheelLeft()
{
}
public void MouseWheelRight()
{
}
public void MouseWheelUp()
{
}
public override void OnApplyTemplate()
{
}
public void PageDown()
{
}
public void PageLeft()
{
}
public void PageRight()
{
}
public void PageUp()
{
}
public ScrollContentPresenter()
{
}
public void SetHorizontalOffset(double offset)
{
}
public void SetVerticalOffset(double offset)
{
}
#endregion
#region Properties and indexers
public System.Windows.Documents.AdornerLayer AdornerLayer
{
get
{
return default(System.Windows.Documents.AdornerLayer);
}
}
public bool CanContentScroll
{
get
{
return default(bool);
}
set
{
}
}
public bool CanHorizontallyScroll
{
get
{
return default(bool);
}
set
{
}
}
public bool CanVerticallyScroll
{
get
{
return default(bool);
}
set
{
}
}
public double ExtentHeight
{
get
{
return default(double);
}
}
public double ExtentWidth
{
get
{
return default(double);
}
}
public double HorizontalOffset
{
get
{
return default(double);
}
}
public ScrollViewer ScrollOwner
{
get
{
return default(ScrollViewer);
}
set
{
}
}
public double VerticalOffset
{
get
{
return default(double);
}
}
public double ViewportHeight
{
get
{
return default(double);
}
}
public double ViewportWidth
{
get
{
return default(double);
}
}
protected override int VisualChildrenCount
{
get
{
return default(int);
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty CanContentScrollProperty;
#endregion
}
}
| |
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace LexLib
{
public class Gen
{
/*
* Member Variables
*/
private StreamReader instream; /* Lex specification file. */
private StreamWriter outstream; /* Lexical analyzer source file. */
private Input ibuf; /* Input buffer class. */
private Dictionary<char, int> tokens; /* Hashtable that maps characters to their
corresponding lexical code for
the internal lexical analyzer. */
private Spec spec; /* Spec class holds information
about the generated lexer. */
private bool init_flag; /* Flag set to true only upon
successful initialization. */
private MakeNfa makeNfa; /* NFA machine generator module. */
private Nfa2Dfa nfa2dfa; /* NFA to DFA machine (transition table)
conversion module. */
private Minimize minimize; /* Transition table compressor. */
//private SimplifyNfa simplifyNfa; /* NFA simplifier using char classes */
private Emit emit; // Output module that emits source code into the generated lexer file. */
/*
* Constants
*/
private const bool ERROR = false;
private const bool NOT_ERROR = true;
private const int BUFFER_SIZE = 1024;
/*
* Constants: Token Types
*/
public const int EOS = 1;
public const int ANY = 2;
public const int AT_BOL = 3;
public const int AT_EOL = 4;
public const int CCL_END = 5;
public const int CCL_START = 6;
public const int CLOSE_CURLY = 7;
public const int CLOSE_PAREN = 8;
public const int CLOSURE = 9;
public const int DASH = 10;
public const int END_OF_INPUT = 11;
public const int L = 12;
public const int OPEN_CURLY = 13;
public const int OPEN_PAREN = 14;
public const int OPTIONAL = 15;
public const int OR = 16;
public const int PLUS_CLOSE = 17;
public Gen(StreamReader sr, StreamWriter sw)
{
this.instream = sr;
this.outstream = sw;
init();
}
void init()
{
/* Create input buffer class. */
ibuf = new Input(instream);
/* Initialize character hash table. */
tokens = new Dictionary<char, int>();
tokens['$'] = AT_EOL;
tokens['('] = OPEN_PAREN;
tokens[')'] = CLOSE_PAREN;
tokens['*'] = CLOSURE;
tokens['+'] = PLUS_CLOSE;
tokens['-'] = DASH;
tokens['.'] = ANY;
tokens['?'] = OPTIONAL;
tokens['['] = CCL_START;
tokens[']'] = CCL_END;
tokens['^'] = AT_BOL;
tokens['{'] = OPEN_CURLY;
tokens['|'] = OR;
tokens['}'] = CLOSE_CURLY;
/* Initialize spec structure. */
// spec = new Spec(this);
spec = new Spec();
/* Nfa to dfa converter. */
nfa2dfa = new Nfa2Dfa();
minimize = new Minimize();
makeNfa = new MakeNfa();
// simplifyNfa = new SimplifyNfa();
emit = new Emit();
/* Successful initialization flag. */
init_flag = true;
}
/*
* Function: generate
* Description:
*/
public void generate()
{
if (!init_flag)
{
Error.parse_error(Error.E_INIT, 0);
}
#if DEBUG
Utility.assert(this != null);
Utility.assert(outstream != null);
Utility.assert(ibuf != null);
Utility.assert(tokens != null);
Utility.assert(spec != null);
Utility.assert(init_flag);
#endif
if (spec.verbose)
{
Console.WriteLine("Processing first section -- user code.");
}
userCode();
if (ibuf.eof_reached)
{
Error.parse_error(Error.E_EOF, ibuf.line_number);
}
if (spec.verbose)
{
Console.WriteLine("Processing second section -- Lex declarations.");
}
userDeclare();
if (ibuf.eof_reached)
{
Error.parse_error(Error.E_EOF, ibuf.line_number);
}
if (spec.verbose)
{
Console.WriteLine("Processing third section -- lexical rules.");
}
userRules();
#if DO_DEBUG
Console.WriteLine("Printing DO_DEBUG header");
print_header();
#endif
if (spec.verbose)
{
Console.WriteLine("Outputting lexical analyzer code.");
}
emit.Write(spec, outstream);
#if OLD_DUMP_DEBUG
details();
#endif
// outstream.Close();
}
/*
* Function: userCode
* Description: Process first section of specification,
* echoing it into output file.
*/
private void userCode()
{
StringBuilder sb = new StringBuilder();
if (!init_flag)
{
Error.parse_error(Error.E_INIT, 0);
}
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
if (ibuf.eof_reached)
{
Error.parse_error(Error.E_EOF, 0);
}
while (true)
{
if (ibuf.GetLine())
{
/* Eof reached. */
Error.parse_error(Error.E_EOF, 0);
}
if (ibuf.line_read >= 2
&& ibuf.line[0] == '%'
&& ibuf.line[1] == '%')
{
spec.usercode = sb.ToString();
/* Discard remainder of line. */
ibuf.line_index = ibuf.line_read;
return;
}
sb.Append(new String(ibuf.line, 0, ibuf.line_read));
}
}
/*
* Function: getName
*/
private String getName()
{
/* Skip white space. */
while (ibuf.line_index < ibuf.line_read
&& Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
}
/* No name? */
if (ibuf.line_index >= ibuf.line_read)
{
Error.parse_error(Error.E_DIRECT, 0);
}
/* Determine length. */
int elem = ibuf.line_index;
while (elem < ibuf.line_read && !Utility.IsNewline(ibuf.line[elem]))
elem++;
/* Allocate non-terminated buffer of exact length. */
StringBuilder sb = new StringBuilder(elem - ibuf.line_index);
/* Copy. */
elem = 0;
while (ibuf.line_index < ibuf.line_read
&& !Utility.IsNewline(ibuf.line[ibuf.line_index]))
{
sb.Append(ibuf.line[ibuf.line_index]);
ibuf.line_index++;
}
return sb.ToString();
}
private const int CLASS_CODE = 0;
private const int INIT_CODE = 1;
private const int EOF_CODE = 2;
private const int EOF_VALUE_CODE = 3;
/*
* Function: packCode
* Description:
*/
//private String packCode(String start_dir, String end_dir,
// String prev_code, int prev_read, int specified)
private String packCode(String st_dir, String end_dir, String prev, int code)
{
#if DEBUG
Utility.assert(INIT_CODE == code
|| CLASS_CODE == code
|| EOF_CODE == code
|| EOF_VALUE_CODE == code
);
#endif
if (Utility.Compare(ibuf.line, st_dir) != 0)
Error.parse_error(Error.E_INTERNAL, 0);
/*
* build up the text to be stored in sb
*/
StringBuilder sb;
if (prev != null)
sb = new StringBuilder(prev, prev.Length * 2); // use any previous text
else
sb = new StringBuilder(Properties.Settings.Default.MaxStr);
ibuf.line_index = st_dir.Length;
while (true)
{
while (ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
Error.parse_error(Error.E_EOF, ibuf.line_number);
if (Utility.Compare(ibuf.line, end_dir) == 0)
{
ibuf.line_index = end_dir.Length - 1;
return sb.ToString();
}
}
while (ibuf.line_index < ibuf.line_read)
{
sb.Append(ibuf.line[ibuf.line_index]);
ibuf.line_index++;
}
}
}
/*
* Member Variables: Lex directives.
*/
private String state_dir = "%state";
private String char_dir = "%char";
private String line_dir = "%line";
private String class_dir = "%class";
private String implements_dir = "%implements";
private String function_dir = "%function";
private String type_dir = "%type";
private String integer_dir = "%integer";
private String intwrap_dir = "%intwrap";
private String full_dir = "%full";
private String unicode_dir = "%unicode";
private String ignorecase_dir = "%ignorecase";
private String init_code_dir = "%init{";
private String init_code_end_dir = "%init}";
private String eof_code_dir = "%eof{";
private String eof_code_end_dir = "%eof}";
private String eof_value_code_dir = "%eofval{";
private String eof_value_code_end_dir = "%eofval}";
private String class_code_dir = "%{";
private String class_code_end_dir = "%}";
private String yyeof_dir = "%yyeof";
private String public_dir = "%public";
private String namespace_dir = "%namespace";
/*
* Function: userDeclare
* Description:
*/
private void userDeclare()
{
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
if (ibuf.eof_reached)
{
/* End-of-file. */
Error.parse_error(Error.E_EOF, ibuf.line_number);
}
while (!ibuf.GetLine())
{
/* Look for double percent. */
if (ibuf.line_read >= 2
&& '%' == ibuf.line[0]
&& '%' == ibuf.line[1])
{
/* Mess around with line. */
for (int elem = 0; elem < ibuf.line.Length - 2; ++elem)
ibuf.line[elem] = ibuf.line[elem + 2];
ibuf.line_read = ibuf.line_read - 2;
ibuf.pushback_line = true;
/* Check for and discard empty line. */
if (ibuf.line_read == 0
|| '\r' == ibuf.line[0]
|| '\n' == ibuf.line[0])
{
ibuf.pushback_line = false;
}
return;
}
if (ibuf.line_read == 0)
continue;
if (ibuf.line[0] == '%')
{
/* Special lex declarations. */
if (1 >= ibuf.line_read)
{
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
continue;
}
switch (ibuf.line[1])
{
case '{':
if (Utility.Compare(ibuf.line, class_code_dir) == 0)
{
spec.class_code = packCode(class_code_dir,
class_code_end_dir,
spec.class_code,
CLASS_CODE);
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'c':
if (Utility.Compare(ibuf.line, char_dir) == 0)
{
/* Set line counting to ON. */
ibuf.line_index = char_dir.Length;
spec.count_chars = true;
break;
}
if (Utility.Compare(ibuf.line, class_dir) == 0)
{
ibuf.line_index = class_dir.Length;
spec.class_name = getName();
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'e':
if (Utility.Compare(ibuf.line, eof_code_dir) == 0)
{
spec.eof_code = packCode(eof_code_dir,
eof_code_end_dir,
spec.eof_code,
EOF_CODE);
break;
}
if (Utility.Compare(ibuf.line, eof_value_code_dir) == 0)
{
spec.eof_value_code = packCode(eof_value_code_dir,
eof_value_code_end_dir,
spec.eof_value_code,
EOF_VALUE_CODE);
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'f':
if (Utility.Compare(ibuf.line, function_dir) == 0)
{
/* Set line counting to ON. */
ibuf.line_index = function_dir.Length;
spec.function_name = getName();
break;
}
if (Utility.Compare(ibuf.line, full_dir) == 0)
{
ibuf.line_index = full_dir.Length;
spec.dtrans_ncols = Utility.MAX_EIGHT_BIT + 1;
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'i':
if (Utility.Compare(ibuf.line, integer_dir) == 0)
{
/* Set line counting to ON. */
ibuf.line_index = integer_dir.Length;
spec.integer_type = true;
break;
}
if (Utility.Compare(ibuf.line, intwrap_dir) == 0)
{
/* Set line counting to ON. */
ibuf.line_index = integer_dir.Length;
spec.intwrap_type = true;
break;
}
if (Utility.Compare(ibuf.line, init_code_dir) == 0)
{
spec.init_code = packCode(init_code_dir,
init_code_end_dir,
spec.init_code,
INIT_CODE);
break;
}
if (Utility.Compare(ibuf.line, implements_dir) == 0)
{
ibuf.line_index = implements_dir.Length;
spec.implements_name = getName();
break;
}
if (Utility.Compare(ibuf.line, ignorecase_dir) == 0)
{
/* Set ignorecase to ON. */
ibuf.line_index = ignorecase_dir.Length;
spec.ignorecase = true;
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'l':
if (Utility.Compare(ibuf.line, line_dir) == 0)
{
/* Set line counting to ON. */
ibuf.line_index = line_dir.Length;
spec.count_lines = true;
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'p':
if (Utility.Compare(ibuf.line, public_dir) == 0)
{
/* Set public flag. */
ibuf.line_index = public_dir.Length;
spec.lex_public = true;
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 's':
if (Utility.Compare(ibuf.line, state_dir) == 0)
{
/* Recognize state list. */
ibuf.line_index = state_dir.Length;
saveStates();
break;
}
/* Undefined directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 't':
if (Utility.Compare(ibuf.line, type_dir) == 0)
{
ibuf.line_index = type_dir.Length;
spec.type_name = getName();
break;
}
/* Undefined directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'u':
if (Utility.Compare(ibuf.line, unicode_dir) == 0)
{
ibuf.line_index = unicode_dir.Length;
/* UNDONE: What to do here? */
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'y':
if (Utility.Compare(ibuf.line, yyeof_dir) == 0)
{
ibuf.line_index = yyeof_dir.Length;
spec.yyeof = true;
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
case 'n':
if (Utility.Compare(ibuf.line, namespace_dir) == 0)
{
ibuf.line_index = namespace_dir.Length;
spec.namespace_name = getName();
break;
}
/* Bad directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
default:
/* Undefined directive. */
Error.parse_error(Error.E_DIRECT, ibuf.line_number);
break;
}
}
else
{
/* Regular expression macro. */
ibuf.line_index = 0;
saveMacro();
}
#if OLD_DEBUG
Console.WriteLine("Line number " + ibuf.line_number + ":");
Console.Write(new String(ibuf.line, 0,ibuf.line_read));
#endif
}
}
/*
* Function: userRules
* Description: Processes third section of Lex
* specification and creates minimized transition table.
*/
private void userRules()
{
if (false == init_flag)
{
Error.parse_error(Error.E_INIT, 0);
}
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
/* UNDONE: Need to handle states preceding rules. */
if (spec.verbose)
{
Console.WriteLine("Creating NFA machine representation.");
}
MakeNfa.Allocate_BOL_EOF(spec);
MakeNfa.CreateMachine(this, spec, ibuf);
SimplifyNfa.simplify(spec);
#if DUMMY
print_nfa();
#endif
#if DEBUG
Utility.assert(END_OF_INPUT == spec.current_token);
#endif
if (spec.verbose)
{
Console.WriteLine("Creating DFA transition table.");
}
Nfa2Dfa.MakeDFA(spec);
#if FOODEBUG
Console.WriteLine("Printing FOODEBUG header");
print_header();
#endif
if (spec.verbose)
{
Console.WriteLine("Minimizing DFA transition table.");
}
minimize.min_dfa(spec);
}
/*
* Function: printccl
* Description: Debuggng routine that outputs readable form
* of character class.
*/
private void printccl(CharSet cset)
{
int i;
Console.Write(" [");
for (i = 0; i < spec.dtrans_ncols; ++i)
{
if (cset.contains(i))
{
Console.Write(interp_int(i));
}
}
Console.Write(']');
}
/*
* Function: plab
* Description:
*/
private String plab(Nfa state)
{
if (null == state)
{
return "--";
}
int index = spec.nfa_states.IndexOf(state, 0, spec.nfa_states.Count);
return index.ToString();
}
/*
* Function: interp_int
* Description:
*/
private String interp_int(int i)
{
switch (i)
{
case (int)'\b':
return "\\b";
case (int)'\t':
return "\\t";
case (int)'\n':
return "\\n";
case (int)'\f':
return "\\f";
case (int)'\r':
return "\\r";
case (int)' ':
return "\\ ";
default:
{
return Char.ToString((char)i);
}
}
}
/*
* Function: print_nfa
* Description:
*/
public void print_nfa()
{
int elem;
Nfa nfa;
int j;
int vsize;
Console.WriteLine("--------------------- NFA -----------------------");
for (elem = 0; elem < spec.nfa_states.Count; elem++)
{
nfa = (Nfa)spec.nfa_states[elem];
Console.Write("Nfa state " + plab(nfa) + ": ");
if (null == nfa.GetNext())
{
Console.Write("(TERMINAL)");
}
else
{
Console.Write("--> " + plab(nfa.GetNext()));
Console.Write("--> " + plab(nfa.GetSib()));
switch (nfa.GetEdge())
{
case Nfa.CCL:
printccl(nfa.GetCharSet());
break;
case Nfa.EPSILON:
Console.Write(" EPSILON ");
break;
default:
Console.Write(" " + interp_int(nfa.GetEdge()));
break;
}
}
if (0 == elem)
{
Console.Write(" (START STATE)");
}
if (null != nfa.GetAccept())
{
Console.Write(" accepting "
+ ((0 != (nfa.GetAnchor() & Spec.START)) ? "^" : "")
+ "<"
+ nfa.GetAccept().action
+ ">"
+ ((0 != (nfa.GetAnchor() & Spec.END)) ? "$" : ""));
}
Console.WriteLine("");
}
foreach (string state in spec.states.Keys)
{
int index = (int)spec.states[state];
#if DEBUG
Utility.assert(null != state);
#endif
Console.WriteLine("State \"" + state
+ "\" has identifying index " + index + ".");
Console.Write("\tStart states of matching rules: ");
vsize = spec.state_rules[index].Count;
for (j = 0; j < vsize; ++j)
{
List<Nfa> a = spec.state_rules[index];
#if DEBUG
Utility.assert(null != a);
#endif
nfa = a[j];
Console.Write(spec.nfa_states.IndexOf(nfa) + " ");
}
Console.WriteLine("");
}
Console.WriteLine("-------------------- NFA ----------------------");
}
/*
* Function: getStates
* Description: Parses the state area of a rule,
* from the beginning of a line.
* < state1, state2 ... > regular_expression { action }
* Returns null on only EOF. Returns all_states,
* initialied properly to correspond to all states,
* if no states are found.
* Special Notes: This function treats commas as optional
* and permits states to be spread over multiple lines.
*/
private BitSet all_states = null;
public BitSet GetStates()
{
int start_state;
int count_state;
BitSet states;
String name;
int index;
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
states = null;
/* Skip white space. */
while (Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
while (ibuf.line_index >= ibuf.line_read)
{
/* Must just be an empty line. */
if (ibuf.GetLine())
{
/* EOF found. */
return null;
}
}
}
/* Look for states. */
if ('<' == ibuf.line[ibuf.line_index])
{
ibuf.line_index++;
states = new BitSet(); // create new BitSet
/* Parse states. */
while (true)
{
/* We may have reached the end of the line. */
while (ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
{
/* EOF found. */
Error.parse_error(Error.E_EOF, ibuf.line_number);
return states;
}
}
while (true)
{
/* Skip white space. */
while (Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
while (ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
{
/* EOF found. */
Error.parse_error(Error.E_EOF, ibuf.line_number);
return states;
}
}
}
if (',' != ibuf.line[ibuf.line_index])
{
break;
}
ibuf.line_index++;
}
if ('>' == ibuf.line[ibuf.line_index])
{
ibuf.line_index++;
if (ibuf.line_index < ibuf.line_read)
{
advance_stop = true;
}
return states;
}
/* Read in state name. */
start_state = ibuf.line_index;
while (false == Utility.IsSpace(ibuf.line[ibuf.line_index])
&& ',' != ibuf.line[ibuf.line_index]
&& '>' != ibuf.line[ibuf.line_index])
{
ibuf.line_index++;
if (ibuf.line_index >= ibuf.line_read)
{
/* End of line means end of state name. */
break;
}
}
count_state = ibuf.line_index - start_state;
/* Save name after checking definition. */
name = new String(ibuf.line, start_state, count_state);
if (!spec.states.TryGetValue(name, out index))
{
/* Uninitialized state. */
Console.WriteLine("Uninitialized State Name: [" + name + "]");
Error.parse_error(Error.E_STATE, ibuf.line_number);
}
states.Set(index, true);
}
}
if (null == all_states)
{
all_states = new BitSet(states.Count, true);
}
if (ibuf.line_index < ibuf.line_read)
{
advance_stop = true;
}
return all_states;
}
/*
* Function: expandMacro
* Description: Returns false on error, true otherwise.
*/
private bool expandMacro()
{
int elem;
int start_macro;
int end_macro;
int start_name;
int count_name;
String def;
int def_elem;
String name;
char[] replace;
int rep_elem;
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
/* Check for macro. */
if ('{' != ibuf.line[ibuf.line_index])
{
Error.parse_error(Error.E_INTERNAL, ibuf.line_number);
return ERROR;
}
start_macro = ibuf.line_index;
elem = ibuf.line_index + 1;
if (elem >= ibuf.line_read)
{
Error.impos("Unfinished macro name");
return ERROR;
}
/* Get macro name. */
start_name = elem;
while ('}' != ibuf.line[elem])
{
++elem;
if (elem >= ibuf.line_read)
{
Error.impos("Unfinished macro name at line " + ibuf.line_number);
return ERROR;
}
}
count_name = elem - start_name;
end_macro = elem;
/* Check macro name. */
if (0 == count_name)
{
Error.impos("Nonexistent macro name");
return ERROR;
}
/* Debug checks. */
#if DEBUG
Utility.assert(0 < count_name);
#endif
/* Retrieve macro definition. */
name = new String(ibuf.line, start_name, count_name);
def = (String)spec.macros[name];
if (null == def)
{
/*Error.impos("Undefined macro \"" + name + "\".");*/
Console.WriteLine("Error: Undefined macro \"" + name + "\".");
Error.parse_error(Error.E_NOMAC, ibuf.line_number);
return ERROR;
}
#if OLD_DUMP_DEBUG
Console.WriteLine("expanded escape: \"" + def + "\"");
#endif
/* Replace macro in new buffer,
beginning by copying first part of line buffer. */
replace = new char[ibuf.line.Length];
for (rep_elem = 0; rep_elem < start_macro; ++rep_elem)
{
replace[rep_elem] = ibuf.line[rep_elem];
#if DEBUG
Utility.assert(rep_elem < replace.Length);
#endif
}
/* Copy macro definition. */
if (rep_elem >= replace.Length)
{
replace = Utility.doubleSize(replace);
}
for (def_elem = 0; def_elem < def.Length; ++def_elem)
{
replace[rep_elem] = def[def_elem];
++rep_elem;
if (rep_elem >= replace.Length)
{
replace = Utility.doubleSize(replace);
}
}
/* Copy last part of line. */
if (rep_elem >= replace.Length)
{
replace = Utility.doubleSize(replace);
}
for (elem = end_macro + 1; elem < ibuf.line_read; ++elem)
{
replace[rep_elem] = ibuf.line[elem];
++rep_elem;
if (rep_elem >= replace.Length)
{
replace = Utility.doubleSize(replace);
}
}
/* Replace buffer. */
ibuf.line = replace;
ibuf.line_read = rep_elem;
#if OLD_DEBUG
Console.WriteLine(new String(ibuf.line,0,ibuf.line_read));
#endif
return NOT_ERROR;
}
/*
* Function: saveMacro
* Description: Saves macro definition of form:
* macro_name = macro_definition
*/
private void saveMacro()
{
int elem;
int start_name;
int count_name;
int start_def;
int count_def;
bool saw_escape;
bool in_quote;
bool in_ccl;
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
/* Macro declarations are of the following form:
macro_name macro_definition */
elem = 0;
/* Skip white space preceding macro name. */
while (Utility.IsSpace(ibuf.line[elem]))
{
++elem;
if (elem >= ibuf.line_read)
{
/* End of line has been reached,
and line was found to be empty. */
return;
}
}
/* Read macro name. */
start_name = elem;
while (false == Utility.IsSpace(ibuf.line[elem])
&& '=' != ibuf.line[elem])
{
++elem;
if (elem >= ibuf.line_read)
{
/* Macro name but no associated definition. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
}
count_name = elem - start_name;
/* Check macro name. */
if (0 == count_name)
{
/* Nonexistent macro name. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
/* Skip white space between name and definition. */
while (Utility.IsSpace(ibuf.line[elem]))
{
++elem;
if (elem >= ibuf.line_read)
{
/* Macro name but no associated definition. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
}
if ('=' == ibuf.line[elem])
{
++elem;
if (elem >= ibuf.line_read)
{
/* Macro name but no associated definition. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
}
/* Skip white space between name and definition. */
while (Utility.IsSpace(ibuf.line[elem]))
{
++elem;
if (elem >= ibuf.line_read)
{
/* Macro name but no associated definition. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
}
/* Read macro definition. */
start_def = elem;
in_quote = false;
in_ccl = false;
saw_escape = false;
while (false == Utility.IsSpace(ibuf.line[elem])
|| true == in_quote
|| true == in_ccl
|| true == saw_escape)
{
if ('\"' == ibuf.line[elem] && false == saw_escape)
{
in_quote = !in_quote;
}
if ('\\' == ibuf.line[elem] && false == saw_escape)
{
saw_escape = true;
}
else
{
saw_escape = false;
}
if (false == saw_escape && false == in_quote)
{
if ('[' == ibuf.line[elem] && false == in_ccl)
in_ccl = true;
if (']' == ibuf.line[elem] && true == in_ccl)
in_ccl = false;
}
++elem;
if (elem >= ibuf.line_read)
{
/* End of line. */
break;
}
}
count_def = elem - start_def;
/* Check macro definition. */
if (count_def == 0)
{
/* Nonexistent macro name. */
Error.parse_error(Error.E_MACDEF, ibuf.line_number);
}
/* Debug checks. */
#if DEBUG
Utility.assert(0 < count_def);
Utility.assert(0 < count_name);
Utility.assert(null != spec.macros);
#endif
String macro_name = new String(ibuf.line, start_name, count_name);
String macro_def = new String(ibuf.line, start_def, count_def);
#if OLD_DEBUG
Console.WriteLine("macro name \"" + macro_name + "\".");
Console.WriteLine("macro definition \"" + macro_def + "\".");
#endif
/* Add macro name and definition to table. */
spec.macros.Add(macro_name, macro_def);
}
/*
* Function: saveStates
* Description: Takes state declaration and makes entries
* for them in state hashtable in CSpec structure.
* State declaration should be of the form:
* %state name0[, name1, name2 ...]
* (But commas are actually optional as long as there is
* white space in between them.)
*/
private void saveStates()
{
int start_state;
int count_state;
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
/* EOF found? */
if (ibuf.eof_reached)
return;
/* Debug checks. */
#if DEBUG
Utility.assert('%' == ibuf.line[0]);
Utility.assert('s' == ibuf.line[1]);
Utility.assert(ibuf.line_index <= ibuf.line_read);
Utility.assert(0 <= ibuf.line_index);
Utility.assert(0 <= ibuf.line_read);
#endif
/* Blank line? No states? */
if (ibuf.line_index >= ibuf.line_read)
return;
while (ibuf.line_index < ibuf.line_read)
{
#if OLD_DEBUG
Console.WriteLine("line read " + ibuf.line_read
+ "\tline index = " + ibuf.line_index);
#endif
/* Skip white space. */
while (Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
if (ibuf.line_index >= ibuf.line_read)
{
/* No more states to be found. */
return;
}
}
/* Look for state name. */
start_state = ibuf.line_index;
while (!Utility.IsSpace(ibuf.line[ibuf.line_index])
&& ibuf.line[ibuf.line_index] != ',')
{
ibuf.line_index++;
if (ibuf.line_index >= ibuf.line_read)
{
/* End of line and end of state name. */
break;
}
}
count_state = ibuf.line_index - start_state;
#if OLD_DEBUG
Console.WriteLine("State name \""
+ new String(ibuf.line,start_state,count_state)
+ "\".");
Console.WriteLine("Integer index \""
+ spec.states.Count
+ "\".");
#endif
/* Enter new state name, along with unique index. */
spec.states[new String(ibuf.line, start_state, count_state)] =
spec.states.Count;
/* Skip comma. */
if (',' == ibuf.line[ibuf.line_index])
{
ibuf.line_index++;
if (ibuf.line_index >= ibuf.line_read)
{
/* End of line. */
return;
}
}
}
}
/*
* Function: expandEscape
* Description: Takes escape sequence and returns
* corresponding character code.
*/
private char expandEscape()
{
char r;
/* Debug checks. */
#if DEBUG
Utility.assert(ibuf.line_index < ibuf.line_read);
Utility.assert(0 < ibuf.line_read);
Utility.assert(0 <= ibuf.line_index);
#endif
if (ibuf.line[ibuf.line_index] != '\\')
{
ibuf.line_index++;
return ibuf.line[ibuf.line_index - 1];
}
else
{
ibuf.line_index++;
switch (Utility.toupper(ibuf.line[ibuf.line_index]))
{
case 'B':
ibuf.line_index++;
return '\b';
case 'T':
ibuf.line_index++;
return '\t';
case 'N':
ibuf.line_index++;
return '\n';
case 'F':
ibuf.line_index++;
return '\f';
case 'R':
ibuf.line_index++;
return '\r';
case '^':
ibuf.line_index++;
r = (char)(Utility.toupper(ibuf.line[ibuf.line_index]) - '@');
ibuf.line_index++;
return r;
case 'X':
ibuf.line_index++;
r = (char)0;
if (Utility.ishexdigit(ibuf.line[ibuf.line_index]))
{
r = Utility.hex2bin(ibuf.line[ibuf.line_index]);
ibuf.line_index++;
}
if (Utility.ishexdigit(ibuf.line[ibuf.line_index]))
{
r = (char)(r << 4);
r = (char)(r | Utility.hex2bin(ibuf.line[ibuf.line_index]));
ibuf.line_index++;
}
if (Utility.ishexdigit(ibuf.line[ibuf.line_index]))
{
r = (char)(r << 4);
r = (char)(r | Utility.hex2bin(ibuf.line[ibuf.line_index]));
ibuf.line_index++;
}
return r;
default:
if (!Utility.isoctdigit(ibuf.line[ibuf.line_index]))
{
r = ibuf.line[ibuf.line_index];
ibuf.line_index++;
}
else
{
r = Utility.oct2bin(ibuf.line[ibuf.line_index]);
ibuf.line_index++;
if (Utility.isoctdigit(ibuf.line[ibuf.line_index]))
{
r = (char)(r << 3);
r = (char)(r | Utility.oct2bin(ibuf.line[ibuf.line_index]));
ibuf.line_index++;
}
if (Utility.isoctdigit(ibuf.line[ibuf.line_index]))
{
r = (char)(r << 3);
r = (char)(r | Utility.oct2bin(ibuf.line[ibuf.line_index]));
ibuf.line_index++;
}
}
return r;
}
}
}
/*
* Function: packAccept
* Description: Packages and returns CAccept
* for action next in input stream.
*/
public Accept packAccept()
{
Accept accept;
int brackets;
bool inquotes;
bool instarcomment;
bool inslashcomment;
bool escaped;
bool slashed;
StringBuilder action = new StringBuilder(BUFFER_SIZE);
#if DEBUG
Utility.assert(null != this);
Utility.assert(null != outstream);
Utility.assert(null != ibuf);
Utility.assert(null != tokens);
Utility.assert(null != spec);
#endif
/* Get a new line, if needed. */
while (ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
{
Error.parse_error(Error.E_EOF, ibuf.line_number);
return null;
}
}
/* Look for beginning of action */
while (Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
/* Get a new line, if needed. */
while (ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
{
Error.parse_error(Error.E_EOF, ibuf.line_number);
return null;
}
}
}
/* Look for brackets. */
if ('{' != ibuf.line[ibuf.line_index])
{
Error.parse_error(Error.E_BRACE, ibuf.line_number);
}
/* Copy new line into action buffer. */
brackets = 0;
inquotes = inslashcomment = instarcomment = false;
escaped = slashed = false;
while (true)
{
action.Append(ibuf.line[ibuf.line_index]);
/* Look for quotes. */
if (inquotes && escaped)
escaped = false; // only protects one char, but this is enough.
else if (inquotes && '\\' == ibuf.line[ibuf.line_index])
escaped = true;
else if ('\"' == ibuf.line[ibuf.line_index])
inquotes = !inquotes; // unescaped quote.
/* Look for comments. */
if (instarcomment)
{ // inside "/*" comment; look for "*/"
if (slashed && '/' == ibuf.line[ibuf.line_index])
instarcomment = slashed = false;
else // note that inside a star comment,
// slashed means starred
slashed = ('*' == ibuf.line[ibuf.line_index]);
}
else if (!inslashcomment)
{ // not in comment, look for /* or //
inslashcomment =
(slashed && '/' == ibuf.line[ibuf.line_index]);
instarcomment =
(slashed && '*' == ibuf.line[ibuf.line_index]);
slashed = ('/' == ibuf.line[ibuf.line_index]);
}
/* Look for brackets. */
if (!inquotes && !instarcomment && !inslashcomment)
{
if ('{' == ibuf.line[ibuf.line_index])
{
++brackets;
}
else if ('}' == ibuf.line[ibuf.line_index])
{
--brackets;
if (0 == brackets)
{
ibuf.line_index++;
break;
}
}
}
ibuf.line_index++;
/* Get a new line, if needed. */
while (ibuf.line_index >= ibuf.line_read)
{
inslashcomment = slashed = false;
if (inquotes)
{ // non-fatal
Error.parse_error(Error.E_NEWLINE, ibuf.line_number);
inquotes = false;
}
if (ibuf.GetLine())
{
Error.parse_error(Error.E_SYNTAX, ibuf.line_number);
return null;
}
}
}
accept = new Accept(action.ToString(), ibuf.line_number);
#if DEBUG
Utility.assert(null != accept);
#endif
#if DESCENT_DEBUG
Console.Write("\nAccepting action:");
Console.WriteLine(accept.action);
#endif
return accept;
}
/*
* Function: advance
* Description: Returns code for next token.
*/
private bool advance_stop = false;
public int Advance()
{
bool saw_escape = false;
if (ibuf.eof_reached)
{
/* EOF has already been reached, so return appropriate code. */
spec.current_token = END_OF_INPUT;
spec.lexeme = '\0';
return spec.current_token;
}
/* End of previous regular expression? Refill line buffer? */
if (EOS == spec.current_token || ibuf.line_index >= ibuf.line_read)
{
if (spec.in_quote)
{
Error.parse_error(Error.E_SYNTAX, ibuf.line_number);
}
while (true)
{
if (!advance_stop || ibuf.line_index >= ibuf.line_read)
{
if (ibuf.GetLine())
{
/* EOF has already been reached, so return appropriate code. */
spec.current_token = END_OF_INPUT;
spec.lexeme = '\0';
return spec.current_token;
}
ibuf.line_index = 0;
}
else
{
advance_stop = false;
}
while (ibuf.line_index < ibuf.line_read
&& true == Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
ibuf.line_index++;
}
if (ibuf.line_index < ibuf.line_read)
{
break;
}
}
}
#if DEBUG
Utility.assert(ibuf.line_index <= ibuf.line_read);
#endif
while (true)
{
if (!spec.in_quote && '{' == ibuf.line[ibuf.line_index])
{
if (!expandMacro())
{
break;
}
if (ibuf.line_index >= ibuf.line_read)
{
spec.current_token = EOS;
spec.lexeme = '\0';
return spec.current_token;
}
}
else if ('\"' == ibuf.line[ibuf.line_index])
{
spec.in_quote = !spec.in_quote;
ibuf.line_index++;
if (ibuf.line_index >= ibuf.line_read)
{
spec.current_token = EOS;
spec.lexeme = '\0';
return spec.current_token;
}
}
else
{
break;
}
}
if (ibuf.line_index > ibuf.line_read)
{
Console.WriteLine("ibuf.line_index = " + ibuf.line_index);
Console.WriteLine("ibuf.line_read = " + ibuf.line_read);
Utility.assert(ibuf.line_index <= ibuf.line_read);
}
/* Look for backslash, and corresponding
escape sequence. */
if ('\\' == ibuf.line[ibuf.line_index])
{
saw_escape = true;
}
else
{
saw_escape = false;
}
if (!spec.in_quote)
{
if (!spec.in_ccl && Utility.IsSpace(ibuf.line[ibuf.line_index]))
{
/* White space means the end of
the current regular expression. */
spec.current_token = EOS;
spec.lexeme = '\0';
return spec.current_token;
}
/* Process escape sequence, if needed. */
if (saw_escape)
{
spec.lexeme = expandEscape();
}
else
{
spec.lexeme = ibuf.line[ibuf.line_index];
ibuf.line_index++;
}
}
else
{
if (saw_escape
&& (ibuf.line_index + 1) < ibuf.line_read
&& '\"' == ibuf.line[ibuf.line_index + 1])
{
spec.lexeme = '\"';
ibuf.line_index = ibuf.line_index + 2;
}
else
{
spec.lexeme = ibuf.line[ibuf.line_index];
ibuf.line_index++;
}
}
if (spec.in_quote || saw_escape)
{
spec.current_token = L;
}
else
{
int code;
if (tokens.TryGetValue(spec.lexeme, out code))
{
spec.current_token = code;
}
else
{
spec.current_token = L;
}
}
if (CCL_START == spec.current_token)
spec.in_ccl = true;
if (CCL_END == spec.current_token)
spec.in_ccl = false;
#if FOODEBUG
DumpLexeme(spec.lexeme, spec.current_token, ibuf.line_index);
#endif
return spec.current_token;
}
#if FOODEBUG
void DumpLexeme(char lexeme, int token, int index)
{
StringBuilder sb = new StringBuilder();
sb.Append("Lexeme: '");
if (lexeme < ' ')
{
lexeme += (char) 64;
sb.Append("^");
}
sb.Append(lexeme);
sb.Append("'\tToken: ");
sb.Append(token);
sb.Append("\tIndex: ");
sb.Append(index);
Console.WriteLine(sb.ToString());
}
#endif
/*
* Function: details
* Description: High level debugging routine.
*/
private void details()
{
Console.WriteLine("\n\t** Macros **");
foreach (string name in spec.macros.Keys)
{
#if DEBUG
Utility.assert(null != name);
#endif
string def = (String)spec.macros[name];
#if DEBUG
Utility.assert(null != def);
#endif
Console.WriteLine("Macro name \"" + name + "\" has definition \""
+ def + "\".");
}
Console.WriteLine("\n\t** States **");
foreach (string state in spec.states.Keys)
{
int index = (int)spec.states[state];
#if DEBUG
Utility.assert(null != state);
#endif
Console.WriteLine("State \"" + state + "\" has identifying index "
+ index + ".");
}
Console.WriteLine("\n\t** Character Counting **");
if (!spec.count_chars)
Console.WriteLine("Character counting is off.");
else
{
#if DEBUG
Utility.assert(spec.count_lines);
#endif
Console.WriteLine("Character counting is on.");
}
Console.WriteLine("\n\t** Line Counting **");
if (!spec.count_lines)
Console.WriteLine("Line counting is off.");
else
{
#if DEBUG
Utility.assert(spec.count_lines);
#endif
Console.WriteLine("Line counting is on.");
}
Console.WriteLine("\n\t** Operating System Specificity **");
#if FOODEBUG
if (spec.nfa_states != null && spec.nfa_start != null)
{
Console.WriteLine("\n\t** NFA machine **");
print_nfa();
}
#endif
if (spec.dtrans_list != null)
{
Console.WriteLine("\n\t** DFA transition table **");
}
}
/*
* Function: print_header
*/
private void print_header()
{
int j;
int chars_printed = 0;
DTrans dtrans;
int last_transition;
String str;
Accept accept;
Console.WriteLine("/*---------------------- DFA -----------------------");
if (spec.states == null)
throw new ApplicationException("States is null");
foreach (string state in spec.states.Keys)
{
int index = (int)spec.states[state];
#if DEBUG
Utility.assert(null != state);
#endif
Console.WriteLine("State \"" + state + "\" has identifying index "
+ index + ".");
if (DTrans.F != spec.state_dtrans[index])
{
Console.WriteLine("\tStart index in transition table: "
+ spec.state_dtrans[index]);
}
else
{
Console.WriteLine("\tNo associated transition states.");
}
}
for (int i = 0; i < spec.dtrans_list.Count; ++i)
{
dtrans = (DTrans)spec.dtrans_list[i];
if (null == spec.accept_list && null == spec.anchor_array)
{
if (null == dtrans.GetAccept())
{
Console.Write(" * State " + i + " [nonaccepting]");
}
else
{
Console.Write(" * State " + i
+ " [accepting, line "
+ dtrans.GetAccept().line_number
+ " <"
+ dtrans.GetAccept().action
+ ">]");
if (Spec.NONE != dtrans.GetAnchor())
{
Console.Write(" Anchor: "
+ ((0 != (dtrans.GetAnchor() & Spec.START))
? "start " : "")
+ ((0 != (dtrans.GetAnchor() & Spec.END))
? "end " : ""));
}
}
}
else
{
accept = (Accept)spec.accept_list[i];
if (null == accept)
{
Console.Write(" * State " + i + " [nonaccepting]");
}
else
{
Console.Write(" * State " + i
+ " [accepting, line "
+ accept.line_number
+ " <"
+ accept.action
+ ">]");
if (Spec.NONE != spec.anchor_array[i])
{
Console.Write(" Anchor: "
+ ((0 != (spec.anchor_array[i] & Spec.START))
? "start " : "")
+ ((0 != (spec.anchor_array[i] & Spec.END))
? "end " : ""));
}
}
}
last_transition = -1;
for (j = 0; j < spec.dtrans_ncols; ++j)
{
if (DTrans.F != dtrans.GetDTrans(j))
{
if (last_transition != dtrans.GetDTrans(j))
{
Console.Write("\n * goto " + dtrans.GetDTrans(j) + " on ");
chars_printed = 0;
}
str = interp_int((int)j);
Console.Write(str);
chars_printed = chars_printed + str.Length;
if (56 < chars_printed)
{
Console.Write("\n * ");
chars_printed = 0;
}
last_transition = dtrans.GetDTrans(j);
}
}
Console.WriteLine("");
}
Console.WriteLine(" */\n");
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Purpose: Unsafe code that uses pointers should use
** SafePointer to fix subtle lifetime problems with the
** underlying resource.
**
===========================================================*/
// Design points:
// *) Avoid handle-recycling problems (including ones triggered via
// resurrection attacks) for all accesses via pointers. This requires tying
// together the lifetime of the unmanaged resource with the code that reads
// from that resource, in a package that uses synchronization to enforce
// the correct semantics during finalization. We're using SafeHandle's
// ref count as a gate on whether the pointer can be dereferenced because that
// controls the lifetime of the resource.
//
// *) Keep the penalties for using this class small, both in terms of space
// and time. Having multiple threads reading from a memory mapped file
// will already require 2 additional interlocked operations. If we add in
// a "current position" concept, that requires additional space in memory and
// synchronization. Since the position in memory is often (but not always)
// something that can be stored on the stack, we can save some memory by
// excluding it from this object. However, avoiding the need for
// synchronization is a more significant win. This design allows multiple
// threads to read and write memory simultaneously without locks (as long as
// you don't write to a region of memory that overlaps with what another
// thread is accessing).
//
// *) Space-wise, we use the following memory, including SafeHandle's fields:
// Object Header MT* handle int bool bool <2 pad bytes> length
// On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes.
// (We can safe 4 bytes on x86 only by shrinking SafeHandle)
//
// *) Wrapping a SafeHandle would have been a nice solution, but without an
// ordering between critical finalizable objects, it would have required
// changes to each SafeHandle subclass to opt in to being usable from a
// SafeBuffer (or some clever exposure of SafeHandle's state fields and a
// way of forcing ReleaseHandle to run even after the SafeHandle has been
// finalized with a ref count > 1). We can use less memory and create fewer
// objects by simply inserting a SafeBuffer into the class hierarchy.
//
// *) In an ideal world, we could get marshaling support for SafeBuffer that
// would allow us to annotate a P/Invoke declaration, saying this parameter
// specifies the length of the buffer, and the units of that length are X.
// P/Invoke would then pass that size parameter to SafeBuffer.
// [DllImport(...)]
// static extern SafeMemoryHandle AllocCharBuffer(int numChars);
// If we could put an attribute on the SafeMemoryHandle saying numChars is
// the element length, and it must be multiplied by 2 to get to the byte
// length, we can simplify the usage model for SafeBuffer.
//
// *) This class could benefit from a constraint saying T is a value type
// containing no GC references.
// Implementation notes:
// *) The Initialize method must be called before you use any instance of
// a SafeBuffer. To avoid ----s when storing SafeBuffers in statics,
// you either need to take a lock when publishing the SafeBuffer, or you
// need to create a local, initialize the SafeBuffer, then assign to the
// static variable (perhaps using Interlocked.CompareExchange). Of course,
// assignments in a static class constructor are under a lock implicitly.
namespace System.Runtime.InteropServices
{
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
[System.Security.SecurityCritical]
public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
// Steal UIntPtr.MaxValue as our uninitialized value.
private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
((UIntPtr) UInt32.MaxValue) : ((UIntPtr) UInt64.MaxValue);
private UIntPtr _numBytes;
protected SafeBuffer(bool ownsHandle) : base(ownsHandle)
{
_numBytes = Uninitialized;
}
/// <summary>
/// Specifies the size of the region of memory, in bytes. Must be
/// called before using the SafeBuffer.
/// </summary>
/// <param name="numBytes">Number of valid bytes in memory.</param>
[CLSCompliant(false)]
public void Initialize(ulong numBytes)
{
if (numBytes < 0)
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
Contract.EndContractBlock();
if (numBytes >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
_numBytes = (UIntPtr) numBytes;
}
/// <summary>
/// Specifies the the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize(uint numElements, uint sizeOfEachElement)
{
if (numElements < 0)
throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (sizeOfEachElement < 0)
throw new ArgumentOutOfRangeException("sizeOfEachElement", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
Contract.EndContractBlock();
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException("numElements", Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
_numBytes = checked((UIntPtr) (numElements * sizeOfEachElement));
}
#if !FEATURE_CORECLR
/// <summary>
/// Specifies the the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
public void Initialize<T>(uint numElements) where T : struct
{
Initialize(numElements, Marshal.AlignedSizeOf<T>());
}
#endif
// Callers should ensure that they check whether the pointer ref param
// is null when AcquirePointer returns. If it is not null, they must
// call ReleasePointer in a CER. This method calls DangerousAddRef
// & exposes the pointer. Unlike Read, it does not alter the "current
// position" of the pointer. Here's how to use it:
//
// byte* pointer = null;
// RuntimeHelpers.PrepareConstrainedRegions();
// try {
// safeBuffer.AcquirePointer(ref pointer);
// // Use pointer here, with your own bounds checking
// }
// finally {
// if (pointer != null)
// safeBuffer.ReleasePointer();
// }
//
// Note: If you cast this byte* to a T*, you have to worry about
// whether your pointer is aligned. Additionally, you must take
// responsibility for all bounds checking with this pointer.
/// <summary>
/// Obtain the pointer from a SafeBuffer for a block of code,
/// with the express responsibility for bounds checking and calling
/// ReleasePointer later within a CER to ensure the pointer can be
/// freed later. This method either completes successfully or
/// throws an exception and returns with pointer set to null.
/// </summary>
/// <param name="pointer">A byte*, passed by reference, to receive
/// the pointer from within the SafeBuffer. You must set
/// pointer to null before calling this method.</param>
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void AcquirePointer(ref byte* pointer)
{
if (_numBytes == Uninitialized)
throw NotInitialized();
pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
}
finally
{
bool junk = false;
DangerousAddRef(ref junk);
pointer = (byte*)handle;
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void ReleasePointer()
{
if (_numBytes == Uninitialized)
throw NotInitialized();
DangerousRelease();
}
#if !FEATURE_CORECLR || FEATURE_CORESYSTEM
/// <summary>
/// Read a value type from memory at the given offset. This is
/// equivalent to: return *(T*)(bytePtr + byteOffset);
/// </summary>
/// <typeparam name="T">The value type to read</typeparam>
/// <param name="byteOffset">Where to start reading from memory. You
/// may have to consider alignment.</param>
/// <returns>An instance of T read from memory.</returns>
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public T Read<T>(ulong byteOffset) where T : struct {
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// return *(T*) (_ptr + byteOffset);
T value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericPtrToStructure<T>(ptr, out value, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
return value;
}
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericPtrToStructure<T>(ptr + alignedSizeofT * i, out array[i + index], sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
/// <summary>
/// Write a value type to memory at the given offset. This is
/// equivalent to: *(T*)(bytePtr + byteOffset) = value;
/// </summary>
/// <typeparam name="T">The type of the value type to write to memory.</typeparam>
/// <param name="byteOffset">The location in memory to write to. You
/// may have to consider alignment.</param>
/// <param name="value">The value type to write to memory.</param>
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void Write<T>(ulong byteOffset, T value) where T : struct {
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, sizeofT);
// *((T*) (_ptr + byteOffset)) = value;
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
GenericStructureToPtr(ref value, ptr, sizeofT);
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
where T : struct
{
if (array == null)
throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
throw NotInitialized();
uint sizeofT = Marshal.SizeOfType(typeof(T));
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
DangerousAddRef(ref mustCallRelease);
for (int i = 0; i < count; i++)
unsafe { GenericStructureToPtr(ref array[i + index], ptr + alignedSizeofT * i, sizeofT); }
}
finally
{
if (mustCallRelease)
DangerousRelease();
}
}
#endif // !FEATURE_CORECLR || FEATURE_CORESYSTEM
/// <summary>
/// Returns the number of bytes in the memory region.
/// </summary>
[CLSCompliant(false)]
public ulong ByteLength {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
if (_numBytes == Uninitialized)
throw NotInitialized();
return (ulong) _numBytes;
}
}
/* No indexer. The perf would be misleadingly bad. People should use
* AcquirePointer and ReleasePointer instead. */
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void SpaceCheck(byte* ptr, ulong sizeInBytes)
{
if ((ulong)_numBytes < sizeInBytes)
NotEnoughRoom();
if ((ulong)(ptr - (byte*) handle) > ((ulong)_numBytes) - sizeInBytes)
NotEnoughRoom();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static void NotEnoughRoom()
{
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static InvalidOperationException NotInitialized()
{
Contract.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize"));
}
// FCALL limitations mean we can't have generic FCALL methods. However, we can pass
// TypedReferences to FCALL methods.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static void GenericPtrToStructure<T>(byte* ptr, out T structure, uint sizeofT) where T : struct
{
structure = default(T); // Dummy assignment to silence the compiler
PtrToStructureNative(ptr, __makeref(structure), sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void PtrToStructureNative(byte* ptr, /*out T*/ TypedReference structure, uint sizeofT);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static void GenericStructureToPtr<T>(ref T structure, byte* ptr, uint sizeofT) where T : struct
{
StructureToPtrNative(__makeref(structure), ptr, sizeofT);
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern void StructureToPtrNative(/*ref T*/ TypedReference structure, byte* ptr, uint sizeofT);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ExtensionsTests
{
[Fact]
public static void ReadExtensions()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
X509ExtensionCollection exts = c.Extensions;
int count = exts.Count;
Assert.Equal(6, count);
X509Extension[] extensions = new X509Extension[count];
exts.CopyTo(extensions, 0);
extensions = extensions.OrderBy(e => e.Oid.Value).ToArray();
// There are an awful lot of magic-looking values in this large test.
// These values are embedded within the certificate, and the test is
// just verifying the object interpretation. In the event the test data
// (TestData.MsCertificate) is replaced, this whole body will need to be
// redone.
{
// Authority Information Access
X509Extension aia = extensions[0];
Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value);
Assert.False(aia.Critical);
byte[] expectedDer = (
"304c304a06082b06010505073002863e687474703a2f2f7777772e6d" +
"6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" +
"645369675043415f30382d33312d323031302e637274").HexToByteArray();
Assert.Equal(expectedDer, aia.RawData);
}
{
// Subject Key Identifier
X509Extension skid = extensions[1];
Assert.Equal("2.5.29.14", skid.Oid.Value);
Assert.False(skid.Critical);
byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray();
Assert.Equal(expected, skid.RawData);
Assert.True(skid is X509SubjectKeyIdentifierExtension);
X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid;
Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier);
}
{
// Subject Alternative Names
X509Extension sans = extensions[2];
Assert.Equal("2.5.29.17", sans.Oid.Value);
Assert.False(sans.Critical);
byte[] expected = (
"3048a4463044310d300b060355040b13044d4f505231333031060355" +
"0405132a33313539352b34666166306237312d616433372d34616133" +
"2d613637312d373662633035323334346164").HexToByteArray();
Assert.Equal(expected, sans.RawData);
}
{
// CRL Distribution Points
X509Extension cdps = extensions[3];
Assert.Equal("2.5.29.31", cdps.Oid.Value);
Assert.False(cdps.Critical);
byte[] expected = (
"304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" +
"66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" +
"6f645369675043415f30382d33312d323031302e63726c").HexToByteArray();
Assert.Equal(expected, cdps.RawData);
}
{
// Authority Key Identifier
X509Extension akid = extensions[4];
Assert.Equal("2.5.29.35", akid.Oid.Value);
Assert.False(akid.Critical);
byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray();
Assert.Equal(expected, akid.RawData);
}
{
// Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced)
X509Extension eku = extensions[5];
Assert.Equal("2.5.29.37", eku.Oid.Value);
Assert.False(eku.Critical);
byte[] expected = "300a06082b06010505070303".HexToByteArray();
Assert.Equal(expected, eku.RawData);
Assert.True(eku is X509EnhancedKeyUsageExtension);
X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku;
OidCollection usages = rich.EnhancedKeyUsages;
Assert.Equal(1, usages.Count);
Oid oid = usages[0];
// Code Signing
Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value);
}
}
}
[Fact]
public static void KeyUsageExtensionDefaultCtor()
{
X509KeyUsageExtension e = new X509KeyUsageExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.15", oidValue);
byte[] r = e.RawData;
Assert.Null(r);
X509KeyUsageFlags keyUsages = e.KeyUsages;
Assert.Equal(X509KeyUsageFlags.None, keyUsages);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_CrlSign()
{
TestKeyUsageExtension(X509KeyUsageFlags.CrlSign, false, "03020102".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_DataEncipherment()
{
TestKeyUsageExtension(X509KeyUsageFlags.DataEncipherment, false, "03020410".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_DecipherOnly()
{
TestKeyUsageExtension(X509KeyUsageFlags.DecipherOnly, false, "0303070080".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_DigitalSignature()
{
TestKeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false, "03020780".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_EncipherOnly()
{
TestKeyUsageExtension(X509KeyUsageFlags.EncipherOnly, false, "03020001".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_KeyAgreement()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyAgreement, false, "03020308".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_KeyCertSign()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyCertSign, false, "03020204".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_KeyEncipherment()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, false, "03020520".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_None()
{
TestKeyUsageExtension(X509KeyUsageFlags.None, false, "030100".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void KeyUsageExtension_NonRepudiation()
{
TestKeyUsageExtension(X509KeyUsageFlags.NonRepudiation, false, "03020640".HexToByteArray());
}
[Fact]
public static void BasicConstraintsExtensionDefault()
{
X509BasicConstraintsExtension e = new X509BasicConstraintsExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.19", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
Assert.False(e.CertificateAuthority);
Assert.False(e.HasPathLengthConstraint);
Assert.Equal(0, e.PathLengthConstraint);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void BasicConstraintsExtension_Leaf()
{
TestBasicConstraintsExtension(false, false, 0, false, "3000".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void BasicConstraintsExtension_CA_NoLength()
{
TestBasicConstraintsExtension(true, false, 0, false, "30030101ff".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void BasicConstraintsExtension_Leaf_Length0()
{
TestBasicConstraintsExtension(false, true, 0, false, "3003020100".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void BasicConstraintsExtension_LeafLongPath()
{
TestBasicConstraintsExtension(false, true, 7654321, false, "3005020374cbb1".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void BasicConstraintsExtension_CA_559()
{
TestBasicConstraintsExtension(true, true, 559, false, "30070101ff0202022f".HexToByteArray());
}
[Fact]
public static void EnhancedKeyUsageExtensionDefault()
{
X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.37", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
OidCollection usages = e.EnhancedKeyUsages;
Assert.Equal(0, usages.Count);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void EnhancedKeyUsageExtension_Empty()
{
OidCollection usages = new OidCollection();
TestEnhancedKeyUsageExtension(usages, false, "3000".HexToByteArray());
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void EnhancedKeyUsageExtension_2Oids()
{
Oid oid1 = Oid.FromOidValue("1.3.6.1.5.5.7.3.1", OidGroup.EnhancedKeyUsage);
Oid oid2 = Oid.FromOidValue("1.3.6.1.4.1.311.10.3.1", OidGroup.EnhancedKeyUsage);
OidCollection usages = new OidCollection();
usages.Add(oid1);
usages.Add(oid2);
TestEnhancedKeyUsageExtension(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray());
}
[Fact]
public static void SubjectKeyIdentifierExtensionDefault()
{
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.14", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
string skid = e.SubjectKeyIdentifier;
Assert.Null(skid);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_Bytes()
{
byte[] sk = { 1, 2, 3, 4 };
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false);
byte[] rawData = e.RawData;
Assert.Equal("040401020304".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("01020304", skid);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_String()
{
string sk = "01ABcd";
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false);
byte[] rawData = e.RawData;
Assert.Equal("040301abcd".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("01ABCD", skid);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_PublicKey()
{
PublicKey pk = new X509Certificate2(TestData.MsCertificate).PublicKey;
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(pk, false);
byte[] rawData = e.RawData;
Assert.Equal("04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", skid);
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_PublicKeySha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.Sha1,
false,
"04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(),
"5971A65A334DDA980780FF841EBE87F9723241F2");
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_PublicKeyShortSha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.ShortSha1,
false,
"04084ebe87f9723241f2".HexToByteArray(),
"4EBE87F9723241F2");
}
[Fact]
[ActiveIssue(1993, PlatformID.AnyUnix)]
public static void SubjectKeyIdentifierExtension_PublicKeyCapiSha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false,
"0414a260a870be1145ed71e2bb5aa19463a4fe9dcc41".HexToByteArray(),
"A260A870BE1145ED71E2BB5AA19463A4FE9DCC41");
}
private static void TestKeyUsageExtension(X509KeyUsageFlags flags, bool critical, byte[] expectedDer)
{
X509KeyUsageExtension ext = new X509KeyUsageExtension(flags, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
// Assert that format doesn't crash
string s = ext.Format(false);
// Rebuild it from the RawData.
ext = new X509KeyUsageExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(flags, ext.KeyUsages);
}
private static void TestBasicConstraintsExtension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint,
bool critical,
byte[] expectedDer)
{
X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension(
certificateAuthority,
hasPathLengthConstraint,
pathLengthConstraint,
critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
ext = new X509BasicConstraintsExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(certificateAuthority, ext.CertificateAuthority);
Assert.Equal(hasPathLengthConstraint, ext.HasPathLengthConstraint);
Assert.Equal(pathLengthConstraint, ext.PathLengthConstraint);
}
private static void TestEnhancedKeyUsageExtension(
OidCollection usages,
bool critical,
byte[] expectedDer)
{
X509EnhancedKeyUsageExtension ext = new X509EnhancedKeyUsageExtension(usages, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
ext = new X509EnhancedKeyUsageExtension(new AsnEncodedData(rawData), critical);
OidCollection actualUsages = ext.EnhancedKeyUsages;
Assert.Equal(usages.Count, actualUsages.Count);
for (int i = 0; i < usages.Count; i++)
{
Assert.Equal(usages[i].Value, actualUsages[i].Value);
}
}
private static void TestSubjectKeyIdentifierExtension(
byte[] certBytes,
X509SubjectKeyIdentifierHashAlgorithm algorithm,
bool critical,
byte[] expectedDer,
string expectedIdentifier)
{
PublicKey pk = new X509Certificate2(certBytes).PublicKey;
X509SubjectKeyIdentifierExtension ext =
new X509SubjectKeyIdentifierExtension(pk, algorithm, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
ext = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(expectedIdentifier, ext.SubjectKeyIdentifier);
}
}
}
| |
using J2N.Threading.Atomic;
using Lucene.Net.Index;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Codecs.Lucene45
{
/*
* 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 BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using IBits = Lucene.Net.Util.IBits;
using BlockPackedReader = Lucene.Net.Util.Packed.BlockPackedReader;
using BytesRef = Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using DocValues = Lucene.Net.Index.DocValues;
using DocValuesType = Lucene.Net.Index.DocValuesType;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOUtils = Lucene.Net.Util.IOUtils;
using Int64Values = Lucene.Net.Util.Int64Values;
using MonotonicBlockPackedReader = Lucene.Net.Util.Packed.MonotonicBlockPackedReader;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using RandomAccessOrds = Lucene.Net.Index.RandomAccessOrds;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Reader for <see cref="Lucene45DocValuesFormat"/>. </summary>
public class Lucene45DocValuesProducer : DocValuesProducer, IDisposable
{
private readonly IDictionary<int, NumericEntry> numerics;
private readonly IDictionary<int, BinaryEntry> binaries;
private readonly IDictionary<int, SortedSetEntry> sortedSets;
private readonly IDictionary<int, NumericEntry> ords;
private readonly IDictionary<int, NumericEntry> ordIndexes;
private readonly AtomicInt64 ramBytesUsed;
private readonly IndexInput data;
private readonly int maxDoc;
private readonly int version;
// memory-resident structures
private readonly IDictionary<int, MonotonicBlockPackedReader> addressInstances = new Dictionary<int, MonotonicBlockPackedReader>();
private readonly IDictionary<int, MonotonicBlockPackedReader> ordIndexInstances = new Dictionary<int, MonotonicBlockPackedReader>();
/// <summary>
/// Expert: instantiates a new reader. </summary>
protected internal Lucene45DocValuesProducer(SegmentReadState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension)
{
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
// read in the entries from the metadata file.
ChecksumIndexInput @in = state.Directory.OpenChecksumInput(metaName, state.Context);
this.maxDoc = state.SegmentInfo.DocCount;
bool success = false;
try
{
version = CodecUtil.CheckHeader(@in, metaCodec, Lucene45DocValuesFormat.VERSION_START, Lucene45DocValuesFormat.VERSION_CURRENT);
numerics = new Dictionary<int, NumericEntry>();
ords = new Dictionary<int, NumericEntry>();
ordIndexes = new Dictionary<int, NumericEntry>();
binaries = new Dictionary<int, BinaryEntry>();
sortedSets = new Dictionary<int, SortedSetEntry>();
ReadFields(@in, state.FieldInfos);
if (version >= Lucene45DocValuesFormat.VERSION_CHECKSUM)
{
CodecUtil.CheckFooter(@in);
}
else
{
#pragma warning disable 612, 618
CodecUtil.CheckEOF(@in);
#pragma warning restore 612, 618
}
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(@in);
}
else
{
IOUtils.DisposeWhileHandlingException(@in);
}
}
success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
data = state.Directory.OpenInput(dataName, state.Context);
int version2 = CodecUtil.CheckHeader(data, dataCodec, Lucene45DocValuesFormat.VERSION_START, Lucene45DocValuesFormat.VERSION_CURRENT);
if (version != version2)
{
throw new Exception("Format versions mismatch");
}
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(this.data);
}
}
ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOfInstance(this.GetType()));
}
private void ReadSortedField(int fieldNumber, IndexInput meta, FieldInfos infos)
{
// sorted = binary + numeric
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sorted entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n = ReadNumericEntry(meta);
ords[fieldNumber] = n;
}
private void ReadSortedSetFieldWithAddresses(int fieldNumber, IndexInput meta, FieldInfos infos)
{
// sortedset = binary + numeric (addresses) + ordIndex
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.BINARY)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n1 = ReadNumericEntry(meta);
ords[fieldNumber] = n1;
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.NUMERIC)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
NumericEntry n2 = ReadNumericEntry(meta);
ordIndexes[fieldNumber] = n2;
}
private void ReadFields(IndexInput meta, FieldInfos infos)
{
int fieldNumber = meta.ReadVInt32();
while (fieldNumber != -1)
{
// check should be: infos.fieldInfo(fieldNumber) != null, which incorporates negative check
// but docvalues updates are currently buggy here (loading extra stuff, etc): LUCENE-5616
if (fieldNumber < 0)
{
// trickier to validate more: because we re-use for norms, because we use multiple entries
// for "composite" types like sortedset, etc.
throw new Exception("Invalid field number: " + fieldNumber + " (resource=" + meta + ")");
}
byte type = meta.ReadByte();
if (type == Lucene45DocValuesFormat.NUMERIC)
{
numerics[fieldNumber] = ReadNumericEntry(meta);
}
else if (type == Lucene45DocValuesFormat.BINARY)
{
BinaryEntry b = ReadBinaryEntry(meta);
binaries[fieldNumber] = b;
}
else if (type == Lucene45DocValuesFormat.SORTED)
{
ReadSortedField(fieldNumber, meta, infos);
}
else if (type == Lucene45DocValuesFormat.SORTED_SET)
{
SortedSetEntry ss = ReadSortedSetEntry(meta);
sortedSets[fieldNumber] = ss;
if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
ReadSortedSetFieldWithAddresses(fieldNumber, meta, infos);
}
else if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED)
{
if (meta.ReadVInt32() != fieldNumber)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
if (meta.ReadByte() != Lucene45DocValuesFormat.SORTED)
{
throw new Exception("sortedset entry for field: " + fieldNumber + " is corrupt (resource=" + meta + ")");
}
ReadSortedField(fieldNumber, meta, infos);
}
else
{
throw new Exception();
}
}
else
{
throw new Exception("invalid type: " + type + ", resource=" + meta);
}
fieldNumber = meta.ReadVInt32();
}
}
internal static NumericEntry ReadNumericEntry(IndexInput meta)
{
NumericEntry entry = new NumericEntry();
entry.format = meta.ReadVInt32();
entry.missingOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.Offset = meta.ReadInt64();
entry.Count = meta.ReadVInt64();
entry.BlockSize = meta.ReadVInt32();
switch (entry.format)
{
case Lucene45DocValuesConsumer.GCD_COMPRESSED:
entry.minValue = meta.ReadInt64();
entry.gcd = meta.ReadInt64();
break;
case Lucene45DocValuesConsumer.TABLE_COMPRESSED:
if (entry.Count > int.MaxValue)
{
throw new Exception("Cannot use TABLE_COMPRESSED with more than MAX_VALUE values, input=" + meta);
}
int uniqueValues = meta.ReadVInt32();
if (uniqueValues > 256)
{
throw new Exception("TABLE_COMPRESSED cannot have more than 256 distinct values, input=" + meta);
}
entry.table = new long[uniqueValues];
for (int i = 0; i < uniqueValues; ++i)
{
entry.table[i] = meta.ReadInt64();
}
break;
case Lucene45DocValuesConsumer.DELTA_COMPRESSED:
break;
default:
throw new Exception("Unknown format: " + entry.format + ", input=" + meta);
}
return entry;
}
internal static BinaryEntry ReadBinaryEntry(IndexInput meta)
{
BinaryEntry entry = new BinaryEntry();
entry.format = meta.ReadVInt32();
entry.missingOffset = meta.ReadInt64();
entry.minLength = meta.ReadVInt32();
entry.maxLength = meta.ReadVInt32();
entry.Count = meta.ReadVInt64();
entry.offset = meta.ReadInt64();
switch (entry.format)
{
case Lucene45DocValuesConsumer.BINARY_FIXED_UNCOMPRESSED:
break;
case Lucene45DocValuesConsumer.BINARY_PREFIX_COMPRESSED:
entry.AddressInterval = meta.ReadVInt32();
entry.AddressesOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
break;
case Lucene45DocValuesConsumer.BINARY_VARIABLE_UNCOMPRESSED:
entry.AddressesOffset = meta.ReadInt64();
entry.PackedInt32sVersion = meta.ReadVInt32();
entry.BlockSize = meta.ReadVInt32();
break;
default:
throw new Exception("Unknown format: " + entry.format + ", input=" + meta);
}
return entry;
}
internal virtual SortedSetEntry ReadSortedSetEntry(IndexInput meta)
{
SortedSetEntry entry = new SortedSetEntry();
if (version >= Lucene45DocValuesFormat.VERSION_SORTED_SET_SINGLE_VALUE_OPTIMIZED)
{
entry.Format = meta.ReadVInt32();
}
else
{
entry.Format = Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES;
}
if (entry.Format != Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED && entry.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
throw new Exception("Unknown format: " + entry.Format + ", input=" + meta);
}
return entry;
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
NumericEntry entry = numerics[field.Number];
return GetNumeric(entry);
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity()
{
if (version >= Lucene45DocValuesFormat.VERSION_CHECKSUM)
{
CodecUtil.ChecksumEntireFile(data);
}
}
internal virtual Int64Values GetNumeric(NumericEntry entry)
{
IndexInput data = (IndexInput)this.data.Clone();
data.Seek(entry.Offset);
switch (entry.format)
{
case Lucene45DocValuesConsumer.DELTA_COMPRESSED:
BlockPackedReader reader = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return reader;
case Lucene45DocValuesConsumer.GCD_COMPRESSED:
long min = entry.minValue;
long mult = entry.gcd;
BlockPackedReader quotientReader = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return new Int64ValuesAnonymousInnerClassHelper(this, min, mult, quotientReader);
case Lucene45DocValuesConsumer.TABLE_COMPRESSED:
long[] table = entry.table;
int bitsRequired = PackedInt32s.BitsRequired(table.Length - 1);
PackedInt32s.Reader ords = PackedInt32s.GetDirectReaderNoHeader(data, PackedInt32s.Format.PACKED, entry.PackedInt32sVersion, (int)entry.Count, bitsRequired);
return new Int64ValuesAnonymousInnerClassHelper2(this, table, ords);
default:
throw new Exception();
}
}
private class Int64ValuesAnonymousInnerClassHelper : Int64Values
{
private readonly Lucene45DocValuesProducer outerInstance;
private long min;
private long mult;
private BlockPackedReader quotientReader;
public Int64ValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long min, long mult, BlockPackedReader quotientReader)
{
this.outerInstance = outerInstance;
this.min = min;
this.mult = mult;
this.quotientReader = quotientReader;
}
public override long Get(long id)
{
return min + mult * quotientReader.Get(id);
}
}
private class Int64ValuesAnonymousInnerClassHelper2 : Int64Values
{
private readonly Lucene45DocValuesProducer outerInstance;
private long[] table;
private PackedInt32s.Reader ords;
public Int64ValuesAnonymousInnerClassHelper2(Lucene45DocValuesProducer outerInstance, long[] table, PackedInt32s.Reader ords)
{
this.outerInstance = outerInstance;
this.table = table;
this.ords = ords;
}
public override long Get(long id)
{
return table[(int)ords.Get((int)id)];
}
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
BinaryEntry bytes = binaries[field.Number];
switch (bytes.format)
{
case Lucene45DocValuesConsumer.BINARY_FIXED_UNCOMPRESSED:
return GetFixedBinary(field, bytes);
case Lucene45DocValuesConsumer.BINARY_VARIABLE_UNCOMPRESSED:
return GetVariableBinary(field, bytes);
case Lucene45DocValuesConsumer.BINARY_PREFIX_COMPRESSED:
return GetCompressedBinary(field, bytes);
default:
throw new Exception();
}
}
private BinaryDocValues GetFixedBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
return new Int64BinaryDocValuesAnonymousInnerClassHelper(this, bytes, data);
}
private class Int64BinaryDocValuesAnonymousInnerClassHelper : Int64BinaryDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private Lucene45DocValuesProducer.BinaryEntry bytes;
private IndexInput data;
public Int64BinaryDocValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, Lucene45DocValuesProducer.BinaryEntry bytes, IndexInput data)
{
this.outerInstance = outerInstance;
this.bytes = bytes;
this.data = data;
}
public override void Get(long id, BytesRef result)
{
long address = bytes.offset + id * bytes.maxLength;
try
{
data.Seek(address);
// NOTE: we could have one buffer, but various consumers (e.g. FieldComparerSource)
// assume "they" own the bytes after calling this!
var buffer = new byte[bytes.maxLength];
data.ReadBytes(buffer, 0, buffer.Length);
result.Bytes = buffer;
result.Offset = 0;
result.Length = buffer.Length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
}
/// <summary>
/// Returns an address instance for variable-length binary values.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetAddressInstance(IndexInput data, FieldInfo field, BinaryEntry bytes)
{
MonotonicBlockPackedReader addresses;
lock (addressInstances)
{
MonotonicBlockPackedReader addrInstance;
if (!addressInstances.TryGetValue(field.Number, out addrInstance) || addrInstance == null)
{
data.Seek(bytes.AddressesOffset);
addrInstance = new MonotonicBlockPackedReader(data, bytes.PackedInt32sVersion, bytes.BlockSize, bytes.Count, false);
addressInstances[field.Number] = addrInstance;
ramBytesUsed.AddAndGet(addrInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
addresses = addrInstance;
}
return addresses;
}
private BinaryDocValues GetVariableBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
MonotonicBlockPackedReader addresses = GetAddressInstance(data, field, bytes);
return new Int64BinaryDocValuesAnonymousInnerClassHelper2(this, bytes, data, addresses);
}
private class Int64BinaryDocValuesAnonymousInnerClassHelper2 : Int64BinaryDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private Lucene45DocValuesProducer.BinaryEntry bytes;
private IndexInput data;
private MonotonicBlockPackedReader addresses;
public Int64BinaryDocValuesAnonymousInnerClassHelper2(Lucene45DocValuesProducer outerInstance, Lucene45DocValuesProducer.BinaryEntry bytes, IndexInput data, MonotonicBlockPackedReader addresses)
{
this.outerInstance = outerInstance;
this.bytes = bytes;
this.data = data;
this.addresses = addresses;
}
public override void Get(long id, BytesRef result)
{
long startAddress = bytes.offset + (id == 0 ? 0 : addresses.Get(id - 1));
long endAddress = bytes.offset + addresses.Get(id);
int length = (int)(endAddress - startAddress);
try
{
data.Seek(startAddress);
// NOTE: we could have one buffer, but various consumers (e.g. FieldComparerSource)
// assume "they" own the bytes after calling this!
var buffer = new byte[length];
data.ReadBytes(buffer, 0, buffer.Length);
result.Bytes = buffer;
result.Offset = 0;
result.Length = length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
}
/// <summary>
/// Returns an address instance for prefix-compressed binary values.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetIntervalInstance(IndexInput data, FieldInfo field, BinaryEntry bytes)
{
MonotonicBlockPackedReader addresses;
long interval = bytes.AddressInterval;
lock (addressInstances)
{
MonotonicBlockPackedReader addrInstance;
if (!addressInstances.TryGetValue(field.Number, out addrInstance))
{
data.Seek(bytes.AddressesOffset);
long size;
if (bytes.Count % interval == 0)
{
size = bytes.Count / interval;
}
else
{
size = 1L + bytes.Count / interval;
}
addrInstance = new MonotonicBlockPackedReader(data, bytes.PackedInt32sVersion, bytes.BlockSize, size, false);
addressInstances[field.Number] = addrInstance;
ramBytesUsed.AddAndGet(addrInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
addresses = addrInstance;
}
return addresses;
}
private BinaryDocValues GetCompressedBinary(FieldInfo field, BinaryEntry bytes)
{
IndexInput data = (IndexInput)this.data.Clone();
MonotonicBlockPackedReader addresses = GetIntervalInstance(data, field, bytes);
return new CompressedBinaryDocValues(bytes, addresses, data);
}
public override SortedDocValues GetSorted(FieldInfo field)
{
int valueCount = (int)binaries[field.Number].Count;
BinaryDocValues binary = GetBinary(field);
NumericEntry entry = ords[field.Number];
IndexInput data = (IndexInput)this.data.Clone();
data.Seek(entry.Offset);
BlockPackedReader ordinals = new BlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, true);
return new SortedDocValuesAnonymousInnerClassHelper(this, valueCount, binary, ordinals);
}
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
private readonly Lucene45DocValuesProducer outerInstance;
private int valueCount;
private BinaryDocValues binary;
private BlockPackedReader ordinals;
public SortedDocValuesAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, int valueCount, BinaryDocValues binary, BlockPackedReader ordinals)
{
this.outerInstance = outerInstance;
this.valueCount = valueCount;
this.binary = binary;
this.ordinals = ordinals;
}
public override int GetOrd(int docID)
{
return (int)ordinals.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
binary.Get(ord, result);
}
public override int ValueCount => valueCount;
public override int LookupTerm(BytesRef key)
{
if (binary is CompressedBinaryDocValues)
{
return (int)((CompressedBinaryDocValues)binary).LookupTerm(key);
}
else
{
return base.LookupTerm(key);
}
}
public override TermsEnum GetTermsEnum()
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).GetTermsEnum();
}
else
{
return base.GetTermsEnum();
}
}
}
/// <summary>
/// Returns an address instance for sortedset ordinal lists.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual MonotonicBlockPackedReader GetOrdIndexInstance(IndexInput data, FieldInfo field, NumericEntry entry)
{
MonotonicBlockPackedReader ordIndex;
lock (ordIndexInstances)
{
MonotonicBlockPackedReader ordIndexInstance;
if (!ordIndexInstances.TryGetValue(field.Number, out ordIndexInstance))
{
data.Seek(entry.Offset);
ordIndexInstance = new MonotonicBlockPackedReader(data, entry.PackedInt32sVersion, entry.BlockSize, entry.Count, false);
ordIndexInstances[field.Number] = ordIndexInstance;
ramBytesUsed.AddAndGet(ordIndexInstance.RamBytesUsed() + RamUsageEstimator.NUM_BYTES_INT32);
}
ordIndex = ordIndexInstance;
}
return ordIndex;
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
SortedSetEntry ss = sortedSets[field.Number];
if (ss.Format == Lucene45DocValuesConsumer.SORTED_SET_SINGLE_VALUED_SORTED)
{
SortedDocValues values = GetSorted(field);
return DocValues.Singleton(values);
}
else if (ss.Format != Lucene45DocValuesConsumer.SORTED_SET_WITH_ADDRESSES)
{
throw new Exception();
}
IndexInput data = (IndexInput)this.data.Clone();
long valueCount = binaries[field.Number].Count;
// we keep the byte[]s and list of ords on disk, these could be large
Int64BinaryDocValues binary = (Int64BinaryDocValues)GetBinary(field);
Int64Values ordinals = GetNumeric(ords[field.Number]);
// but the addresses to the ord stream are in RAM
MonotonicBlockPackedReader ordIndex = GetOrdIndexInstance(data, field, ordIndexes[field.Number]);
return new RandomAccessOrdsAnonymousInnerClassHelper(this, valueCount, binary, ordinals, ordIndex);
}
private class RandomAccessOrdsAnonymousInnerClassHelper : RandomAccessOrds
{
private readonly Lucene45DocValuesProducer outerInstance;
private long valueCount;
private Lucene45DocValuesProducer.Int64BinaryDocValues binary;
private Int64Values ordinals;
private MonotonicBlockPackedReader ordIndex;
public RandomAccessOrdsAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long valueCount, Lucene45DocValuesProducer.Int64BinaryDocValues binary, Int64Values ordinals, MonotonicBlockPackedReader ordIndex)
{
this.outerInstance = outerInstance;
this.valueCount = valueCount;
this.binary = binary;
this.ordinals = ordinals;
this.ordIndex = ordIndex;
}
internal long startOffset;
internal long offset;
internal long endOffset;
public override long NextOrd()
{
if (offset == endOffset)
{
return NO_MORE_ORDS;
}
else
{
long ord = ordinals.Get(offset);
offset++;
return ord;
}
}
public override void SetDocument(int docID)
{
startOffset = offset = (docID == 0 ? 0 : ordIndex.Get(docID - 1));
endOffset = ordIndex.Get(docID);
}
public override void LookupOrd(long ord, BytesRef result)
{
binary.Get(ord, result);
}
public override long ValueCount => valueCount;
public override long LookupTerm(BytesRef key)
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).LookupTerm(key);
}
else
{
return base.LookupTerm(key);
}
}
public override TermsEnum GetTermsEnum()
{
if (binary is CompressedBinaryDocValues)
{
return ((CompressedBinaryDocValues)binary).GetTermsEnum();
}
else
{
return base.GetTermsEnum();
}
}
public override long OrdAt(int index)
{
return ordinals.Get(startOffset + index);
}
public override int Cardinality()
{
return (int)(endOffset - startOffset);
}
}
private IBits GetMissingBits(long offset)
{
if (offset == -1)
{
return new Bits.MatchAllBits(maxDoc);
}
else
{
IndexInput @in = (IndexInput)data.Clone();
return new BitsAnonymousInnerClassHelper(this, offset, @in);
}
}
private class BitsAnonymousInnerClassHelper : IBits
{
private readonly Lucene45DocValuesProducer outerInstance;
private long offset;
private IndexInput @in;
public BitsAnonymousInnerClassHelper(Lucene45DocValuesProducer outerInstance, long offset, IndexInput @in)
{
this.outerInstance = outerInstance;
this.offset = offset;
this.@in = @in;
}
public virtual bool Get(int index)
{
try
{
@in.Seek(offset + (index >> 3));
return (@in.ReadByte() & (1 << (index & 7))) != 0;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public virtual int Length => outerInstance.maxDoc;
}
public override IBits GetDocsWithField(FieldInfo field)
{
switch (field.DocValuesType)
{
case DocValuesType.SORTED_SET:
return DocValues.DocsWithValue(GetSortedSet(field), maxDoc);
case DocValuesType.SORTED:
return DocValues.DocsWithValue(GetSorted(field), maxDoc);
case DocValuesType.BINARY:
BinaryEntry be = binaries[field.Number];
return GetMissingBits(be.missingOffset);
case DocValuesType.NUMERIC:
NumericEntry ne = numerics[field.Number];
return GetMissingBits(ne.missingOffset);
default:
throw new InvalidOperationException();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
data.Dispose();
}
/// <summary>
/// Metadata entry for a numeric docvalues field. </summary>
protected internal class NumericEntry
{
internal NumericEntry()
{
}
/// <summary>
/// Offset to the bitset representing docsWithField, or -1 if no documents have missing values. </summary>
internal long missingOffset;
/// <summary>
/// Offset to the actual numeric values. </summary>
public long Offset { get; set; }
internal int format;
/// <summary>
/// Packed <see cref="int"/>s version used to encode these numerics.
/// <para/>
/// NOTE: This was packedIntsVersion (field) in Lucene
/// </summary>
public int PackedInt32sVersion { get; set; }
/// <summary>
/// Count of values written. </summary>
public long Count { get; set; }
/// <summary>
/// Packed <see cref="int"/>s blocksize. </summary>
public int BlockSize { get; set; }
internal long minValue;
internal long gcd;
internal long[] table;
}
/// <summary>
/// Metadata entry for a binary docvalues field. </summary>
protected internal class BinaryEntry
{
internal BinaryEntry()
{
}
/// <summary>
/// Offset to the bitset representing docsWithField, or -1 if no documents have missing values. </summary>
internal long missingOffset;
/// <summary>
/// Offset to the actual binary values. </summary>
internal long offset;
internal int format;
/// <summary>
/// Count of values written. </summary>
public long Count { get; set; }
internal int minLength;
internal int maxLength;
/// <summary>
/// Offset to the addressing data that maps a value to its slice of the <see cref="T:byte[]"/>. </summary>
public long AddressesOffset { get; set; }
/// <summary>
/// Interval of shared prefix chunks (when using prefix-compressed binary). </summary>
public long AddressInterval { get; set; }
/// <summary>
/// Packed ints version used to encode addressing information.
/// <para/>
/// NOTE: This was packedIntsVersion (field) in Lucene.
/// </summary>
public int PackedInt32sVersion { get; set; }
/// <summary>
/// Packed ints blocksize. </summary>
public int BlockSize { get; set; }
}
/// <summary>
/// Metadata entry for a sorted-set docvalues field. </summary>
protected internal class SortedSetEntry
{
internal SortedSetEntry()
{
}
internal int Format { get; set; }
}
// internally we compose complex dv (sorted/sortedset) from other ones
/// <summary>
/// NOTE: This was LongBinaryDocValues in Lucene.
/// </summary>
internal abstract class Int64BinaryDocValues : BinaryDocValues
{
public override sealed void Get(int docID, BytesRef result)
{
Get((long)docID, result);
}
public abstract void Get(long id, BytesRef result);
}
// in the compressed case, we add a few additional operations for
// more efficient reverse lookup and enumeration
internal class CompressedBinaryDocValues : Int64BinaryDocValues
{
internal readonly BinaryEntry bytes;
internal readonly long interval;
internal readonly long numValues;
internal readonly long numIndexValues;
internal readonly MonotonicBlockPackedReader addresses;
internal readonly IndexInput data;
internal readonly TermsEnum termsEnum;
public CompressedBinaryDocValues(BinaryEntry bytes, MonotonicBlockPackedReader addresses, IndexInput data)
{
this.bytes = bytes;
this.interval = bytes.AddressInterval;
this.addresses = addresses;
this.data = data;
this.numValues = bytes.Count;
this.numIndexValues = addresses.Count;
this.termsEnum = GetTermsEnum(data);
}
public override void Get(long id, BytesRef result)
{
try
{
termsEnum.SeekExact(id);
BytesRef term = termsEnum.Term;
result.Bytes = term.Bytes;
result.Offset = term.Offset;
result.Length = term.Length;
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
internal virtual long LookupTerm(BytesRef key)
{
try
{
TermsEnum.SeekStatus status = termsEnum.SeekCeil(key);
if (status == TermsEnum.SeekStatus.END)
{
return -numValues - 1;
}
else if (status == TermsEnum.SeekStatus.FOUND)
{
return termsEnum.Ord;
}
else
{
return -termsEnum.Ord - 1;
}
}
catch (IOException bogus)
{
throw new Exception(bogus.ToString(), bogus);
}
}
internal virtual TermsEnum GetTermsEnum()
{
try
{
return GetTermsEnum((IndexInput)data.Clone());
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
internal virtual TermsEnum GetTermsEnum(IndexInput input)
{
input.Seek(bytes.offset);
return new TermsEnumAnonymousInnerClassHelper(this, input);
}
private class TermsEnumAnonymousInnerClassHelper : TermsEnum
{
private readonly CompressedBinaryDocValues outerInstance;
private IndexInput input;
public TermsEnumAnonymousInnerClassHelper(CompressedBinaryDocValues outerInstance, IndexInput input)
{
this.outerInstance = outerInstance;
this.input = input;
currentOrd = -1;
termBuffer = new BytesRef(outerInstance.bytes.maxLength < 0 ? 0 : outerInstance.bytes.maxLength);
term = new BytesRef();
}
private long currentOrd;
// TODO: maxLength is negative when all terms are merged away...
private readonly BytesRef termBuffer;
private readonly BytesRef term;
public override BytesRef Next()
{
if (DoNext() == null)
{
return null;
}
else
{
SetTerm();
return term;
}
}
private BytesRef DoNext()
{
if (++currentOrd >= outerInstance.numValues)
{
return null;
}
else
{
int start = input.ReadVInt32();
int suffix = input.ReadVInt32();
input.ReadBytes(termBuffer.Bytes, start, suffix);
termBuffer.Length = start + suffix;
return termBuffer;
}
}
public override TermsEnum.SeekStatus SeekCeil(BytesRef text)
{
// binary-search just the index values to find the block,
// then scan within the block
long low = 0;
long high = outerInstance.numIndexValues - 1;
while (low <= high)
{
long mid = (int)((uint)(low + high) >> 1);
DoSeek(mid * outerInstance.interval);
int cmp = termBuffer.CompareTo(text);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
// we got lucky, found an indexed term
SetTerm();
return TermsEnum.SeekStatus.FOUND;
}
}
if (outerInstance.numIndexValues == 0)
{
return TermsEnum.SeekStatus.END;
}
// block before insertion point
long block = low - 1;
DoSeek(block < 0 ? -1 : block * outerInstance.interval);
while (DoNext() != null)
{
int cmp = termBuffer.CompareTo(text);
if (cmp == 0)
{
SetTerm();
return TermsEnum.SeekStatus.FOUND;
}
else if (cmp > 0)
{
SetTerm();
return TermsEnum.SeekStatus.NOT_FOUND;
}
}
return TermsEnum.SeekStatus.END;
}
public override void SeekExact(long ord)
{
DoSeek(ord);
SetTerm();
}
private void DoSeek(long ord)
{
long block = ord / outerInstance.interval;
if (ord >= currentOrd && block == currentOrd / outerInstance.interval)
{
// seek within current block
}
else
{
// position before start of block
currentOrd = ord - ord % outerInstance.interval - 1;
input.Seek(outerInstance.bytes.offset + outerInstance.addresses.Get(block));
}
while (currentOrd < ord)
{
DoNext();
}
}
private void SetTerm()
{
// TODO: is there a cleaner way
term.Bytes = new byte[termBuffer.Length];
term.Offset = 0;
term.CopyBytes(termBuffer);
}
public override BytesRef Term => term;
public override long Ord => currentOrd;
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override int DocFreq => throw new NotSupportedException();
public override long TotalTermFreq => -1;
public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
throw new NotSupportedException();
}
public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags)
{
throw new NotSupportedException();
}
}
}
}
}
| |
using System;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class encapsulates the Tar Entry Header used in Tar Archives.
/// The class also holds a number of tar constants, used mostly in headers.
/// </summary>
/// <remarks>
/// The tar format and its POSIX successor PAX have a long history which makes for compatability
/// issues when creating and reading files.
///
/// This is further complicated by a large number of programs with variations on formats
/// One common issue is the handling of names longer than 100 characters.
/// GNU style long names are currently supported.
///
/// This is the ustar (Posix 1003.1) header.
///
/// struct header
/// {
/// char t_name[100]; // 0 Filename
/// char t_mode[8]; // 100 Permissions
/// char t_uid[8]; // 108 Numerical User ID
/// char t_gid[8]; // 116 Numerical Group ID
/// char t_size[12]; // 124 Filesize
/// char t_mtime[12]; // 136 st_mtime
/// char t_chksum[8]; // 148 Checksum
/// char t_typeflag; // 156 Type of File
/// char t_linkname[100]; // 157 Target of Links
/// char t_magic[6]; // 257 "ustar" or other...
/// char t_version[2]; // 263 Version fixed to 00
/// char t_uname[32]; // 265 User Name
/// char t_gname[32]; // 297 Group Name
/// char t_devmajor[8]; // 329 Major for devices
/// char t_devminor[8]; // 337 Minor for devices
/// char t_prefix[155]; // 345 Prefix for t_name
/// char t_mfill[12]; // 500 Filler up to 512
/// };
/// </remarks>
public class TarHeader
{
#region Constants
/// <summary>
/// The length of the name field in a header buffer.
/// </summary>
public const int NAMELEN = 100;
/// <summary>
/// The length of the mode field in a header buffer.
/// </summary>
public const int MODELEN = 8;
/// <summary>
/// The length of the user id field in a header buffer.
/// </summary>
public const int UIDLEN = 8;
/// <summary>
/// The length of the group id field in a header buffer.
/// </summary>
public const int GIDLEN = 8;
/// <summary>
/// The length of the checksum field in a header buffer.
/// </summary>
public const int CHKSUMLEN = 8;
/// <summary>
/// Offset of checksum in a header buffer.
/// </summary>
public const int CHKSUMOFS = 148;
/// <summary>
/// The length of the size field in a header buffer.
/// </summary>
public const int SIZELEN = 12;
/// <summary>
/// The length of the magic field in a header buffer.
/// </summary>
public const int MAGICLEN = 6;
/// <summary>
/// The length of the version field in a header buffer.
/// </summary>
public const int VERSIONLEN = 2;
/// <summary>
/// The length of the modification time field in a header buffer.
/// </summary>
public const int MODTIMELEN = 12;
/// <summary>
/// The length of the user name field in a header buffer.
/// </summary>
public const int UNAMELEN = 32;
/// <summary>
/// The length of the group name field in a header buffer.
/// </summary>
public const int GNAMELEN = 32;
/// <summary>
/// The length of the devices field in a header buffer.
/// </summary>
public const int DEVLEN = 8;
/// <summary>
/// The length of the name prefix field in a header buffer.
/// </summary>
public const int PREFIXLEN = 155;
//
// LF_ constants represent the "type" of an entry
//
/// <summary>
/// The "old way" of indicating a normal file.
/// </summary>
public const byte LF_OLDNORM = 0;
/// <summary>
/// Normal file type.
/// </summary>
public const byte LF_NORMAL = (byte)'0';
/// <summary>
/// Link file type.
/// </summary>
public const byte LF_LINK = (byte)'1';
/// <summary>
/// Symbolic link file type.
/// </summary>
public const byte LF_SYMLINK = (byte)'2';
/// <summary>
/// Character device file type.
/// </summary>
public const byte LF_CHR = (byte)'3';
/// <summary>
/// Block device file type.
/// </summary>
public const byte LF_BLK = (byte)'4';
/// <summary>
/// Directory file type.
/// </summary>
public const byte LF_DIR = (byte)'5';
/// <summary>
/// FIFO (pipe) file type.
/// </summary>
public const byte LF_FIFO = (byte)'6';
/// <summary>
/// Contiguous file type.
/// </summary>
public const byte LF_CONTIG = (byte)'7';
/// <summary>
/// Posix.1 2001 global extended header
/// </summary>
public const byte LF_GHDR = (byte)'g';
/// <summary>
/// Posix.1 2001 extended header
/// </summary>
public const byte LF_XHDR = (byte)'x';
// POSIX allows for upper case ascii type as extensions
/// <summary>
/// Solaris access control list file type
/// </summary>
public const byte LF_ACL = (byte)'A';
/// <summary>
/// GNU dir dump file type
/// This is a dir entry that contains the names of files that were in the
/// dir at the time the dump was made
/// </summary>
public const byte LF_GNU_DUMPDIR = (byte)'D';
/// <summary>
/// Solaris Extended Attribute File
/// </summary>
public const byte LF_EXTATTR = (byte)'E';
/// <summary>
/// Inode (metadata only) no file content
/// </summary>
public const byte LF_META = (byte)'I';
/// <summary>
/// Identifies the next file on the tape as having a long link name
/// </summary>
public const byte LF_GNU_LONGLINK = (byte)'K';
/// <summary>
/// Identifies the next file on the tape as having a long name
/// </summary>
public const byte LF_GNU_LONGNAME = (byte)'L';
/// <summary>
/// Continuation of a file that began on another volume
/// </summary>
public const byte LF_GNU_MULTIVOL = (byte)'M';
/// <summary>
/// For storing filenames that dont fit in the main header (old GNU)
/// </summary>
public const byte LF_GNU_NAMES = (byte)'N';
/// <summary>
/// GNU Sparse file
/// </summary>
public const byte LF_GNU_SPARSE = (byte)'S';
/// <summary>
/// GNU Tape/volume header ignore on extraction
/// </summary>
public const byte LF_GNU_VOLHDR = (byte)'V';
/// <summary>
/// The magic tag representing a POSIX tar archive. (would be written with a trailing NULL)
/// </summary>
public const string TMAGIC = "ustar";
/// <summary>
/// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it
/// </summary>
public const string GNU_TMAGIC = "ustar ";
private const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds
private static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
#endregion Constants
#region Constructors
/// <summary>
/// Initialise a default TarHeader instance
/// </summary>
public TarHeader()
{
Magic = TMAGIC;
Version = " ";
Name = "";
LinkName = "";
UserId = defaultUserId;
GroupId = defaultGroupId;
UserName = defaultUser;
GroupName = defaultGroupName;
Size = 0;
}
#endregion Constructors
#region Properties
/// <summary>
/// Get/set the name for this tar entry.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set the property to null.</exception>
public string Name
{
get { return name; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
name = value;
}
}
/// <summary>
/// Get the name of this entry.
/// </summary>
/// <returns>The entry's name.</returns>
[Obsolete("Use the Name property instead", true)]
public string GetName()
{
return name;
}
/// <summary>
/// Get/set the entry's Unix style permission mode.
/// </summary>
public int Mode
{
get { return mode; }
set { mode = value; }
}
/// <summary>
/// The entry's user id.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// The default is zero.
/// </remarks>
public int UserId
{
get { return userId; }
set { userId = value; }
}
/// <summary>
/// Get/set the entry's group id.
/// </summary>
/// <remarks>
/// This is only directly relevant to linux/unix systems.
/// The default value is zero.
/// </remarks>
public int GroupId
{
get { return groupId; }
set { groupId = value; }
}
/// <summary>
/// Get/set the entry's size.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the size to less than zero.</exception>
public long Size
{
get { return size; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Cannot be less than zero");
}
size = value;
}
}
/// <summary>
/// Get/set the entry's modification time.
/// </summary>
/// <remarks>
/// The modification time is only accurate to within a second.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown when setting the date time to less than 1/1/1970.</exception>
public DateTime ModTime
{
get { return modTime; }
set
{
if (value < dateTime1970)
{
throw new ArgumentOutOfRangeException(nameof(value), "ModTime cannot be before Jan 1st 1970");
}
modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second);
}
}
/// <summary>
/// Get the entry's checksum. This is only valid/updated after writing or reading an entry.
/// </summary>
public int Checksum
{
get { return checksum; }
}
/// <summary>
/// Get value of true if the header checksum is valid, false otherwise.
/// </summary>
public bool IsChecksumValid
{
get { return isChecksumValid; }
}
/// <summary>
/// Get/set the entry's type flag.
/// </summary>
public byte TypeFlag
{
get { return typeFlag; }
set { typeFlag = value; }
}
/// <summary>
/// The entry's link name.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set LinkName to null.</exception>
public string LinkName
{
get { return linkName; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
linkName = value;
}
}
/// <summary>
/// Get/set the entry's magic tag.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Magic to null.</exception>
public string Magic
{
get { return magic; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
magic = value;
}
}
/// <summary>
/// The entry's version.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown when attempting to set Version to null.</exception>
public string Version
{
get
{
return version;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
version = value;
}
}
/// <summary>
/// The entry's user name.
/// </summary>
public string UserName
{
get { return userName; }
set
{
if (value != null)
{
userName = value.Substring(0, Math.Min(UNAMELEN, value.Length));
}
else
{
string currentUser = "user";
if (currentUser.Length > UNAMELEN)
{
currentUser = currentUser.Substring(0, UNAMELEN);
}
userName = currentUser;
}
}
}
/// <summary>
/// Get/set the entry's group name.
/// </summary>
/// <remarks>
/// This is only directly relevant to unix systems.
/// </remarks>
public string GroupName
{
get { return groupName; }
set
{
if (value == null)
{
groupName = "None";
}
else
{
groupName = value;
}
}
}
/// <summary>
/// Get/set the entry's major device number.
/// </summary>
public int DevMajor
{
get { return devMajor; }
set { devMajor = value; }
}
/// <summary>
/// Get/set the entry's minor device number.
/// </summary>
public int DevMinor
{
get { return devMinor; }
set { devMinor = value; }
}
#endregion Properties
#region ICloneable Members
/// <summary>
/// Create a new <see cref="TarHeader"/> that is a copy of the current instance.
/// </summary>
/// <returns>A new <see cref="Object"/> that is a copy of the current instance.</returns>
public object Clone()
{
return this.MemberwiseClone();
}
#endregion ICloneable Members
/// <summary>
/// Parse TarHeader information from a header buffer.
/// </summary>
/// <param name = "header">
/// The tar entry header buffer to get information from.
/// </param>
public void ParseBuffer(byte[] header)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
int offset = 0;
name = ParseName(header, offset, NAMELEN).ToString();
offset += NAMELEN;
mode = (int)ParseOctal(header, offset, MODELEN);
offset += MODELEN;
UserId = (int)ParseOctal(header, offset, UIDLEN);
offset += UIDLEN;
GroupId = (int)ParseOctal(header, offset, GIDLEN);
offset += GIDLEN;
Size = ParseBinaryOrOctal(header, offset, SIZELEN);
offset += SIZELEN;
ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN));
offset += MODTIMELEN;
checksum = (int)ParseOctal(header, offset, CHKSUMLEN);
offset += CHKSUMLEN;
TypeFlag = header[offset++];
LinkName = ParseName(header, offset, NAMELEN).ToString();
offset += NAMELEN;
Magic = ParseName(header, offset, MAGICLEN).ToString();
offset += MAGICLEN;
if (Magic == "ustar")
{
Version = ParseName(header, offset, VERSIONLEN).ToString();
offset += VERSIONLEN;
UserName = ParseName(header, offset, UNAMELEN).ToString();
offset += UNAMELEN;
GroupName = ParseName(header, offset, GNAMELEN).ToString();
offset += GNAMELEN;
DevMajor = (int)ParseOctal(header, offset, DEVLEN);
offset += DEVLEN;
DevMinor = (int)ParseOctal(header, offset, DEVLEN);
offset += DEVLEN;
string prefix = ParseName(header, offset, PREFIXLEN).ToString();
if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name;
}
isChecksumValid = Checksum == TarHeader.MakeCheckSum(header);
}
/// <summary>
/// 'Write' header information to buffer provided, updating the <see cref="Checksum">check sum</see>.
/// </summary>
/// <param name="outBuffer">output buffer for header information</param>
public void WriteHeader(byte[] outBuffer)
{
if (outBuffer == null)
{
throw new ArgumentNullException(nameof(outBuffer));
}
int offset = 0;
offset = GetNameBytes(Name, outBuffer, offset, NAMELEN);
offset = GetOctalBytes(mode, outBuffer, offset, MODELEN);
offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN);
offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN);
offset = GetBinaryOrOctalBytes(Size, outBuffer, offset, SIZELEN);
offset = GetOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN);
int csOffset = offset;
for (int c = 0; c < CHKSUMLEN; ++c)
{
outBuffer[offset++] = (byte)' ';
}
outBuffer[offset++] = TypeFlag;
offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN);
offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN);
offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN);
offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN);
offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN);
if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK))
{
offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN);
offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN);
}
for (; offset < outBuffer.Length;)
{
outBuffer[offset++] = 0;
}
checksum = ComputeCheckSum(outBuffer);
GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN);
isChecksumValid = true;
}
/// <summary>
/// Get a hash code for the current object.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Determines if this instance is equal to the specified object.
/// </summary>
/// <param name="obj">The object to compare with.</param>
/// <returns>true if the objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
var localHeader = obj as TarHeader;
bool result;
if (localHeader != null)
{
result = (name == localHeader.name)
&& (mode == localHeader.mode)
&& (UserId == localHeader.UserId)
&& (GroupId == localHeader.GroupId)
&& (Size == localHeader.Size)
&& (ModTime == localHeader.ModTime)
&& (Checksum == localHeader.Checksum)
&& (TypeFlag == localHeader.TypeFlag)
&& (LinkName == localHeader.LinkName)
&& (Magic == localHeader.Magic)
&& (Version == localHeader.Version)
&& (UserName == localHeader.UserName)
&& (GroupName == localHeader.GroupName)
&& (DevMajor == localHeader.DevMajor)
&& (DevMinor == localHeader.DevMinor);
}
else
{
result = false;
}
return result;
}
/// <summary>
/// Set defaults for values used when constructing a TarHeader instance.
/// </summary>
/// <param name="userId">Value to apply as a default for userId.</param>
/// <param name="userName">Value to apply as a default for userName.</param>
/// <param name="groupId">Value to apply as a default for groupId.</param>
/// <param name="groupName">Value to apply as a default for groupName.</param>
static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName)
{
defaultUserId = userIdAsSet = userId;
defaultUser = userNameAsSet = userName;
defaultGroupId = groupIdAsSet = groupId;
defaultGroupName = groupNameAsSet = groupName;
}
static internal void RestoreSetValues()
{
defaultUserId = userIdAsSet;
defaultUser = userNameAsSet;
defaultGroupId = groupIdAsSet;
defaultGroupName = groupNameAsSet;
}
// Return value that may be stored in octal or binary. Length must exceed 8.
//
static private long ParseBinaryOrOctal(byte[] header, int offset, int length)
{
if (header[offset] >= 0x80)
{
// File sizes over 8GB are stored in 8 right-justified bytes of binary indicated by setting the high-order bit of the leftmost byte of a numeric field.
long result = 0;
for (int pos = length - 8; pos < length; pos++)
{
result = result << 8 | header[offset + pos];
}
return result;
}
return ParseOctal(header, offset, length);
}
/// <summary>
/// Parse an octal string from a header buffer.
/// </summary>
/// <param name = "header">The header buffer from which to parse.</param>
/// <param name = "offset">The offset into the buffer from which to parse.</param>
/// <param name = "length">The number of header bytes to parse.</param>
/// <returns>The long equivalent of the octal string.</returns>
static public long ParseOctal(byte[] header, int offset, int length)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
long result = 0;
bool stillPadding = true;
int end = offset + length;
for (int i = offset; i < end; ++i)
{
if (header[i] == 0)
{
break;
}
if (header[i] == (byte)' ' || header[i] == '0')
{
if (stillPadding)
{
continue;
}
if (header[i] == (byte)' ')
{
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
}
/// <summary>
/// Parse a name from a header buffer.
/// </summary>
/// <param name="header">
/// The header buffer from which to parse.
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to parse.
/// </param>
/// <param name="length">
/// The number of header bytes to parse.
/// </param>
/// <returns>
/// The name parsed.
/// </returns>
static public StringBuilder ParseName(byte[] header, int offset, int length)
{
if (header == null)
{
throw new ArgumentNullException(nameof(header));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be less than zero");
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), "Cannot be less than zero");
}
if (offset + length > header.Length)
{
throw new ArgumentException("Exceeds header size", nameof(length));
}
var result = new StringBuilder(length);
for (int i = offset; i < offset + length; ++i)
{
if (header[i] == 0)
{
break;
}
result.Append((char)header[i]);
}
return result;
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length);
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="nameOffset">The offset of the first character</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="bufferOffset">The index of the first byte to add</param>
/// <param name="length">The number of characters/bytes to add</param>
/// <returns>The next free index in the <paramref name="buffer"/></returns>
public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
int i;
for (i = 0; i < length && nameOffset + i < name.Length; ++i)
{
buffer[bufferOffset + i] = (byte)name[nameOffset + i];
}
for (; i < length; ++i)
{
buffer[bufferOffset + i] = 0;
}
return bufferOffset + length;
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">
/// The name to add
/// </param>
/// <param name="buffer">
/// The buffer to add to
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to start adding
/// </param>
/// <param name="length">
/// The number of header bytes to add
/// </param>
/// <returns>
/// The index of the next free byte in the buffer
/// </returns>
public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
return GetNameBytes(name.ToString(), 0, buffer, offset, length);
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">The name to add</param>
/// <param name="buffer">The buffer to add to</param>
/// <param name="offset">The offset into the buffer from which to start adding</param>
/// <param name="length">The number of header bytes to add</param>
/// <returns>The index of the next free byte in the buffer</returns>
public static int GetNameBytes(string name, byte[] buffer, int offset, int length)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
return GetNameBytes(name, 0, buffer, offset, length);
}
/// <summary>
/// Add a string to a buffer as a collection of ascii bytes.
/// </summary>
/// <param name="toAdd">The string to add</param>
/// <param name="nameOffset">The offset of the first character to add.</param>
/// <param name="buffer">The buffer to add to.</param>
/// <param name="bufferOffset">The offset to start adding at.</param>
/// <param name="length">The number of ascii characters to add.</param>
/// <returns>The next free index in the buffer.</returns>
public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length)
{
if (toAdd == null)
{
throw new ArgumentNullException(nameof(toAdd));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
int i;
for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i)
{
buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i];
}
// If length is beyond the toAdd string length (which is OK by the prev loop condition), eg if a field has fixed length and the string is shorter, make sure all of the extra chars are written as NULLs, so that the reader func would ignore them and get back the original string
for (; i < length; ++i)
buffer[bufferOffset + i] = 0;
return bufferOffset + length;
}
/// <summary>
/// Put an octal representation of a value into a buffer
/// </summary>
/// <param name = "value">
/// the value to be converted to octal
/// </param>
/// <param name = "buffer">
/// buffer to store the octal string
/// </param>
/// <param name = "offset">
/// The offset into the buffer where the value starts
/// </param>
/// <param name = "length">
/// The length of the octal string to create
/// </param>
/// <returns>
/// The offset of the character next byte after the octal string
/// </returns>
public static int GetOctalBytes(long value, byte[] buffer, int offset, int length)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
int localIndex = length - 1;
// Either a space or null is valid here. We use NULL as per GNUTar
buffer[offset + localIndex] = 0;
--localIndex;
if (value > 0)
{
for (long v = value; (localIndex >= 0) && (v > 0); --localIndex)
{
buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7));
v >>= 3;
}
}
for (; localIndex >= 0; --localIndex)
{
buffer[offset + localIndex] = (byte)'0';
}
return offset + length;
}
/// <summary>
/// Put an octal or binary representation of a value into a buffer
/// </summary>
/// <param name = "value">Value to be convert to octal</param>
/// <param name = "buffer">The buffer to update</param>
/// <param name = "offset">The offset into the buffer to store the value</param>
/// <param name = "length">The length of the octal string. Must be 12.</param>
/// <returns>Index of next byte</returns>
private static int GetBinaryOrOctalBytes(long value, byte[] buffer, int offset, int length)
{
if (value > 0x1FFFFFFFF)
{ // Octal 77777777777 (11 digits)
// Put value as binary, right-justified into the buffer. Set high order bit of left-most byte.
for (int pos = length - 1; pos > 0; pos--)
{
buffer[offset + pos] = (byte)value;
value = value >> 8;
}
buffer[offset] = 0x80;
return offset + length;
}
return GetOctalBytes(value, buffer, offset, length);
}
/// <summary>
/// Add the checksum integer to header buffer.
/// </summary>
/// <param name = "value"></param>
/// <param name = "buffer">The header buffer to set the checksum for</param>
/// <param name = "offset">The offset into the buffer for the checksum</param>
/// <param name = "length">The number of header bytes to update.
/// It's formatted differently from the other fields: it has 6 digits, a
/// null, then a space -- rather than digits, a space, then a null.
/// The final space is already there, from checksumming
/// </param>
/// <returns>The modified buffer offset</returns>
private static void GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length)
{
GetOctalBytes(value, buffer, offset, length - 1);
}
/// <summary>
/// Compute the checksum for a tar entry header.
/// The checksum field must be all spaces prior to this happening
/// </summary>
/// <param name = "buffer">The tar entry's header buffer.</param>
/// <returns>The computed checksum.</returns>
private static int ComputeCheckSum(byte[] buffer)
{
int sum = 0;
for (int i = 0; i < buffer.Length; ++i)
{
sum += buffer[i];
}
return sum;
}
/// <summary>
/// Make a checksum for a tar entry ignoring the checksum contents.
/// </summary>
/// <param name = "buffer">The tar entry's header buffer.</param>
/// <returns>The checksum for the buffer</returns>
private static int MakeCheckSum(byte[] buffer)
{
int sum = 0;
for (int i = 0; i < CHKSUMOFS; ++i)
{
sum += buffer[i];
}
for (int i = 0; i < CHKSUMLEN; ++i)
{
sum += (byte)' ';
}
for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i)
{
sum += buffer[i];
}
return sum;
}
private static int GetCTime(DateTime dateTime)
{
return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor));
}
private static DateTime GetDateTimeFromCTime(long ticks)
{
DateTime result;
try
{
result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor);
}
catch (ArgumentOutOfRangeException)
{
result = dateTime1970;
}
return result;
}
#region Instance Fields
private string name;
private int mode;
private int userId;
private int groupId;
private long size;
private DateTime modTime;
private int checksum;
private bool isChecksumValid;
private byte typeFlag;
private string linkName;
private string magic;
private string version;
private string userName;
private string groupName;
private int devMajor;
private int devMinor;
#endregion Instance Fields
#region Class Fields
// Values used during recursive operations.
static internal int userIdAsSet;
static internal int groupIdAsSet;
static internal string userNameAsSet;
static internal string groupNameAsSet = "None";
static internal int defaultUserId;
static internal int defaultGroupId;
static internal string defaultGroupName = "None";
static internal string defaultUser;
#endregion Class Fields
}
}
| |
// ============================================================
// Name: UMABonePoseMixerWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
namespace UMA.PoseTools
{
public class UMABonePoseMixerWindow : EditorWindow
{
public Transform skeleton = null;
public UnityEngine.Object poseFolder = null;
public UMABonePose newComponent = null;
public string poseName = "";
private Dictionary<UMABonePose, float> poseComponents = new Dictionary<UMABonePose, float>();
private Dictionary<string, float> boneComponents = new Dictionary<string, float>();
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
Transform newSkeleton = EditorGUILayout.ObjectField("Rig Prefab", skeleton, typeof(Transform), true) as Transform;
if (skeleton != newSkeleton)
{
skeleton = newSkeleton;
boneComponents = new Dictionary<string, float>();
Transform[] transforms = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (Transform bone in transforms)
{
boneComponents.Add(bone.name, 1f);
}
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Poses");
EditorGUI.indentLevel++;
UMABonePose changedPose = null;
UMABonePose deletedPose = null;
float sliderVal = 0;
List<string> activeBones = new List<string>();
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
GUILayout.BeginHorizontal();
sliderVal = EditorGUILayout.Slider(entry.Key.name, entry.Value, 0f, 2f);
if (sliderVal != entry.Value)
{
changedPose = entry.Key;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = entry.Key;
}
else
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (!activeBones.Contains(pose.bone))
{
activeBones.Add(pose.bone);
}
}
}
GUILayout.EndHorizontal();
}
if (changedPose != null)
{
poseComponents[changedPose] = sliderVal;
}
if (deletedPose != null)
{
poseComponents.Remove(deletedPose);
}
GUILayout.BeginHorizontal();
newComponent = EditorGUILayout.ObjectField(newComponent, typeof(UMABonePose), false) as UMABonePose;
GUI.enabled = (newComponent != null);
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poseComponents.Add(newComponent, 1f);
newComponent = null;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Bones");
EditorGUI.indentLevel++;
foreach (string bone in activeBones)
{
GUILayout.BeginHorizontal();
if (boneComponents.ContainsKey(bone))
{
boneComponents[bone] = EditorGUILayout.Slider(bone, boneComponents[bone], 0f, 2f);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Left"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 1f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 0f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Right"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 0f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 1f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Mirror"))
{
foreach (string bone in activeBones)
{
boneComponents[bone] = Mathf.Max(1f - boneComponents[bone], 0f);
}
if (poseName.EndsWith("_L"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "R";
}
else if (poseName.EndsWith("_R"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "L";
}
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
GUILayout.BeginHorizontal();
poseName = EditorGUILayout.TextField("New Pose", poseName);
if ((skeleton == null) || (poseFolder == null) || (poseComponents.Count < 1) || (poseName.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build", GUILayout.Width(60f)))
{
string folderPath = AssetDatabase.GetAssetPath(poseFolder);
UMABonePose newPose = CreatePoseAsset(folderPath, poseName);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (string bone in activeBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone);
if (source != null)
{
Vector3 position = source.localPosition;
Quaternion rotation = source.localRotation;
Vector3 scale = source.localScale;
bool include = false;
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
float strength = entry.Value * boneComponents[bone];
if (strength > 0f)
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (pose.bone == bone)
{
position += pose.position * strength;
Quaternion posedRotation = rotation * pose.rotation;
rotation = Quaternion.Slerp(rotation, posedRotation, strength);
scale = Vector3.Slerp(scale, pose.scale, strength);
}
}
include = true;
}
}
if (include)
{
newPose.AddBone(source, position, rotation, scale);
}
}
else
{
Debug.LogWarning("Bone not found in skeleton: " + bone);
}
}
EditorUtility.SetDirty(newPose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
return asset;
}
[MenuItem("UMA/Pose Tools/UMA Bone Pose Mixer")]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseMixerWindow));
#if !UNITY_4_6 && !UNITY_5_0
win.titleContent.text = "Pose Mixer";
#else
win.title = "Pose Mixer";
#endif
}
}
}
#endif
| |
/*
* MindTouch MediaWiki Converter
* Copyright (C) 2006-2008 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* http://www.gnu.org/copyleft/lesser.html
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using MindTouch.Deki;
using MindTouch.Deki.Converter;
using MindTouch.Deki.Data;
using MindTouch.Deki.Logic;
using MindTouch.Dream;
using MindTouch.Tasking;
using Mindtouch.Tools;
using MindTouch.Xml;
namespace MindTouch.Tools {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch MediWiki Converter Service", "MindTouch Inc. 2006",
SID = new string[] { "http://services.mindtouch.com/deki/internal/2007/12/mediawiki-converter" }
)]
[DreamServiceConfig("db-mwconnection", "string?", "MediaWiki database connection string.")]
class MediaWikiConverterService : DekiWikiService {
private const string REDIRECT_TEXT = "#REDIRECT [[{0}]]";
private static Regex PARAM_REGEX = new Regex(@"\{\{\{((?<intValue>\d+)|(?<namedValue>[^\{\}]+))\}\}\}", RegexOptions.Compiled);
private static Regex VARIABLE_REGEX = new Regex(@"^(CURRENTDAY|CURRENTDAY2|CURRENTDAYNAME|CURRENTDOW|CURRENTMONTH|CURRENTMONTHABBREV|CURRENTMONTHNAME|CURRENTTIME|CURRENTHOUR|CURRENTWEEK|CURRENTYEAR|CURRENTTIMESTAMP|PAGENAME|NUMBEROFARTICLES|NUMBEROFUSERS|NAMESPACE|REVISIONDAY|REVISIONDAY2|REVISIONMONTH|REVISIONYEAR|REVISIONTIMESTAMP|SITENAME|SERVER|SERVERNAME)$", RegexOptions.Compiled);
Dictionary<string, string> _MWToDWUserNameMap = new Dictionary<string, string>();
Dictionary<string, ulong> _MWToDWOldIDMap = new Dictionary<string, ulong>();
Dictionary<string, ulong> _MWToDWPageIDMap = new Dictionary<string, ulong>();
Dictionary<Site, string> _MWInterwikiBySite;
XDoc log = new XDoc("html");
public override DreamFeatureStage[] Prologues {
get {
return new DreamFeatureStage[] {
new DreamFeatureStage("set-deki-context", this.PrologueDekiContext, DreamAccess.Public),
new DreamFeatureStage("set-mediawikiconverter-context", this.PrologueMediaWikiConverterContext, DreamAccess.Public)
};
}
}
public override DreamFeatureStage[] Epilogues {
get {
return new DreamFeatureStage[] { };
}
}
private Yield PrologueMediaWikiConverterContext(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
MediaWikiConverterContext mwContext = new MediaWikiConverterContext(Config);
DreamContext.Current.SetState<MediaWikiConverterContext>(mwContext);
// continue processing
response.Return(request);
yield break;
}
public string OriginalTemplateDir {
get {
return Path.Combine(MediaWikiConverterContext.Current.MWTemplatePath, "Original");
}
}
public string OverrideTemplateDir {
get {
return Path.Combine(MediaWikiConverterContext.Current.MWTemplatePath, "Override");
}
}
public string GetTemplateFilename(Title title) {
return String.Format("{0}.txt", title.Path.ToString());
}
/// <summary>
/// Indicates which page to keep, given a group of pages with the same title but different case.
/// All other pages will be discarded
/// </summary>
/// <param name="pages">Group of pages with the same title</param>
/// <returns>The page to keep</returns>
public PageBE GetPredominantPage(List<PageBE> pages) {
PageBE predominantPage = pages[0];
foreach (PageBE page in pages) {
if (((predominantPage.IsRedirect == page.IsRedirect) && (page.TimeStamp > predominantPage.TimeStamp)) || (predominantPage.IsRedirect && !page.IsRedirect)) {
predominantPage = page;
}
}
return predominantPage;
}
public bool CreateLanguageHierarchyForNS(NS ns) {
// create a namespace heirarchy for everything but the user and template namespaces
return (NS.USER != ns && NS.USER_TALK != ns && NS.TEMPLATE != ns && NS.TEMPLATE_TALK != ns && NS.SPECIAL != ns);
}
/// <summary>
/// Converts a MediaWiki title to its MindTouch format
/// </summary>
/// <param name="mwTitle">The title to convert</param>
/// <returns>The converted title</returns>
public Title MWToDWTitle(Site site, Title mwTitle) {
return MWToDWTitle(site, mwTitle, true);
}
/// <summary>
/// Converts a MediaWiki title to its MindTouch format
/// </summary>
/// <param name="mwTitle">The title to convert</param>
/// <param name="replaceSeparator">If true, replace ":" with "/"</param>
/// <returns>The converted title</returns>
public Title MWToDWTitle(Site site, Title mwTitle, bool useNewFormat) {
string dbPrefix = null;
string dbPath = mwTitle.AsUnprefixedDbPath();
string displayName = mwTitle.DisplayName;
// create a language heirarchy in the main namespaces
if (CreateLanguageHierarchyForNS(mwTitle.Namespace)) {
dbPrefix = site.DWRootPage + "/";
if (site.MWRootPage == mwTitle.Path && useNewFormat) {
displayName = displayName ?? mwTitle.AsUserFriendlyName();
dbPath = String.Empty;
}
}
// prefix template pages with language to make unique accross langauges
else if (mwTitle.IsTemplate || NS.TEMPLATE_TALK == mwTitle.Namespace || mwTitle.IsSpecial) {
return mwTitle;
}
// if this is a user page that corresponds to a renamed user, rename the page.
else if (mwTitle.IsUser || NS.USER_TALK == mwTitle.Namespace) {
string parentSegment = mwTitle.AsUnprefixedDbSegments()[0];
string newParentSegment;
if (_MWToDWUserNameMap.TryGetValue(parentSegment, out newParentSegment)) {
dbPath = newParentSegment + mwTitle.Path.Substring(newParentSegment.Length - 1);
}
}
if ('/' != MediaWikiConverterContext.Current.MWPageSeparator) {
dbPath = dbPath.Replace("/", "//");
// If desired, replace the page separator with "/"
if (useNewFormat && 0 < MediaWikiConverterContext.Current.MWPageSeparator) {
String[] segments = dbPath.Split(MediaWikiConverterContext.Current.MWPageSeparator);
if (1 < segments.Length) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < segments.Length; i++) {
if ((0 < i && !String.IsNullOrEmpty(segments[i - 1])) &&
!(i == segments.Length - 1 && String.IsNullOrEmpty(segments[i]))) {
result.Append("/");
}
if (String.IsNullOrEmpty(segments[i])) {
result.Append(MediaWikiConverterContext.Current.MWPageSeparator);
} else {
result.Append(segments[i].Trim(new char[] { '_' }));
}
}
dbPath = result.ToString();
}
}
}
dbPath = dbPrefix + dbPath;
return Title.FromDbPath(mwTitle.Namespace, dbPath.Trim('/'), displayName, mwTitle.Filename, mwTitle.Anchor, mwTitle.Query);
}
public void MWToDWTitles(Site site, PageBE page, bool isOld, XDoc xml) {
// set the display name to the title-override value
page.Title.DisplayName = xml["//mediawiki:extension[@function='title-override']"].AsText;
// map each page include to its new MindTouch location
foreach (XDoc template in xml["//mediawiki:template"].ToList()) {
XDoc templateName = template["mediawiki:name"];
if (0 == templateName.Elements.ListLength) {
string pagePath = template["mediawiki:name"].Contents.Trim();
if (pagePath.StartsWith(":")) {
Title mwTitle = Title.FromUIUri(null, pagePath.Substring(1), false);
templateName.ReplaceValue(":" + MWToDWTitle(site, mwTitle).AsPrefixedDbPath());
} else {
Title mwTitle = null;
mwTitle = Title.FromUIUri(null, pagePath, false);
mwTitle.Namespace = NS.TEMPLATE;
templateName.ReplaceValue(MWToDWTitle(site, mwTitle).AsUnprefixedDbPath());
}
}
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
// log all template references
StringBuilder templateString = new StringBuilder();
templateString.Append(template["mediawiki:name"].AsText);
templateString.Append('(');
bool isFirstArg = true;
foreach (XDoc templateArg in template["mediawiki:arg"]) {
if (!isFirstArg) {
templateString.Append(", ");
} else {
isFirstArg = false;
}
templateString.Append(templateArg.Contents);
}
templateString.Append(")");
log["/html/body/table[@id='templates']"].Add(new XDoc("tr").Elem("td", (isOld ? String.Format("Revision ({0}): ", page.TimeStamp) : String.Empty) + MWToDWTitle(site, page.Title).AsPrefixedDbPath()).Elem("td", templateString.ToString()));
}
#endregion
}
foreach (XDoc function in xml["//mediawiki:function"].ToList()) {
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
// log all function references
if (!page.Title.IsTemplate) {
string functionString = String.Format("{0}({1})", function["@name"].AsText, function["@arg"].Contents);
log["/html/body/table[@id='functions']"].Add(new XDoc("tr").Elem("td", (isOld ? String.Format("Revision ({0}): ", page.TimeStamp) : String.Empty) + MWToDWTitle(site, page.Title).AsPrefixedDbPath()).Elem("td", functionString));
}
}
#endregion
}
// map links to pages on the wiki in a different language to internal links
foreach (XDoc link in xml["//mediawiki:link[@type='external']"].ToList()) {
string href = link["@href"].Contents;
XUri xuri;
if (XUri.TryParse(href, out xuri)) {
if ("lang" == xuri.Scheme.ToLowerInvariant()) {
link.Attr("type", "internal");
}
}
}
// map file links to image links
foreach (XDoc link in xml["//mediawiki:link[@type='file']"].ToList()) {
link.Attr("ns", 6);
link.Attr("type", "internal");
link.Attr("href", "Image:" + link["@href"].Contents);
}
// map each internal link to its new MindTouch location
foreach (XDoc link in xml["//mediawiki:link[@type='internal']"].ToList()) {
Site linkSite = site;
// if this is a link to a page on the wiki in a different language, map it accordingly
XUri xuri;
if (XUri.TryParse(link["@href"].Contents, out xuri)) {
if ("lang" == xuri.Scheme.ToLowerInvariant()) {
linkSite = MediaWikiConverterContext.Current.GetMWSite(xuri.Authority);
link.Attr("href", xuri.PathQueryFragment);
}
}
Title dwTitle = Title.FromUIUri(page.Title, link["@href"].Contents);
switch (link["@ns"].AsInt) {
case -1:
dwTitle = Title.FromUIUri(page.Title, XUri.Decode(link["@href"].Contents));
dwTitle = MWToDWTitle(linkSite, dwTitle);
#region logging
PageBE specialPage = PageBL.GetPageByTitle(dwTitle);
if ((specialPage == null || specialPage.ID == 0) && !StringUtil.StartsWithInvariantIgnoreCase(dwTitle.Path, "Contributions/")) {
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='specialpages']"].Add(new XDoc("tr").Elem("td", MWToDWTitle(site, page.Title).AsPrefixedDbPath()).Elem("td", dwTitle.AsPrefixedDbPath()));
}
}
#endregion
break;
// media links are remapped to the a link to the image on the media gallery
case 6:
case 7:
string filename = dwTitle.Path.Substring(6);
dwTitle = DWMediaGalleryTitle(linkSite);
dwTitle.Filename = filename;
break;
// category links are remapped to Special:Tags
case 14:
case 15:
if (string.IsNullOrEmpty(link.Contents)) {
link.ReplaceValue(dwTitle.AsUserFriendlyName());
}
dwTitle = Title.FromDbPath(NS.SPECIAL, "Tags", null, null, null, String.Format("tag={0}&language={1}", dwTitle.Path.Substring(9), linkSite.Language));
break;
default:
dwTitle = MWToDWTitle(linkSite, dwTitle);
break;
};
if (string.IsNullOrEmpty(link.Contents)) {
link.ReplaceValue(link["@href"].Contents);
}
if (!link["@href"].Contents.StartsWith("#")) {
link.Attr("href", dwTitle.AsUiUriPath());
}
}
// map each internal image to its new MindTouch location
foreach (XDoc image in xml["//mediawiki:image[@type='internal']"].ToList()) {
Title mediaGalleryTitle = DWMediaGalleryTitle(site);
mediaGalleryTitle.Filename = image["@href"].Contents;
image.Attr("href", mediaGalleryTitle.AsUiUriPath());
}
}
public Title DWMediaGalleryTitle(Site site) {
return MWToDWTitle(site, Title.FromDbPath(NS.MAIN, "Media_Gallery", null));
}
public string MWToDWUserName(string mwName) {
uint suffix = 0;
UserBE matchingUser = null;
string dwName;
do {
dwName = mwName;
if (suffix > 0)
dwName = dwName + suffix.ToString();
matchingUser = DbUtils.CurrentSession.Users_GetByName(dwName);
suffix++;
} while (matchingUser != null);
return dwName;
}
public bool OverrideTemplate(Site site, PageBE page) {
if (page.Title.IsTemplate && !String.IsNullOrEmpty(MediaWikiConverterContext.Current.MWTemplatePath)) {
string templateFilename = GetTemplateFilename(page.Title);
string templateOriginal = Path.Combine(OriginalTemplateDir, site.Language + "-" + templateFilename);
// check the template against its base version to see if it's changed
if (!File.Exists(templateOriginal)) {
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='outdatedtemplates']"].Add(new XDoc("tr").Elem("td", MWToDWTitle(site, page.Title).AsPrefixedDbPath()));
}
#endregion
File.WriteAllLines(templateOriginal, new string[] { page.TimeStamp.ToString() });
File.AppendAllText(templateOriginal, page.GetText(DbUtils.CurrentSession));
} else {
DateTime baseTimestamp = DateTime.MinValue;
string[] lines = File.ReadAllLines(templateOriginal);
if (0 < lines.Length) {
DateTime.TryParse(lines[0], out baseTimestamp);
}
if (DateTime.MinValue == baseTimestamp || baseTimestamp < page.TimeStamp) {
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='outdatedtemplates']"].Add(new XDoc("tr").Elem("td", MWToDWTitle(site, page.Title).AsPrefixedDbPath()));
}
#endregion
File.WriteAllLines(templateOriginal, new string[] { page.TimeStamp.ToString() });
File.AppendAllText(templateOriginal, page.GetText(DbUtils.CurrentSession));
}
}
// check if the template's content has been overriden
string templateOverride = Path.Combine(OverrideTemplateDir, templateFilename);
if (File.Exists(templateOverride)) {
page.SetText(File.ReadAllText(templateOverride));
page.ContentType = DekiMimeType.DEKI_TEXT;
ParserResult parserResult = DekiXmlParser.Parse(page, ParserMode.SAVE, -1, false);
page.IsRedirect = (null != parserResult.RedirectsToTitle) || (null != parserResult.RedirectsToUri);
return true;
}
}
return false;
}
public void MWToDWContent(Site site, PageBE page, bool isOld) {
try {
// check for template content overrides
if (OverrideTemplate(site, page)) {
return;
}
Plug converterUri = MediaWikiConverterContext.Current.MWConverterUri;
if (null != converterUri) {
string interwikiInfo = String.Empty;
if (null != _MWInterwikiBySite) {
_MWInterwikiBySite.TryGetValue(site, out interwikiInfo);
}
XDoc xml = converterUri.With("title", page.Title.AsPrefixedDbPath()).With("lang", site.Language).With("site", site.Name).With("interwiki", interwikiInfo).With("text", page.GetText(DbUtils.CurrentSession)).PostAsForm().ToDocument();
xml.UsePrefix("mediawiki", "#mediawiki");
// if this is a redirect, set the page text accordingly]
if (page.IsRedirect) {
ParserResult result = DekiXmlParser.Parse(page, ParserMode.SAVE, -1, false);
if (result.RedirectsToTitle != null) {
page.SetText(String.Format(REDIRECT_TEXT, MWToDWTitle(site, Title.FromUIUri(null, xml["//mediawiki:link/@href"].Contents, true)).AsPrefixedDbPath().Replace("&", "&")));
} else {
page.SetText(String.Format(REDIRECT_TEXT, xml["//mediawiki:link/@href"].Contents.Replace("&", "&"), true));
}
page.ContentType = DekiMimeType.DEKI_XML0805;
return;
}
// remove extra paragraph tags from templates
if (page.Title.IsTemplate) {
List<XDoc> topLevelParagraphs = xml["/html/body/p"].ToList();
if (1 == topLevelParagraphs.Count) {
topLevelParagraphs[0].ReplaceWithNodes(topLevelParagraphs[0]);
}
}
// Map MediaWiki titles to MindTouch
MWToDWTitles(site, page, isOld, xml);
// Convert from MediaWiki output to MindTouch
WikiTextProcessor.Convert(site, xml, page.Title.IsTemplate);
// If the page is available in other languages, insert wiki.languages
List<XDoc> languageList = xml["//mediawiki:meta[@type='language']"].ToList();
if (0 < languageList.Count) {
StringBuilder languageData = new StringBuilder("{{ wiki.languages( { ");
for (int i = 0; i < languageList.Count; i++) {
if (0 < i) {
languageData.Append(", ");
}
string relatedLanguage = languageList[i]["@language"].AsText;
Title relatedTitle = Title.FromUIUri(null, languageList[i].Contents, false);
Site relatedSite = MediaWikiConverterContext.Current.GetMWSite(relatedLanguage);
languageData.AppendFormat("{0}: {1}", StringUtil.QuoteString(relatedLanguage), StringUtil.QuoteString(MWToDWTitle(relatedSite, relatedTitle).AsPrefixedDbPath()));
languageList[i].Remove();
}
languageData.Append(" } ) }}");
xml["//body"].Value(languageData.ToString());
}
string contents = xml.ToString();
int first = contents.IndexOf("<body>");
int last = contents.LastIndexOf("</body>");
if ((first >= 0) && (last >= 0)) {
page.SetText(contents.Substring(first + 6, last - (first + 6)));
page.ContentType = DekiMimeType.DEKI_TEXT;
}
}
} catch (Exception e) {
Console.Out.WriteLine("An unexpected exception has occurred:");
Console.Out.WriteLine(e.GetCoroutineStackTrace());
Console.Out.WriteLine("MediaWiki page text that produced the exception:");
Console.Out.WriteLine(page.GetText(DbUtils.CurrentSession));
}
}
/// <summary>
/// Convert MediaWiki users to MindTouch users
/// </summary>
public void ConvertUsers() {
Console.Out.Write("Migrating users... ");
// Delete any existing users
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWUsers();
// Create the anonymous user with an unused user ID, so that it won't get trampled
UserBE anonUser = new UserBE();
anonUser.Name = DekiWikiService.ANON_USERNAME;
anonUser.RoleId = 3;
anonUser.ServiceId = 1;
uint anonUserID = DbUtils.CurrentSession.Users_Insert(anonUser);
MediaWikiDA.UpdateDWUserID(anonUserID, 0);
long maxUserID = 0;
UserBE[] users = MediaWikiDA.GetUsers();
foreach (UserBE user in users) {
uint oldID = user.ID;
maxUserID = Math.Max(oldID, maxUserID);
string oldName = user.Name;
user.Name = MWToDWUserName(user.Name);
if (oldName != user.Name) {
_MWToDWUserNameMap.Add(Title.FromUIUsername(oldName).Path, Title.FromUIUsername(user.Name).Path);
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='renamedUsers']"].Add(new XDoc("tr").Elem("td", oldName).Elem("td", user.Name));
}
#endregion
}
uint userId = DbUtils.CurrentSession.Users_Insert(user);
MediaWikiDA.UpdateDWUserID(userId, oldID);
}
// Update the anonymous user ID to be valid
MediaWikiDA.UpdateDWUserID(anonUserID, (uint)maxUserID + 1);
}
Console.Out.WriteLine("Done!");
}
public void ConvertIPBlocks() {
Console.Out.Write("Migrating ipblocks... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWIPBlocks();
IPBlockBE[] ipBlocks = MediaWikiDA.GetIPBlocks();
foreach (IPBlockBE ipBlock in ipBlocks) {
MediaWikiDA.InsertDWIPBlock(ipBlock);
}
}
Console.Out.WriteLine("Done!");
}
public void ConvertConfiguration() {
Console.Out.Write("Migrating configuration... ");
// Delete exisiting custom extensions if they exist
IList<ServiceBE> services = DbUtils.CurrentSession.Services_GetAll();
foreach (ServiceBE existingService in services) {
if (StringUtil.EqualsInvariantIgnoreCase(existingService.Description, "Custom RSS Extension") ||
StringUtil.EqualsInvariantIgnoreCase(existingService.Description, "MediaWiki Extension")) {
MediaWikiDA.DeleteDWServiceById(existingService.Id);
}
}
// Register the Custom RSS Extension
ServiceBE rssService = new ServiceBE();
rssService.Type = ServiceType.EXT;
rssService.SID = "http://services.mindtouch.com/deki/draft/2007/12/dekiscript";
rssService.Description = "Custom RSS Extension";
rssService._ServiceEnabled = 1;
rssService._ServiceLocal = 1;
rssService.Config.Add("manifest", "http://scripts.mindtouch.com/ajaxrss.xml");
MediaWikiDA.InsertDWService(rssService);
// Register the Media Wiki Extension
ServiceBE mwService = new ServiceBE();
mwService.Type = ServiceType.EXT;
mwService.SID = "http://services.mindtouch.com/deki/draft/2008/04/mediawiki";
mwService.Description = "MediaWiki Extension";
mwService._ServiceEnabled = 1;
mwService._ServiceLocal = 1;
// populate the config keys used for interwiki links
Dictionary<Site, NameValueCollection> interWikiBySite = MediaWikiDA.GetInterWikiBySite();
_MWInterwikiBySite = new Dictionary<Site, string>();
Dictionary<string, string> interWiki = new Dictionary<string, string>();
foreach (KeyValuePair<Site, NameValueCollection> interWikiPair in interWikiBySite) {
foreach (string key in interWikiPair.Value.Keys) {
if (_MWInterwikiBySite.ContainsKey(interWikiPair.Key)) {
_MWInterwikiBySite[interWikiPair.Key] += "," + key;
} else {
_MWInterwikiBySite[interWikiPair.Key] = key;
}
string normalized_key = key.Replace(' ', '_').ToLowerInvariant();
string value = null;
if (interWiki.TryGetValue(normalized_key, out value)) {
if (value != interWikiPair.Value[normalized_key]) {
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='interWikiConflicts']"].Add(new XDoc("tr").Elem("td", normalized_key).Elem("td", value).Elem("td", interWikiPair.Value[key] + "(" + interWikiPair.Key.Language + ")"));
}
#endregion
}
} else {
interWiki.Add(normalized_key, interWikiPair.Value[key]);
mwService.Config.Set(normalized_key, interWikiPair.Value[key]);
}
}
}
// populate the config keys used to map from language to language root
foreach (Site site in MediaWikiConverterContext.Current.MWSites) {
mwService.Config.Set("rootpage-" + site.Language, site.DWRootPage);
mwService.Config.Set("projectname", site.Name);
mwService.Config.Set("pageseparator", MediaWikiConverterContext.Current.MWPageSeparator.ToString());
}
MediaWikiDA.InsertDWService(mwService);
// configure the wiki languages
StringBuilder languages = new StringBuilder();
foreach (Site site in MediaWikiConverterContext.Current.MWSites) {
if (0 < languages.Length) {
languages.Append(",");
}
languages.Append(site.Language);
}
ConfigBL.SetInstanceSettingsValue("languages", languages.ToString());
Console.Out.WriteLine("Done!");
}
public PageBE EnsureParent(bool isRedirect, PageBE page) {
PageBE parentPage = null;
Title parentTitle = page.Title.GetParent();
// attempt to retrieve the parent and create it if not found
if (!page.Title.IsTalk && null != parentTitle) {
parentPage = PageBL.GetPageByTitle(parentTitle);
if ( (null == parentPage) || (0 == parentPage.ID) || (!isRedirect && parentPage.IsRedirect)) {
parentPage.SetText(DekiResources.EMPTY_PARENT_ARTICLE_TEXT);
parentPage.ContentType = DekiMimeType.DEKI_TEXT;
parentPage.Comment = parentPage.TIP = String.Empty;
parentPage.TimeStamp = parentPage.Touched = DateTime.Now;
parentPage.Language = page.Language;
PageBE grandparentPage = EnsureParent(isRedirect, parentPage);
if (null != grandparentPage) {
parentPage.ParentID = grandparentPage.Title.IsRoot ? 0 : grandparentPage.ID;
}
if (0 == parentPage.ID) {
uint revisionNumber;
ulong parentPageId = DbUtils.CurrentSession.Pages_Insert(parentPage, 0);
parentPage.ID = parentPageId;
} else {
DbUtils.CurrentSession.Pages_Update(parentPage);
parentPage = PageBL.GetPageById(parentPage.ID);
}
}
}
return parentPage;
}
/// <summary>
/// Convert MediaWiki pages to MindTouch pages
/// </summary>
public void ConvertPages(out Title[] titles, out Dictionary<Title, List<PageBE>> oldTitleToPageMap) {
Console.Out.Write("Migrating pages... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWLinks();
MediaWikiDA.DeleteDWPages();
}
Dictionary<Site, List<PageBE>> pagesBySite = MediaWikiDA.GetPagesBySite();
oldTitleToPageMap = new Dictionary<Title, List<PageBE>>();
foreach (Site site in pagesBySite.Keys) {
// group by pages having the same title
foreach (PageBE page in pagesBySite[site]) {
// convert from MediaWiki to MindTouch content
MWToDWContent(site, page, false);
Title oldTitle = MWToDWTitle(site, page.Title, false);
page.Title = MWToDWTitle(site, page.Title);
List<PageBE> pagesByTitle;
oldTitleToPageMap.TryGetValue(oldTitle, out pagesByTitle);
if (null == pagesByTitle) {
pagesByTitle = new List<PageBE>();
pagesByTitle.Add(page);
oldTitleToPageMap.Add(oldTitle, pagesByTitle);
} else {
pagesByTitle.Add(page);
}
}
// create a media gallery page to hold images
PageBE mediaGalleryPage = new PageBE();
mediaGalleryPage.Title = DWMediaGalleryTitle(site);
mediaGalleryPage.ContentType = DekiMimeType.DEKI_TEXT;
mediaGalleryPage.Comment = mediaGalleryPage.TIP = String.Empty;
mediaGalleryPage.TimeStamp = mediaGalleryPage.Touched = DateTime.Now;
mediaGalleryPage.Language = site.Language;
mediaGalleryPage.SetText(String.Empty);
oldTitleToPageMap.Add(mediaGalleryPage.Title, new List<PageBE>(new PageBE[] { mediaGalleryPage }));
}
// order by new title length so that parent pages are created before their children
titles = new Title[oldTitleToPageMap.Keys.Count];
int[] titleLengths = new int[titles.Length];
oldTitleToPageMap.Keys.CopyTo(titles, 0);
for (int i = 0; i < titles.Length; i++) {
titleLengths[i] = GetPredominantPage(oldTitleToPageMap[titles[i]]).Title.AsUnprefixedDbPath().Length;
}
Array.Sort(titleLengths, titles);
// save the pages
foreach (Title title in titles) {
List<PageBE> pagesByTitle = oldTitleToPageMap[title];
PageBE predominantPage = GetPredominantPage(pagesByTitle);
ulong oldID = predominantPage.ID;
string oldLanguage = predominantPage.Language;
// ensure the parent exists and set the parent id
PageBE parentPage = EnsureParent(predominantPage.IsRedirect, predominantPage);
if (null != parentPage) {
predominantPage.ParentID = parentPage.Title.IsRoot ? 0 : parentPage.ID;
}
// detect conflicts
List<PageBE> conflictedPages = new List<PageBE>();
bool differsByLanguage = true;
foreach (PageBE page in pagesByTitle) {
if ((predominantPage != page) && (page.GetText(DbUtils.CurrentSession).Trim() != predominantPage.GetText(DbUtils.CurrentSession).Trim()) && !page.IsRedirect) {
conflictedPages.Add(page);
if (page.Language == predominantPage.Language) {
differsByLanguage = false;
}
}
}
// detect if a page with the same title already exists
PageBE pageWithMatchingName = PageBL.GetPageByTitle(predominantPage.Title);
if ( ( null != pageWithMatchingName ) && ( 0 != pageWithMatchingName.ID ) ) {
conflictedPages.Add(predominantPage);
predominantPage = pageWithMatchingName;
} else {
// for templates, add each language version in a localized section
if (predominantPage.Title.IsTemplate) {
List<string> languages = new List<string>();
if (!File.Exists(Path.Combine(OverrideTemplateDir, GetTemplateFilename(predominantPage.Title)))) {
String pageText = String.Empty;
foreach (PageBE page in pagesByTitle) {
if (page.IsRedirect) {
ParserResult result = DekiXmlParser.Parse(page, ParserMode.SAVE, -1, false);
languages.Add(page.Language);
if(result.RedirectsToTitle != null) {
pageText = String.Format("{0}<span lang='{1}' class='lang lang-{1}'>{{{{wiki.template('{2}', args)}}}}</span>", pageText, page.Language, result.RedirectsToTitle.AsPrefixedDbPath());
if ("en" == page.Language || 1 == pagesByTitle.Count) {
pageText = String.Format("{0}<span lang='{1}' class='lang lang-{1}'>{{{{wiki.template('{2}', args)}}}}</span>", pageText, "*", result.RedirectsToTitle.AsPrefixedDbPath());
}
}
} else {
languages.Add(page.Language);
pageText = String.Format("{0}<span lang='{1}' class='lang lang-{1}'>{2}</span>", pageText, page.Language, page.GetText(DbUtils.CurrentSession));
if ("en" == page.Language || 1 == pagesByTitle.Count) {
pageText = String.Format("{0}<span lang='{1}' class='lang lang-{1}'>{2}</span>", pageText, "*", page.GetText(DbUtils.CurrentSession));
}
}
}
predominantPage.SetText(pageText);
}
predominantPage.Language = String.Empty;
#region logging
if (1 < languages.Count && MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='pagesMerged']"].Add(new XDoc("tr").Elem("td", predominantPage.Title.AsPrefixedDbPath()).Elem("td", String.Join(" ", languages.ToArray())));
}
#endregion
} else if (differsByLanguage && 0 < conflictedPages.Count) {
List<string> languages = new List<string>();
String pageText = String.Empty;
foreach (PageBE page in pagesByTitle) {
if (!languages.Contains(page.Language)) {
languages.Add(page.Language);
if (page.IsRedirect) {
ParserResult result = DekiXmlParser.Parse(page, ParserMode.SAVE, -1, false);
// TODO (steveb): not sure how to handle external redirects
if(result.RedirectsToTitle != null) {
page.SetText("{{wiki.page('" + result.RedirectsToTitle.AsPrefixedDbPath() + "')}}");
}
}
pageText = String.Format("{0}\n<div style='border: 1px solid #777777; margin: 10px 0px; padding: 0px 10px; background-color: #eeeeee; font-weight: bold; text-align: center;'><p style='margin: 4px 0px;'>Content merged from {1}</p></div>\n{2}", pageText, page.Language, page.GetText(DbUtils.CurrentSession));
}
}
predominantPage.SetText(pageText);
predominantPage.Language = String.Empty;
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='pagesMerged']"].Add(new XDoc("tr").Elem("td", predominantPage.Title.AsPrefixedDbPath()).Elem("td", String.Join(" ", languages.ToArray())));
}
#endregion
}
// save the page
uint revisionNumber;
ulong predominantPageId = DbUtils.CurrentSession.Pages_Insert(predominantPage, 0);
predominantPage = PageBL.GetPageById(predominantPageId);
if (0 != oldID) {
_MWToDWPageIDMap.Add(oldLanguage + oldID, predominantPage.ID);
}
// generate redirect page if the title has changed
Title oldTitle = title;
if (predominantPage.Title != oldTitle) {
PageBE redirect = new PageBE();
redirect.Title = oldTitle;
redirect.SetText(String.Format(REDIRECT_TEXT, predominantPage.Title.AsPrefixedDbPath().Replace("&", "&")));
redirect.Comment = redirect.TIP = String.Empty;
redirect.TimeStamp = redirect.Touched = DateTime.Now;
redirect.ContentType = DekiMimeType.DEKI_XML0805;
redirect.Language = predominantPage.Language;
redirect.IsRedirect = true;
uint tempRevisionNumber;
DbUtils.CurrentSession.Pages_Insert(redirect, 0);
}
}
// Report any title conflicts to the user
if (0 < conflictedPages.Count) {
foreach (PageBE page in conflictedPages) {
#region logging
if (!page.IsRedirect && !differsByLanguage && MediaWikiConverterContext.Current.LoggingEnabled) {
log["/html/body/table[@id='removedPages']"].Add(new XDoc("tr").Elem("td", page.Title.AsPrefixedDbPath()));
}
#endregion
}
}
}
Console.Out.WriteLine("Done!");
}
public void ConvertFiles() {
Console.Out.Write("Migrating files... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWFiles();
}
MD5 MD5 = MD5CryptoServiceProvider.Create();
Dictionary<Site, List<AttachmentBE>> filesBySite = MediaWikiDA.GetFilesBySite();
foreach(Site site in filesBySite.Keys) {
PageBE mediaGalleryPage = PageBL.GetPageByTitle(DWMediaGalleryTitle(site));
AttachmentBE previous = null;
foreach(AttachmentBE file in filesBySite[site]) {
AttachmentBE currentFile = file;
try {
currentFile.ParentPageId = (uint) mediaGalleryPage.ID;
if((null != previous) && (previous.Name == currentFile.Name) && (previous.ParentPageId == currentFile.ParentPageId)) {
currentFile.ResourceId = previous.ResourceId;
currentFile.Revision = previous.Revision + 1;
} else {
previous = null;
}
string utf8FileName = currentFile.MetaXml["physicalfilename"].Contents;
string latin1FileName = Encoding.GetEncoding("ISO-8859-1").GetString(Encoding.UTF8.GetBytes(utf8FileName));
uint fileid = ResourceMapBL.GetNewFileId();
currentFile.FileId = fileid;
// Save revision to db
currentFile = (AttachmentBE) DbUtils.CurrentSession.Resources_SaveRevision(currentFile);
ResourceMapBL.UpdateFileIdMapping(fileid, currentFile.ResourceId);
// store the file on the file system
string sourcePath = site.ImageDir;
if (currentFile.Name != utf8FileName) {
sourcePath = Path.Combine(site.ImageDir, "archive");
}
string md5HashString = MD5.ComputeHash(Encoding.UTF8.GetBytes(currentFile.Name))[0].ToString("x2");
sourcePath = sourcePath + Path.DirectorySeparatorChar + md5HashString[0] + Path.DirectorySeparatorChar + md5HashString;
string fileName = Path.Combine(sourcePath, latin1FileName);
if(!File.Exists(fileName)) {
char[] fileNameChars = latin1FileName.ToCharArray();
for(int i = 0; i < fileNameChars.Length; i++) {
if(128 <= fileNameChars[i] && 159 >= fileNameChars[i]) {
fileNameChars[i] = '?';
}
}
string[] files = Directory.GetFiles(sourcePath, new string(fileNameChars));
if(0 < files.Length) {
fileName = Directory.GetFiles(sourcePath, new string(fileNameChars))[0];
} else {
continue;
}
}
using(FileStream fs = File.OpenRead(fileName)) {
try {
DekiContext.Current.Instance.Storage.PutFile(currentFile, SizeType.ORIGINAL, new StreamInfo(fs, fs.Length));
} catch { }
}
previous = currentFile;
} catch(Exception e) {
Console.Out.WriteLine("Error converting " + file.Name+ ":");
Console.Out.WriteLine(e.GetCoroutineStackTrace());
}
}
}
Console.Out.WriteLine("Done!");
}
public void ConvertPageData(Title[] titles, Dictionary<Title, List<PageBE>> oldTitleToPageMap) {
Console.Out.Write("Migrating page data... ");
// update the page links, usecache, and summary info
foreach (Title title in titles) {
PageBE page = GetPredominantPage(oldTitleToPageMap[title]);
ulong thisoldid;
if (_MWToDWPageIDMap.TryGetValue(page.Language + page.ID, out thisoldid)) {
page.ID = thisoldid;
ParserResult parserResult = DekiXmlParser.Parse(page, ParserMode.SAVE, -1, false);
page.UseCache = !parserResult.HasScriptContent;
page.TIP = parserResult.Summary;
page.ContentType = parserResult.ContentType;
if (!page.IsRedirect) {
page.SetText(parserResult.BodyText);
}
PageBL.UpdateLinks(page, parserResult.Links.ToArray());
MediaWikiDA.UpdateDWPageData(page);
}
}
Console.Out.WriteLine("Done!");
}
/// <summary>
/// Convert from MediaWiki categories to MindTouch tags
/// </summary>
public void ConvertCategories() {
Console.Out.Write("Migrating categories... ");
Dictionary<string, List<string>> pageToCategoryMap = MediaWikiDA.GetCategoryNamesByPage();
foreach (KeyValuePair<string, List<string>> categoriesByPage in pageToCategoryMap) {
TagBE[] tags = new TagBE[categoriesByPage.Value.Count];
for (int i = 0; i < tags.Length; i++) {
TagBE categoryTag = new TagBE();
categoryTag.Type = TagType.TEXT;
categoryTag.Name = categoriesByPage.Value[i];
tags[i] = categoryTag;
}
ulong pageID;
if (_MWToDWPageIDMap.TryGetValue(categoriesByPage.Key, out pageID)) {
TagBL.InsertTags(pageID, tags);
}
}
Console.Out.WriteLine("Done!");
}
/// <summary>
/// Convert MediaWiki page revisions to MindTouch revisions
/// </summary>
public void ConvertRevisions() {
Console.Out.Write("Migrating revisions... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWRevisions();
}
Dictionary<Site, List<PageBE>> revisionsBySite = MediaWikiDA.GetRevisionsBySite();
List<PageBE> revisions = new List<PageBE>();
foreach (Site site in revisionsBySite.Keys) {
foreach (PageBE revision in revisionsBySite[site]) {
revisions.Add(revision);
}
}
// sort the revisions to ensure they are inserted chronologically
revisions.Sort(delegate(PageBE left, PageBE right) { return DateTime.Compare(left.TimeStamp, right.TimeStamp); });
foreach (PageBE revision in revisions) {
Site site = MediaWikiConverterContext.Current.GetMWSite(revision.Language);
PageBE populatedRevision = MediaWikiDA.GetPopulatedRevision(site, revision);
// convert from MediaWiki to MindTouch content
MWToDWContent(site, populatedRevision, true);
populatedRevision.Title = MWToDWTitle(site, populatedRevision.Title);
OldBE old = PageBL.InsertOld(populatedRevision, 0);
_MWToDWOldIDMap.Add(populatedRevision.Language + populatedRevision.ID, old.ID);
}
Console.Out.WriteLine("Done!");
}
/// <summary>
/// Convert from MediaWiki recent changes to MindTouch recent changes
/// </summary>
public void ConvertRecentChanges() {
Console.Out.Write("Migrating recent changes... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWRecentChanges();
}
Dictionary<Site, List<RecentChangeBE>> recentChangesBySite = MediaWikiDA.GetRecentChangesBySite();
foreach (Site site in recentChangesBySite.Keys) {
foreach (RecentChangeBE recentChange in recentChangesBySite[site]) {
ulong id;
if (_MWToDWPageIDMap.TryGetValue(site.Language + recentChange.Page.ID, out id)) {
recentChange.Page.ID = id;
ulong thisoldid, lastoldid;
_MWToDWOldIDMap.TryGetValue(site.Language + recentChange.ThisOldID, out thisoldid);
_MWToDWOldIDMap.TryGetValue(site.Language + recentChange.LastOldID, out lastoldid);
recentChange.ThisOldID = thisoldid;
recentChange.LastOldID = lastoldid;
recentChange.Page.Title = MWToDWTitle(site, recentChange.Page.Title);
MediaWikiDA.InsertDWRecentChange(recentChange);
}
}
}
Console.Out.WriteLine("Done!");
}
public void ConvertWatchlist() {
Console.Out.Write("Migrating user watchlist... ");
if (!MediaWikiConverterContext.Current.Merge) {
MediaWikiDA.DeleteDWWatch();
Dictionary<Site, List<WatchlistBE>> watchlistBySite = MediaWikiDA.GetWatchlistBySite();
foreach (Site site in watchlistBySite.Keys) {
foreach (WatchlistBE watch in watchlistBySite[site]) {
watch.Title = MWToDWTitle(site, watch.Title);
MediaWikiDA.InsertDWWatch(watch);
}
}
}
Console.Out.WriteLine("Done!");
}
public void Convert() {
try {
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log.Start("head").Elem("title", "MediaWiki to MindTouch Converter Output").End();
log.Start("body").Elem("h1", "MediaWiki to MindTouch Converter Output");
log.Start("h2").Value("Renamed Users").Elem("br").End();
log.Elem("p", "These users were issued a new name since their previous name differed only by case with another user.");
log.Start("table").Attr("border", 1).Attr("id", "renamedUsers").Start("tr").Start("td").Elem("strong", "Previous Name").End().Start("td").Elem("strong", "New Name").End().End().End();
log.Start("h2").Value("Interwiki Conflicts").Elem("br").End();
log.Elem("p", "These interwiki settings differed between languages.");
log.Start("table").Attr("border", 1).Attr("id", "interWikiConflicts").Start("tr").Start("td").Elem("strong", "Interwiki Prefix").End().Start("td").Elem("strong", "Interwiki Link").End().Start("td").Elem("strong", "Conflict").End().End().End();
log.Start("h2").Value("Page Content Merged").Elem("br").End();
log.Elem("p", "These pages previously existed in multiple languages. Since MindTouch provides single user/template pages across all languages, the content from each language has been merged.");
log.Start("table").Attr("border", 1).Attr("id", "pagesMerged").Start("tr").Start("td").Elem("strong", "Page Title").End().Start("td").Elem("strong", "Languages Merged").End().End().End();
log.Start("h2").Value("Removed Pages").Elem("br").End();
log.Elem("p", "These pages were removed since they differed only by case with an existing page.");
log.Start("table").Attr("border", 1).Attr("id", "removedPages").Start("tr").Start("td").Elem("strong", "Removed Page").End().End().End();
log.Start("h2").Value("Pages containing links to Special pages that no longer exist").Elem("br").End();
log.Elem("p", "These pages link to one or more Special pages that no longer exist.");
log.Start("table").Attr("border", 1).Attr("id", "specialpages").Start("tr").Start("td").Elem("strong", "Page Title").End().Start("td").Elem("strong", "Special Page Link").End().End().End();
log.Start("h2").Value("Pages containing functions").Elem("br").End();
log.Elem("p", "These pages reference one or more parser functions and should be individually reviewed.");
log.Start("table").Attr("border", 1).Attr("id", "functions").Start("tr").Start("td").Elem("strong", "Page Title").End().Start("td").Elem("strong", "Function Reference").End().End().End();
log.Start("h2").Value("Pages containing templates").Elem("br").End();
log.Elem("p", "These pages reference one or more templates and should be individually reviewed.");
log.Start("table").Attr("border", 1).Attr("id", "templates").Start("tr").Start("td").Elem("strong", "Page Title").End().Start("td").Elem("strong", "Template Reference").End().End().End();
log.Start("h2").Value("Customized templates that are outdated").Elem("br").End();
log.Elem("p", "These templates have changed since the last conversion.");
log.Start("table").Attr("border", 1).Attr("id", "outdatedtemplates").Start("tr").Start("td").Elem("strong", "Template Title").End().End().End();
}
#endregion
Title[] titles;
Dictionary<Title, List<PageBE>> oldTitleToPageMap;
ConvertUsers();
ConvertIPBlocks();
ConvertConfiguration();
ConvertPages(out titles, out oldTitleToPageMap);
ConvertFiles();
ConvertPageData(titles, oldTitleToPageMap);
ConvertCategories();
ConvertRevisions();
ConvertRecentChanges();
ConvertWatchlist();
#region logging
if (MediaWikiConverterContext.Current.LoggingEnabled) {
log.End();
File.WriteAllText(MediaWikiConverterContext.Current.LogPath, log.Contents, Encoding.UTF8);
try { System.Diagnostics.Process.Start(MediaWikiConverterContext.Current.LogPath); } catch { }
}
#endregion
Console.Out.WriteLine("Migration completed. Press enter to continue");
} catch (Exception e) {
Console.Out.WriteLine("An unexpected exception has occurred:");
Console.Out.WriteLine(e.GetCoroutineStackTrace());
}
}
[DreamFeature("POST:", "")]
public Yield PostConvert(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
Convert();
response.Return(DreamMessage.Ok());
yield break;
}
}
}
| |
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// ZipNameTransform transforms names as per the Zip file naming convention.
/// </summary>
/// <remarks>The use of absolute names is supported although its use is not valid
/// according to Zip naming conventions, and should not be used if maximum compatability is desired.</remarks>
public class ZipNameTransform : INameTransform
{
#region Constructors
/// <summary>
/// Initialize a new instance of <see cref="ZipNameTransform"></see>
/// </summary>
public ZipNameTransform()
{
}
/// <summary>
/// Initialize a new instance of <see cref="ZipNameTransform"></see>
/// </summary>
/// <param name="trimPrefix">The string to trim from the front of paths if found.</param>
public ZipNameTransform(string trimPrefix)
{
TrimPrefix = trimPrefix;
}
#endregion
/// <summary>
/// Static constructor.
/// </summary>
static ZipNameTransform()
{
char[] invalidPathChars;
invalidPathChars = Path.GetInvalidPathChars();
int howMany = invalidPathChars.Length + 2;
InvalidEntryCharsRelaxed = new char[howMany];
Array.Copy(invalidPathChars, 0, InvalidEntryCharsRelaxed, 0, invalidPathChars.Length);
InvalidEntryCharsRelaxed[howMany - 1] = '*';
InvalidEntryCharsRelaxed[howMany - 2] = '?';
howMany = invalidPathChars.Length + 4;
InvalidEntryChars = new char[howMany];
Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length);
InvalidEntryChars[howMany - 1] = ':';
InvalidEntryChars[howMany - 2] = '\\';
InvalidEntryChars[howMany - 3] = '*';
InvalidEntryChars[howMany - 4] = '?';
}
/// <summary>
/// Transform a windows directory name according to the Zip file naming conventions.
/// </summary>
/// <param name="name">The directory name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformDirectory(string name)
{
name = TransformFile(name);
if (name.Length > 0) {
if (!name.EndsWith("/", StringComparison.Ordinal)) {
name += "/";
}
} else {
throw new ZipException("Cannot have an empty directory name");
}
return name;
}
/// <summary>
/// Transform a windows file name according to the Zip file naming conventions.
/// </summary>
/// <param name="name">The file name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformFile(string name)
{
if (name != null) {
string lowerName = name.ToLower();
if ((trimPrefix_ != null) && (lowerName.IndexOf(trimPrefix_, StringComparison.Ordinal) == 0)) {
name = name.Substring(trimPrefix_.Length);
}
name = name.Replace(@"\", "/");
name = WindowsPathUtils.DropPathRoot(name);
// Drop any leading slashes.
while ((name.Length > 0) && (name[0] == '/')) {
name = name.Remove(0, 1);
}
// Drop any trailing slashes.
while ((name.Length > 0) && (name[name.Length - 1] == '/')) {
name = name.Remove(name.Length - 1, 1);
}
// Convert consecutive // characters to /
int index = name.IndexOf("//", StringComparison.Ordinal);
while (index >= 0) {
name = name.Remove(index, 1);
index = name.IndexOf("//", StringComparison.Ordinal);
}
name = MakeValidName(name, '_');
} else {
name = string.Empty;
}
return name;
}
/// <summary>
/// Get/set the path prefix to be trimmed from paths if present.
/// </summary>
/// <remarks>The prefix is trimmed before any conversion from
/// a windows path is done.</remarks>
public string TrimPrefix {
get { return trimPrefix_; }
set {
trimPrefix_ = value;
if (trimPrefix_ != null) {
trimPrefix_ = trimPrefix_.ToLower();
}
}
}
/// <summary>
/// Force a name to be valid by replacing invalid characters with a fixed value
/// </summary>
/// <param name="name">The name to force valid</param>
/// <param name="replacement">The replacement character to use.</param>
/// <returns>Returns a valid name</returns>
static string MakeValidName(string name, char replacement)
{
int index = name.IndexOfAny(InvalidEntryChars);
if (index >= 0) {
var builder = new StringBuilder(name);
while (index >= 0) {
builder[index] = replacement;
if (index >= name.Length) {
index = -1;
} else {
index = name.IndexOfAny(InvalidEntryChars, index + 1);
}
}
name = builder.ToString();
}
if (name.Length > 0xffff) {
throw new PathTooLongException();
}
return name;
}
/// <summary>
/// Test a name to see if it is a valid name for a zip entry.
/// </summary>
/// <param name="name">The name to test.</param>
/// <param name="relaxed">If true checking is relaxed about windows file names and absolute paths.</param>
/// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
/// <remarks>Zip path names are actually in Unix format, and should only contain relative paths.
/// This means that any path stored should not contain a drive or
/// device letter, or a leading slash. All slashes should forward slashes '/'.
/// An empty name is valid for a file where the input comes from standard input.
/// A null name is not considered valid.
/// </remarks>
public static bool IsValidName(string name, bool relaxed)
{
bool result = (name != null);
if (result) {
if (relaxed) {
result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0;
} else {
result =
(name.IndexOfAny(InvalidEntryChars) < 0) &&
(name.IndexOf('/') != 0);
}
}
return result;
}
/// <summary>
/// Test a name to see if it is a valid name for a zip entry.
/// </summary>
/// <param name="name">The name to test.</param>
/// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
/// <remarks>Zip path names are actually in unix format,
/// and should only contain relative paths if a path is present.
/// This means that the path stored should not contain a drive or
/// device letter, or a leading slash. All slashes should forward slashes '/'.
/// An empty name is valid where the input comes from standard input.
/// A null name is not considered valid.
/// </remarks>
public static bool IsValidName(string name)
{
bool result =
(name != null) &&
(name.IndexOfAny(InvalidEntryChars) < 0) &&
(name.IndexOf('/') != 0)
;
return result;
}
#region Instance Fields
string trimPrefix_;
#endregion
#region Class Fields
static readonly char[] InvalidEntryChars;
static readonly char[] InvalidEntryCharsRelaxed;
#endregion
}
}
| |
namespace Trionic5Controls
{
partial class HexViewer
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HexViewer));
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.miClose = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.miFind = new System.Windows.Forms.ToolStripButton();
this.miFindNext = new System.Windows.Forms.ToolStripButton();
this.miSave = new System.Windows.Forms.ToolStripButton();
this.printToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.miCut = new System.Windows.Forms.ToolStripButton();
this.miCopy = new System.Windows.Forms.ToolStripButton();
this.miPaste = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.panel1 = new System.Windows.Forms.Panel();
this.hexBox1 = new Be.Windows.Forms.HexBox();
this.toolStrip1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.AccessibleDescription = null;
this.toolStrip1.AccessibleName = null;
resources.ApplyResources(this.toolStrip1, "toolStrip1");
this.toolStrip1.BackgroundImage = null;
this.toolStrip1.Font = null;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miClose,
this.openToolStripButton,
this.miFind,
this.miFindNext,
this.miSave,
this.printToolStripButton,
this.toolStripSeparator,
this.miCut,
this.miCopy,
this.miPaste,
this.toolStripSeparator1,
this.toolStripLabel1,
this.toolStripButton1,
this.toolStripSeparator2});
this.toolStrip1.Name = "toolStrip1";
//
// miClose
//
this.miClose.AccessibleDescription = null;
this.miClose.AccessibleName = null;
resources.ApplyResources(this.miClose, "miClose");
this.miClose.BackgroundImage = null;
this.miClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miClose.Name = "miClose";
this.miClose.Click += new System.EventHandler(this.miClose_Click);
//
// openToolStripButton
//
this.openToolStripButton.AccessibleDescription = null;
this.openToolStripButton.AccessibleName = null;
resources.ApplyResources(this.openToolStripButton, "openToolStripButton");
this.openToolStripButton.BackgroundImage = null;
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Click += new System.EventHandler(this.openToolStripButton_Click);
//
// miFind
//
this.miFind.AccessibleDescription = null;
this.miFind.AccessibleName = null;
resources.ApplyResources(this.miFind, "miFind");
this.miFind.BackgroundImage = null;
this.miFind.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miFind.Name = "miFind";
this.miFind.Click += new System.EventHandler(this.miFind_Click);
//
// miFindNext
//
this.miFindNext.AccessibleDescription = null;
this.miFindNext.AccessibleName = null;
resources.ApplyResources(this.miFindNext, "miFindNext");
this.miFindNext.BackgroundImage = null;
this.miFindNext.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miFindNext.Name = "miFindNext";
this.miFindNext.Click += new System.EventHandler(this.miFindNext_Click);
//
// miSave
//
this.miSave.AccessibleDescription = null;
this.miSave.AccessibleName = null;
resources.ApplyResources(this.miSave, "miSave");
this.miSave.BackgroundImage = null;
this.miSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miSave.Name = "miSave";
this.miSave.Click += new System.EventHandler(this.miSave_Click);
//
// printToolStripButton
//
this.printToolStripButton.AccessibleDescription = null;
this.printToolStripButton.AccessibleName = null;
resources.ApplyResources(this.printToolStripButton, "printToolStripButton");
this.printToolStripButton.BackgroundImage = null;
this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printToolStripButton.Name = "printToolStripButton";
this.printToolStripButton.Click += new System.EventHandler(this.printToolStripButton_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.AccessibleDescription = null;
this.toolStripSeparator.AccessibleName = null;
resources.ApplyResources(this.toolStripSeparator, "toolStripSeparator");
this.toolStripSeparator.Name = "toolStripSeparator";
//
// miCut
//
this.miCut.AccessibleDescription = null;
this.miCut.AccessibleName = null;
resources.ApplyResources(this.miCut, "miCut");
this.miCut.BackgroundImage = null;
this.miCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miCut.Name = "miCut";
this.miCut.Click += new System.EventHandler(this.miCut_Click);
//
// miCopy
//
this.miCopy.AccessibleDescription = null;
this.miCopy.AccessibleName = null;
resources.ApplyResources(this.miCopy, "miCopy");
this.miCopy.BackgroundImage = null;
this.miCopy.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miCopy.Name = "miCopy";
this.miCopy.Click += new System.EventHandler(this.miCopy_Click);
//
// miPaste
//
this.miPaste.AccessibleDescription = null;
this.miPaste.AccessibleName = null;
resources.ApplyResources(this.miPaste, "miPaste");
this.miPaste.BackgroundImage = null;
this.miPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.miPaste.Name = "miPaste";
this.miPaste.Click += new System.EventHandler(this.miPaste_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.AccessibleDescription = null;
this.toolStripSeparator1.AccessibleName = null;
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
this.toolStripSeparator1.Name = "toolStripSeparator1";
//
// toolStripLabel1
//
this.toolStripLabel1.AccessibleDescription = null;
this.toolStripLabel1.AccessibleName = null;
resources.ApplyResources(this.toolStripLabel1, "toolStripLabel1");
this.toolStripLabel1.BackgroundImage = null;
this.toolStripLabel1.ForeColor = System.Drawing.Color.SeaGreen;
this.toolStripLabel1.Name = "toolStripLabel1";
//
// toolStripButton1
//
this.toolStripButton1.AccessibleDescription = null;
this.toolStripButton1.AccessibleName = null;
resources.ApplyResources(this.toolStripButton1, "toolStripButton1");
this.toolStripButton1.BackgroundImage = null;
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton1.ForeColor = System.Drawing.Color.RoyalBlue;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.AccessibleDescription = null;
this.toolStripSeparator2.AccessibleName = null;
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
this.toolStripSeparator2.Name = "toolStripSeparator2";
//
// panel1
//
this.panel1.AccessibleDescription = null;
this.panel1.AccessibleName = null;
resources.ApplyResources(this.panel1, "panel1");
this.panel1.BackgroundImage = null;
this.panel1.Controls.Add(this.hexBox1);
this.panel1.Font = null;
this.panel1.Name = "panel1";
//
// hexBox1
//
this.hexBox1.AccessibleDescription = null;
this.hexBox1.AccessibleName = null;
resources.ApplyResources(this.hexBox1, "hexBox1");
this.hexBox1.BackColor = System.Drawing.Color.AntiqueWhite;
this.hexBox1.BackgroundImage = null;
this.hexBox1.ForeColor = System.Drawing.Color.Black;
this.hexBox1.LineInfoForeColor = System.Drawing.Color.DarkGray;
this.hexBox1.LineInfoVisible = true;
this.hexBox1.Name = "hexBox1";
this.hexBox1.ShadowSelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(60)))), ((int)(((byte)(188)))), ((int)(((byte)(255)))));
this.hexBox1.StringViewVisible = true;
this.hexBox1.UseFixedBytesPerLine = true;
this.hexBox1.VScrollBarVisible = true;
this.hexBox1.SelectionStartChanged += new System.EventHandler(this.hexBox1_SelectionStartChanged);
this.hexBox1.CurrentPositionInLineChanged += new System.EventHandler(this.hexBox1_CurrentPositionInLineChanged);
this.hexBox1.DoubleClick += new System.EventHandler(this.hexBox1_DoubleClick);
this.hexBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.hexBox1_DragDrop);
this.hexBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.hexBox1_DragEnter);
this.hexBox1.SelectionLengthChanged += new System.EventHandler(this.hexBox1_SelectionLengthChanged);
this.hexBox1.CurrentLineChanged += new System.EventHandler(this.hexBox1_CurrentPositionInLineChanged);
//
// HexViewer
//
this.AccessibleDescription = null;
this.AccessibleName = null;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = null;
this.Controls.Add(this.panel1);
this.Controls.Add(this.toolStrip1);
this.Name = "HexViewer";
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton miClose;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripButton miSave;
private System.Windows.Forms.ToolStripButton printToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private System.Windows.Forms.ToolStripButton miCut;
private System.Windows.Forms.ToolStripButton miCopy;
private System.Windows.Forms.ToolStripButton miPaste;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.Panel panel1;
private Be.Windows.Forms.HexBox hexBox1;
private System.Windows.Forms.ToolStripButton miFind;
private System.Windows.Forms.ToolStripButton miFindNext;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripButton toolStripButton1;
}
}
| |
#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;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Contoso.Primitives.TextPacks
{
/// <summary>
/// <root key="value">
/// <sub key2="value2">text</sub>
/// </root>
/// Key = value {attrib on root}
/// Sub:: = text {node in root}
/// Sub::Key2 = value2 {attrib on node}
/// </summary>
public class XmlTextPack : ITextPack
{
/// <summary>
/// Delimiter
/// </summary>
public static string Delimiter = "::";
#region Private
///// <summary>
///// Context
///// </summary>
//private class Context
//{
// public string Key;
// public string ScopeKey;
// public XmlElement XmlElement;
// public XmlDocument XmlDocument;
// public static Context GetContext(string pack, string contextKey, ref object context)
// {
// if (contextKey == null)
// throw new ArgumentNullException("contextKey");
// if (context == null)
// context = new Context();
// var context2 = (Context)context;
// if (context2.Key == contextKey)
// return context2;
// context2.Key = contextKey;
// var xmlDocument = new XmlDocument();
// if (pack.Length > 0)
// xmlDocument.LoadXml(pack);
// context2.XmlDocument = xmlDocument;
// return context2;
// }
//}
private static string EncodeKey(string key)
{
return (key.IndexOf(Delimiter) == -1 ? "\x01" + key.Replace(Delimiter, "\x01") + "-" : key.Replace(Delimiter, "\x01") + "_") ;
}
private static string DecodeKey(string key)
{
return (key.EndsWith("-") ? key.Substring(1, key.Length - 2).Replace("\x01", Delimiter) : key.Substring(0, key.Length - 1).Replace("\x01", Delimiter));
}
private static void ParseEncodedKey(string key, out bool isValue, out string scopeKey, out string itemKey)
{
int keyLength = key.Length;
isValue = (key[keyLength - 2] == '\x01');
if (!isValue)
{
int scopeIndex = key.LastIndexOf("\x01", keyLength - 2);
if (scopeIndex == 0)
{
scopeKey = string.Empty;
itemKey = key.Substring(1, keyLength - 2);
}
else
{
scopeIndex += 1;
scopeKey = key.Substring(0, scopeIndex);
itemKey = key.Substring(scopeIndex, keyLength - scopeIndex - 1);
}
}
else
{
scopeKey = key.Substring(0, keyLength - 1);
itemKey = string.Empty;
}
}
private static void ParseKey(string key, out bool isValue, out string scopeKey, out string itemKey)
{
if (key.IndexOf(Delimiter) == -1)
key = Delimiter + key;
isValue = key.EndsWith(Delimiter);
if (!isValue)
{
int scopeIndex = key.LastIndexOf(Delimiter);
if (scopeIndex == 0)
{
scopeKey = string.Empty;
itemKey = key.Substring(2);
}
else
{
scopeIndex += 2;
scopeKey = key.Substring(0, scopeIndex);
itemKey = key.Substring(scopeIndex);
}
}
else
{
scopeKey = key;
itemKey = string.Empty;
}
}
#endregion
///// <summary>
///// Gets the value associated with the specified key out of the packed representation provided.
///// </summary>
//public override string GetValue(string pack, string key, string contextKey, ref object context)
//{
// if (string.IsNullOrEmpty(pack))
// return string.Empty;
// // context
// var context2 = Context.GetContext(pack, contextKey, ref context);
// var xmlDocument = context2.XmlDocument;
// // parse key
// bool isValue;
// string scopeKey;
// string itemKey;
// ParseKey(key, out isValue, out scopeKey, out itemKey);
// // xmlelement
// XmlElement xmlElement;
// if (context2.ScopeKey != scopeKey)
// {
// context2.ScopeKey = scopeKey;
// // find element
// xmlElement = xmlDocument.DocumentElement;
// if (xmlElement == null)
// {
// context2.XmlElement = null;
// return string.Empty;
// }
// string xpath = "/" + xmlElement.Name;
// if (scopeKey.Length > 0)
// // singhj: scopeKey doesn't include trailing "::"
// xpath += "/" + scopeKey.Replace(Delimiter, "/"); // was: xpath += "/" + scopeKey.Substring(0, scopeKey.Length - 2).Replace(KernelText.Scope, "/");
// xmlElement = (xmlDocument.SelectSingleNode(xpath) as XmlElement);
// context2.XmlElement = xmlElement;
// }
// else
// xmlElement = context2.XmlElement;
// // get value
// return (xmlElement != null ? (!isValue ? xmlElement.GetAttribute(itemKey) : xmlElement.InnerText) : string.Empty);
//}
///// <summary>
///// Sets the value within the packed string specified that is associated with the key provided.
///// </summary>
//public override string SetValue(string pack, string key, string value, string contextKey, ref object context)
//{
// // context
// var context2 = Context.GetContext(pack, contextKey, ref context);
// var xmlDocument = context2.XmlDocument;
// // parse key
// bool isValue;
// string scopeKey;
// string itemKey;
// ParseKey(key, out isValue, out scopeKey, out itemKey);
// // xmlelement
// XmlElement xmlElement;
// if (context2.ScopeKey != scopeKey)
// {
// context2.ScopeKey = scopeKey;
// // find element
// xmlElement = xmlDocument.DocumentElement;
// if (xmlElement == null)
// {
// xmlElement = xmlDocument.CreateElement("root");
// xmlDocument.AppendChild(xmlElement);
// }
// if (scopeKey.Length > 0)
// {
// // singhj: scopeKey doesn't include trailing "::"
// string[] scopeKeyArray = scopeKey.Split(new string[] { Delimiter }, StringSplitOptions.None); //was: string[] scopeKeyArray = scopeKey.Substring(0, scopeKey.Length - 2).Split(new string[] { KernelText.Scope }, StringSplitOptions.None);
// foreach (string scopeKey2 in scopeKeyArray)
// {
// var xmlElement2 = xmlElement[scopeKey2];
// if (xmlElement2 == null)
// {
// xmlElement2 = xmlDocument.CreateElement(scopeKey2);
// xmlElement.AppendChild(xmlElement2);
// }
// xmlElement = xmlElement2;
// }
// }
// context2.XmlElement = xmlElement;
// }
// else
// xmlElement = context2.XmlElement;
// // set value
// if (!isValue)
// xmlElement.SetAttribute(itemKey, value);
// else
// xmlElement.Value = value;
// return xmlDocument.InnerXml;
//}
/// <summary>
/// Provides the ability to decode the contents of the pack provided into the hash instance provided, based on the logic
/// provided by <see cref="M:PackDecodeRecurse">PackDecodeRecurse</see>. The result is contained in the hash provided.
/// </summary>
/// <param name="pack">The packed string to process.</param>
/// <param name="namespaceID">The namespace ID.</param>
/// <param name="predicate">The predicate.</param>
/// <returns></returns>
public static IDictionary<string, string> Decode(string pack, string namespaceID, Predicate<string> predicate)
{
var values = new Dictionary<string, string>();
if (string.IsNullOrEmpty(pack))
return values;
using (var r = XmlReader.Create(new StringReader(pack)))
{
if (r.IsStartElement())
DecodeInternalRecurse(string.Empty, r, (namespaceID ?? string.Empty), values, predicate);
}
return values;
}
private static void DecodeInternalRecurse(string scope, XmlReader r, string namespaceID, IDictionary<string, string> values, Predicate<string> predicate)
{
bool inNamespace = scope.StartsWith(namespaceID, StringComparison.OrdinalIgnoreCase);
if (inNamespace)
{
// parse attributes
if (r.HasAttributes)
{
while (r.MoveToNextAttribute())
{
string key = scope + r.Name;
// check validkeyindex and commit
if ((predicate == null) || predicate(key))
values[scope + r.Name] = r.Value;
}
// move the reader back to the element node.
r.MoveToElement();
}
}
if (!r.IsEmptyElement)
{
// read the start tag.
r.Read();
bool isRead = true;
while (isRead)
switch (r.MoveToContent())
{
case XmlNodeType.CDATA:
case XmlNodeType.Text:
if (inNamespace)
{
string key = (scope.Length > 0 ? scope : Delimiter);
// check validkeyindex and commit
if ((predicate == null) || predicate(key))
values[key] = r.Value;
}
r.Read();
break;
case XmlNodeType.Element:
// handle nested elements.
if (r.IsStartElement())
{
DecodeInternalRecurse(scope + r.Name + Delimiter, r, namespaceID, values, predicate);
r.Read();
}
break;
default:
isRead = false;
break;
}
}
}
/// <summary>
/// Provides the ability to pack the contents in the hash provided into a different string representation.
/// Results is contained in the provided StringBuilder instance.
/// </summary>
public static string Encode(IDictionary<string, string> values, string namespaceID, Predicate<string> predicate)
{
if (values == null)
throw new ArgumentNullException("set");
if (values.Count == 0)
return string.Empty;
var b = new StringBuilder();
// pull keys from existing hash and validate against provided IDictionary, and encode into tree key structure
// field is prepended with identifyer for unencoding at the end to find original key
var keys = new List<string>(values.Keys);
for (int keyIndex = keys.Count - 1; keyIndex >= 0; keyIndex--)
{
string key = keys[keyIndex];
// check for validkeyindex
if ((predicate != null) && !predicate(key))
{
keys.RemoveAt(keyIndex);
continue;
}
// encode key
keys[keyIndex] = EncodeKey(key);
}
keys.Sort(0, keys.Count, StringComparer.OrdinalIgnoreCase);
//
using (var w = XmlTextWriter.Create(b))
{
w.WriteStartElement("r");
//
string lastScopeKey = string.Empty;
string elementValue = null;
foreach (string key in keys)
{
// parse encoded key
bool isValue;
string scopeKey;
string itemKey;
ParseEncodedKey(key, out isValue, out scopeKey, out itemKey);
// process element
if ((scopeKey.Length > 1) && (lastScopeKey != scopeKey))
{
// write latched value
if (elementValue != null)
{
w.WriteString(elementValue);
elementValue = null;
}
// element
if (scopeKey.StartsWith(lastScopeKey))
{
// start elements
int lastScopeKeyLength = lastScopeKey.Length;
var createScopeKeyArray = scopeKey.Substring(lastScopeKeyLength, scopeKey.Length - lastScopeKeyLength - 1).Split('\x01');
foreach (string createScopeKey in createScopeKeyArray)
w.WriteStartElement(createScopeKey);
}
else
{
// end and start elements
var lastScopeKeyArray = lastScopeKey.Substring(0, lastScopeKey.Length - 1).Split('\x01');
var scopeKeyArray = scopeKey.Substring(0, scopeKey.Length - 1).Split('\x01');
int scopeKeyArrayLength = scopeKeyArray.Length;
// skip existing elements
int index;
for (index = 0; index < lastScopeKeyArray.Length; index++)
if ((index >= scopeKeyArrayLength) || (scopeKeyArray[index] != lastScopeKeyArray[index]))
break;
// end elements
for (int lastScopeKeyIndex = lastScopeKeyArray.Length - 1; lastScopeKeyIndex >= index; lastScopeKeyIndex--)
w.WriteEndElement();
// start elements
for (int scopeKeyIndex = index; scopeKeyIndex < scopeKeyArray.Length; scopeKeyIndex++)
w.WriteStartElement(scopeKeyArray[scopeKeyIndex]);
}
lastScopeKey = scopeKey;
}
// decode key and set value
string value = values[DecodeKey(key)];
if (!isValue)
w.WriteAttributeString(itemKey, (value ?? string.Empty));
else
if (!string.IsNullOrEmpty(value))
elementValue = value;
}
// overflow close, write latched value
if (elementValue != null)
w.WriteString(elementValue);
w.WriteEndDocument();
}
return b.ToString();
}
#region ITextPack
IDictionary<string, string> ITextPack.Decode(string pack, string namespaceID, Predicate<string> predicate) { return Decode(pack, namespaceID, predicate); }
string ITextPack.Encode(IDictionary<string, string> values, string namespaceID, Predicate<string> predicate) { return Encode(values, namespaceID, predicate); }
#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 System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.LanguageServices.ProjectInfoService;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> :
IGenerateTypeService
where TService : AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
where TSimpleNameSyntax : TExpressionSyntax
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TExpressionSyntax : SyntaxNode
where TTypeDeclarationSyntax : SyntaxNode
where TArgumentSyntax : SyntaxNode
{
protected AbstractGenerateTypeService()
{
}
protected abstract bool TryInitializeState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions);
protected abstract TExpressionSyntax GetLeftSideOfDot(TSimpleNameSyntax simpleName);
protected abstract bool TryGetArgumentList(TObjectCreationExpressionSyntax objectCreationExpression, out IList<TArgumentSyntax> argumentList);
protected abstract string DefaultFileExtension { get; }
protected abstract IList<ITypeParameterSymbol> GetTypeParameters(State state, SemanticModel semanticModel, CancellationToken cancellationToken);
protected abstract Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken);
protected abstract IList<ParameterName> GenerateParameterNames(SemanticModel semanticModel, IList<TArgumentSyntax> arguments);
protected abstract INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, TSimpleNameSyntax simpleName, CancellationToken cancellationToken);
protected abstract ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, TArgumentSyntax argument, CancellationToken cancellationToken);
protected abstract bool IsInCatchDeclaration(TExpressionSyntax expression);
protected abstract bool IsArrayElementType(TExpressionSyntax expression);
protected abstract bool IsInVariableTypeContext(TExpressionSyntax expression);
protected abstract bool IsInValueTypeConstraintContext(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken);
protected abstract bool IsInInterfaceList(TExpressionSyntax expression);
internal abstract bool TryGetBaseList(TExpressionSyntax expression, out TypeKindOptions returnValue);
internal abstract bool IsPublicOnlyAccessibility(TExpressionSyntax expression, Project project);
internal abstract bool IsGenericName(TSimpleNameSyntax simpleName);
internal abstract bool IsSimpleName(TExpressionSyntax expression);
internal abstract Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, TSimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken);
protected abstract bool TryGetNameParts(TExpressionSyntax expression, out IList<string> nameParts);
public abstract string GetRootNamespace(CompilationOptions options);
public abstract Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken);
public async Task<IEnumerable<CodeAction>> GenerateTypeAsync(
Document document,
SyntaxNode node,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateType, cancellationToken))
{
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false);
if (state != null)
{
var actions = GetActions(semanticDocument, node, state, cancellationToken).ToList();
if (actions.Count > 1)
{
// Wrap the generate type actions into a single top level suggestion
// so as to not clutter the list.
return SpecializedCollections.SingletonEnumerable(
new MyCodeAction(FeaturesResources.Generate_type, actions.AsImmutable()));
}
else
{
return actions;
}
}
return SpecializedCollections.EmptyEnumerable<CodeAction>();
}
}
private IEnumerable<CodeAction> GetActions(
SemanticDocument document,
SyntaxNode node,
State state,
CancellationToken cancellationToken)
{
var generateNewTypeInDialog = false;
if (state.NamespaceToGenerateInOpt != null)
{
var workspace = document.Project.Solution.Workspace;
if (workspace == null || workspace.CanApplyChange(ApplyChangesKind.AddDocument))
{
generateNewTypeInDialog = true;
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: true);
}
// If they just are generating "Foo" then we want to offer to generate it into the
// namespace in the same file. However, if they are generating "SomeNS.Foo", then we
// only want to allow them to generate if "SomeNS" is the namespace they are
// currently in.
var isSimpleName = state.SimpleName == state.NameOrMemberAccessExpression;
var generateIntoContaining = IsGeneratingIntoContainingNamespace(document, node, state, cancellationToken);
if ((isSimpleName || generateIntoContaining) &&
CanGenerateIntoContainingNamespace(document, node, state, cancellationToken))
{
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: false);
}
}
if (state.TypeToGenerateInOpt != null)
{
yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: false, inNewFile: false);
}
if (generateNewTypeInDialog)
{
yield return new GenerateTypeCodeActionWithOption((TService)this, document.Document, state);
}
}
private bool CanGenerateIntoContainingNamespace(SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken)
{
var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken);
// Only allow if the containing namespace is one that can be generated
// into.
var declarationService = document.Project.LanguageServices.GetService<ISymbolDeclarationService>();
var decl = declarationService.GetDeclarations(containingNamespace)
.Where(r => r.SyntaxTree == node.SyntaxTree)
.Select(r => r.GetSyntax(cancellationToken))
.FirstOrDefault(node.GetAncestorsOrThis<SyntaxNode>().Contains);
return
decl != null &&
document.Project.LanguageServices.GetService<ICodeGenerationService>().CanAddTo(decl, document.Project.Solution, cancellationToken);
}
private bool IsGeneratingIntoContainingNamespace(
SemanticDocument document,
SyntaxNode node,
State state,
CancellationToken cancellationToken)
{
var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken);
if (containingNamespace != null)
{
var containingNamespaceName = containingNamespace.ToDisplayString();
return containingNamespaceName.Equals(state.NamespaceToGenerateInOpt);
}
return false;
}
protected static string GetTypeName(State state)
{
const string AttributeSuffix = "Attribute";
return state.IsAttribute && !state.NameIsVerbatim && !state.Name.EndsWith(AttributeSuffix, StringComparison.Ordinal)
? state.Name + AttributeSuffix
: state.Name;
}
protected IList<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
IEnumerable<SyntaxNode> typeArguments,
CancellationToken cancellationToken)
{
var arguments = typeArguments.ToList();
var arity = arguments.Count;
var typeParameters = new List<ITypeParameterSymbol>();
// For anything that was a type parameter, just use the name (if we haven't already
// used it). Otherwise, synthesize new names for the parameters.
var names = new string[arity];
var isFixed = new bool[arity];
for (var i = 0; i < arity; i++)
{
var argument = i < arguments.Count ? arguments[i] : null;
var type = argument == null ? null : semanticModel.GetTypeInfo(argument, cancellationToken).Type;
if (type is ITypeParameterSymbol)
{
var name = type.Name;
// If we haven't seen this type parameter already, then we can use this name
// and 'fix' it so that it doesn't change. Otherwise, use it, but allow it
// to be changed if it collides with anything else.
isFixed[i] = !names.Contains(name);
names[i] = name;
typeParameters.Add((ITypeParameterSymbol)type);
}
else
{
names[i] = "T";
typeParameters.Add(null);
}
}
// We can use a type parameter as long as it hasn't been used in an outer type.
var canUse = state.TypeToGenerateInOpt == null
? default(Func<string, bool>)
: s => state.TypeToGenerateInOpt.GetAllTypeParameters().All(t => t.Name != s);
var uniqueNames = NameGenerator.EnsureUniqueness(names, isFixed, canUse: canUse);
for (int i = 0; i < uniqueNames.Count; i++)
{
if (typeParameters[i] == null || typeParameters[i].Name != uniqueNames[i])
{
typeParameters[i] = CodeGenerationSymbolFactory.CreateTypeParameterSymbol(uniqueNames[i]);
}
}
return typeParameters;
}
protected Accessibility DetermineDefaultAccessibility(
State state,
SemanticModel semanticModel,
bool intoNamespace,
CancellationToken cancellationToken)
{
if (state.IsPublicAccessibilityForTypeGeneration)
{
return Accessibility.Public;
}
// If we're a nested type of the type being generated into, then the new type can be
// private. otherwise, it needs to be internal.
if (!intoNamespace && state.TypeToGenerateInOpt != null)
{
var outerTypeSymbol = semanticModel.GetEnclosingNamedType(state.SimpleName.SpanStart, cancellationToken);
if (outerTypeSymbol != null && outerTypeSymbol.IsContainedWithin(state.TypeToGenerateInOpt))
{
return Accessibility.Private;
}
}
return Accessibility.Internal;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters(
State state,
SemanticModel semanticModel,
bool intoNamespace,
CancellationToken cancellationToken)
{
var availableInnerTypeParameters = GetTypeParameters(state, semanticModel, cancellationToken);
var availableOuterTypeParameters = !intoNamespace && state.TypeToGenerateInOpt != null
? state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
protected async Task<bool> IsWithinTheImportingNamespaceAsync(Document document, int triggeringPosition, string includeUsingsOrImports, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (semanticModel != null)
{
var namespaceSymbol = semanticModel.GetEnclosingNamespace(triggeringPosition, cancellationToken);
if (namespaceSymbol != null && namespaceSymbol.ToDisplayString().StartsWith(includeUsingsOrImports, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
protected bool GeneratedTypesMustBePublic(Project project)
{
var projectInfoService = project.Solution.Workspace.Services.GetService<IProjectInfoService>();
if (projectInfoService != null)
{
return projectInfoService.GeneratedTypesMustBePublic(project);
}
return false;
}
private class MyCodeAction : CodeAction.SimpleCodeAction
{
public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions)
: base(title, nestedActions)
{
}
}
}
}
| |
using System;
using System.Collections;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using umbraco.DataLayer;
using Umbraco.Core.Persistence.Querying;
namespace umbraco.BusinessLogic
{
/// <summary>
/// represents a Umbraco back end user
/// </summary>
[Obsolete("Use the UserService instead")]
public class User
{
internal IUser UserEntity;
private int? _lazyId;
private bool? _defaultToLiveEditing;
private readonly Hashtable _notifications = new Hashtable();
private bool _notificationsInitialized = false;
internal User(IUser user)
{
UserEntity = user;
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="ID">The ID.</param>
public User(int ID)
{
SetupUser(ID);
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="ID">The ID.</param>
/// <param name="noSetup">if set to <c>true</c> [no setup].</param>
public User(int ID, bool noSetup)
{
_lazyId = ID;
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="Login">The login.</param>
/// <param name="Password">The password.</param>
public User(string Login, string Password)
{
SetupUser(getUserId(Login, Password));
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="Login">The login.</param>
public User(string Login)
{
SetupUser(getUserId(Login));
}
private void SetupUser(int ID)
{
UserEntity = ApplicationContext.Current.Services.UserService.GetUserById(ID);
if (UserEntity == null)
{
throw new ArgumentException("No User exists with ID " + ID);
}
}
/// <summary>
/// Used to persist object changes to the database.
/// </summary>
public void Save()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
ApplicationContext.Current.Services.UserService.Save(UserEntity);
OnSaving(EventArgs.Empty);
}
/// <summary>
/// Gets or sets the users name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Name;
}
set
{
UserEntity.Name = value;
}
}
/// <summary>
/// Gets or sets the users email.
/// </summary>
/// <value>The email.</value>
public string Email
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Email;
}
set
{
UserEntity.Email = value;
}
}
/// <summary>
/// Gets or sets the users language.
/// </summary>
/// <value>The language.</value>
public string Language
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Language;
}
set
{
UserEntity.Language = value;
}
}
/// <summary>
/// Gets or sets the users password.
/// </summary>
/// <value>The password.</value>
public string Password
{
get
{
return GetPassword();
}
set
{
UserEntity.RawPasswordValue = value;
}
}
/// <summary>
/// Gets the password.
/// </summary>
/// <returns></returns>
public string GetPassword()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.RawPasswordValue;
}
/// <summary>
/// Determines whether this user is an admin.
/// </summary>
/// <returns>
/// <c>true</c> if this user is admin; otherwise, <c>false</c>.
/// </returns>
[Obsolete("Use Umbraco.Core.Models.IsAdmin extension method instead", false)]
public bool IsAdmin()
{
return UserEntity.IsAdmin();
}
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public bool ValidatePassword(string password)
{
var userLogin = ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar<string>(
"SELECT userLogin FROM umbracoUser WHERE userLogin = @login AND UserPasword = @password",
new {login = LoginName, password = password});
return userLogin == this.LoginName;
}
/// <summary>
/// Determines whether this user is the root (super user).
/// </summary>
/// <returns>
/// <c>true</c> if this user is root; otherwise, <c>false</c>.
/// </returns>
public bool IsRoot()
{
return Id == 0;
}
/// <summary>
/// Gets the applications which the user has access to.
/// </summary>
/// <value>The users applications.</value>
public Application[] Applications
{
get
{
return GetApplications().ToArray();
}
}
/// <summary>
/// Get the application which the user has access to as a List
/// </summary>
/// <returns></returns>
public List<Application> GetApplications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var allApps = Application.getAll();
var apps = new List<Application>();
var sections = UserEntity.AllowedSections;
foreach (var s in sections)
{
var app = allApps.SingleOrDefault(x => x.alias == s);
if (app != null)
apps.Add(app);
}
return apps;
}
/// <summary>
/// Gets or sets the users login name
/// </summary>
/// <value>The loginname.</value>
public string LoginName
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Username;
}
set
{
if (EnsureUniqueLoginName(value, this) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", value));
UserEntity.Username = value;
}
}
private static bool EnsureUniqueLoginName(string loginName, User currentUser)
{
User[] u = User.getAllByLoginName(loginName);
if (u.Length != 0)
{
if (u[0].Id != currentUser.Id)
return false;
}
return true;
}
/// <summary>
/// Validates the users credentials.
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <returns></returns>
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public static bool validateCredentials(string lname, string passw)
{
return validateCredentials(lname, passw, true);
}
/// <summary>
/// Validates the users credentials.
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <param name="checkForUmbracoConsoleAccess">if set to <c>true</c> [check for umbraco console access].</param>
/// <returns></returns>
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public static bool validateCredentials(string lname, string passw, bool checkForUmbracoConsoleAccess)
{
string consoleCheckSql = "";
if (checkForUmbracoConsoleAccess)
consoleCheckSql = "and userNoConsole = 0 ";
using (var sqlHelper = Application.SqlHelper)
{
object tmp = sqlHelper.ExecuteScalar<object>(
"select id from umbracoUser where userDisabled = 0 " + consoleCheckSql + " and userLogin = @login and userPassword = @pw",
sqlHelper.CreateParameter("@login", lname),
sqlHelper.CreateParameter("@pw", passw)
);
// Logging
if (tmp == null)
{
LogHelper.Info<User>("Login: '" + lname + "' failed, from IP: " + System.Web.HttpContext.Current.Request.UserHostAddress);
}
return (tmp != null);
}
}
/// <summary>
/// Gets all users
/// </summary>
/// <returns></returns>
public static User[] getAll()
{
int totalRecs;
var users = ApplicationContext.Current.Services.UserService.GetAll(
0, int.MaxValue, out totalRecs);
return users.Select(x => new User(x))
.OrderBy(x => x.Name)
.ToArray();
}
/// <summary>
/// Gets the current user (logged in)
/// </summary>
/// <returns>A user or null</returns>
public static User GetCurrent()
{
try
{
if (BasePages.BasePage.umbracoUserContextID != "")
return GetUser(BasePages.BasePage.GetUserId(BasePages.BasePage.umbracoUserContextID));
else
return null;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Gets all users by email.
/// </summary>
/// <param name="email">The email.</param>
/// <returns></returns>
public static User[] getAllByEmail(string email)
{
return getAllByEmail(email, false);
}
/// <summary>
/// Gets all users by email.
/// </summary>
/// <param name="email">The email.</param>
/// <param name="useExactMatch">match exact email address or partial email address.</param>
/// <returns></returns>
public static User[] getAllByEmail(string email, bool useExactMatch)
{
int totalRecs;
if (useExactMatch)
{
return ApplicationContext.Current.Services.UserService.FindByEmail(
email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
else
{
return ApplicationContext.Current.Services.UserService.FindByEmail(
string.Format("%{0}%", email), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
}
/// <summary>
/// Gets all users by login name.
/// </summary>
/// <param name="login">The login.</param>
/// <returns></returns>
public static User[] getAllByLoginName(string login)
{
return GetAllByLoginName(login, false).ToArray();
}
/// <summary>
/// Gets all users by login name.
/// </summary>
/// <param name="login">The login.</param>
/// <param name="partialMatch">whether to use a partial match</param>
/// <returns></returns>
public static User[] getAllByLoginName(string login, bool partialMatch)
{
return GetAllByLoginName(login, partialMatch).ToArray();
}
public static IEnumerable<User> GetAllByLoginName(string login, bool partialMatch)
{
int totalRecs;
if (partialMatch)
{
return ApplicationContext.Current.Services.UserService.FindByUsername(
string.Format("%{0}%", login), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
else
{
return ApplicationContext.Current.Services.UserService.FindByUsername(
login, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
}
/// <summary>
/// Create a new user.
/// </summary>
/// <param name="name">The full name.</param>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
public static User MakeNew(string name, string lname, string passw)
{
var user = new Umbraco.Core.Models.Membership.User(name, "", lname, passw);
ApplicationContext.Current.Services.UserService.Save(user);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
}
/// <summary>
/// Creates a new user.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lname">The lname.</param>
/// <param name="passw">The passw.</param>
/// <param name="email">The email.</param>
public static User MakeNew(string name, string lname, string passw, string email)
{
var user = new Umbraco.Core.Models.Membership.User(name, email, lname, passw);
ApplicationContext.Current.Services.UserService.Save(user);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
}
/// <summary>
/// Updates the name, login name and password for the user with the specified id.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="name">The name.</param>
/// <param name="lname">The lname.</param>
/// <param name="email">The email.</param>
public static void Update(int id, string name, string lname, string email)
{
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
ApplicationContext.Current.Services.UserService.Save(found);
}
public static void Update(int id, string name, string lname, string email, bool disabled, bool noConsole)
{
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
/// Updates the membership provider properties
/// </summary>
/// <param name="id">The id.</param>
/// <param name="email"></param>
/// <param name="disabled"></param>
/// <param name="noConsole"></param>
public static void Update(int id, string email, bool disabled, bool noConsole)
{
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Email = email;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
/// Gets the ID from the user with the specified login name and password
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <returns>a user ID</returns>
public static int getUserId(string lname, string passw)
{
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found.RawPasswordValue == passw ? found.Id : -1;
}
/// <summary>
/// Gets the ID from the user with the specified login name
/// </summary>
/// <param name="lname">The login name.</param>
/// <returns>a user ID</returns>
public static int getUserId(string lname)
{
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found == null ? -1 : found.Id;
}
/// <summary>
/// Deletes this instance.
/// </summary>
[Obsolete("Deleting users are NOT supported as history needs to be kept. Please use the disable() method instead")]
public void delete()
{
//make sure you cannot delete the admin user!
if (this.Id == 0)
throw new InvalidOperationException("The Administrator account cannot be deleted");
OnDeleting(EventArgs.Empty);
ApplicationContext.Current.Services.UserService.Delete(UserEntity, true);
FlushFromCache();
}
/// <summary>
/// Disables this instance.
/// </summary>
public void disable()
{
OnDisabling(EventArgs.Empty);
//delete without the true overload will perform the disable operation
ApplicationContext.Current.Services.UserService.Delete(UserEntity);
}
/// <summary>
/// Gets the users permissions based on a nodes path
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
public string GetPermissions(string path)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var userService = ApplicationContext.Current.Services.UserService;
return string.Join("",
userService.GetPermissionsForPath(UserEntity, path).GetAllPermissions());
}
/// <summary>
/// Initializes the user node permissions
/// </summary>
[Obsolete("This method doesn't do anything whatsoever and will be removed in future versions")]
public void initCruds()
{
}
/// <summary>
/// Gets a users notifications for a specified node path.
/// </summary>
/// <param name="Path">The node path.</param>
/// <returns></returns>
public string GetNotifications(string Path)
{
string notifications = "";
if (_notificationsInitialized == false)
initNotifications();
foreach (string nodeId in Path.Split(','))
{
if (_notifications.ContainsKey(int.Parse(nodeId)))
notifications = _notifications[int.Parse(nodeId)].ToString();
}
return notifications;
}
/// <summary>
/// Clears the internal hashtable containing cached information about notifications for the user
/// </summary>
public void resetNotificationCache()
{
_notificationsInitialized = false;
_notifications.Clear();
}
/// <summary>
/// Initializes the notifications and caches them.
/// </summary>
public void initNotifications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var notifications = ApplicationContext.Current.Services.NotificationService.GetUserNotifications(UserEntity);
foreach (var n in notifications.OrderBy(x => x.EntityId))
{
int nodeId = n.EntityId;
if (_notifications.ContainsKey(nodeId) == false)
{
_notifications.Add(nodeId, string.Empty);
}
_notifications[nodeId] += n.Action;
}
_notificationsInitialized = true;
}
/// <summary>
/// Gets the user id.
/// </summary>
/// <value>The id.</value>
public int Id
{
get { return UserEntity.Id; }
}
/// <summary>
/// Clears the list of groups the user is in, ensure to call Save afterwords
/// </summary>
public void ClearGroups()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
UserEntity.ClearGroups();
}
/// <summary>
/// Adds a group to the list of groups for the user, ensure to call Save() afterwords
/// </summary>
public void AddGroup(string groupAlias)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var group = ApplicationContext.Current.Services.UserService.GetUserGroupByAlias(groupAlias);
if (group != null)
UserEntity.AddGroup(group.ToReadOnlyGroup());
}
/// <summary>
/// Returns the assigned user group aliases for the user
/// </summary>
/// <returns></returns>
public string[] GetGroups()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Groups.Select(x => x.Alias).ToArray();
}
/// <summary>
/// Gets or sets a value indicating whether the user has access to the Umbraco back end.
/// </summary>
/// <value><c>true</c> if the user has access to the back end; otherwise, <c>false</c>.</value>
public bool NoConsole
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.IsLockedOut;
}
set
{
UserEntity.IsLockedOut = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="User"/> is disabled.
/// </summary>
/// <value><c>true</c> if disabled; otherwise, <c>false</c>.</value>
public bool Disabled
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.IsApproved == false;
}
set
{
UserEntity.IsApproved = value == false;
}
}
[Obsolete("This should not be used, it will return invalid data because a user can have multiple start nodes, this will only return the first")]
public int StartNodeId
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.StartContentIds == null || UserEntity.StartContentIds.Length == 0 ? -1 : UserEntity.StartContentIds[0];
}
set
{
UserEntity.StartContentIds = new int[] { value };
}
}
[Obsolete("This should not be used, it will return invalid data because a user can have multiple start nodes, this will only return the first")]
public int StartMediaId
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.StartMediaIds == null || UserEntity.StartMediaIds.Length == 0 ? -1 : UserEntity.StartMediaIds[0];
}
set
{
UserEntity.StartMediaIds = new int[] { value };
}
}
/// <summary>
/// Flushes the user from cache.
/// </summary>
[Obsolete("This method should not be used, cache flushing is handled automatically by event handling in the web application and ensures that all servers are notified, this will not notify all servers in a load balanced environment")]
public void FlushFromCache()
{
OnFlushingFromCache(EventArgs.Empty);
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IUser>();
}
/// <summary>
/// Gets the user with a specified ID
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
[Obsolete("The legacy user object should no longer be used, use the WebSecurity class to access the current user or the UserService to retrieve a user by id")]
public static User GetUser(int id)
{
var result = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (result == null)
{
throw new ArgumentException("No user found with id " + id);
}
return new User(result);
}
[Obsolete("This should not be used it exists for legacy reasons only, use user groups and the IUserService instead, it will be removed in future versions")]
[EditorBrowsable(EditorBrowsableState.Never)]
public void AddApplication(string appAlias)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
UserEntity.AddAllowedSection(appAlias);
}
[Obsolete("This method will implicitly cause a multiple database saves and will reset the current user's dirty property, do not use this method, use the AddApplication method instead and then call Save() when you are done performing all user changes to persist the chagnes in one transaction")]
[EditorBrowsable(EditorBrowsableState.Never)]
public void addApplication(string AppAlias)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
UserEntity.AddAllowedSection(AppAlias);
//For backwards compatibility this requires an implicit save
ApplicationContext.Current.Services.UserService.Save(UserEntity);
}
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SavingEventHandler(User sender, EventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(User sender, EventArgs e);
/// <summary>
/// The disable event handler
/// </summary>
public delegate void DisablingEventHandler(User sender, EventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeletingEventHandler(User sender, EventArgs e);
/// <summary>
/// The Flush User from cache event handler
/// </summary>
public delegate void FlushingFromCacheEventHandler(User sender, EventArgs e);
/// <summary>
/// Occurs when [saving].
/// </summary>
public static event SavingEventHandler Saving;
/// <summary>
/// Raises the <see cref="E:Saving"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnSaving(EventArgs e)
{
if (Saving != null)
Saving(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(EventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [disabling].
/// </summary>
public static event DisablingEventHandler Disabling;
/// <summary>
/// Raises the <see cref="E:Disabling"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnDisabling(EventArgs e)
{
if (Disabling != null)
Disabling(this, e);
}
/// <summary>
/// Occurs when [deleting].
/// </summary>
public static event DeletingEventHandler Deleting;
/// <summary>
/// Raises the <see cref="E:Deleting"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnDeleting(EventArgs e)
{
if (Deleting != null)
Deleting(this, e);
}
/// <summary>
/// Occurs when [flushing from cache].
/// </summary>
public static event FlushingFromCacheEventHandler FlushingFromCache;
/// <summary>
/// Raises the <see cref="E:FlushingFromCache"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnFlushingFromCache(EventArgs e)
{
if (FlushingFromCache != null)
FlushingFromCache(this, e);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ServiceModel.Security;
using System.IdentityModel.Selectors;
namespace System.ServiceModel
{
public abstract class MessageSecurityVersion
{
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion Default
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
internal static MessageSecurityVersion WSSXDefault
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
internal MessageSecurityVersion() { }
public SecurityVersion SecurityVersion
{
get
{
return MessageSecurityTokenVersion.SecurityVersion;
}
}
public TrustVersion TrustVersion
{
get
{
return MessageSecurityTokenVersion.TrustVersion;
}
}
public SecureConversationVersion SecureConversationVersion
{
get
{
return MessageSecurityTokenVersion.SecureConversationVersion;
}
}
public SecurityTokenVersion SecurityTokenVersion
{
get
{
return MessageSecurityTokenVersion;
}
}
public abstract SecurityPolicyVersion SecurityPolicyVersion { get; }
public abstract BasicSecurityProfileVersion BasicSecurityProfileVersion { get; }
internal abstract MessageSecurityTokenVersion MessageSecurityTokenVersion { get; }
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11";
}
}
internal class WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return "WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10";
}
}
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10";
}
}
internal class WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10";
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13; }
}
public override string ToString()
{
return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12";
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
private static MessageSecurityVersion s_instance = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public static MessageSecurityVersion Instance
{
get { return s_instance; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10";
}
}
}
}
| |
using Lucene.Net.Support;
using System;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/* some code derived from jodk: http://code.google.com/p/jodk/ (apache 2.0)
* asin() derived from fdlibm: http://www.netlib.org/fdlibm/e_asin.c (public domain):
* =============================================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* =============================================================================
*/
/// <summary>
/// Math functions that trade off accuracy for speed. </summary>
public class SloppyMath
{
/// <summary>
/// Returns the distance in kilometers between two points
/// specified in decimal degrees (latitude/longitude). </summary>
/// <param name="lat1"> Latitude of the first point. </param>
/// <param name="lon1"> Longitude of the first point. </param>
/// <param name="lat2"> Latitude of the second point. </param>
/// <param name="lon2"> Longitude of the second point. </param>
/// <returns> distance in kilometers. </returns>
public static double Haversin(double lat1, double lon1, double lat2, double lon2)
{
double x1 = lat1 * TO_RADIANS;
double x2 = lat2 * TO_RADIANS;
double h1 = 1 - Cos(x1 - x2);
double h2 = 1 - Cos((lon1 - lon2) * TO_RADIANS);
double h = (h1 + Cos(x1) * Cos(x2) * h2) / 2;
double avgLat = (x1 + x2) / 2d;
double diameter = EarthDiameter(avgLat);
return diameter * Asin(Math.Min(1, Math.Sqrt(h)));
}
/// <summary>
/// Returns the trigonometric cosine of an angle.
/// <para/>
/// Error is around 1E-15.
/// <para/>
/// Special cases:
/// <list type="bullet">
/// <item><description>If the argument is <see cref="double.NaN"/> or an infinity, then the result is <see cref="double.NaN"/>.</description></item>
/// </list>
/// </summary>
/// <param name="a"> An angle, in radians. </param>
/// <returns> The cosine of the argument. </returns>
/// <seealso cref="Math.Cos(double)"/>
public static double Cos(double a)
{
if (a < 0.0)
{
a = -a;
}
if (a > SIN_COS_MAX_VALUE_FOR_INT_MODULO)
{
return Math.Cos(a);
}
// index: possibly outside tables range.
int index = (int)(a * SIN_COS_INDEXER + 0.5);
double delta = (a - index * SIN_COS_DELTA_HI) - index * SIN_COS_DELTA_LO;
// Making sure index is within tables range.
// Last value of each table is the same than first, so we ignore it (tabs size minus one) for modulo.
index &= (SIN_COS_TABS_SIZE - 2); // index % (SIN_COS_TABS_SIZE-1)
double indexCos = cosTab[index];
double indexSin = sinTab[index];
return indexCos + delta * (-indexSin + delta * (-indexCos * ONE_DIV_F2 + delta * (indexSin * ONE_DIV_F3 + delta * indexCos * ONE_DIV_F4)));
}
/// <summary>
/// Returns the arc sine of a value.
/// <para/>
/// The returned angle is in the range <i>-pi</i>/2 through <i>pi</i>/2.
/// Error is around 1E-7.
/// <para/>
/// Special cases:
/// <list type="bullet">
/// <item><description>If the argument is <see cref="double.NaN"/> or its absolute value is greater than 1, then the result is <see cref="double.NaN"/>.</description></item>
/// </list>
/// </summary>
/// <param name="a"> the value whose arc sine is to be returned. </param>
/// <returns> arc sine of the argument </returns>
/// <seealso cref="Math.Asin(double)"/>
// because asin(-x) = -asin(x), asin(x) only needs to be computed on [0,1].
// ---> we only have to compute asin(x) on [0,1].
// For values not close to +-1, we use look-up tables;
// for values near +-1, we use code derived from fdlibm.
public static double Asin(double a)
{
bool negateResult;
if (a < 0.0)
{
a = -a;
negateResult = true;
}
else
{
negateResult = false;
}
if (a <= ASIN_MAX_VALUE_FOR_TABS)
{
int index = (int)(a * ASIN_INDEXER + 0.5);
double delta = a - index * ASIN_DELTA;
double result = asinTab[index] + delta * (asinDer1DivF1Tab[index] + delta * (asinDer2DivF2Tab[index] + delta * (asinDer3DivF3Tab[index] + delta * asinDer4DivF4Tab[index])));
return negateResult ? -result : result;
} // value > ASIN_MAX_VALUE_FOR_TABS, or value is NaN
else
{
// this part is derived from fdlibm.
if (a < 1.0)
{
double t = (1.0 - a) * 0.5;
double p = t * (ASIN_PS0 + t * (ASIN_PS1 + t * (ASIN_PS2 + t * (ASIN_PS3 + t * (ASIN_PS4 + t * ASIN_PS5)))));
double q = 1.0 + t * (ASIN_QS1 + t * (ASIN_QS2 + t * (ASIN_QS3 + t * ASIN_QS4)));
double s = Math.Sqrt(t);
double z = s + s * (p / q);
double result = ASIN_PIO2_HI - ((z + z) - ASIN_PIO2_LO);
return negateResult ? -result : result;
} // value >= 1.0, or value is NaN
else
{
if (a == 1.0)
{
return negateResult ? -Math.PI / 2 : Math.PI / 2;
}
else
{
return double.NaN;
}
}
}
}
/// <summary>
/// Return an approximate value of the diameter of the earth at the given latitude, in kilometers. </summary>
public static double EarthDiameter(double latitude)
{
if(double.IsNaN(latitude))
return double.NaN;
int index = (int)(Math.Abs(latitude) * RADIUS_INDEXER + 0.5) % earthDiameterPerLatitude.Length;
return earthDiameterPerLatitude[index];
}
// haversin
private static readonly double TO_RADIANS = Math.PI / 180D;
// cos/asin
private const double ONE_DIV_F2 = 1 / 2.0;
private const double ONE_DIV_F3 = 1 / 6.0;
private const double ONE_DIV_F4 = 1 / 24.0;
private static readonly double PIO2_HI = BitConverter.Int64BitsToDouble(0x3FF921FB54400000L); // 1.57079632673412561417e+00 first 33 bits of pi/2
private static readonly double PIO2_LO = BitConverter.Int64BitsToDouble(0x3DD0B4611A626331L); // 6.07710050650619224932e-11 pi/2 - PIO2_HI
private static readonly double TWOPI_HI = 4 * PIO2_HI;
private static readonly double TWOPI_LO = 4 * PIO2_LO;
private static readonly int SIN_COS_TABS_SIZE = (1 << 11) + 1;
private static readonly double SIN_COS_DELTA_HI = TWOPI_HI / (SIN_COS_TABS_SIZE - 1);
private static readonly double SIN_COS_DELTA_LO = TWOPI_LO / (SIN_COS_TABS_SIZE - 1);
private static readonly double SIN_COS_INDEXER = 1 / (SIN_COS_DELTA_HI + SIN_COS_DELTA_LO);
private static readonly double[] sinTab = new double[SIN_COS_TABS_SIZE];
private static readonly double[] cosTab = new double[SIN_COS_TABS_SIZE];
// Max abs value for fast modulo, above which we use regular angle normalization.
// this value must be < (Integer.MAX_VALUE / SIN_COS_INDEXER), to stay in range of int type.
// The higher it is, the higher the error, but also the faster it is for lower values.
// If you set it to ((Integer.MAX_VALUE / SIN_COS_INDEXER) * 0.99), worse accuracy on double range is about 1e-10.
internal static readonly double SIN_COS_MAX_VALUE_FOR_INT_MODULO = ((int.MaxValue >> 9) / SIN_COS_INDEXER) * 0.99;
// Supposed to be >= sin(77.2deg), as fdlibm code is supposed to work with values > 0.975,
// but seems to work well enough as long as value >= sin(25deg).
private static readonly double ASIN_MAX_VALUE_FOR_TABS = Math.Sin(73.0.ToRadians());
private static readonly int ASIN_TABS_SIZE = (1 << 13) + 1;
private static readonly double ASIN_DELTA = ASIN_MAX_VALUE_FOR_TABS / (ASIN_TABS_SIZE - 1);
private static readonly double ASIN_INDEXER = 1 / ASIN_DELTA;
private static readonly double[] asinTab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer1DivF1Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer2DivF2Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer3DivF3Tab = new double[ASIN_TABS_SIZE];
private static readonly double[] asinDer4DivF4Tab = new double[ASIN_TABS_SIZE];
private static readonly double ASIN_PIO2_HI = BitConverter.Int64BitsToDouble(0x3FF921FB54442D18L); // 1.57079632679489655800e+00
private static readonly double ASIN_PIO2_LO = BitConverter.Int64BitsToDouble(0x3C91A62633145C07L); // 6.12323399573676603587e-17
private static readonly double ASIN_PS0 = BitConverter.Int64BitsToDouble(0x3fc5555555555555L); // 1.66666666666666657415e-01
private static readonly double ASIN_PS1 = BitConverter.Int64BitsToDouble(unchecked((long)0xbfd4d61203eb6f7dL)); // -3.25565818622400915405e-01
private static readonly double ASIN_PS2 = BitConverter.Int64BitsToDouble(0x3fc9c1550e884455L); // 2.01212532134862925881e-01
private static readonly double ASIN_PS3 = BitConverter.Int64BitsToDouble(unchecked((long)0xbfa48228b5688f3bL)); // -4.00555345006794114027e-02
private static readonly double ASIN_PS4 = BitConverter.Int64BitsToDouble(0x3f49efe07501b288L); // 7.91534994289814532176e-04
private static readonly double ASIN_PS5 = BitConverter.Int64BitsToDouble(0x3f023de10dfdf709L); // 3.47933107596021167570e-05
private static readonly double ASIN_QS1 = BitConverter.Int64BitsToDouble(unchecked((long)0xc0033a271c8a2d4bL)); // -2.40339491173441421878e+00
private static readonly double ASIN_QS2 = BitConverter.Int64BitsToDouble(0x40002ae59c598ac8L); // 2.02094576023350569471e+00
private static readonly double ASIN_QS3 = BitConverter.Int64BitsToDouble(unchecked((long)0xbfe6066c1b8d0159L)); // -6.88283971605453293030e-01
private static readonly double ASIN_QS4 = BitConverter.Int64BitsToDouble(0x3fb3b8c5b12e9282L); // 7.70381505559019352791e-02
private static readonly int RADIUS_TABS_SIZE = (1 << 10) + 1;
private static readonly double RADIUS_DELTA = (Math.PI / 2d) / (RADIUS_TABS_SIZE - 1);
private static readonly double RADIUS_INDEXER = 1d / RADIUS_DELTA;
private static readonly double[] earthDiameterPerLatitude = new double[RADIUS_TABS_SIZE];
/// <summary>
/// Initializes look-up tables. </summary>
static SloppyMath()
{
// sin and cos
int SIN_COS_PI_INDEX = (SIN_COS_TABS_SIZE - 1) / 2;
int SIN_COS_PI_MUL_2_INDEX = 2 * SIN_COS_PI_INDEX;
int SIN_COS_PI_MUL_0_5_INDEX = SIN_COS_PI_INDEX / 2;
int SIN_COS_PI_MUL_1_5_INDEX = 3 * SIN_COS_PI_INDEX / 2;
for (int i = 0; i < SIN_COS_TABS_SIZE; i++)
{
// angle: in [0,2*PI].
double angle = i * SIN_COS_DELTA_HI + i * SIN_COS_DELTA_LO;
double sinAngle = Math.Sin(angle);
double cosAngle = Math.Cos(angle);
// For indexes corresponding to null cosine or sine, we make sure the value is zero
// and not an epsilon. this allows for a much better accuracy for results close to zero.
if (i == SIN_COS_PI_INDEX)
{
sinAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_2_INDEX)
{
sinAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_0_5_INDEX)
{
cosAngle = 0.0;
}
else if (i == SIN_COS_PI_MUL_1_5_INDEX)
{
cosAngle = 0.0;
}
sinTab[i] = sinAngle;
cosTab[i] = cosAngle;
}
// asin
for (int i = 0; i < ASIN_TABS_SIZE; i++)
{
// x: in [0,ASIN_MAX_VALUE_FOR_TABS].
double x = i * ASIN_DELTA;
asinTab[i] = Math.Asin(x);
double oneMinusXSqInv = 1.0 / (1 - x * x);
double oneMinusXSqInv0_5 = Math.Sqrt(oneMinusXSqInv);
double oneMinusXSqInv1_5 = oneMinusXSqInv0_5 * oneMinusXSqInv;
double oneMinusXSqInv2_5 = oneMinusXSqInv1_5 * oneMinusXSqInv;
double oneMinusXSqInv3_5 = oneMinusXSqInv2_5 * oneMinusXSqInv;
asinDer1DivF1Tab[i] = oneMinusXSqInv0_5;
asinDer2DivF2Tab[i] = (x * oneMinusXSqInv1_5) * ONE_DIV_F2;
asinDer3DivF3Tab[i] = ((1 + 2 * x * x) * oneMinusXSqInv2_5) * ONE_DIV_F3;
asinDer4DivF4Tab[i] = ((5 + 2 * x * (2 + x * (5 - 2 * x))) * oneMinusXSqInv3_5) * ONE_DIV_F4;
}
// WGS84 earth-ellipsoid major (a) and minor (b) radius
const double a = 6378137; // [m]
const double b = 6356752.31420; // [m]
double a2 = a * a;
double b2 = b * b;
earthDiameterPerLatitude[0] = 2 * a / 1000d;
earthDiameterPerLatitude[RADIUS_TABS_SIZE - 1] = 2 * b / 1000d;
// earth radius
for (int i = 1; i < RADIUS_TABS_SIZE - 1; i++)
{
double lat = Math.PI * i / (2d * RADIUS_TABS_SIZE - 1);
double one = Math.Pow(a2 * Math.Cos(lat), 2);
double two = Math.Pow(b2 * Math.Sin(lat), 2);
double three = Math.Pow(a * Math.Cos(lat), 2);
double four = Math.Pow(b * Math.Sin(lat), 2);
double radius = Math.Sqrt((one + two) / (three + four));
earthDiameterPerLatitude[i] = 2 * radius / 1000d;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Validation;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner Builder class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A sorted dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// This class allows multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The binary tree used to store the contents of the map. Contents are typically not entirely frozen.
/// </summary>
private Node root = Node.EmptyNode;
/// <summary>
/// The key comparer.
/// </summary>
private IComparer<TKey> keyComparer = Comparer<TKey>.Default;
/// <summary>
/// The value comparer.
/// </summary>
private IEqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
/// <summary>
/// The number of entries in the map.
/// </summary>
private int count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedDictionary<TKey, TValue> immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="map">A map to act as the basis for a new map.</param>
internal Builder(ImmutableSortedDictionary<TKey, TValue> map)
{
Requires.NotNull(map, "map");
this.root = map.root;
this.keyComparer = map.KeyComparer;
this.valueComparer = map.ValueComparer;
this.count = map.Count;
this.immutable = map;
}
#region IDictionary<TKey, TValue> Properties and Indexer
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Root.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get { return this.Root.Keys; }
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Root.Values.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get { return this.Root.Values; }
}
/// <summary>
/// Gets the number of elements in this map.
/// </summary>
public int Count
{
get { return this.count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return this.version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return this.root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
this.version++;
if (this.root != value)
{
this.root = value;
// Clear any cached value for the immutable view since it is now invalidated.
this.immutable = null;
}
}
}
#region IDictionary<TKey, TValue> Indexer
/// <summary>
/// Gets or sets the value for a given key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the given key.</returns>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
bool replacedExistingValue, mutated;
this.Root = this.root.SetItem(key, value, this.keyComparer, this.valueComparer, out replacedExistingValue, out mutated);
if (mutated && !replacedExistingValue)
{
this.count++;
}
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection" />.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (this.syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null);
}
return this.syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection" /> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IComparer<TKey> KeyComparer
{
get
{
return this.keyComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.keyComparer)
{
var newRoot = Node.EmptyNode;
int count = 0;
foreach (var item in this)
{
bool mutated;
newRoot = newRoot.Add(item.Key, item.Value, value, this.valueComparer, out mutated);
if (mutated)
{
count++;
}
}
this.keyComparer = value;
this.Root = newRoot;
this.count = count;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return this.valueComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != this.valueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
this.valueComparer = value;
this.immutable = null; // invalidate cached immutable
}
}
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name="key">The <see cref="T:System.Object" /> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="T:System.Object" /> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IDictionary" /> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary" /> object.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.IDictionary" /> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="T:System.Collections.IDictionaryEnumerator" /> object for the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IDictionaryEnumerator" /> object for the <see cref="T:System.Collections.IDictionary" /> object.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary" /> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array" /> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
this.Root.CopyTo(array, index, this.Count);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public void Add(TKey key, TValue value)
{
bool mutated;
this.Root = this.Root.Add(key, value, this.keyComparer, this.valueComparer, out mutated);
if (mutated)
{
this.count++;
}
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public bool ContainsKey(TKey key)
{
return this.Root.ContainsKey(key, this.keyComparer);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public bool Remove(TKey key)
{
bool mutated;
this.Root = this.Root.Remove(key, this.keyComparer, out mutated);
if (mutated)
{
this.count--;
}
return mutated;
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
return this.Root.TryGetValue(key, this.keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary<TKey, TValue>"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, "equalKey");
return this.Root.TryGetKey(equalKey, this.keyComparer, out actualKey);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode;
this.count = 0;
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this.Root.Contains(item, this.keyComparer, this.valueComparer);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex, this.Count);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// See <see cref="IDictionary<TKey, TValue>"/>
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Public methods
/// <summary>
/// Determines whether the ImmutableSortedMap<TKey,TValue>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the ImmutableSortedMap<TKey,TValue>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the ImmutableSortedMap<TKey,TValue> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return this.root.ContainsValue(value, this.valueComparer);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="items">The keys for entries to remove from the dictionary.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
foreach (var pair in items)
{
this.Add(pair);
}
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or <c>default(TValue)</c> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable sorted dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (this.immutable == null)
{
this.immutable = Wrap(this.Root, this.count, this.keyComparer, this.valueComparer);
}
return this.immutable;
}
#endregion
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
[ExcludeFromCodeCoverage]
internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedDictionary<TKey, TValue>.Builder map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue>"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, "map");
this.map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (this.contents == null)
{
this.contents = this.map.ToArray(this.map.Count);
}
return this.contents;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
namespace Mono.Cecil.CodeDom.Rocks
{
internal static class NodeMatcherEx
{
[DebuggerStepThrough]
public static NodeMatcherEx.NodeMatcher ToMatcher(this CodeDomExpression node)
{
return new NodeMatcherEx.NodeMatcher(node);
}
internal struct NodeMatcher
{
private CodeDomExpression _node;
private bool _ismatch;
[DebuggerStepThrough]
public NodeMatcher(CodeDomExpression node)
{
this = new NodeMatcherEx.NodeMatcher();
this._node = node;
this._ismatch = node != null;
}
[DebuggerStepThrough]
public static implicit operator bool(NodeMatcherEx.NodeMatcher matcher)
{
return matcher._ismatch;
}
public NodeMatcherEx.NodeMatcher Match<T>(out T typedNode, Predicate<T> predicate) where T : CodeDomExpression
{
typedNode = default (T);
if (!this._ismatch)
return this;
typedNode = this._node as T;
return (typedNode == null || predicate != null && !predicate(typedNode)) ? this.Fail() : this;
}
public NodeMatcherEx.NodeMatcher Match<T>(Predicate<T> predicate) where T : CodeDomExpression
{
T typedNode;
return this.Match<T>(out typedNode, predicate);
}
public NodeMatcherEx.NodeMatcher Match<T>(out T typedNode) where T : CodeDomExpression
{
return this.Match<T>(out typedNode, (Predicate<T>) null);
}
public NodeMatcherEx.NodeMatcher Match<T>() where T : CodeDomExpression
{
T typedNode;
return this.Match<T>(out typedNode, (Predicate<T>) null);
}
/*
public NodeMatcherEx.NodeMatcher MatchLocalVariableReference(ILocalVariable variable)
{
if (!this._ismatch)
return this;
ILocalVariableReferenceExpression referenceExpression = this._node as ILocalVariableReferenceExpression;
if (referenceExpression == null || referenceExpression.Variable != variable)
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchLocalVariableReference(out ILocalVariable variable)
{
variable = (ILocalVariable) null;
if (!this._ismatch)
return this;
ILocalVariableReferenceExpression referenceExpression = this._node as ILocalVariableReferenceExpression;
if (referenceExpression == null)
return this.Fail();
variable = referenceExpression.Variable;
return this;
}
public NodeMatcherEx.NodeMatcher MatchParameterReference(IMethodParameter parameter)
{
if (!this._ismatch)
return this;
IParameterReferenceExpression referenceExpression = this._node as IParameterReferenceExpression;
if (referenceExpression == null || referenceExpression.Parameter != parameter)
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchParameterReference(out IMethodParameter parameter)
{
parameter = (IMethodParameter) null;
if (!this._ismatch)
return this;
IParameterReferenceExpression referenceExpression = this._node as IParameterReferenceExpression;
if (referenceExpression == null)
return this.Fail();
parameter = referenceExpression.Parameter;
return this;
}
public NodeMatcherEx.NodeMatcher MatchLiteralAgainstValue([NotNull] object value)
{
if (value == null)
throw new ArgumentNullException("value");
if (!this._ismatch)
return this;
ILiteralExpression literalExpression = this._node as ILiteralExpression;
if (literalExpression == null)
return this.Fail();
this._ismatch = literalExpression.Value.ElementType == MetadataEx.ToElementType(value.GetType()) && object.Equals(literalExpression.Value.Value, value);
return this;
}
public NodeMatcherEx.NodeMatcher MatchLiteralAgainstConstant([NotNull] Constant value)
{
if (value == null)
throw new ArgumentNullException("value");
if (!this._ismatch)
return this;
ILiteralExpression literalExpression = this._node as ILiteralExpression;
if (literalExpression == null)
return this.Fail();
this._ismatch = literalExpression.Value.Equals(value);
return this;
}
public NodeMatcherEx.NodeMatcher MatchLiteral<T>(out T value)
{
value = default (T);
if (!this._ismatch)
return this;
ILiteralExpression literalExpression = this._node as ILiteralExpression;
if (literalExpression == null || !literalExpression.Value.Is<T>())
return this.Fail();
value = literalExpression.Value.As<T>();
return this;
}
public NodeMatcherEx.NodeMatcher MatchNullLiteral()
{
if (!this._ismatch)
return this;
ILiteralExpression literalExpression = this._node as ILiteralExpression;
if (literalExpression == null || !literalExpression.Value.IsNull)
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchExpressionStatement<T>(out IExpressionStatement expressionStatement, Predicate<T> predicate) where T : class, IExpression
{
expressionStatement = (IExpressionStatement) null;
if (!this._ismatch)
return this;
expressionStatement = this._node as IExpressionStatement;
if (expressionStatement == null)
return this.Fail();
T obj = expressionStatement.Expression as T;
if ((object) obj == null)
return this.Fail();
this._ismatch = predicate(obj);
return this;
}
public NodeMatcherEx.NodeMatcher MatchExpressionStatement<T>(Predicate<T> predicate) where T : class, IExpression
{
IExpressionStatement expressionStatement;
return this.MatchExpressionStatement<T>(out expressionStatement, predicate);
}
public NodeMatcherEx.NodeMatcher MatchExpressionStatement<T>(out T expression, Predicate<T> predicate) where T : class, IExpression
{
expression = default (T);
if (!this._ismatch)
return this;
IExpressionStatement expressionStatement = this._node as IExpressionStatement;
if (expressionStatement == null)
return this.Fail();
expression = expressionStatement.Expression as T;
if ((object) expression == null || predicate != null && !predicate(expression))
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchExpressionStatement<T>(out T expression) where T : class, IExpression
{
return this.MatchExpressionStatement<T>(out expression, (Predicate<T>) null);
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, IMetadataType expectedType, out ITypeCastExpression typeCast, Predicate<T> predicate) where T : class, IExpression
{
typeCast = (ITypeCastExpression) null;
if (!this._ismatch)
return this;
typeCast = this._node as ITypeCastExpression;
INode node;
if (typeCast != null && (expectedType == null || MetadataTypeEx.IsEqualTo(typeCast.TargetType, expectedType)))
{
node = (INode) typeCast.Argument;
}
else
{
if (isMandatory)
return this.Fail();
node = this._node;
}
T obj = node as T;
if ((object) obj == null || predicate != null && !predicate(obj))
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, IMetadataType expectedType, Predicate<T> predicate) where T : class, IExpression
{
ITypeCastExpression typeCast;
return this.MatchTypeCast<T>(isMandatory, expectedType, out typeCast, predicate);
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, out ITypeCastExpression typeCast, Predicate<T> predicate) where T : class, IExpression
{
return this.MatchTypeCast<T>(isMandatory, (IMetadataType) null, out typeCast, predicate);
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, IMetadataType expectedType, out T expression, Predicate<T> predicate) where T : class, IExpression
{
expression = default (T);
if (!this._ismatch)
return this;
ITypeCastExpression typeCastExpression = this._node as ITypeCastExpression;
INode node;
if (typeCastExpression != null && (expectedType == null || MetadataTypeEx.IsEqualTo(typeCastExpression.TargetType, expectedType)))
{
node = (INode) typeCastExpression.Argument;
}
else
{
if (isMandatory)
return this.Fail();
node = this._node;
}
expression = node as T;
if ((object) expression == null || predicate != null && !predicate(expression))
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, out T expression, Predicate<T> predicate) where T : class, IExpression
{
return this.MatchTypeCast<T>(isMandatory, (IMetadataType) null, out expression, predicate);
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, IMetadataType expectedType, out T expression) where T : class, IExpression
{
return this.MatchTypeCast<T>(isMandatory, expectedType, out expression, (Predicate<T>) null);
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, IMetadataType expectedType, out ITypeCastExpression typeCast, out T expression) where T : class, IExpression
{
typeCast = (ITypeCastExpression) null;
expression = default (T);
if (!this._ismatch)
return this;
typeCast = this._node as ITypeCastExpression;
INode node;
if (typeCast != null && (expectedType == null || MetadataTypeEx.IsEqualTo(typeCast.TargetType, expectedType)))
{
node = (INode) typeCast.Argument;
}
else
{
if (isMandatory)
return this.Fail();
node = this._node;
}
expression = node as T;
if ((object) expression == null)
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchTypeCast<T>(bool isMandatory, out ITypeCastExpression typeCast, out T expression) where T : class, IExpression
{
return this.MatchTypeCast<T>(isMandatory, (IMetadataType) null, out typeCast, out expression);
}
public NodeMatcherEx.NodeMatcher MatchBox<T>(bool isMandatory, IMetadataType type, out T expression, Predicate<T> predicate) where T : class, IExpression
{
expression = default (T);
if (!this._ismatch)
return this;
IBoxExpression boxExpression = this._node as IBoxExpression;
INode node;
if (boxExpression != null && MetadataTypeEx.IsEqualTo(boxExpression.SourceType, type))
{
node = (INode) boxExpression.Argument;
}
else
{
if (isMandatory)
return this.Fail();
node = this._node;
}
expression = node as T;
if ((object) expression == null || predicate != null && !predicate(expression))
return this.Fail();
else
return this;
}
public NodeMatcherEx.NodeMatcher MatchBox<T>(bool isMandatory, IMetadataType type, out T expression) where T : class, IExpression
{
return this.MatchBox<T>(isMandatory, type, out expression, (Predicate<T>) null);
}
public NodeMatcherEx.NodeMatcher MatchBox<T>(bool isMandatory, IMetadataType type, Predicate<T> predicate) where T : class, IExpression
{
T expression;
return this.MatchBox<T>(isMandatory, type, out expression, predicate);
}
public NodeMatcherEx.NodeMatcher MatchBox()
{
if (!this._ismatch)
return this;
IBoxExpression boxExpression = this._node as IBoxExpression;
if (boxExpression == null)
return this.Fail();
this._node = (INode) boxExpression.Argument;
return this;
}
public NodeMatcherEx.NodeMatcher MatchRef()
{
if (!this._ismatch)
return this;
IRefExpression refExpression = this._node as IRefExpression;
if (refExpression == null)
return this.Fail();
this._node = (INode) refExpression.Argument;
return this;
}
public NodeMatcherEx.NodeMatcher MatchDeref()
{
if (!this._ismatch)
return this;
IDerefExpression derefExpression = this._node as IDerefExpression;
if (derefExpression == null)
return this.Fail();
this._node = (INode) derefExpression.Argument;
return this;
}
public NodeMatcherEx.NodeMatcher MatchOptionalNegation(out bool negate)
{
negate = false;
if (!this._ismatch)
return this;
IUnaryOperationExpression operationExpression = this._node as IUnaryOperationExpression;
if (operationExpression == null || operationExpression.OperationType != OperationType.LogicalNeg)
return this;
negate = true;
this._node = (INode) operationExpression.Argument;
return this;
}
public NodeMatcherEx.NodeMatcher MatchEqualityComparison<T>(out bool negate, Predicate<T> predicate) where T : class, IAbstractBinaryOperationExpression
{
this = this.MatchOptionalNegation(out negate);
if (!this._ismatch)
return this;
T obj = this._node as T;
if ((object) obj == null || !OperationTypeEx.IsAnyOf(obj.OperationType, OperationType.Equal, OperationType.NotEqual))
return this.Fail();
// ISSUE: explicit reference operation
// ISSUE: variable of a reference type
bool& local = @negate;
// ISSUE: explicit reference operation
int num = ^local ^ obj.OperationType == OperationType.NotEqual ? 1 : 0;
// ISSUE: explicit reference operation
^local = num != 0;
if (!predicate(obj))
return this.Fail();
else
return this;
}
*/
public NodeMatcherEx.NodeMatcher MatchNullRightSibling()
{
if (!_ismatch)
return this;
_ismatch = _node.GetRightSibling() == null;
return this;
}
public NodeMatcherEx.NodeMatcher MatchNullLeftSibling()
{
if (!_ismatch)
return this;
_ismatch = _node.GetLeftSibling() == null;
return this;
}
public NodeMatcherEx.NodeMatcher ToParent()
{
if (!_ismatch)
return this;
if (_node.ParentNode == null)
return Fail();
_node = _node.ParentNode;
return this;
}
public NodeMatcherEx.NodeMatcher ToLeftSibling()
{
if (!_ismatch)
return this;
var leftSibling = _node.GetLeftSibling();
if (leftSibling == null)
return Fail();
_node = leftSibling;
return this;
}
public NodeMatcherEx.NodeMatcher ToRightSibling()
{
if (!_ismatch)
return this;
var rightSibling = _node.GetRightSibling();
if (rightSibling == null)
return Fail();
_node = rightSibling;
return this;
}
public NodeMatcherEx.NodeMatcher ToFirstStatement()
{
if (!_ismatch)
return this;
var blockStatement = _node as CodeDomGroupExpression;
if (blockStatement == null)
return this;
var first = blockStatement.Nodes.FirstOrDefault();
if (first == null)
return Fail();
_node = first;
return this;
}
public NodeMatcherEx.NodeMatcher ToLastStatement()
{
if (!_ismatch)
return this;
var blockStatement = _node as CodeDomGroupExpression;
if (blockStatement == null)
return this;
var last = blockStatement.Nodes.LastOrDefault();
if (last == null)
return Fail();
_node = last;
return this;
}
public NodeMatcherEx.NodeMatcher ToOnlyStatement()
{
if (!_ismatch)
return this;
var blockStatement = _node as CodeDomGroupExpression;
if (blockStatement == null)
return this;
if (blockStatement.Nodes.Count != 1)
return Fail();
_node = blockStatement.Nodes.First();
return this;
}
private NodeMatcherEx.NodeMatcher Fail()
{
_ismatch = false;
return this;
}
}
}
}
| |
// 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.ComponentModel;
using System.Xml.Serialization;
using System.Diagnostics;
namespace System.Xml.Schema
{
public class XmlSchemaElement : XmlSchemaParticle
{
private bool _isAbstract;
private bool _hasAbstractAttribute;
private bool _isNillable;
private bool _hasNillableAttribute;
private bool _isLocalTypeDerivationChecked;
private XmlSchemaDerivationMethod _block = XmlSchemaDerivationMethod.None;
private XmlSchemaDerivationMethod _final = XmlSchemaDerivationMethod.None;
private XmlSchemaForm _form = XmlSchemaForm.None;
private string _defaultValue;
private string _fixedValue;
private string _name;
private XmlQualifiedName _refName = XmlQualifiedName.Empty;
private XmlQualifiedName _substitutionGroup = XmlQualifiedName.Empty;
private XmlQualifiedName _typeName = XmlQualifiedName.Empty;
private XmlSchemaType _type = null;
private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty;
private XmlSchemaType _elementType;
private XmlSchemaDerivationMethod _blockResolved;
private XmlSchemaDerivationMethod _finalResolved;
private XmlSchemaObjectCollection _constraints;
private SchemaElementDecl _elementDecl;
[XmlAttribute("abstract"), DefaultValue(false)]
public bool IsAbstract
{
get { return _isAbstract; }
set
{
_isAbstract = value;
_hasAbstractAttribute = true;
}
}
[XmlAttribute("block"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod Block
{
get { return _block; }
set { _block = value; }
}
[XmlAttribute("default")]
[DefaultValue(null)]
public string DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; }
}
[XmlAttribute("final"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod Final
{
get { return _final; }
set { _final = value; }
}
[XmlAttribute("fixed")]
[DefaultValue(null)]
public string FixedValue
{
get { return _fixedValue; }
set { _fixedValue = value; }
}
[XmlAttribute("form"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm Form
{
get { return _form; }
set { _form = value; }
}
[XmlAttribute("name"), DefaultValue("")]
public string Name
{
get { return _name; }
set { _name = value; }
}
[XmlAttribute("nillable"), DefaultValue(false)]
public bool IsNillable
{
get { return _isNillable; }
set { _isNillable = value; _hasNillableAttribute = true; }
}
[XmlIgnore]
internal bool HasNillableAttribute
{
get { return _hasNillableAttribute; }
}
[XmlIgnore]
internal bool HasAbstractAttribute
{
get { return _hasAbstractAttribute; }
}
[XmlAttribute("ref")]
public XmlQualifiedName RefName
{
get { return _refName; }
set { _refName = (value == null ? XmlQualifiedName.Empty : value); }
}
[XmlAttribute("substitutionGroup")]
public XmlQualifiedName SubstitutionGroup
{
get { return _substitutionGroup; }
set { _substitutionGroup = (value == null ? XmlQualifiedName.Empty : value); }
}
[XmlAttribute("type")]
public XmlQualifiedName SchemaTypeName
{
get { return _typeName; }
set { _typeName = (value == null ? XmlQualifiedName.Empty : value); }
}
[XmlElement("complexType", typeof(XmlSchemaComplexType)),
XmlElement("simpleType", typeof(XmlSchemaSimpleType))]
public XmlSchemaType SchemaType
{
get { return _type; }
set { _type = value; }
}
[XmlElement("key", typeof(XmlSchemaKey)),
XmlElement("keyref", typeof(XmlSchemaKeyref)),
XmlElement("unique", typeof(XmlSchemaUnique))]
public XmlSchemaObjectCollection Constraints
{
get
{
if (_constraints == null)
{
_constraints = new XmlSchemaObjectCollection();
}
return _constraints;
}
}
[XmlIgnore]
public XmlQualifiedName QualifiedName
{
get { return _qualifiedName; }
}
[XmlIgnore]
[Obsolete("This property has been deprecated. Please use ElementSchemaType property that returns a strongly typed element type. https://go.microsoft.com/fwlink/?linkid=14202")]
public object ElementType
{
get
{
if (_elementType == null)
return null;
if (_elementType.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return _elementType.Datatype; //returns XmlSchemaDatatype;
}
return _elementType;
}
}
[XmlIgnore]
public XmlSchemaType ElementSchemaType
{
get { return _elementType; }
}
[XmlIgnore]
public XmlSchemaDerivationMethod BlockResolved
{
get { return _blockResolved; }
}
[XmlIgnore]
public XmlSchemaDerivationMethod FinalResolved
{
get { return _finalResolved; }
}
internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler)
{
if (schemaSet != null)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
readerSettings.ValidationEventHandler += valEventHandler;
return new XsdValidatingReader(reader, resolver, readerSettings, this);
}
return null;
}
internal void SetQualifiedName(XmlQualifiedName value)
{
_qualifiedName = value;
}
internal void SetElementType(XmlSchemaType value)
{
_elementType = value;
}
internal void SetBlockResolved(XmlSchemaDerivationMethod value)
{
_blockResolved = value;
}
internal void SetFinalResolved(XmlSchemaDerivationMethod value)
{
_finalResolved = value;
}
[XmlIgnore]
internal bool HasDefault
{
get { return _defaultValue != null && _defaultValue.Length > 0; }
}
internal bool HasConstraints
{
get { return _constraints != null && _constraints.Count > 0; }
}
internal bool IsLocalTypeDerivationChecked
{
get
{
return _isLocalTypeDerivationChecked;
}
set
{
_isLocalTypeDerivationChecked = value;
}
}
internal SchemaElementDecl ElementDecl
{
get { return _elementDecl; }
set { _elementDecl = value; }
}
[XmlIgnore]
internal override string NameAttribute
{
get { return Name; }
set { Name = value; }
}
[XmlIgnore]
internal override string NameString
{
get
{
return _qualifiedName.ToString();
}
}
internal override XmlSchemaObject Clone()
{
System.Diagnostics.Debug.Fail("Should never call Clone() on XmlSchemaElement. Call Clone(XmlSchema) instead.");
return Clone(null);
}
internal XmlSchemaObject Clone(XmlSchema parentSchema)
{
XmlSchemaElement newElem = (XmlSchemaElement)MemberwiseClone();
//Deep clone the QNames as these will be updated on chameleon includes
newElem._refName = _refName.Clone();
newElem._substitutionGroup = _substitutionGroup.Clone();
newElem._typeName = _typeName.Clone();
newElem._qualifiedName = _qualifiedName.Clone();
// If this element has a complex type which is anonymous (declared in place with the element)
// it needs to be cloned as well, since it may contain named elements and such. And these names
// will need to be cloned since they may change their namespace on chameleon includes
XmlSchemaComplexType complexType = _type as XmlSchemaComplexType;
if (complexType != null && complexType.QualifiedName.IsEmpty)
{
newElem._type = (XmlSchemaType)complexType.Clone(parentSchema);
}
//Clear compiled tables
newElem._constraints = null;
return newElem;
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Globalization;
namespace System.Collections.Immutable
{
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A node in the AVL tree storing this map.
/// </summary>
[DebuggerDisplay("{_key} = {_value}")]
internal sealed class Node : IBinaryTree<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>
{
/// <summary>
/// The default empty node.
/// </summary>
internal static readonly Node EmptyNode = new Node();
/// <summary>
/// The key associated with this node.
/// </summary>
private readonly TKey _key;
/// <summary>
/// The value associated with this node.
/// </summary>
private readonly TValue _value;
/// <summary>
/// A value indicating whether this node has been frozen (made immutable).
/// </summary>
/// <remarks>
/// Nodes must be frozen before ever being observed by a wrapping collection type
/// to protect collections from further mutations.
/// </remarks>
private bool _frozen;
/// <summary>
/// The depth of the tree beneath this node.
/// </summary>
private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2)
/// <summary>
/// The left tree.
/// </summary>
private Node _left;
/// <summary>
/// The right tree.
/// </summary>
private Node _right;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is pre-frozen.
/// </summary>
private Node()
{
_frozen = true; // the empty node is *always* frozen.
Debug.Assert(this.IsEmpty);
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class
/// that is not yet frozen.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <param name="frozen">Whether this node is prefrozen.</param>
private Node(TKey key, TValue value, Node left, Node right, bool frozen = false)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(left, nameof(left));
Requires.NotNull(right, nameof(right));
Debug.Assert(!frozen || (left._frozen && right._frozen));
_key = key;
_value = value;
_left = left;
_right = right;
_height = checked((byte)(1 + Math.Max(left._height, right._height)));
_frozen = frozen;
Debug.Assert(!this.IsEmpty);
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get
{
return _left == null;
}
}
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Right
{
get { return _right; }
}
/// <summary>
/// Gets the height of the tree beneath this node.
/// </summary>
public int Height { get { return _height; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
public Node Left { get { return _left; } }
/// <summary>
/// Gets the left branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Left
{
get { return _left; }
}
/// <summary>
/// Gets the right branch of this node.
/// </summary>
public Node Right { get { return _right; } }
/// <summary>
/// Gets the right branch of this node.
/// </summary>
IBinaryTree IBinaryTree.Right
{
get { return _right; }
}
/// <summary>
/// Gets the value represented by the current node.
/// </summary>
public KeyValuePair<TKey, TValue> Value
{
get { return new KeyValuePair<TKey, TValue>(_key, _value); }
}
/// <summary>
/// Gets the number of elements contained by this node and below.
/// </summary>
int IBinaryTree.Count
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the keys.
/// </summary>
internal IEnumerable<TKey> Keys
{
get { return Linq.Enumerable.Select(this, p => p.Key); }
}
/// <summary>
/// Gets the values.
/// </summary>
internal IEnumerable<TValue> Values
{
get { return Linq.Enumerable.Select(this, p => p.Value); }
}
#region IEnumerable<TKey> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <param name="builder">The builder, if applicable.</param>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
internal Enumerator GetEnumerator(Builder builder)
{
return new Enumerator(this, builder);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
internal void CopyTo(Array array, int arrayIndex, int dictionarySize)
{
Requires.NotNull(array, nameof(array));
Requires.Range(arrayIndex >= 0, nameof(arrayIndex));
Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex));
foreach (var item in this)
{
array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++);
}
}
/// <summary>
/// Creates a node tree from an existing (mutable) collection.
/// </summary>
/// <param name="dictionary">The collection.</param>
/// <returns>The root of the node tree.</returns>
[Pure]
internal static Node NodeTreeFromSortedDictionary(SortedDictionary<TKey, TValue> dictionary)
{
Requires.NotNull(dictionary, nameof(dictionary));
var list = dictionary.AsOrderedCollection();
return NodeTreeFromList(list, 0, list.Count);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node Add(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
bool dummy;
return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out dummy, out mutated);
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
internal Node SetItem(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
return this.SetOrAdd(key, value, keyComparer, valueComparer, true, out replacedExistingValue, out mutated);
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
internal Node Remove(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return this.RemoveRecursive(key, keyComparer, out mutated);
}
#if !NETSTANDARD10
/// <summary>
/// Returns a read-only reference to the value associated with the provided key.
/// </summary>
/// <exception cref="KeyNotFoundException">If the key is not present.</exception>
[Pure]
internal ref readonly TValue ValueRef(TKey key, IComparer<TKey> keyComparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(key, keyComparer);
if (match.IsEmpty)
{
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
return ref match._value;
}
#endif
/// <summary>
/// Tries to get the value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="value">The value.</param>
/// <returns>True if the key was found.</returns>
[Pure]
internal bool TryGetValue(TKey key, IComparer<TKey> keyComparer, out TValue value)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(key, keyComparer);
if (match.IsEmpty)
{
value = default(TValue);
return false;
}
else
{
value = match._value;
return true;
}
}
/// <summary>
/// Searches the dictionary for a given key and returns the equal key it finds, if any.
/// </summary>
/// <param name="equalKey">The key to search for.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// the canonical value, or a value that has more complete data than the value you currently have,
/// although their comparer functions indicate they are equal.
/// </remarks>
[Pure]
internal bool TryGetKey(TKey equalKey, IComparer<TKey> keyComparer, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, nameof(equalKey));
Requires.NotNull(keyComparer, nameof(keyComparer));
var match = this.Search(equalKey, keyComparer);
if (match.IsEmpty)
{
actualKey = equalKey;
return false;
}
else
{
actualKey = match._key;
return true;
}
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool ContainsKey(TKey key, IComparer<TKey> keyComparer)
{
Requires.NotNullAllowStructs(key, nameof(key));
Requires.NotNull(keyComparer, nameof(keyComparer));
return !this.Search(key, keyComparer).IsEmpty;
}
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <param name="valueComparer">The value comparer to use.</param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
internal bool ContainsValue(TValue value, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull(valueComparer, nameof(valueComparer));
foreach (KeyValuePair<TKey, TValue> item in this)
{
if (valueComparer.Equals(value, item.Value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether [contains] [the specified pair].
/// </summary>
/// <param name="pair">The pair.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified pair]; otherwise, <c>false</c>.
/// </returns>
[Pure]
internal bool Contains(KeyValuePair<TKey, TValue> pair, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNullAllowStructs(pair.Key, nameof(pair.Key));
Requires.NotNull(keyComparer, nameof(keyComparer));
Requires.NotNull(valueComparer, nameof(valueComparer));
var matchingNode = this.Search(pair.Key, keyComparer);
if (matchingNode.IsEmpty)
{
return false;
}
return valueComparer.Equals(matchingNode._value, pair.Value);
}
/// <summary>
/// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes.
/// </summary>
internal void Freeze()
{
// If this node is frozen, all its descendants must already be frozen.
if (!_frozen)
{
_left.Freeze();
_right.Freeze();
_frozen = true;
}
}
#region Tree balancing methods
/// <summary>
/// AVL rotate left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
var right = tree._right;
return right.Mutate(left: tree.Mutate(right: right._left));
}
/// <summary>
/// AVL rotate right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node RotateRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
var left = tree._left;
return left.Mutate(right: tree.Mutate(left: left._right));
}
/// <summary>
/// AVL rotate double-left operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleLeft(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._right.IsEmpty)
{
return tree;
}
Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right));
return RotateLeft(rotatedRightChild);
}
/// <summary>
/// AVL rotate double-right operation.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>The rotated tree.</returns>
private static Node DoubleRight(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (tree._left.IsEmpty)
{
return tree;
}
Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left));
return RotateRight(rotatedLeftChild);
}
/// <summary>
/// Returns a value indicating whether the tree is in balance.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns>
[Pure]
private static int Balance(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return tree._right._height - tree._left._height;
}
/// <summary>
/// Determines whether the specified tree is right heavy.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>
/// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>.
/// </returns>
[Pure]
private static bool IsRightHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) >= 2;
}
/// <summary>
/// Determines whether the specified tree is left heavy.
/// </summary>
[Pure]
private static bool IsLeftHeavy(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
return Balance(tree) <= -2;
}
/// <summary>
/// Balances the specified tree.
/// </summary>
/// <param name="tree">The tree.</param>
/// <returns>A balanced tree.</returns>
[Pure]
private static Node MakeBalanced(Node tree)
{
Requires.NotNull(tree, nameof(tree));
Debug.Assert(!tree.IsEmpty);
if (IsRightHeavy(tree))
{
return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree);
}
if (IsLeftHeavy(tree))
{
return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree);
}
return tree;
}
#endregion
/// <summary>
/// Creates a node tree that contains the contents of a list.
/// </summary>
/// <param name="items">An indexable list with the contents that the new node tree should contain.</param>
/// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param>
/// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param>
/// <returns>The root of the created node tree.</returns>
[Pure]
private static Node NodeTreeFromList(IOrderedCollection<KeyValuePair<TKey, TValue>> items, int start, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(start >= 0, nameof(start));
Requires.Range(length >= 0, nameof(length));
if (length == 0)
{
return EmptyNode;
}
int rightCount = (length - 1) / 2;
int leftCount = (length - 1) - rightCount;
Node left = NodeTreeFromList(items, start, leftCount);
Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount);
var item = items[start + leftCount];
return new Node(item.Key, item.Value, left, right, true);
}
/// <summary>
/// Adds the specified key. Callers are expected to have validated arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param>
/// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node SetOrAdd(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated)
{
// Arg validation skipped in this private method because it's recursive and the tax
// of revalidating arguments on each recursive call is significant.
// All our callers are therefore required to have done input validation.
replacedExistingValue = false;
if (this.IsEmpty)
{
mutated = true;
return new Node(key, value, this, this);
}
else
{
Node result = this;
int compareResult = keyComparer.Compare(key, _key);
if (compareResult > 0)
{
var newRight = _right.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
else if (compareResult < 0)
{
var newLeft = _left.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
if (valueComparer.Equals(_value, value))
{
mutated = false;
return this;
}
else if (overwriteExistingValue)
{
mutated = true;
replacedExistingValue = true;
result = new Node(key, value, _left, _right);
}
else
{
throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
}
return mutated ? MakeBalanced(result) : result;
}
}
/// <summary>
/// Removes the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
/// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param>
/// <returns>The new AVL tree.</returns>
private Node RemoveRecursive(TKey key, IComparer<TKey> keyComparer, out bool mutated)
{
// Skip parameter validation because it's too expensive and pointless in recursive methods.
if (this.IsEmpty)
{
mutated = false;
return this;
}
else
{
Node result = this;
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
// We have a match.
mutated = true;
// If this is a leaf, just remove it
// by returning Empty. If we have only one child,
// replace the node with the child.
if (_right.IsEmpty && _left.IsEmpty)
{
result = EmptyNode;
}
else if (_right.IsEmpty && !_left.IsEmpty)
{
result = _left;
}
else if (!_right.IsEmpty && _left.IsEmpty)
{
result = _right;
}
else
{
// We have two children. Remove the next-highest node and replace
// this node with it.
var successor = _right;
while (!successor._left.IsEmpty)
{
successor = successor._left;
}
bool dummyMutated;
var newRight = _right.Remove(successor._key, keyComparer, out dummyMutated);
result = successor.Mutate(left: _left, right: newRight);
}
}
else if (compare < 0)
{
var newLeft = _left.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(left: newLeft);
}
}
else
{
var newRight = _right.Remove(key, keyComparer, out mutated);
if (mutated)
{
result = this.Mutate(right: newRight);
}
}
return result.IsEmpty ? result : MakeBalanced(result);
}
}
/// <summary>
/// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node
/// with the described changes.
/// </summary>
/// <param name="left">The left branch of the mutated node.</param>
/// <param name="right">The right branch of the mutated node.</param>
/// <returns>The mutated (or created) node.</returns>
private Node Mutate(Node left = null, Node right = null)
{
if (_frozen)
{
return new Node(_key, _value, left ?? _left, right ?? _right);
}
else
{
if (left != null)
{
_left = left;
}
if (right != null)
{
_right = right;
}
_height = checked((byte)(1 + Math.Max(_left._height, _right._height)));
return this;
}
}
/// <summary>
/// Searches the specified key. Callers are expected to validate arguments.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="keyComparer">The key comparer.</param>
[Pure]
private Node Search(TKey key, IComparer<TKey> keyComparer)
{
// Arg validation is too expensive for recursive methods.
// Callers are expected to have validated parameters.
if (this.IsEmpty)
{
return this;
}
else
{
int compare = keyComparer.Compare(key, _key);
if (compare == 0)
{
return this;
}
else if (compare > 0)
{
return _right.Search(key, keyComparer);
}
else
{
return _left.Search(key, keyComparer);
}
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// LightAnimData
//------------------------------------------------------------------------------
datablock LightAnimData( NullLightAnim )
{
animEnabled = false;
};
datablock LightAnimData( PulseLightAnim )
{
brightnessA = 0;
brightnessZ = 1;
brightnessPeriod = 1;
brightnessKeys = "aza";
brightnessSmooth = true;
};
datablock LightAnimData( SubtlePulseLightAnim )
{
brightnessA = 0.5;
brightnessZ = 1;
brightnessPeriod = 1;
brightnessKeys = "aza";
brightnessSmooth = true;
};
datablock LightAnimData( FlickerLightAnim )
{
brightnessA = 1;
brightnessZ = 0;
brightnessPeriod = 5;
brightnessKeys = "aaazaaaaaazaaazaaazaaaaazaaaazzaaaazaaaaaazaaaazaaaza";
brightnessSmooth = false;
};
datablock LightAnimData( BlinkLightAnim )
{
brightnessA = 0;
brightnessZ = 1;
brightnessPeriod = 5;
brightnessKeys = "azaaaazazaaaaaazaaaazaaaazzaaaaaazaazaaazaaaaaaa";
brightnessSmooth = false;
};
datablock LightAnimData( FireLightAnim )
{
brightnessA = 0.75;
brightnessZ = 1;
brightnessPeriod = 0.7;
brightnessKeys = "annzzznnnzzzaznzzzz";
brightnessSmooth = 0;
offsetA[0] = "-0.05";
offsetA[1] = "-0.05";
offsetA[2] = "-0.05";
offsetZ[0] = "0.05";
offsetZ[1] = "0.05";
offsetZ[2] = "0.05";
offsetPeriod[0] = "1.25";
offsetPeriod[1] = "1.25";
offsetPeriod[2] = "1.25";
offsetKeys[0] = "ahahaazahakayajza";
offsetKeys[1] = "ahahaazahakayajza";
offsetKeys[2] = "ahahaazahakayajza";
rotKeys[0] = "";
rotKeys[1] = "";
rotKeys[2] = "";
colorKeys[0] = "";
colorKeys[1] = "";
colorKeys[2] = "";
};
datablock LightAnimData( SpinLightAnim )
{
rotA[2] = "0";
rotZ[2] = "360";
rotPeriod[2] = "1";
rotKeys[2] = "az";
rotSmooth[2] = true;
};
//------------------------------------------------------------------------------
// LightFlareData
//------------------------------------------------------------------------------
datablock LightFlareData( NullLightFlare )
{
flareEnabled = false;
};
datablock LightFlareData( SunFlareExample )
{
overallScale = 4.0;
flareEnabled = true;
renderReflectPass = false;
flareTexture = "./../special/lensFlareSheet0";
elementRect[0] = "512 0 512 512";
elementDist[0] = 0.0;
elementScale[0] = 2.0;
elementTint[0] = "0.6 0.6 0.6";
elementRotate[0] = true;
elementUseLightColor[0] = true;
elementRect[1] = "1152 0 128 128";
elementDist[1] = 0.3;
elementScale[1] = 0.7;
elementTint[1] = "1.0 1.0 1.0";
elementRotate[1] = true;
elementUseLightColor[1] = true;
elementRect[2] = "1024 0 128 128";
elementDist[2] = 0.5;
elementScale[2] = 0.25;
elementTint[2] = "1.0 1.0 1.0";
elementRotate[2] = true;
elementUseLightColor[2] = true;
elementRect[3] = "1024 128 128 128";
elementDist[3] = 0.8;
elementScale[3] = 0.7;
elementTint[3] = "1.0 1.0 1.0";
elementRotate[3] = true;
elementUseLightColor[3] = true;
elementRect[4] = "1024 0 128 128";
elementDist[4] = 1.18;
elementScale[4] = 0.5;
elementTint[4] = "1.0 1.0 1.0";
elementRotate[4] = true;
elementUseLightColor[4] = true;
elementRect[5] = "1152 128 128 128";
elementDist[5] = 1.25;
elementScale[5] = 0.25;
elementTint[5] = "1.0 1.0 1.0";
elementRotate[5] = true;
elementUseLightColor[5] = true;
elementRect[6] = "1024 0 128 128";
elementDist[6] = 2.0;
elementScale[6] = 0.25;
elementTint[6] = "1.0 1.0 1.0";
elementRotate[6] = true;
elementUseLightColor[6] = true;
occlusionRadius = "0.25";
};
datablock LightFlareData( SunFlareExample2 )
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = false;
flareTexture = "./../special/lensFlareSheet0";
elementRect[0] = "1024 0 128 128";
elementDist[0] = 0.5;
elementScale[0] = 0.25;
elementTint[0] = "1.0 1.0 1.0";
elementRotate[0] = true;
elementUseLightColor[0] = true;
elementRect[1] = "1024 128 128 128";
elementDist[1] = 0.8;
elementScale[1] = 0.7;
elementTint[1] = "1.0 1.0 1.0";
elementRotate[1] = true;
elementUseLightColor[1] = true;
elementRect[2] = "1024 0 128 128";
elementDist[2] = 1.18;
elementScale[2] = 0.5;
elementTint[2] = "1.0 1.0 1.0";
elementRotate[2] = true;
elementUseLightColor[2] = true;
elementRect[3] = "1152 128 128 128";
elementDist[3] = 1.25;
elementScale[3] = 0.25;
elementTint[3] = "1.0 1.0 1.0";
elementRotate[3] = true;
elementUseLightColor[3] = true;
elementRect[4] = "1024 0 128 128";
elementDist[4] = 2.0;
elementScale[4] = 0.25;
elementTint[4] = "0.7 0.7 0.7";
elementRotate[4] = true;
elementUseLightColor[4] = true;
occlusionRadius = "0.25";
};
datablock LightFlareData(SunFlareExample3)
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = false;
flareTexture = "core/art/special/lensflareSheet3.png";
elementRect[0] = "0 256 256 256";
elementDist[0] = "-0.6";
elementScale[0] = "3.5";
elementTint[0] = "0.537255 0.537255 0.537255 1";
elementRotate[0] = true;
elementUseLightColor[0] = true;
elementRect[1] = "128 128 128 128";
elementDist[1] = "0.1";
elementScale[1] = "1.5";
elementTint[1] = "0.996078 0.976471 0.721569 1";
elementRotate[1] = true;
elementUseLightColor[1] = true;
elementRect[2] = "0 0 64 64";
elementDist[2] = "0.4";
elementScale[2] = "0.25";
elementTint[2] = "0 0 1 1";
elementRotate[2] = true;
elementUseLightColor[2] = true;
elementRect[3] = "0 0 64 64";
elementDist[3] = "0.45";
elementScale[3] = 0.25;
elementTint[3] = "0 1 0 1";
elementRotate[3] = true;
elementUseLightColor[3] = true;
elementRect[4] = "0 0 64 64";
elementDist[4] = "0.5";
elementScale[4] = 0.25;
elementTint[4] = "1 0 0 1";
elementRotate[4] = true;
elementUseLightColor[4] = true;
elementRect[9] = "256 0 256 256";
elementDist[3] = "0.45";
elementScale[3] = "0.25";
elementScale[9] = "2";
elementRect[4] = "0 0 64 64";
elementRect[5] = "128 0 128 128";
elementDist[4] = "0.5";
elementDist[5] = "1.2";
elementScale[1] = "1.5";
elementScale[4] = "0.25";
elementScale[5] = "0.5";
elementTint[1] = "0.996078 0.976471 0.721569 1";
elementTint[2] = "0 0 1 1";
elementTint[5] = "0.721569 0 1 1";
elementRotate[5] = "0";
elementUseLightColor[5] = "1";
elementRect[0] = "0 256 256 256";
elementRect[1] = "128 128 128 128";
elementRect[2] = "0 0 64 64";
elementRect[3] = "0 0 64 64";
elementDist[0] = "-0.6";
elementDist[1] = "0.1";
elementDist[2] = "0.4";
elementScale[0] = "3.5";
elementScale[2] = "0.25";
elementTint[0] = "0.537255 0.537255 0.537255 1";
elementTint[3] = "0 1 0 1";
elementTint[4] = "1 0 0 1";
elementRect[6] = "64 64 64 64";
elementDist[6] = "0.9";
elementScale[6] = "4";
elementTint[6] = "0.00392157 0.721569 0.00392157 1";
elementRotate[6] = "0";
elementUseLightColor[6] = "1";
elementRect[7] = "64 64 64 64";
elementRect[8] = "64 64 64 64";
elementDist[7] = "0.25";
elementDist[8] = "0.18";
elementDist[9] = "0";
elementScale[7] = "2";
elementScale[8] = "0.5";
elementTint[7] = "0.6 0.0117647 0.741176 1";
elementTint[8] = "0.027451 0.690196 0.0117647 1";
elementTint[9] = "0.647059 0.647059 0.647059 1";
elementRotate[9] = "0";
elementUseLightColor[7] = "1";
elementUseLightColor[8] = "1";
elementRect[10] = "256 256 256 256";
elementRect[11] = "0 64 64 64";
elementRect[12] = "0 64 64 64";
elementRect[13] = "64 0 64 64";
elementDist[10] = "0";
elementDist[11] = "-0.3";
elementDist[12] = "-0.32";
elementDist[13] = "1";
elementScale[10] = "10";
elementScale[11] = "2.5";
elementScale[12] = "0.3";
elementScale[13] = "0.4";
elementTint[10] = "0.321569 0.321569 0.321569 1";
elementTint[11] = "0.443137 0.0431373 0.00784314 1";
elementTint[12] = "0.00784314 0.996078 0.0313726 1";
elementTint[13] = "0.996078 0.94902 0.00784314 1";
elementUseLightColor[10] = "1";
elementUseLightColor[11] = "1";
elementUseLightColor[13] = "1";
elementRect[14] = "0 0 64 64";
elementDist[14] = "0.15";
elementScale[14] = "0.8";
elementTint[14] = "0.505882 0.0470588 0.00784314 1";
elementRotate[14] = "1";
elementUseLightColor[9] = "1";
elementUseLightColor[14] = "1";
elementRect[15] = "64 64 64 64";
elementRect[16] = "0 64 64 64";
elementRect[17] = "0 0 64 64";
elementRect[18] = "0 64 64 64";
elementRect[19] = "256 0 256 256";
elementDist[15] = "0.8";
elementDist[16] = "0.7";
elementDist[17] = "1.4";
elementDist[18] = "-0.5";
elementDist[19] = "-1.5";
elementScale[15] = "3";
elementScale[16] = "0.3";
elementScale[17] = "0.2";
elementScale[18] = "1";
elementScale[19] = "35";
elementTint[15] = "0.00784314 0.00784314 0.996078 1";
elementTint[16] = "0.992157 0.992157 0.992157 1";
elementTint[17] = "0.996078 0.603922 0.00784314 1";
elementTint[18] = "0.2 0.00392157 0.47451 1";
elementTint[19] = "0.607843 0.607843 0.607843 1";
elementUseLightColor[15] = "1";
elementUseLightColor[18] = "1";
elementUseLightColor[19] = "1";
occlusionRadius = "0.25";
};
datablock LightFlareData(SunFlarePacificIsland)
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = false;
flareTexture = "art/special/lensflareSheet3.png";
elementRect[0] = "0 256 256 256";
elementDist[0] = "-0.6";
elementScale[0] = "3.5";
elementTint[0] = "0.537255 0.537255 0.537255 1";
elementRotate[0] = true;
elementUseLightColor[0] = true;
elementRect[1] = "128 128 128 128";
elementDist[1] = "0.1";
elementScale[1] = "1.5";
elementTint[1] = "0.996078 0.976471 0.721569 1";
elementRotate[1] = true;
elementUseLightColor[1] = true;
elementRect[2] = "0 0 64 64";
elementDist[2] = "0.4";
elementScale[2] = "0.25";
elementTint[2] = "0 0 1 1";
elementRotate[2] = true;
elementUseLightColor[2] = true;
elementRect[3] = "0 0 64 64";
elementDist[3] = "0.45";
elementScale[3] = 0.25;
elementTint[3] = "0 1 0 1";
elementRotate[3] = true;
elementUseLightColor[3] = true;
elementRect[4] = "0 0 64 64";
elementDist[4] = "0.5";
elementScale[4] = 0.25;
elementTint[4] = "1 0 0 1";
elementRotate[4] = true;
elementUseLightColor[4] = true;
elementRect[9] = "256 0 256 256";
elementDist[3] = "0.45";
elementScale[3] = "0.25";
elementScale[9] = "2";
elementRect[4] = "0 0 64 64";
elementRect[5] = "128 0 128 128";
elementDist[4] = "0.5";
elementDist[5] = "1.2";
elementScale[1] = "1.5";
elementScale[4] = "0.25";
elementScale[5] = "0.5";
elementTint[1] = "0.996078 0.976471 0.721569 1";
elementTint[2] = "0 0 1 1";
elementTint[5] = "0.721569 0 1 1";
elementRotate[5] = "0";
elementUseLightColor[5] = "1";
elementRect[0] = "0 256 256 256";
elementRect[1] = "128 128 128 128";
elementRect[2] = "0 0 64 64";
elementRect[3] = "0 0 64 64";
elementDist[0] = "-0.6";
elementDist[1] = "0.1";
elementDist[2] = "0.4";
elementScale[0] = "3.5";
elementScale[2] = "0.25";
elementTint[0] = "0.537255 0.537255 0.537255 1";
elementTint[3] = "0 1 0 1";
elementTint[4] = "1 0 0 1";
elementRect[6] = "64 64 64 64";
elementDist[6] = "0.9";
elementScale[6] = "4";
elementTint[6] = "0.00392157 0.721569 0.00392157 1";
elementRotate[6] = "0";
elementUseLightColor[6] = "1";
elementRect[7] = "64 64 64 64";
elementRect[8] = "64 64 64 64";
elementDist[7] = "0.25";
elementDist[8] = "0.18";
elementDist[9] = "0";
elementScale[7] = "2";
elementScale[8] = "0.5";
elementTint[7] = "0.6 0.0117647 0.741176 1";
elementTint[8] = "0.027451 0.690196 0.0117647 1";
elementTint[9] = "0.647059 0.647059 0.647059 1";
elementRotate[9] = "0";
elementUseLightColor[7] = "1";
elementUseLightColor[8] = "1";
elementRect[10] = "256 256 256 256";
elementRect[11] = "0 64 64 64";
elementRect[12] = "0 64 64 64";
elementRect[13] = "64 0 64 64";
elementDist[10] = "0";
elementDist[11] = "-0.3";
elementDist[12] = "-0.32";
elementDist[13] = "1";
elementScale[10] = "10";
elementScale[11] = "2.5";
elementScale[12] = "0.3";
elementScale[13] = "0.4";
elementTint[10] = "0.321569 0.321569 0.321569 1";
elementTint[11] = "0.443137 0.0431373 0.00784314 1";
elementTint[12] = "0.00784314 0.996078 0.0313726 1";
elementTint[13] = "0.996078 0.94902 0.00784314 1";
elementUseLightColor[10] = "1";
elementUseLightColor[11] = "1";
elementUseLightColor[13] = "1";
elementRect[14] = "0 0 64 64";
elementDist[14] = "0.15";
elementScale[14] = "0.8";
elementTint[14] = "0.505882 0.0470588 0.00784314 1";
elementRotate[14] = "1";
elementUseLightColor[9] = "1";
elementUseLightColor[14] = "1";
elementRect[15] = "64 64 64 64";
elementRect[16] = "0 64 64 64";
elementRect[17] = "0 0 64 64";
elementRect[18] = "0 64 64 64";
elementRect[19] = "256 0 256 256";
elementDist[15] = "0.8";
elementDist[16] = "0.7";
elementDist[17] = "1.4";
elementDist[18] = "-0.5";
elementDist[19] = "-1.5";
elementScale[15] = "3";
elementScale[16] = "0.3";
elementScale[17] = "0.2";
elementScale[18] = "1";
elementScale[19] = "35";
elementTint[15] = "0.00784314 0.00784314 0.996078 1";
elementTint[16] = "0.992157 0.992157 0.992157 1";
elementTint[17] = "0.996078 0.603922 0.00784314 1";
elementTint[18] = "0.2 0.00392157 0.47451 1";
elementTint[19] = "0.607843 0.607843 0.607843 1";
elementUseLightColor[15] = "1";
elementUseLightColor[18] = "1";
elementUseLightColor[19] = "1";
};
datablock LightFlareData( LightFlareExample0 )
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = true;
flareTexture = "./../special/lensFlareSheet1";
elementRect[0] = "0 512 512 512";
elementDist[0] = 0.0;
elementScale[0] = 0.5;
elementTint[0] = "1.0 1.0 1.0";
elementRotate[0] = false;
elementUseLightColor[0] = false;
elementRect[1] = "512 0 512 512";
elementDist[1] = 0.0;
elementScale[1] = 2.0;
elementTint[1] = "0.5 0.5 0.5";
elementRotate[1] = false;
elementUseLightColor[1] = false;
occlusionRadius = "0.25";
};
datablock LightFlareData( LightFlareExample1 )
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = true;
flareTexture = "./../special/lensFlareSheet1";
elementRect[0] = "512 512 512 512";
elementDist[0] = 0.0;
elementScale[0] = 0.5;
elementTint[0] = "1.0 1.0 1.0";
elementRotate[0] = false;
elementUseLightColor[0] = false;
elementRect[1] = "512 0 512 512";
elementDist[1] = 0.0;
elementScale[1] = 2.0;
elementTint[1] = "0.5 0.5 0.5";
elementRotate[1] = false;
elementUseLightColor[1] = false;
occlusionRadius = "0.25";
};
datablock LightFlareData( LightFlareExample2 )
{
overallScale = 2.0;
flareEnabled = true;
renderReflectPass = true;
flareTexture = "./../special/lensFlareSheet0";
elementRect[0] = "512 512 512 512";
elementDist[0] = 0.0;
elementScale[0] = 0.5;
elementTint[0] = "1.0 1.0 1.0";
elementRotate[0] = true;
elementUseLightColor[0] = true;
elementRect[1] = "512 0 512 512";
elementDist[1] = 0.0;
elementScale[1] = 2.0;
elementTint[1] = "0.7 0.7 0.7";
elementRotate[1] = true;
elementUseLightColor[1] = true;
elementRect[2] = "1152 0 128 128";
elementDist[2] = 0.3;
elementScale[2] = 0.5;
elementTint[2] = "1.0 1.0 1.0";
elementRotate[2] = true;
elementUseLightColor[2] = true;
elementRect[3] = "1024 0 128 128";
elementDist[3] = 0.5;
elementScale[3] = 0.25;
elementTint[3] = "1.0 1.0 1.0";
elementRotate[3] = true;
elementUseLightColor[3] = true;
elementRect[4] = "1024 128 128 128";
elementDist[4] = 0.8;
elementScale[4] = 0.6;
elementTint[4] = "1.0 1.0 1.0";
elementRotate[4] = true;
elementUseLightColor[4] = true;
elementRect[5] = "1024 0 128 128";
elementDist[5] = 1.18;
elementScale[5] = 0.5;
elementTint[5] = "0.7 0.7 0.7";
elementRotate[5] = true;
elementUseLightColor[5] = true;
elementRect[6] = "1152 128 128 128";
elementDist[6] = 1.25;
elementScale[6] = 0.35;
elementTint[6] = "0.8 0.8 0.8";
elementRotate[6] = true;
elementUseLightColor[6] = true;
elementRect[7] = "1024 0 128 128";
elementDist[7] = 2.0;
elementScale[7] = 0.25;
elementTint[7] = "1.0 1.0 1.0";
elementRotate[7] = true;
elementUseLightColor[7] = true;
};
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Runtime.Session;
using Abp.UI;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Abp.Authorization.Users
{
public class AbpUserManager<TRole, TUser> : UserManager<TUser>, IDomainService
where TRole : AbpRole<TUser>, new()
where TUser : AbpUser<TUser>
{
protected IUserPermissionStore<TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TUser>;
}
}
public ILocalizationManager LocalizationManager { get; set; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TRole, TUser> RoleManager { get; }
public AbpUserStore<TRole, TUser> AbpStore { get; }
public IMultiTenancyConfig MultiTenancy { get; set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly ICacheManager _cacheManager;
private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository;
private readonly IOrganizationUnitSettings _organizationUnitSettings;
private readonly ISettingManager _settingManager;
public AbpUserManager(
AbpRoleManager<TRole, TUser> roleManager,
AbpUserStore<TRole, TUser> store,
IOptions<IdentityOptions> optionsAccessor,
IPasswordHasher<TUser> passwordHasher,
IEnumerable<IUserValidator<TUser>> userValidators,
IEnumerable<IPasswordValidator<TUser>> passwordValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
IServiceProvider services,
ILogger<UserManager<TUser>> logger,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ICacheManager cacheManager,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IOrganizationUnitSettings organizationUnitSettings,
ISettingManager settingManager)
: base(
store,
optionsAccessor,
passwordHasher,
userValidators,
passwordValidators,
keyNormalizer,
errors,
services,
logger)
{
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_cacheManager = cacheManager;
_organizationUnitRepository = organizationUnitRepository;
_userOrganizationUnitRepository = userOrganizationUnitRepository;
_organizationUnitSettings = organizationUnitSettings;
_settingManager = settingManager;
AbpStore = store;
RoleManager = roleManager;
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var tenantId = GetCurrentTenantId();
if (tenantId.HasValue && !user.TenantId.HasValue)
{
user.TenantId = tenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide()))
{
return false;
}
//Check for depended features
if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant)
{
if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
if (cacheItem == null)
{
return false;
}
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId.ToString());
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public override async Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
//Admin user's username can not be changed!
if (user.UserName != AbpUserBase.AdminUserName)
{
if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName)
{
throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName));
}
}
return await base.UpdateAsync(user);
}
public override async Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUserBase.AdminUserName)
{
throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var errors = new List<IdentityError>();
foreach (var validator in PasswordValidators)
{
var validationResult = await validator.ValidateAsync(this, user, newPassword);
if (!validationResult.Succeeded)
{
errors.AddRange(validationResult.Errors);
}
}
if (errors.Any())
{
return IdentityResult.Failed(errors.ToArray());
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
await AbpStore.UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles);
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId.ToString());
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId)
{
return await IsInOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
return await _userOrganizationUnitRepository.CountAsync(uou =>
uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id
) > 0;
}
public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId)
{
await AddToOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
var currentOus = await GetOrganizationUnitsAsync(user);
if (currentOus.Any(cou => cou.Id == ou.Id))
{
return;
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1);
await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id));
}
public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId)
{
await RemoveFromOrganizationUnitAsync(
await GetUserByIdAsync(userId),
await _organizationUnitRepository.GetAsync(ouId)
);
}
public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou)
{
await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id);
}
public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds)
{
await SetOrganizationUnitsAsync(
await GetUserByIdAsync(userId),
organizationUnitIds
);
}
private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount)
{
var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId);
if (requestedCount > maxCount)
{
throw new AbpException($"Can not set more than {maxCount} organization unit for a user!");
}
}
public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds)
{
if (organizationUnitIds == null)
{
organizationUnitIds = new long[0];
}
await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length);
var currentOus = await GetOrganizationUnitsAsync(user);
//Remove from removed OUs
foreach (var currentOu in currentOus)
{
if (!organizationUnitIds.Contains(currentOu.Id))
{
await RemoveFromOrganizationUnitAsync(user, currentOu);
}
}
//Add to added OUs
foreach (var organizationUnitId in organizationUnitIds)
{
if (currentOus.All(ou => ou.Id != organizationUnitId))
{
await AddToOrganizationUnitAsync(
user,
await _organizationUnitRepository.GetAsync(organizationUnitId)
);
}
}
}
[UnitOfWork]
public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where uou.UserId == user.Id
select ou;
return Task.FromResult(query.ToList());
}
[UnitOfWork]
public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false)
{
if (!includeChildren)
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in Users on uou.UserId equals user.Id
where uou.OrganizationUnitId == organizationUnit.Id
select user;
return Task.FromResult(query.ToList());
}
else
{
var query = from uou in _userOrganizationUnitRepository.GetAll()
join user in Users on uou.UserId equals user.Id
join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id
where ou.Code.StartsWith(organizationUnit.Code)
select user;
return Task.FromResult(query.ToList());
}
}
public virtual async Task InitializeOptionsAsync(int? tenantId)
{
Options = new IdentityOptions();
//Lockout
Options.Lockout.AllowedForNewUsers = await IsTrueAsync(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId);
Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId));
Options.Lockout.MaxFailedAccessAttempts = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId);
//Password complexity
Options.Password.RequireDigit = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId);
Options.Password.RequireLowercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId);
Options.Password.RequireNonAlphanumeric = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId);
Options.Password.RequireUppercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId);
Options.Password.RequiredLength = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId);
}
protected virtual Task<string> GetOldUserNameAsync(long userId)
{
return AbpStore.GetUserNameFromDatabaseAsync(userId);
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0);
return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () =>
{
var user = await FindByIdAsync(userId.ToString());
if (user == null)
{
return null;
}
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(user))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user)
{
var providers = new List<string>();
foreach (var provider in await base.GetValidTwoFactorProvidersAsync(user))
{
if (provider == "Email" &&
!await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId))
{
continue;
}
if (provider == "Phone" &&
!await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId))
{
continue;
}
providers.Add(provider);
}
return providers;
}
private bool IsTrue(string settingName, int? tenantId)
{
return GetSettingValue<bool>(settingName, tenantId);
}
private Task<bool> IsTrueAsync(string settingName, int? tenantId)
{
return GetSettingValueAsync<bool>(settingName, tenantId);
}
private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplication<T>(settingName)
: _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value);
}
private Task<T> GetSettingValueAsync<T>(string settingName, int? tenantId) where T : struct
{
return tenantId == null
? _settingManager.GetSettingValueForApplicationAsync<T>(settingName)
: _settingManager.GetSettingValueForTenantAsync<T>(settingName, tenantId.Value);
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
private int? GetCurrentTenantId()
{
if (_unitOfWorkManager.Current != null)
{
return _unitOfWorkManager.Current.GetTenantId();
}
return AbpSession.TenantId;
}
private MultiTenancySides GetCurrentMultiTenancySide()
{
if (_unitOfWorkManager.Current != null)
{
return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue
? MultiTenancySides.Host
: MultiTenancySides.Tenant;
}
return AbpSession.MultiTenancySide;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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.Linq;
using System.Text;
using NUnit.Framework;
using OpenSim.Framework;
using OpenMetaverse;
namespace InWorldz.Data.Inventory.Cassandra
{
[TestFixture]
class UnitTests
{
private InventoryStorage _storage;
[SetUp]
public void Setup()
{
_storage = new InventoryStorage("inworldzbeta");
}
[TestCase]
public void TestBasicCreateFolder()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Test Root 1";
folder.Level = InventoryFolderBase.FolderLevel.Root;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = 1;
_storage.CreateFolder(folder);
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.IsTrue(skel.Count == 1);
Assert.AreEqual(skel[0].ID, folder.ID);
InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID);
AssertFolderEqual(folder, folderCopy, true);
Assert.AreEqual(1, folderCopy.Version);
_storage.SaveFolder(folderCopy);
InventoryFolderBase folderCopy2 = _storage.GetFolderAttributes(folder.ID);
AssertFolderEqual(folder, folderCopy2, true);
Assert.AreEqual(2, folderCopy2.Version);
}
[TestCase]
public void TestSkeletonDataMatchesFolderProps()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "TestFolder";
folder.Level = InventoryFolderBase.FolderLevel.Root;
folder.Owner = userId;
folder.ParentID = UUID.Random();
folder.Type = -1;
_storage.CreateFolder(folder);
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.IsTrue(skel.Count == 1);
AssertFolderEqual(skel[0], folder, true);
InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID);
AssertFolderEqual(folder, folderCopy, true);
AssertFolderEqual(skel[0], folderCopy, true);
Assert.AreEqual(1, folderCopy.Version);
}
[TestCase]
public void TestUpdateFolderKeepsIndexUpdated()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Test Folder zzzzzz";
folder.Level = InventoryFolderBase.FolderLevel.Root;
folder.Owner = userId;
folder.ParentID = UUID.Random();
folder.Type = -1;
_storage.CreateFolder(folder);
folder.Name = "Updated TestFolderZZZ";
_storage.SaveFolder(folder);
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(1, skel.Count);
Assert.AreEqual(2, skel[0].Version);
AssertFolderEqual(folder, skel[0], true);
UUID newParent = UUID.Random();
_storage.MoveFolder(folder, newParent);
InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID);
skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(1, skel.Count);
Assert.AreEqual(3, skel[0].Version);
Assert.AreEqual(newParent, folderCopy.ParentID);
AssertFolderEqual(folderCopy, skel[0], true);
}
private void AssertFolderEqual(InventoryFolderBase f1, InventoryFolderBase f2, bool checkParent)
{
Assert.AreEqual(f1.ID, f2.ID);
Assert.AreEqual(f1.Level, f2.Level);
Assert.AreEqual(f1.Name, f2.Name);
Assert.AreEqual(f1.Owner, f2.Owner);
if (checkParent)
{
Assert.AreEqual(f1.ParentID, f2.ParentID);
}
Assert.AreEqual(f1.Type, f2.Type);
}
[TestCase]
public void TestMoveFolderToNewParent()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Test Root 1";
folder.Level = InventoryFolderBase.FolderLevel.Root;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = 1;
_storage.CreateFolder(folder);
InventoryFolderBase firstLeaf = new InventoryFolderBase();
firstLeaf.ID = UUID.Random();
firstLeaf.Name = "Leaf 1";
firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf;
firstLeaf.Owner = userId;
firstLeaf.ParentID = folder.ID;
firstLeaf.Type = 1;
InventoryFolderBase secondLeaf = new InventoryFolderBase();
secondLeaf.ID = UUID.Random();
secondLeaf.Name = "Leaf 2";
secondLeaf.Level = InventoryFolderBase.FolderLevel.Leaf;
secondLeaf.Owner = userId;
secondLeaf.ParentID = folder.ID;
secondLeaf.Type = 1;
_storage.CreateFolder(firstLeaf);
_storage.CreateFolder(secondLeaf);
InventoryFolderBase secondLeafCopy = _storage.GetFolderAttributes(secondLeaf.ID);
AssertFolderEqual(secondLeaf, secondLeafCopy, true);
Assert.AreEqual(1, secondLeafCopy.Version);
_storage.MoveFolder(secondLeaf, firstLeaf.ID);
InventoryFolderBase secondLeafWithNewParent = _storage.GetFolderAttributes(secondLeaf.ID);
AssertFolderEqual(secondLeaf, secondLeafWithNewParent, false);
Assert.AreEqual(firstLeaf.ID, secondLeafWithNewParent.ParentID);
Assert.AreEqual(2, secondLeafWithNewParent.Version);
InventoryFolderBase firstLeafWithSecondLeafChild = _storage.GetFolder(firstLeaf.ID);
AssertFolderEqual(firstLeafWithSecondLeafChild, firstLeaf, true);
Assert.AreEqual(1, firstLeafWithSecondLeafChild.SubFolders.Count);
Assert.AreEqual(secondLeaf.Name, firstLeafWithSecondLeafChild.SubFolders[0].Name);
Assert.AreEqual(secondLeaf.ID, firstLeafWithSecondLeafChild.SubFolders[0].ID);
Assert.AreEqual(2, firstLeafWithSecondLeafChild.Version);
}
[TestCase]
public void TestFolderChangeUpdateParent()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Test Root 1";
folder.Level = InventoryFolderBase.FolderLevel.Root;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = 1;
_storage.CreateFolder(folder);
InventoryFolderBase firstLeaf = new InventoryFolderBase();
firstLeaf.ID = UUID.Random();
firstLeaf.Name = "Leaf 1";
firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf;
firstLeaf.Owner = userId;
firstLeaf.ParentID = folder.ID;
firstLeaf.Type = 1;
_storage.CreateFolder(firstLeaf);
firstLeaf.Name = "Leaf 1, Updated";
_storage.SaveFolder(firstLeaf);
InventoryFolderBase folderWithUpdatedChild = _storage.GetFolder(folder.ID);
Assert.AreEqual(1, folderWithUpdatedChild.SubFolders.Count);
Assert.AreEqual(firstLeaf.Name, folderWithUpdatedChild.SubFolders[0].Name);
Assert.AreEqual(firstLeaf.ID, folderWithUpdatedChild.SubFolders[0].ID);
}
[TestCase]
public void TestSendFolderToTrash()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Trash Folder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = (short)OpenMetaverse.AssetType.TrashFolder;
_storage.CreateFolder(folder);
InventoryFolderBase trashFolderRetrieved = _storage.GetFolder(folder.ID);
Assert.AreEqual((short)OpenMetaverse.AssetType.TrashFolder, trashFolderRetrieved.Type);
InventoryFolderBase firstLeaf = new InventoryFolderBase();
firstLeaf.ID = UUID.Random();
firstLeaf.Name = "Leaf 1";
firstLeaf.Level = InventoryFolderBase.FolderLevel.Leaf;
firstLeaf.Owner = userId;
firstLeaf.ParentID = UUID.Zero;
firstLeaf.Type = 1;
_storage.CreateFolder(firstLeaf);
_storage.SendFolderToTrash(firstLeaf, UUID.Zero);
InventoryFolderBase leafFolderAfterTrashed = _storage.GetFolder(firstLeaf.ID);
Assert.AreEqual(folder.ID, leafFolderAfterTrashed.ParentID);
InventoryFolderBase trashFolderAfterLeafTrashed = _storage.GetFolder(folder.ID);
Assert.AreEqual(1, trashFolderAfterLeafTrashed.SubFolders.Count);
Assert.AreEqual(leafFolderAfterTrashed.ID, trashFolderAfterLeafTrashed.SubFolders[0].ID);
Assert.AreEqual(leafFolderAfterTrashed.Name, trashFolderAfterLeafTrashed.SubFolders[0].Name);
}
[TestCase]
public void TestBasicCreateItem()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Root Folder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder);
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = 0xFF,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = 0xFFF,
Description = "A good item, of goodness",
EveryOnePermissions = 0xFFFF,
Flags = 0x12,
Folder = folder.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.CreateItem(item);
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
AssertItemEqual(itemCopy, item);
InventoryFolderBase folderWithItem = _storage.GetFolder(folder.ID);
Assert.AreEqual(1, folderWithItem.Items.Count);
Assert.AreEqual(2, folderWithItem.Version);
AssertItemEqual(itemCopy, folderWithItem.Items[0]);
}
[TestCase]
public void TestSaveItem()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Root Folder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder);
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = 0xFF,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = 0xFFF,
Description = "A good item, of goodness",
EveryOnePermissions = 0xFFFF,
Flags = 0x12,
Folder = folder.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.CreateItem(item);
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
AssertItemEqual(itemCopy, item);
item.AssetID = assetId;
item.AssetType = (int)OpenMetaverse.AssetType.Sound;
item.BasePermissions = 0xAA;
item.CreationDate = Util.UnixTimeSinceEpoch();
item.CreatorId = userId.ToString();
item.CurrentPermissions = 0xAAA;
item.Description = "A good itemddddd";
item.EveryOnePermissions = 0xAAAA;
item.Flags = 0x24;
item.Folder = folder.ID;
item.GroupID = UUID.Random();
item.GroupOwned = true;
item.GroupPermissions = 0x456;
item.ID = itemId;
item.InvType = (int)OpenMetaverse.InventoryType.Sound;
item.Name = "Itemjkhdsahjkadshkjasds";
item.NextPermissions = 0xA;
item.Owner = userId;
item.SalePrice = 10;
item.SaleType = 8;
_storage.SaveItem(item);
itemCopy = _storage.GetItem(itemId, UUID.Zero);
AssertItemEqual(itemCopy, item);
InventoryFolderBase folderCopy = _storage.GetFolderAttributes(folder.ID);
Assert.AreEqual(3, folderCopy.Version);
}
[TestCase]
public void TestSaveItemInt32Extremes()
{
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "Root Folder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.ParentID = UUID.Zero;
folder.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder);
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = folder.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.CreateItem(item);
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
AssertItemEqual(itemCopy, item);
}
[Test]
[Repeat(10)]
public void TestBasicMoveItem()
{
UUID userId = UUID.Random();
InventoryFolderBase folder1 = new InventoryFolderBase();
folder1.ID = UUID.Random();
folder1.Name = "Folder1";
folder1.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder1.Owner = userId;
folder1.ParentID = UUID.Zero;
folder1.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder1);
InventoryFolderBase folder2 = new InventoryFolderBase();
folder2.ID = UUID.Random();
folder2.Name = "Folder1";
folder2.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder2.Owner = userId;
folder2.ParentID = UUID.Zero;
folder2.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder2);
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = folder1.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.CreateItem(item);
///
/// NOTE: The race mentioned here should be fixed. I replaced the UnixTimeSinceEpochInMicroseconds
/// Implementation to fix it. I am leaving the comments here as historical information.
/// The sleep is no longer needed
///
//I'm seeing a race here, that could be explained by
//the timestamps in the ItemParents CF being the same between
//the create and the move call. The index is left in a state
//still pointing at the old folder
//we sleep to mitigate this problem since we should never see a create
//and a move executed in the same tick in a real inventory situation
//this highlights the need for all clocks on the network to be synchronized
//System.Threading.Thread.Sleep(30);
_storage.MoveItem(item, folder2);
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
AssertItemEqual(item, itemCopy);
Assert.AreEqual(folder2.ID, item.Folder);
InventoryFolderBase containingFolder = _storage.GetFolder(folder2.ID);
Assert.AreEqual(2, containingFolder.Version);
Assert.AreEqual(1, containingFolder.Items.Count);
AssertItemEqual(item, containingFolder.Items[0]);
InventoryFolderBase oldFolder = _storage.GetFolder(folder1.ID);
Assert.AreEqual(0, oldFolder.Items.Count);
Assert.AreEqual(3, oldFolder.Version);
}
[Test]
public void TestItemPurge()
{
UUID userId = UUID.Random();
InventoryFolderBase folder1 = new InventoryFolderBase();
folder1.ID = UUID.Random();
folder1.Name = "Folder1";
folder1.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder1.Owner = userId;
folder1.ParentID = UUID.Zero;
folder1.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder1);
Amib.Threading.SmartThreadPool pool = new Amib.Threading.SmartThreadPool(1000, 20);
pool.Start();
for (int i = 0; i < 1000; i++)
{
pool.QueueWorkItem(() =>
{
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = folder1.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.PurgeItem(item);
_storage.CreateItem(item);
_storage.PurgeItem(item);
_storage.CreateItem(item);
_storage.PurgeItem(item);
var ex =
Assert.Throws<InventoryObjectMissingException>(delegate()
{
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
});
Assert.AreEqual("Item was not found in the index", ex.ErrorDetails);
});
}
pool.WaitForIdle();
InventoryFolderBase newFolder = _storage.GetFolder(folder1.ID);
Assert.AreEqual(0, newFolder.Items.Count);
Assert.AreEqual(5001, newFolder.Version);
}
[Test]
public void TestPurgeCreateConsistent()
{
Amib.Threading.SmartThreadPool pool = new Amib.Threading.SmartThreadPool(1000, 20);
pool.Start();
var userId = UUID.Parse("01EAE367-3A88-48B2-A226-AB3234EE506B");
InventoryFolderBase folder1 = new InventoryFolderBase();
folder1.ID = UUID.Parse("F1EAE367-3A88-48B2-A226-AB3234EE506B");
folder1.Name = "Folder1";
folder1.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder1.Owner = userId;
folder1.ParentID = UUID.Zero;
folder1.Type = (short)OpenMetaverse.AssetType.RootFolder;
try
{
_storage.GetFolderAttributes(folder1.ID);
}
catch (InventoryObjectMissingException e)
{
_storage.CreateFolder(folder1);
}
for (int i = 0; i < 100; i++)
{
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = folder1.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
pool.QueueWorkItem(() =>
{
_storage.CreateItem(item);
});
pool.QueueWorkItem(() =>
{
_storage.PurgeItem(item);
});
pool.QueueWorkItem(() =>
{
_storage.CreateItem(item);
});
pool.QueueWorkItem(() =>
{
_storage.PurgeItem(item);
});
pool.WaitForIdle();
InventoryFolderBase newFolder = _storage.GetFolder(folder1.ID);
//either the item should completely exist or not
if (newFolder.Items.Exists((InventoryItemBase litem) => { return litem.ID == itemId; }))
{
Assert.DoesNotThrow(delegate()
{
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
});
//cleanup
_storage.PurgeItem(item);
}
else
{
var ex =
Assert.Throws<InventoryObjectMissingException>(delegate()
{
InventoryItemBase itemCopy = _storage.GetItem(itemId, UUID.Zero);
});
Assert.AreEqual("Item was not found in the index", ex.ErrorDetails);
}
}
InventoryFolderBase finalFolder = _storage.GetFolder(folder1.ID);
Assert.AreEqual(0, finalFolder.Items.Count);
}
[TestCase]
public void TestItemMove()
{
UUID userId = UUID.Random();
InventoryFolderBase folder1 = new InventoryFolderBase();
folder1.ID = UUID.Random();
folder1.Name = "Folder1";
folder1.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder1.Owner = userId;
folder1.ParentID = UUID.Zero;
folder1.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder1);
InventoryFolderBase folder2 = new InventoryFolderBase();
folder2.ID = UUID.Random();
folder2.Name = "Folder2";
folder2.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder2.Owner = userId;
folder2.ParentID = UUID.Zero;
folder2.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(folder1);
_storage.CreateFolder(folder2);
UUID assetId = UUID.Random();
UUID itemId = UUID.Random();
InventoryItemBase item = new InventoryItemBase
{
AssetID = assetId,
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = folder1.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = itemId,
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.CreateItem(item);
_storage.MoveItem(item, folder2);
InventoryFolderBase newFolder1 = _storage.GetFolder(folder1.ID);
InventoryFolderBase newFolder2 = _storage.GetFolder(folder2.ID);
AssertFolderEqual(folder1, newFolder1, true);
AssertFolderEqual(folder2, newFolder2, true);
Assert.AreEqual(0, newFolder1.Items.Count);
Assert.AreEqual(1, newFolder2.Items.Count);
InventoryItemBase newItem = _storage.GetItem(item.ID, UUID.Zero);
item.Folder = newFolder2.ID;
AssertItemEqual(item, newItem);
}
[TestCase]
public void TestSendItemToTrash()
{
UUID userId = UUID.Random();
InventoryFolderBase rootFolder = new InventoryFolderBase();
rootFolder.ID = UUID.Random();
rootFolder.Name = "Root Folder";
rootFolder.Level = InventoryFolderBase.FolderLevel.TopLevel;
rootFolder.Owner = userId;
rootFolder.ParentID = UUID.Zero;
rootFolder.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(rootFolder);
InventoryFolderBase trashFolder = new InventoryFolderBase();
trashFolder.ID = UUID.Random();
trashFolder.Name = "Trash Folder";
trashFolder.Level = InventoryFolderBase.FolderLevel.TopLevel;
trashFolder.Owner = userId;
trashFolder.ParentID = rootFolder.ID;
trashFolder.Type = (short)OpenMetaverse.AssetType.TrashFolder;
_storage.CreateFolder(trashFolder);
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Random(),
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
Folder = rootFolder.ID,
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = UUID.Random(),
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "Item of Goodness",
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
_storage.SendItemToTrash(item, UUID.Zero);
InventoryItemBase trashedItem = _storage.GetItem(item.ID, UUID.Zero);
Assert.AreEqual(trashedItem.Folder, trashFolder.ID);
AssertItemEqual(item, trashedItem);
}
[TestCase]
public void TestFolderPurgeContents()
{
UUID userId = UUID.Random();
InventoryFolderBase rootFolder = new InventoryFolderBase();
rootFolder.ID = UUID.Random();
rootFolder.Name = "Root Folder";
rootFolder.Level = InventoryFolderBase.FolderLevel.TopLevel;
rootFolder.Owner = userId;
rootFolder.ParentID = UUID.Zero;
rootFolder.Type = (short)OpenMetaverse.AssetType.RootFolder;
_storage.CreateFolder(rootFolder);
InventoryFolderBase trashFolder = new InventoryFolderBase();
trashFolder.ID = UUID.Random();
trashFolder.Name = "Trash Folder";
trashFolder.Level = InventoryFolderBase.FolderLevel.TopLevel;
trashFolder.Owner = userId;
trashFolder.ParentID = rootFolder.ID;
trashFolder.Type = (short)OpenMetaverse.AssetType.TrashFolder;
_storage.CreateFolder(trashFolder);
//generate 50 folders with 500 items in them
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
List<InventoryItemBase> items = new List<InventoryItemBase>();
Random r = new Random();
for (int i = 0; i < 50; i++)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder" + i.ToString();
folder.Level = InventoryFolderBase.FolderLevel.Leaf;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.TrashFolder;
int index = r.Next(-1, folders.Count - 1);
if (index == -1)
{
folder.ParentID = trashFolder.ID;
}
else
{
folder.ParentID = folders[index].ID;
}
folders.Add(folder);
}
for (int i = 0; i < 200; i++)
{
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Random(),
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = UUID.Random(),
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "RandomItem" + i.ToString(),
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1
};
int index = r.Next(-1, folders.Count - 1);
if (index == -1)
{
item.Folder = trashFolder.ID;
}
else
{
item.Folder = folders[index].ID;
}
items.Add(item);
}
foreach (InventoryFolderBase folder in folders)
{
_storage.CreateFolder(folder);
}
foreach (InventoryItemBase item in items)
{
_storage.CreateItem(item);
}
//verify the trash folder is now full of stuff
InventoryFolderBase fullTrash = _storage.GetFolder(trashFolder.ID);
Assert.That(fullTrash.SubFolders.Count > 0);
//make sure all folders are accounted for
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(52, skel.Count);
//do some raw queries to verify we have good indexing happening
foreach (InventoryItemBase item in items)
{
Guid parent = _storage.FindItemParentFolderId(item.ID);
Assert.AreEqual(parent, item.Folder.Guid);
}
//purge the trash
_storage.PurgeFolderContents(trashFolder);
//verify the index is empty except for the trash and the root
skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(2, skel.Count);
//verify none of the items are accessable anymore
foreach (InventoryItemBase item in items)
{
Assert.Throws<InventoryObjectMissingException>(delegate()
{
_storage.GetItem(item.ID, UUID.Zero);
});
Assert.Throws<InventoryObjectMissingException>(delegate()
{
_storage.GetItem(item.ID, item.Folder);
});
}
//verify the root folder doesn't show any items or subfolders
InventoryFolderBase emptyTrash = _storage.GetFolder(trashFolder.ID);
Assert.AreEqual(0, emptyTrash.Items.Count);
Assert.AreEqual(0, emptyTrash.SubFolders.Count);
}
[TestCase]
public void TestFolderIndexPagination()
{
TestFolderIndexPagination(1);
TestFolderIndexPagination(1023);
TestFolderIndexPagination(1024);
TestFolderIndexPagination(1025);
TestFolderIndexPagination(2047);
TestFolderIndexPagination(2048);
TestFolderIndexPagination(2049);
}
private void TestFolderIndexPagination(int FOLDER_COUNT)
{
UUID userId = UUID.Random();
List<InventoryFolderBase> folders = new List<InventoryFolderBase>(FOLDER_COUNT);
for (int i = 0; i < FOLDER_COUNT; i++)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder" + i.ToString();
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = UUID.Zero;
_storage.CreateFolder(folder);
folders.Add(folder);
//add an item to the folder so that its version is 2
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Random(),
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "A good item, of goodness",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = UUID.Random(),
InvType = (int)OpenMetaverse.InventoryType.Texture,
Name = "RandomItem" + i.ToString(),
NextPermissions = 0xF,
Owner = userId,
SalePrice = 100,
SaleType = 1,
Folder = folder.ID
};
_storage.CreateItem(item);
}
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(FOLDER_COUNT, skel.Count);
Dictionary<UUID, InventoryFolderBase> indexOfFolders = new Dictionary<UUID, InventoryFolderBase>();
foreach (InventoryFolderBase folder in skel)
{
indexOfFolders.Add(folder.ID, folder);
Assert.AreEqual(2, folder.Version);
}
foreach (InventoryFolderBase folder in folders)
{
Assert.That(indexOfFolders.ContainsKey(folder.ID));
AssertFolderEqual(folder, indexOfFolders[folder.ID], true);
}
}
[TestCase]
public void TestSinglePurgeFolder()
{
UUID userId = UUID.Random();
InventoryFolderBase parentFolder = new InventoryFolderBase();
parentFolder.ID = UUID.Random();
parentFolder.Name = "RootFolder";
parentFolder.Level = InventoryFolderBase.FolderLevel.Root;
parentFolder.Owner = userId;
parentFolder.Type = (short)OpenMetaverse.AssetType.RootFolder;
parentFolder.ParentID = UUID.Zero;
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = parentFolder.ID;
_storage.CreateFolder(parentFolder);
_storage.CreateFolder(folder);
//System.Threading.Thread.Sleep(30);
_storage.PurgeFolder(folder);
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(1, skel.Count);
Assert.Throws<InventoryObjectMissingException>(delegate()
{
_storage.GetFolder(folder.ID);
});
InventoryFolderBase updatedParent = _storage.GetFolder(parentFolder.ID);
Assert.AreEqual(0, updatedParent.SubFolders.Count);
}
[TestCase]
public void TestMultiPurgeFolder()
{
const int FOLDER_COUNT = 20;
UUID userId = UUID.Random();
List<InventoryFolderBase> folders = new List<InventoryFolderBase>(FOLDER_COUNT);
for (int i = 0; i < FOLDER_COUNT; i++)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder" + i.ToString();
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = UUID.Zero;
_storage.CreateFolder(folder);
folders.Add(folder);
}
System.Threading.Thread.Sleep(30);
_storage.PurgeFolders(folders);
List<InventoryFolderBase> skel = _storage.GetInventorySkeleton(userId);
Assert.AreEqual(0, skel.Count);
foreach (InventoryFolderBase folder in folders)
{
Assert.Throws<InventoryObjectMissingException>(delegate()
{
_storage.GetFolder(folder.ID);
});
}
}
[TestCase]
public void TestGestureTracking()
{
const int NUM_GESTURES = 100;
List<InventoryItemBase> gestures = new List<InventoryItemBase>();
Dictionary<UUID, InventoryItemBase> gestureIndex = new Dictionary<UUID, InventoryItemBase>();
UUID userId = UUID.Random();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = UUID.Zero;
_storage.CreateFolder(folder);
for (int i = 0; i < NUM_GESTURES; i++)
{
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Random(),
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "Gesture",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = UUID.Random(),
InvType = (int)OpenMetaverse.InventoryType.Gesture,
Name = "RandomItem" + i.ToString(),
NextPermissions = 0xF,
Owner = userId,
Folder = folder.ID
};
gestures.Add(item);
gestureIndex.Add(item.ID, item);
_storage.CreateItem(item);
}
_storage.ActivateGestures(userId, (from item in gestures select item.ID));
//make sure all the gestures show active
List<InventoryItemBase> items = _storage.GetActiveGestureItems(userId);
Assert.AreEqual(NUM_GESTURES, items.Count);
foreach (InventoryItemBase item in items)
{
Assert.That(gestureIndex.ContainsKey(item.ID));
AssertItemEqual(gestureIndex[item.ID], item);
gestureIndex.Remove(item.ID);
}
Assert.AreEqual(0, gestureIndex.Count);
_storage.DeactivateGestures(userId, (from item in gestures select item.ID));
items = _storage.GetActiveGestureItems(userId);
Assert.AreEqual(0, items.Count);
}
private void AssertItemEqual(InventoryItemBase i1, InventoryItemBase i2)
{
Assert.AreEqual(i1.AssetID, i2.AssetID);
Assert.AreEqual(i1.AssetType, i2.AssetType);
Assert.AreEqual(i1.BasePermissions, i2.BasePermissions);
Assert.AreEqual(i1.ContainsMultipleItems, i2.ContainsMultipleItems);
Assert.AreEqual(i1.CreationDate, i2.CreationDate);
Assert.AreEqual(i1.CreatorId, i2.CreatorId);
Assert.AreEqual(i1.CreatorIdAsUuid, i2.CreatorIdAsUuid);
Assert.AreEqual(i1.CurrentPermissions, i2.CurrentPermissions);
Assert.AreEqual(i1.Description, i2.Description);
Assert.AreEqual(i1.EveryOnePermissions, i2.EveryOnePermissions);
Assert.AreEqual(i1.Flags, i2.Flags);
Assert.AreEqual(i1.Folder, i2.Folder);
Assert.AreEqual(i1.GroupID, i2.GroupID);
Assert.AreEqual(i1.GroupOwned, i2.GroupOwned);
Assert.AreEqual(i1.GroupPermissions, i2.GroupPermissions);
Assert.AreEqual(i1.ID, i2.ID);
Assert.AreEqual(i1.InvType, i2.InvType);
Assert.AreEqual(i1.Name, i2.Name);
Assert.AreEqual(i1.NextPermissions, i2.NextPermissions);
Assert.AreEqual(i1.Owner, i2.Owner);
Assert.AreEqual(i1.SalePrice, i2.SalePrice);
Assert.AreEqual(i1.SaleType, i2.SaleType);
}
[TestCase]
public void TestInvalidSubfolderIndexCleanup()
{
UUID userId = UUID.Random();
InventoryFolderBase parentFolder = new InventoryFolderBase();
parentFolder.ID = UUID.Random();
parentFolder.Name = "RootFolder";
parentFolder.Level = InventoryFolderBase.FolderLevel.Root;
parentFolder.Owner = userId;
parentFolder.Type = (short)OpenMetaverse.AssetType.RootFolder;
parentFolder.ParentID = UUID.Zero;
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Name = "RandomFolder";
folder.Level = InventoryFolderBase.FolderLevel.TopLevel;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = parentFolder.ID;
_storage.CreateFolder(parentFolder);
_storage.CreateFolder(folder);
InventoryFolderBase validChild = new InventoryFolderBase();
validChild.ID = UUID.Random();
validChild.Name = "ValidChild";
validChild.Level = InventoryFolderBase.FolderLevel.Leaf;
validChild.Owner = userId;
validChild.Type = (short)OpenMetaverse.AssetType.Unknown;
validChild.ParentID = folder.ID;
_storage.CreateFolder(validChild);
InventoryItemBase item = new InventoryItemBase
{
AssetID = UUID.Random(),
AssetType = (int)OpenMetaverse.AssetType.Texture,
BasePermissions = UInt32.MaxValue,
CreationDate = Util.UnixTimeSinceEpoch(),
CreatorId = userId.ToString(),
CurrentPermissions = unchecked((uint)-1),
Description = "Gesture",
EveryOnePermissions = Int32.MaxValue + (uint)1,
Flags = unchecked((uint)Int32.MinValue),
GroupID = UUID.Zero,
GroupOwned = false,
GroupPermissions = 0x123,
ID = UUID.Random(),
InvType = (int)OpenMetaverse.InventoryType.Gesture,
Name = "RandomItem",
NextPermissions = 0xF,
Owner = userId,
Folder = validChild.ID
};
_storage.SaveItem(item);
InventoryFolderBase invalidChild = new InventoryFolderBase();
invalidChild.ID = UUID.Random();
invalidChild.Name = "InvalidChild";
invalidChild.Level = InventoryFolderBase.FolderLevel.Leaf;
folder.Owner = userId;
folder.Type = (short)OpenMetaverse.AssetType.Unknown;
folder.ParentID = folder.ID;
_storage.UpdateParentWithNewChild(invalidChild, folder.ID.Guid, Guid.Empty, Util.UnixTimeSinceEpochInMicroseconds());
//reread the folder
folder = _storage.GetFolder(folder.ID);
//ensure that the dud link exists
Assert.That(folder.SubFolders.Count == 2);
foreach (var subfolder in folder.SubFolders)
{
Assert.IsTrue(subfolder.ID == invalidChild.ID || subfolder.ID == validChild.ID);
}
//Run a repair
_storage.Maint_RepairSubfolderIndexes(userId);
//verify we got rid of the dud link, but everything else is in tact
folder = _storage.GetFolder(folder.ID);
Assert.That(folder.SubFolders.Count == 1);
Assert.AreEqual(folder.SubFolders.First().ID, validChild.ID);
validChild = _storage.GetFolder(validChild.ID);
Assert.AreEqual(validChild.Name, "ValidChild");
Assert.That(validChild.Items.Count == 1);
Assert.AreEqual(validChild.Items[0].Name, "RandomItem");
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// RedeemRequestInfo
/// </summary>
[DataContract]
public partial class RedeemRequestInfo : IEquatable<RedeemRequestInfo>, IValidatableObject
{
/// <summary>
/// Gets or Sets Status
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Submited for "Submited"
/// </summary>
[EnumMember(Value = "Submited")]
Submited,
/// <summary>
/// Enum Approved for "Approved"
/// </summary>
[EnumMember(Value = "Approved")]
Approved,
/// <summary>
/// Enum Rejected for "Rejected"
/// </summary>
[EnumMember(Value = "Rejected")]
Rejected
}
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="RedeemRequestInfo" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="Status">Status.</param>
/// <param name="StatusComment">StatusComment.</param>
/// <param name="TableNumber">TableNumber.</param>
public RedeemRequestInfo(string Id = null, StatusEnum? Status = null, string StatusComment = null, string TableNumber = null)
{
this.Id = Id;
this.Status = Status;
this.StatusComment = StatusComment;
this.TableNumber = TableNumber;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets StatusComment
/// </summary>
[DataMember(Name="statusComment", EmitDefaultValue=true)]
public string StatusComment { get; set; }
/// <summary>
/// Gets or Sets TableNumber
/// </summary>
[DataMember(Name="tableNumber", EmitDefaultValue=true)]
public string TableNumber { 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 RedeemRequestInfo {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" StatusComment: ").Append(StatusComment).Append("\n");
sb.Append(" TableNumber: ").Append(TableNumber).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 RedeemRequestInfo);
}
/// <summary>
/// Returns true if RedeemRequestInfo instances are equal
/// </summary>
/// <param name="other">Instance of RedeemRequestInfo to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RedeemRequestInfo other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.StatusComment == other.StatusComment ||
this.StatusComment != null &&
this.StatusComment.Equals(other.StatusComment)
) &&
(
this.TableNumber == other.TableNumber ||
this.TableNumber != null &&
this.TableNumber.Equals(other.TableNumber)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.StatusComment != null)
hash = hash * 59 + this.StatusComment.GetHashCode();
if (this.TableNumber != null)
hash = hash * 59 + this.TableNumber.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Dbg = System.Management.Automation.Diagnostics;
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Implements a cmdlet that gets the list of loaded modules...
/// </summary>
[Cmdlet(VerbsCommon.Get, "Module", DefaultParameterSetName = ParameterSet_Loaded,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=141552")]
[OutputType(typeof(PSModuleInfo))]
public sealed class GetModuleCommand : ModuleCmdletBase, IDisposable
{
#region Cmdlet parameters
private const string ParameterSet_Loaded = "Loaded";
private const string ParameterSet_AvailableLocally = "Available";
private const string ParameterSet_AvailableInPsrpSession = "PsSession";
private const string ParameterSet_AvailableInCimSession = "CimSession";
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Loaded, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_AvailableLocally, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, ValueFromPipeline = true, Position = 0)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "Cmdlets use arrays for parameters.")]
public string[] Name { get; set; }
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Loaded, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = ParameterSet_AvailableLocally, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, ValueFromPipelineByPropertyName = true)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Justification = "Cmdlets use arrays for parameters.")]
public ModuleSpecification[] FullyQualifiedName { get; set; }
/// <summary>
/// If specified, all loaded modules should be returned, otherwise only the visible
/// modules should be returned.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Loaded)]
[Parameter(ParameterSetName = ParameterSet_AvailableLocally)]
public SwitchParameter All { get; set; }
/// <summary>
/// If specified, then Get-Module will return the set of available modules...
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableLocally, Mandatory = true)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)]
public SwitchParameter ListAvailable { get; set; }
/// <summary>
/// If specified, then Get-Module will return the set of available modules which supports the specified PowerShell edition...
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableLocally)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)]
[ArgumentCompleter(typeof(PSEditionArgumentCompleter))]
public string PSEdition { get; set; }
/// <summary>
/// When set, CompatiblePSEditions checking is disabled for modules in the System32 (Windows PowerShell) module directory.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableLocally)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)]
public SwitchParameter SkipEditionCheck
{
get { return (SwitchParameter)BaseSkipEditionCheck; }
set { BaseSkipEditionCheck = value; }
}
/// <summary>
/// If specified, then Get-Module refreshes the internal cmdlet analysis cache.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableLocally)]
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession)]
public SwitchParameter Refresh { get; set; }
/// <summary>
/// If specified, then Get-Module will attempt to discover PowerShell modules on a remote computer using the specified session.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableInPsrpSession, Mandatory = true)]
[ValidateNotNull]
public PSSession PSSession { get; set; }
/// <summary>
/// If specified, then Get-Module will attempt to discover PS-CIM modules on a remote computer using the specified session.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = true)]
[ValidateNotNull]
public CimSession CimSession { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom resource URI.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = false)]
[ValidateNotNull]
public Uri CimResourceUri { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom namespace.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_AvailableInCimSession, Mandatory = false)]
[ValidateNotNullOrEmpty]
public string CimNamespace { get; set; }
#endregion Cmdlet parameters
#region Remote discovery
private IEnumerable<PSModuleInfo> GetAvailableViaPsrpSessionCore(string[] moduleNames, Runspace remoteRunspace)
{
Dbg.Assert(remoteRunspace != null, "Caller should verify remoteRunspace != null");
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = remoteRunspace;
powerShell.AddCommand("Get-Module");
powerShell.AddParameter("ListAvailable", true);
if (Refresh.IsPresent)
{
powerShell.AddParameter("Refresh", true);
}
if (moduleNames != null)
{
powerShell.AddParameter("Name", moduleNames);
}
string errorMessageTemplate = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryRemotePsrpCommandFailed,
"Get-Module");
foreach (
PSObject outputObject in
RemoteDiscoveryHelper.InvokePowerShell(powerShell, this.CancellationToken, this,
errorMessageTemplate))
{
PSModuleInfo moduleInfo = RemoteDiscoveryHelper.RehydratePSModuleInfo(outputObject);
yield return moduleInfo;
}
}
}
private PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule)
{
return new PSModuleInfo(cimModule.ModuleName, null, null);
}
private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.CimModule cimModule,
string computerName)
{
try
{
bool containedErrors = false;
if (cimModule.MainManifest == null)
{
return GetModuleInfoForRemoteModuleWithoutManifest(cimModule);
}
string temporaryModuleManifestPath = Path.Combine(
RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, computerName,
this.Context.CurrentRunspace),
Path.GetFileName(cimModule.ModuleName));
Hashtable mainData = null;
if (!containedErrors)
{
mainData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable(
cimModule.MainManifest,
temporaryModuleManifestPath,
this,
ref containedErrors);
if (mainData == null)
{
return GetModuleInfoForRemoteModuleWithoutManifest(cimModule);
}
}
if (!containedErrors)
{
mainData = RemoteDiscoveryHelper.RewriteManifest(mainData);
}
Hashtable localizedData = mainData; // TODO/FIXME - this needs full path support from the provider
PSModuleInfo moduleInfo = null;
if (!containedErrors)
{
ImportModuleOptions throwAwayOptions = new ImportModuleOptions();
moduleInfo = LoadModuleManifest(
temporaryModuleManifestPath,
null, // scriptInfo
mainData,
localizedData,
0 /* - don't write errors, don't load elements, don't return null on first error */,
this.BaseMinimumVersion,
this.BaseMaximumVersion,
this.BaseRequiredVersion,
this.BaseGuid,
ref throwAwayOptions,
ref containedErrors);
}
if ((moduleInfo == null) || containedErrors)
{
moduleInfo = GetModuleInfoForRemoteModuleWithoutManifest(cimModule);
}
return moduleInfo;
}
catch (Exception e)
{
ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, cimModule.ModuleName);
this.WriteError(errorRecord);
return null;
}
}
private IEnumerable<PSModuleInfo> GetAvailableViaCimSessionCore(IEnumerable<string> moduleNames,
CimSession cimSession, Uri resourceUri,
string cimNamespace)
{
IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules(
cimSession,
resourceUri,
cimNamespace,
moduleNames,
true /* onlyManifests */,
this,
this.CancellationToken);
IEnumerable<PSModuleInfo> remoteModuleInfos = remoteModules
.Select(cimModule => this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName))
.Where(moduleInfo => moduleInfo != null);
return remoteModuleInfos;
}
#endregion Remote discovery
#region Cancellation support
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private CancellationToken CancellationToken
{
get { return _cancellationTokenSource.Token; }
}
/// <summary>
/// When overridden in the derived class, interrupts currently
/// running code within the command. It should interrupt BeginProcessing,
/// ProcessRecord, and EndProcessing.
/// Default implementation in the base class just returns.
/// </summary>
protected override void StopProcessing()
{
_cancellationTokenSource.Cancel();
}
#endregion
#region IDisposable Members
/// <summary>
/// Releases resources associated with this object.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases resources associated with this object.
/// </summary>
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_cancellationTokenSource.Dispose();
}
_disposed = true;
}
private bool _disposed;
#endregion
private void AssertListAvailableMode()
{
if (!this.ListAvailable.IsPresent)
{
string errorMessage = Modules.RemoteDiscoveryWorksOnlyInListAvailableMode;
ArgumentException argumentException = new ArgumentException(errorMessage);
ErrorRecord errorRecord = new ErrorRecord(
argumentException,
"RemoteDiscoveryWorksOnlyInListAvailableMode",
ErrorCategory.InvalidArgument,
null);
this.ThrowTerminatingError(errorRecord);
}
}
/// <summary>
/// Write out the specified modules...
/// </summary>
protected override void ProcessRecord()
{
// Name and FullyQualifiedName should not be specified at the same time.
// Throw out terminating error if this is the case.
if ((Name != null) && (FullyQualifiedName != null))
{
string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Name", "FullyQualifiedName");
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "NameAndFullyQualifiedNameCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(error);
}
// -SkipEditionCheck only makes sense for -ListAvailable (otherwise the module is already loaded)
if (SkipEditionCheck && !ListAvailable)
{
ErrorRecord error = new ErrorRecord(
new InvalidOperationException(Modules.SkipEditionCheckNotSupportedWithoutListAvailable),
nameof(Modules.SkipEditionCheckNotSupportedWithoutListAvailable),
ErrorCategory.InvalidOperation,
targetObject: null);
ThrowTerminatingError(error);
}
var strNames = new List<string>();
if (Name != null)
{
strNames.AddRange(Name);
}
var moduleSpecTable = new Dictionary<string, ModuleSpecification>(StringComparer.OrdinalIgnoreCase);
if (FullyQualifiedName != null)
{
// TODO:
// FullyQualifiedName.Name could be a path, in which case it will not match module.Name.
// This is potentially a bug (since version checks are ignored).
// We should normalize FullyQualifiedName.Name here with ModuleIntrinsics.NormalizeModuleName().
moduleSpecTable = FullyQualifiedName.ToDictionary(moduleSpecification => moduleSpecification.Name, StringComparer.OrdinalIgnoreCase);
strNames.AddRange(FullyQualifiedName.Select(spec => spec.Name));
}
string[] names = strNames.Count > 0 ? strNames.ToArray() : null;
if (ParameterSetName.Equals(ParameterSet_Loaded, StringComparison.OrdinalIgnoreCase))
{
AssertNameDoesNotResolveToAPath(names,
Modules.ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames,
"ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames");
GetLoadedModules(names, moduleSpecTable, this.All);
}
else if (ParameterSetName.Equals(ParameterSet_AvailableLocally, StringComparison.OrdinalIgnoreCase))
{
if (ListAvailable.IsPresent)
{
GetAvailableLocallyModules(names, moduleSpecTable, this.All);
}
else
{
AssertNameDoesNotResolveToAPath(names,
Modules.ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames,
"ModuleDiscoveryForLoadedModulesWorksOnlyForUnQualifiedNames");
GetLoadedModules(names, moduleSpecTable, this.All);
}
}
else if (ParameterSetName.Equals(ParameterSet_AvailableInPsrpSession, StringComparison.OrdinalIgnoreCase))
{
AssertListAvailableMode();
AssertNameDoesNotResolveToAPath(names,
Modules.RemoteDiscoveryWorksOnlyForUnQualifiedNames,
"RemoteDiscoveryWorksOnlyForUnQualifiedNames");
GetAvailableViaPsrpSession(names, moduleSpecTable, this.PSSession);
}
else if (ParameterSetName.Equals(ParameterSet_AvailableInCimSession, StringComparison.OrdinalIgnoreCase))
{
AssertListAvailableMode();
AssertNameDoesNotResolveToAPath(names,
Modules.RemoteDiscoveryWorksOnlyForUnQualifiedNames,
"RemoteDiscoveryWorksOnlyForUnQualifiedNames");
GetAvailableViaCimSession(names, moduleSpecTable, this.CimSession,
this.CimResourceUri, this.CimNamespace);
}
else
{
Dbg.Assert(false, "Unrecognized parameter set");
}
}
private void AssertNameDoesNotResolveToAPath(string[] names, string stringFormat, string resourceId)
{
if (names != null)
{
foreach (var n in names)
{
if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1)
{
string errorMessage = StringUtil.Format(stringFormat, n);
var argumentException = new ArgumentException(errorMessage);
var errorRecord = new ErrorRecord(
argumentException,
resourceId,
ErrorCategory.InvalidArgument,
n);
this.ThrowTerminatingError(errorRecord);
}
}
}
}
private void GetAvailableViaCimSession(IEnumerable<string> names, IDictionary<string, ModuleSpecification> moduleSpecTable,
CimSession cimSession, Uri resourceUri, string cimNamespace)
{
IEnumerable<PSModuleInfo> remoteModules = GetAvailableViaCimSessionCore(names, cimSession, resourceUri, cimNamespace);
foreach (PSModuleInfo remoteModule in FilterModulesForEditionAndSpecification(remoteModules, moduleSpecTable))
{
RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, cimSession, resourceUri,
cimNamespace);
this.WriteObject(remoteModule);
}
}
private void GetAvailableViaPsrpSession(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, PSSession session)
{
IEnumerable<PSModuleInfo> remoteModules = GetAvailableViaPsrpSessionCore(names, session.Runspace);
foreach (PSModuleInfo remoteModule in FilterModulesForEditionAndSpecification(remoteModules, moduleSpecTable))
{
RemoteDiscoveryHelper.AssociatePSModuleInfoWithSession(remoteModule, session);
this.WriteObject(remoteModule);
}
}
private void GetAvailableLocallyModules(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, bool all)
{
IEnumerable<PSModuleInfo> modules = GetModule(names, all, Refresh);
foreach (PSModuleInfo module in FilterModulesForEditionAndSpecification(modules, moduleSpecTable))
{
var psModule = new PSObject(module);
psModule.TypeNames.Insert(0, "ModuleInfoGrouping");
WriteObject(psModule);
}
}
private void GetLoadedModules(string[] names, IDictionary<string, ModuleSpecification> moduleSpecTable, bool all)
{
var modulesToWrite = Context.Modules.GetModules(names, all);
foreach (PSModuleInfo moduleInfo in FilterModulesForEditionAndSpecification(modulesToWrite, moduleSpecTable))
{
WriteObject(moduleInfo);
}
}
/// <summary>
/// Filter an enumeration of PowerShell modules based on the required PowerShell edition
/// and the module specification constraints set for each module (if any).
/// </summary>
/// <param name="modules">The modules to filter through.</param>
/// <param name="moduleSpecificationTable">Module constraints, keyed by module name, to filter modules of that name by.</param>
/// <returns>All modules from the original input that meet both any module edition and module specification constraints provided.</returns>
private IEnumerable<PSModuleInfo> FilterModulesForEditionAndSpecification(
IEnumerable<PSModuleInfo> modules,
IDictionary<string, ModuleSpecification> moduleSpecificationTable)
{
#if !UNIX
// Edition check only applies to Windows System32 module path
if (!SkipEditionCheck && ListAvailable && !All)
{
modules = modules.Where(module => module.IsConsideredEditionCompatible);
}
#endif
if (!string.IsNullOrEmpty(PSEdition))
{
modules = modules.Where(module => module.CompatiblePSEditions.Contains(PSEdition, StringComparer.OrdinalIgnoreCase));
}
if (moduleSpecificationTable != null && moduleSpecificationTable.Count > 0)
{
modules = FilterModulesForSpecificationMatch(modules, moduleSpecificationTable);
}
return modules;
}
/// <summary>
/// Take an enumeration of modules and only return those that match a specification
/// in the given specification table, or have no corresponding entry in the specification table.
/// </summary>
/// <param name="modules">The modules to filter by specification match.</param>
/// <param name="moduleSpecificationTable">The specification lookup table to filter the modules on.</param>
/// <returns>The modules that match their corresponding table entry, or which have no table entry.</returns>
private static IEnumerable<PSModuleInfo> FilterModulesForSpecificationMatch(
IEnumerable<PSModuleInfo> modules,
IDictionary<string, ModuleSpecification> moduleSpecificationTable)
{
Dbg.Assert(moduleSpecificationTable != null, $"Caller to verify that {nameof(moduleSpecificationTable)} is not null");
Dbg.Assert(moduleSpecificationTable.Count != 0, $"Caller to verify that {nameof(moduleSpecificationTable)} is not empty");
foreach (PSModuleInfo module in modules)
{
// TODO:
// moduleSpecification.Name may be a path and will not match module.Name when they refer to the same module.
// This actually causes the module to be returned always, so other specification checks are skipped erroneously.
// Instead we need to be able to look up or match modules by path as well (e.g. a new comparer for PSModuleInfo).
// No table entry means we return the module
if (!moduleSpecificationTable.TryGetValue(module.Name, out ModuleSpecification moduleSpecification))
{
yield return module;
continue;
}
// Modules with table entries only get returned if they match them
if (ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpecification))
{
yield return module;
}
}
}
}
/// <summary>
/// PSEditionArgumentCompleter for PowerShell Edition names.
/// </summary>
public class PSEditionArgumentCompleter : IArgumentCompleter
{
/// <summary>
/// CompleteArgument.
/// </summary>
public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
{
var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase);
foreach (var edition in Utils.AllowedEditionValues)
{
if (wordToCompletePattern.IsMatch(edition))
{
yield return new CompletionResult(edition, edition, CompletionResultType.Text, edition);
}
}
}
}
}
| |
// 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.
//
//
// All P/invokes used by internal Interop code goes here
//
// !!IMPORTANT!!
//
// Do not rely on MCG to generate marshalling code for these p/invokes as MCG might not see them at all
// due to not seeing dependency to those calls (before the MCG generated code is generated). Instead,
// always manually marshal the arguments
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
// TODO : Remove the remaning methods in this file to correct interop*.cs files under Interop folder
partial class Interop
{
#if TARGET_CORE_API_SET
internal const string CORE_SYNCH_L2 = "api-ms-win-core-synch-l1-2-0.dll";
#else
//
// Define dll names for previous version of Windows earlier than Windows 8
//
internal const string CORE_SYNCH_L2 = "kernel32.dll";
internal const string CORE_COM = "ole32.dll";
internal const string CORE_COM_AUT = "OleAut32.dll";
#endif
internal unsafe partial class MinCore
{
#if RHTESTCL
[DllImport(CORE_SYNCH_L2)]
[McgGeneratedNativeCallCodeAttribute]
static internal extern void Sleep(int milliseconds);
#else
private static readonly System.Threading.WaitHandle s_sleepHandle = new System.Threading.ManualResetEvent(false);
static internal void Sleep(uint milliseconds)
{
#if CORECLR
System.Threading.Thread.Sleep(0);
#else
if (milliseconds == 0)
System.Threading.SpinWait.Yield();
else
s_sleepHandle.WaitOne((int)milliseconds);
#endif
}
#endif
}
internal unsafe partial class COM
{
//
// IIDs
//
internal static Guid IID_IUnknown = new Guid(0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
internal static Guid IID_IMarshal = new Guid(0x00000003, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
internal static Guid IID_IAgileObject = new Guid(unchecked((int)0x94ea2b94), unchecked((short)0xe9cc), 0x49e0, 0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90);
internal static Guid IID_IContextCallback = new Guid(0x000001da, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
internal static Guid IID_IEnterActivityWithNoLock = new Guid(unchecked((int)0xd7174f82), 0x36b8, 0x4aa8, 0x80, 0x0a, 0xe9, 0x63, 0xab, 0x2d, 0xfa, 0xb9);
internal static Guid IID_ICustomPropertyProvider = new Guid(unchecked(((int)(0x7C925755u))), unchecked(((short)(0x3E48))), unchecked(((short)(0x42B4))), 0x86, 0x77, 0x76, 0x37, 0x22, 0x67, 0x3, 0x3F);
internal static Guid IID_IInspectable = new Guid(unchecked((int)0xAF86E2E0), unchecked((short)0xB12D), 0x4c6a, 0x9C, 0x5A, 0xD7, 0xAA, 0x65, 0x10, 0x1E, 0x90);
internal static Guid IID_IWeakReferenceSource = new Guid(0x00000038, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
internal static Guid IID_IWeakReference = new Guid(0x00000037, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
internal static Guid IID_IFindDependentWrappers = new Guid(0x04b3486c, 0x4687, 0x4229, 0x8d, 0x14, 0x50, 0x5a, 0xb5, 0x84, 0xdd, 0x88);
internal static Guid IID_IStringable = new Guid(unchecked((int)0x96369f54), unchecked((short)0x8eb6), 0x48f0, 0xab, 0xce, 0xc1, 0xb2, 0x11, 0xe6, 0x27, 0xc3);
internal static Guid IID_IRestrictedErrorInfo = new Guid(unchecked((int)0x82ba7092), unchecked((short)0x4c88), unchecked((short)0x427d), 0xa7, 0xbc, 0x16, 0xdd, 0x93, 0xfe, 0xb6, 0x7e);
internal static Guid IID_ILanguageExceptionErrorInfo = new Guid(unchecked((int)0x04a2dbf3), unchecked((short)0xdf83), unchecked((short)0x116c), 0x09, 0x46, 0x08, 0x12, 0xab, 0xf6, 0xe0, 0x7d);
internal static Guid IID_INoMarshal = new Guid(unchecked((int)0xECC8691B), unchecked((short)0xC1DB), 0x4DC0, 0x85, 0x5E, 0x65, 0xF6, 0xC5, 0x51, 0xAF, 0x49);
internal static Guid IID_IStream = new Guid(0x0000000C, 0x0000, 0x0000, 0xC0, 0x00, 0x00,0x00,0x00, 0x00,0x00, 0x46);
internal static Guid IID_ISequentialStream = new Guid(unchecked((int)0x0C733A30), 0x2A1C, 0x11CE, 0xAD, 0xE5, 0x00, 0xAA, 0x00, 0x44, 0x77, 0x3D);
//
// Jupiter IIDs.
//
// Note that the Windows sources refer to these IIDs via different names:
//
// IClrServices = Windows.UI.Xaml.Hosting.IReferenceTrackerHost
// IJupiterObject = Windows.UI.Xaml.Hosting.IReferenceTracker
// ICCW = Windows.UI.Xaml.Hosting.IReferenceTrackerTarget
//
internal static Guid IID_ICLRServices = new Guid(0x29a71c6a, 0x3c42, 0x4416, 0xa3, 0x9d, 0xe2, 0x82, 0x5a, 0x07, 0xa7, 0x73);
internal static Guid IID_IJupiterObject = new Guid(0x11d3b13a, 0x180e, 0x4789, 0xa8, 0xbe, 0x77, 0x12, 0x88, 0x28, 0x93, 0xe6);
internal static Guid IID_ICCW = new Guid(0x64bd43f8, unchecked((short)0xbfee), 0x4ec4, 0xb7, 0xeb, 0x29, 0x35, 0x15, 0x8d, 0xae, 0x21);
//
// CLSIDs
//
internal static Guid CLSID_InProcFreeMarshaler = new Guid(0x0000033A, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
[StructLayout(LayoutKind.Sequential)]
internal struct MULTI_QI
{
internal IntPtr pIID;
internal IntPtr pItf;
internal int hr;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static unsafe internal string ConvertBSTRToString(IntPtr pBSTR)
{
String myString = null;
if (pBSTR != default(IntPtr))
{
myString = new String((char*)pBSTR, 0, (int)ExternalInterop.SysStringLen(pBSTR));
}
return myString;
}
//
// Constants and enums
//
internal enum MSHCTX : uint
{
MSHCTX_LOCAL = 0, // unmarshal context is local (eg.shared memory)
MSHCTX_NOSHAREDMEM = 1, // unmarshal context has no shared memory access
MSHCTX_DIFFERENTMACHINE = 2,// unmarshal context is on a different machine
MSHCTX_INPROC = 3, // unmarshal context is on different thread
}
[Flags]
internal enum MSHLFLAGS : uint
{
MSHLFLAGS_NORMAL = 0, // normal marshaling via proxy/stub
MSHLFLAGS_TABLESTRONG = 1, // keep object alive; must explicitly release
MSHLFLAGS_TABLEWEAK = 2, // doesn't hold object alive; still must release
MSHLFLAGS_NOPING = 4 // remote clients dont 'ping' to keep objects alive
}
internal enum STREAM_SEEK : uint
{
STREAM_SEEK_SET = 0,
STREAM_SEEK_CUR = 1,
STREAM_SEEK_END = 2
}
//
// HRESULTs
//
internal const int S_OK = 0;
internal const int S_FALSE = 0x00000001;
internal const int E_FAIL = unchecked((int)0x80004005);
internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E);
internal const int E_NOTIMPL = unchecked((int)0x80004001);
internal const int E_NOINTERFACE = unchecked((int)0x80004002);
internal const int E_INVALIDARG = unchecked((int)0x80070057);
internal const int E_BOUNDS = unchecked((int)0x8000000B);
internal const int E_POINTER = unchecked((int)0x80004003);
internal const int E_CHANGED_STATE = unchecked((int)0x8000000C);
internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
internal const int RO_E_CLOSED = unchecked((int)0x80000013);
/// <summary>
/// Error indicates that you are accessing a CCW whose target object has already been garbage
/// collected while the CCW still has non-0 jupiter ref counts
/// </summary>
internal const int COR_E_ACCESSING_CCW = unchecked((int)0x80131544);
#pragma warning disable 649, 169 // Field 'blah' is never assigned to/Field 'blah' is never used
// I use __vtbl to distingush from MCG vtables that are used for CCWs
internal struct __vtbl_IUnknown
{
// IUnknown methods
internal IntPtr pfnQueryInterface;
internal IntPtr pfnAddRef;
internal IntPtr pfnRelease;
}
internal struct __vtbl_ISequentialStream
{
__vtbl_IUnknown parent;
internal IntPtr pfnRead;
internal IntPtr pfnWrite;
}
internal unsafe struct __IStream
{
internal __vtbl_IStream* vtbl;
}
internal struct __vtbl_IStream
{
__vtbl_ISequentialStream parent;
internal IntPtr pfnSeek;
internal IntPtr pfnSetSize;
internal IntPtr pfnCopyTo;
internal IntPtr pfnCommit;
internal IntPtr pfnRevert;
internal IntPtr pfnLockRegion;
internal IntPtr pfnUnlockRegion;
internal IntPtr pfnStat;
internal IntPtr pfnClone;
}
internal unsafe struct __IMarshal
{
internal __vtbl_IMarshal* vtbl;
}
internal struct __vtbl_IMarshal
{
__vtbl_IUnknown parent;
internal IntPtr pfnGetUnmarshalClass;
internal IntPtr pfnGetMarshalSizeMax;
internal IntPtr pfnMarshalInterface;
internal IntPtr pfnUnmarshalInterface;
internal IntPtr pfnReleaseMarshalData;
internal IntPtr pfnDisconnectObject;
}
internal unsafe struct __IContextCallback
{
internal __vtbl_IContextCallback* vtbl;
}
internal struct __vtbl_IContextCallback
{
__vtbl_IUnknown parent;
internal IntPtr pfnContextCallback;
}
internal struct ComCallData
{
internal uint dwDispid;
internal uint dwReserved;
internal IntPtr pUserDefined;
}
#pragma warning restore 649, 169
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using fyiReporting.RdlDesign.Resources;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogAbout.
/// </summary>
public partial class DialogToolOptions
{
bool bDesktop = false;
bool bToolbar = false;
bool bMaps = false;
// Desktop server configuration
private XmlDocument _DesktopDocument;
private XmlNode _DesktopConfig;
private XmlNode _DesktopPort;
private XmlNode _DesktopDirectory;
private XmlNode _DesktopLocal;
private XmlNode _DesktopLanguage;
public DialogToolOptions(RdlDesigner rdl)
{
_RdlDesigner = rdl;
//
// Required for Windows Form Designer support
//
InitializeComponent();
Init();
return;
}
private void Init()
{
this.tbRecentFilesMax.Text = _RdlDesigner.RecentFilesMax.ToString();
this.tbHelpUrl.Text = _RdlDesigner.HelpUrl;
// init the toolbar
// list of items in current toolbar
foreach (string ti in _RdlDesigner.Toolbar)
{
this.lbToolbar.Items.Add(ti);
}
this.cbEditLines.Checked = _RdlDesigner.ShowEditLines;
this.cbOutline.Checked = _RdlDesigner.ShowReportItemOutline;
this.cbTabInterface.Checked = _RdlDesigner.ShowTabbedInterface;
chkPBAutoHide.Checked = _RdlDesigner.PropertiesAutoHide;
this.cbShowReportWaitDialog.Checked = _RdlDesigner.ShowPreviewWaitDialog;
switch (_RdlDesigner.PropertiesLocation)
{
case DockStyle.Top:
this.rbPBTop.Checked = true;
break;
case DockStyle.Bottom:
this.rbPBBottom.Checked = true;
break;
case DockStyle.Right:
this.rbPBRight.Checked = true;
break;
case DockStyle.Left:
default:
this.rbPBLeft.Checked = true;
break;
}
InitLanguages();
InitOperations();
InitDesktop();
InitMaps();
bDesktop = bToolbar = bMaps = false; // start with no changes
}
private void InitLanguages()
{
foreach (var cult in GetAvailableCultures())
{
tbLanguage.Items.Add(cult);
}
tbLanguage.SelectedItem = Thread.CurrentThread.CurrentCulture;
}
private void InitDesktop()
{
string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
try
{
XmlDocument xDoc = _DesktopDocument = new XmlDocument();
xDoc.PreserveWhitespace = true;
xDoc.Load(optFileName);
_DesktopConfig = xDoc.SelectSingleNode("//config");
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in _DesktopConfig.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name.ToLower())
{
case "port":
this.tbPort.Text = xNodeLoop.InnerText;
_DesktopPort = xNodeLoop;
break;
case "localhostonly":
string tf = xNodeLoop.InnerText.ToLower();
this.ckLocal.Checked = !(tf == "false");
_DesktopLocal = xNodeLoop;
break;
case "serverroot":
this.tbDirectory.Text = xNodeLoop.InnerText;
_DesktopDirectory = xNodeLoop;
break;
case "language":
try
{
tbLanguage.SelectedItem = CultureInfo.GetCultureInfo(xNodeLoop.InnerText);
}
catch (CultureNotFoundException)
{
tbLanguage.SelectedItem = CultureInfo.InvariantCulture;
}
_DesktopLanguage = xNodeLoop;
break;
case "cachedirectory":
// wd = xNodeLoop.InnerText;
break;
case "tracelevel":
break;
case "maxreadcache":
break;
case "maxreadcacheentrysize":
break;
case "mimetypes":
break;
default:
break;
}
}
}
catch (Exception ex)
{ // Didn't sucessfully get the startup state: use defaults
MessageBox.Show(string.Format(Strings.DialogToolOptions_Show_ConfigError, ex.Message), Strings.DialogToolOptions_Show_Options);
this.tbPort.Text = "8080";
this.ckLocal.Checked = true;
this.tbDirectory.Text = "Examples";
}
}
private void InitMaps()
{
lbMaps.Items.Clear();
lbMaps.Items.AddRange(RdlDesigner.MapSubtypes);
}
private void InitOperations()
{
// list of operations;
lbOperation.Items.Clear();
List<string> dups = _RdlDesigner.ToolbarAllowDups;
foreach (string ti in _RdlDesigner.ToolbarOperations)
{
// if item is allowed to be duplicated or if
// item has not already been used we add to operation list
if (dups.Contains(ti) || !lbToolbar.Items.Contains(ti))
this.lbOperation.Items.Add(ti);
}
}
private bool Verify()
{
try
{
int i = Convert.ToInt32(this.tbRecentFilesMax.Text);
return (i >= 1 || i <= 50);
}
catch
{
MessageBox.Show(Strings.DialogToolOptions_Show_RecentFilesMax, Strings.DialogToolOptions_Show_Options);
return false;
}
}
private void bOK_Click(object sender, System.EventArgs e)
{
if (DoApply())
{
DialogResult = DialogResult.OK;
this.Close();
}
}
private bool DoApply()
{
lock (this)
{
try
{
if (!Verify())
return false;
HandleRecentFilesMax();
_RdlDesigner.HelpUrl = this.tbHelpUrl.Text;
HandleShows();
HandleProperties();
if (bToolbar)
HandleToolbar();
if (bDesktop)
HandleDesktop();
if (bMaps)
HandleMaps();
bToolbar = bDesktop = false; // no changes now
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Strings.DialogToolOptions_Show_Options);
return false;
}
}
}
private void HandleProperties()
{
DockStyle ds = DockStyle.Right;
if (this.rbPBTop.Checked)
ds = DockStyle.Top;
else if (this.rbPBBottom.Checked)
ds = DockStyle.Bottom;
else if (this.rbPBLeft.Checked)
ds = DockStyle.Left;
_RdlDesigner.PropertiesLocation = ds;
_RdlDesigner.PropertiesAutoHide = chkPBAutoHide.Checked;
}
private void HandleDesktop()
{
if (_DesktopDocument == null)
{
_DesktopDocument = new XmlDocument();
XmlProcessingInstruction xPI;
xPI = _DesktopDocument.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
_DesktopDocument.AppendChild(xPI);
}
if (_DesktopConfig == null)
{
_DesktopConfig = _DesktopDocument.CreateElement("config");
_DesktopDocument.AppendChild(_DesktopConfig);
}
if (_DesktopPort == null)
{
_DesktopPort = _DesktopDocument.CreateElement("port");
_DesktopConfig.AppendChild(_DesktopPort);
}
_DesktopPort.InnerText = this.tbPort.Text;
if (_DesktopDirectory == null)
{
_DesktopDirectory = _DesktopDocument.CreateElement("serverroot");
_DesktopConfig.AppendChild(_DesktopDirectory);
}
_DesktopDirectory.InnerText = this.tbDirectory.Text;
if (_DesktopLanguage== null)
{
_DesktopLanguage = _DesktopDocument.CreateElement("language");
_DesktopConfig.AppendChild(_DesktopLanguage);
}
_DesktopLanguage.InnerText = ((CultureInfo)tbLanguage.SelectedItem).Name;
if (_DesktopLocal == null)
{
_DesktopLocal = _DesktopDocument.CreateElement("localhostonly");
_DesktopConfig.AppendChild(_DesktopLocal);
}
_DesktopLocal.InnerText = this.ckLocal.Checked ? "true" : "false";
string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
_DesktopDocument.Save(optFileName);
this._RdlDesigner.menuToolsCloseProcess(false); // close the server
}
private void HandleMaps()
{
string[] maps = new string[lbMaps.Items.Count];
for (int i = 0; i < lbMaps.Items.Count; i++)
{
maps[i] = lbMaps.Items[i] as string;
}
RdlDesigner.MapSubtypes = maps;
}
private void HandleRecentFilesMax()
{
// Handle the RecentFilesMax
int i = Convert.ToInt32(this.tbRecentFilesMax.Text);
if (i < 1 || i > 50)
throw new Exception(Strings.DialogToolOptions_Error_RecentFilesMax);
if (this._RdlDesigner.RecentFilesMax == i) // if not different we don't need to do anything
return;
this._RdlDesigner.RecentFilesMax = i;
// Make the list match the maximum size
bool bChangeMenu = false;
while (_RdlDesigner.RecentFiles.Count > _RdlDesigner.RecentFilesMax)
{
_RdlDesigner.RecentFiles.RemoveAt(0); // remove the first entry
bChangeMenu = true;
}
if (bChangeMenu)
_RdlDesigner.RecentFilesMenu(); // reset the menu since the list changed
return;
}
private void HandleToolbar()
{
List<string> ar = new List<string>();
foreach (string item in this.lbToolbar.Items)
ar.Add(item);
this._RdlDesigner.Toolbar = ar;
}
private void HandleShows()
{
_RdlDesigner.ShowEditLines = this.cbEditLines.Checked;
_RdlDesigner.ShowReportItemOutline = this.cbOutline.Checked;
_RdlDesigner.ShowTabbedInterface = this.cbTabInterface.Checked;
_RdlDesigner.ShowPreviewWaitDialog = this.cbShowReportWaitDialog.Checked;
foreach (MDIChild mc in _RdlDesigner.MdiChildren)
{
mc.ShowEditLines(this.cbEditLines.Checked);
mc.ShowReportItemOutline = this.cbOutline.Checked;
mc.ShowPreviewWaitDialog(this.cbShowReportWaitDialog.Checked);
}
}
private void bCopyItem_Click(object sender, System.EventArgs e)
{
bToolbar = true;
int i = this.lbOperation.SelectedIndex;
if (i < 0)
return;
string itm = lbOperation.Items[i] as String;
lbToolbar.Items.Add(itm);
// Remove from list if not allowed to be duplicated in toolbar
if (!_RdlDesigner.ToolbarAllowDups.Contains(itm))
lbOperation.Items.RemoveAt(i);
}
private void bRemove_Click(object sender, System.EventArgs e)
{
bToolbar = true;
int i = this.lbToolbar.SelectedIndex;
if (i < 0)
return;
string itm = lbToolbar.Items[i] as String;
if (itm == "Newline" || itm == "Space")
{ }
else
lbOperation.Items.Add(itm);
lbToolbar.Items.RemoveAt(i);
}
private void bUp_Click(object sender, System.EventArgs e)
{
int i = this.lbToolbar.SelectedIndex;
if (i <= 0)
return;
Swap(i - 1, i);
}
private void bDown_Click(object sender, System.EventArgs e)
{
int i = this.lbToolbar.SelectedIndex;
if (i < 0 || i == lbToolbar.Items.Count - 1)
return;
Swap(i, i + 1);
}
/// <summary>
/// Swap items in the toolbar listbox. i1 should always be less than i2
/// </summary>
/// <param name="i1"></param>
/// <param name="i2"></param>
private void Swap(int i1, int i2)
{
bToolbar = true;
bool b1 = (i1 == lbToolbar.SelectedIndex);
string s1 = lbToolbar.Items[i1] as string;
string s2 = lbToolbar.Items[i2] as string;
lbToolbar.SuspendLayout();
lbToolbar.Items.RemoveAt(i2);
lbToolbar.Items.RemoveAt(i1);
lbToolbar.Items.Insert(i1, s2);
lbToolbar.Items.Insert(i2, s1);
lbToolbar.SelectedIndex = b1 ? i2 : i1;
lbToolbar.ResumeLayout(true);
}
private void bReset_Click(object sender, System.EventArgs e)
{
bToolbar = true;
this.lbToolbar.Items.Clear();
List<string> ar = this._RdlDesigner.ToolbarDefault;
foreach (string itm in ar)
this.lbToolbar.Items.Add(itm);
InitOperations();
}
private void bApply_Click(object sender, System.EventArgs e)
{
DoApply();
}
private void Desktop_Changed(object sender, System.EventArgs e)
{
bDesktop = true;
}
private void bBrowse_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
// Set the help text description for the FolderBrowserDialog.
fbd.Description =
"Select the directory that will contain reports.";
// Do not allow the user to create new files via the FolderBrowserDialog.
fbd.ShowNewFolderButton = false;
// fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
fbd.SelectedPath = this.tbDirectory.Text.Length == 0 ?
"Examples" : tbDirectory.Text;
try
{
if (fbd.ShowDialog(this) == DialogResult.Cancel)
return;
tbDirectory.Text = fbd.SelectedPath;
bDesktop = true; // we modified Desktop settings
}
finally
{
fbd.Dispose();
}
return;
}
static internal DesktopConfig DesktopConfiguration
{
get
{
string optFileName = AppDomain.CurrentDomain.BaseDirectory + "config.xml";
DesktopConfig dc = new DesktopConfig();
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(optFileName);
XmlNode xNode;
xNode = xDoc.SelectSingleNode("//config");
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name.ToLower())
{
case "serverroot":
dc.Directory = xNodeLoop.InnerText;
break;
case "port":
dc.Port = xNodeLoop.InnerText;
break;
case "language":
dc.Language = xNodeLoop.InnerText;
break;
}
}
return dc;
}
catch (Exception ex)
{
throw new Exception(string.Format(Strings.DialogToolOptions_Error_UnableConfig, ex.Message));
}
}
}
private void cbTabInterface_CheckedChanged(object sender, EventArgs e)
{
this.bToolbar = true; // tabbed interface is part of the toolbar
}
private void bAddMap_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
ofd.DefaultExt = "rdl";
ofd.Filter = Strings.DialogToolOptions_bAddMap_Click_MapFilesFilter;
ofd.FilterIndex = 1;
ofd.CheckFileExists = true;
ofd.Multiselect = true;
try
{
if (ofd.ShowDialog(this) == DialogResult.OK)
{
foreach (string file in ofd.FileNames)
{
string nm = Path.GetFileNameWithoutExtension(file);
if (!lbMaps.Items.Contains(nm))
{
lbMaps.Items.Add(nm);
bMaps = true;
}
}
}
}
finally
{
ofd.Dispose();
}
}
private void bRemoveMap_Click(object sender, EventArgs e)
{
if (lbMaps.SelectedIndex < 0)
return;
lbMaps.Items.RemoveAt(lbMaps.SelectedIndex);
bMaps = true;
return;
}
private static IEnumerable<CultureInfo> GetAvailableCultures()
{
var list = new List<CultureInfo>();
var startupDir = Application.StartupPath;
var asm = Assembly.GetEntryAssembly();
var neutralCulture = CultureInfo.InvariantCulture;
if (asm != null)
{
var attr = Attribute.GetCustomAttribute(asm, typeof(NeutralResourcesLanguageAttribute)) as NeutralResourcesLanguageAttribute;
if (attr != null)
{
neutralCulture = CultureInfo.GetCultureInfo(attr.CultureName);
}
}
list.Add(neutralCulture);
if (asm != null)
{
var baseName = asm.GetName().Name;
foreach (var dir in Directory.GetDirectories(startupDir))
{
// Check that the directory name is a valid culture
var dirinfo = new DirectoryInfo(dir);
CultureInfo tCulture;
try
{
tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);
}
// Not a valid culture : skip that directory
catch (ArgumentException)
{
continue;
}
// Check that the directory contains satellite assemblies
if (dirinfo.GetFiles(baseName + ".resources.dll").Length > 0)
{
list.Add(tCulture);
}
}
}
return list.AsReadOnly();
}
}
internal class DesktopConfig
{
internal string Directory;
internal string Port;
internal string Language;
}
}
| |
using System;
using GameTimer;
using InputHelper;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ResolutionBuddy;
namespace MenuBuddy
{
/// <summary>
/// This is a abs layout that is in a window with scroll bars
/// </summary>
public class ScrollLayout : AbsoluteLayout, ITransitionable
{
#region Delegates
private delegate void DrawStuffDelegate(IScreen screen, GameClock gameTime);
#endregion //Delegates
#region Fields
private Vector2 _scrollPos = Vector2.Zero;
private RenderTarget2D _renderTarget = null;
private Vector2 _minScroll = Vector2.Zero;
private Vector2 _maxScroll = Vector2.Zero;
private Rectangle _verticalScrollBar = Rectangle.Empty;
private Rectangle _horizScrollBar = Rectangle.Empty;
public const float ScrollBarWidth = 16f;
#endregion //Fields
#region Properties
/// <summary>
/// the current scorll position of this thing
/// </summary>
public Vector2 ScrollPosition
{
get
{
return _scrollPos;
}
set
{
//constrain the scroll to within the total rect
value = ConstrainScroll(value);
if (_scrollPos != value)
{
//set the scroll position
var valuePoint = value.ToPoint();
var delta = _scrollPos.ToPoint() - valuePoint;
_scrollPos = valuePoint.ToVector2();
//update the position of all the items
foreach (var item in Items)
{
item.Position += delta;
}
UpdateScrollBars();
}
}
}
public override Vector2 Size
{
get
{
return base.Size;
}
set
{
//make sure to redo the rendertarget
_renderTarget = null;
base.Size = value;
}
}
/// <summary>
/// This is the total max rect, containing all the widgets.
/// </summary>
public Rectangle TotalRect
{
get
{
Rectangle result = Rect;
//add all the widgets in this dude
foreach (var item in Items)
{
result = Rectangle.Union(result, item.Rect);
}
return result;
}
}
public Vector2 MinScroll
{
get
{
return _minScroll;
}
set
{
_minScroll = value;
}
}
public Vector2 MaxScroll
{
get
{
return _maxScroll;
}
set
{
_maxScroll = value;
}
}
public Rectangle VerticalScrollBar
{
get
{
return _verticalScrollBar;
}
}
public Rectangle HorizontalScrollBar
{
get
{
return _horizScrollBar;
}
}
public bool DrawVerticalScrollBar { get; private set; }
public bool DrawHorizontalScrollBar { get; private set; }
private bool DrawScrollbars
{
get; set;
}
private bool _showScrollBars;
public bool ShowScrollBars
{
get
{
return _showScrollBars;
}
set
{
ShowVerticalScrollBars = value;
ShowHorizontalScrollBars = value;
_showScrollBars = value;
}
}
public bool ShowVerticalScrollBars { get; set; }
public bool ShowHorizontalScrollBars { get; set; }
private bool CurrentlyDragging { get; set; }
public override ITransitionObject TransitionObject { get; set; }
private RenderTargetBinding[] prevRenderTargets;
#endregion //Properties
#region Initialization
public ScrollLayout()
{
TransitionObject = new WipeTransitionObject(StyleSheet.DefaultTransition);
DrawVerticalScrollBar = false;
DrawHorizontalScrollBar = false;
UpdateScrollBars();
DrawScrollbars = false;
ShowScrollBars = true;
CurrentlyDragging = false;
}
public ScrollLayout(ScrollLayout inst) : base(inst)
{
_scrollPos = new Vector2(inst._scrollPos.X, inst._scrollPos.Y);
_renderTarget = inst._renderTarget;
TransitionObject = inst.TransitionObject;
_minScroll = new Vector2(inst._minScroll.X, inst._minScroll.Y);
_maxScroll = new Vector2(inst._maxScroll.X, inst._maxScroll.Y);
_verticalScrollBar = new Rectangle(inst._verticalScrollBar.Location, inst._verticalScrollBar.Size);
_horizScrollBar = new Rectangle(inst._horizScrollBar.Location, inst._horizScrollBar.Size);
DrawVerticalScrollBar = inst.DrawVerticalScrollBar;
DrawHorizontalScrollBar = inst.DrawHorizontalScrollBar;
DrawScrollbars = inst.DrawScrollbars;
TransitionObject = inst.TransitionObject;
ShowScrollBars = inst.ShowScrollBars;
CurrentlyDragging = inst.CurrentlyDragging;
}
public override IScreenItem DeepCopy()
{
return new ScrollLayout(this);
}
#endregion //Initialization
#region Methods
public override void AddItem(IScreenItem item)
{
//Items in a scroll layout don't transition
var widget = item as ITransitionable;
if (null != widget)
{
widget.TransitionObject = new WipeTransitionObject(TransitionWipeType.None);
}
base.AddItem(item);
UpdateMinMaxScroll();
UpdateScrollBars();
}
private void InitializeRenderTarget(IScreen screen)
{
if (null == _renderTarget)
{
_renderTarget = new RenderTarget2D(screen.ScreenManager.GraphicsDevice,
(int)Size.X,
(int)Size.Y,
false,
screen.ScreenManager.GraphicsDevice.PresentationParameters.BackBufferFormat,
screen.ScreenManager.GraphicsDevice.PresentationParameters.DepthStencilFormat,
0,
RenderTargetUsage.PreserveContents);
screen.ScreenManager.GraphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
}
}
public override void Update(IScreen screen, GameClock gameTime)
{
//set the scroll bars to "not drawn" at the beginning of every update... input methods will set it correctly.
DrawScrollbars = false;
base.Update(screen, gameTime);
}
private void DrawStuff(IScreen screen, GameClock gameTime, DrawStuffDelegate del, bool clear)
{
try
{
//grab the old stuff
var curPos = Position;
var curHor = Horizontal;
var curVert = Vertical;
Position = Point.Zero;
Horizontal = HorizontalAlignment.Left;
Vertical = VerticalAlignment.Top;
var screenManager = screen.ScreenManager;
//initialize the render target if necessary
InitializeRenderTarget(screen);
//end the current draw loop
screenManager.SpriteBatchEnd();
//set the rendertarget
prevRenderTargets = screenManager.GraphicsDevice.GetRenderTargets();
screenManager.GraphicsDevice.SetRenderTarget(_renderTarget);
if (clear)
{
screenManager.GraphicsDevice.Clear(Color.Transparent);
}
//start a new draw loop
screenManager.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
//call the provided delegate to draw everything
del(screen, gameTime);
//end the loop
screenManager.SpriteBatchEnd();
//set the position back
Position = curPos;
Vertical = curVert;
Horizontal = curHor;
//set the render target back
screenManager.GraphicsDevice.SetRenderTargets(prevRenderTargets);
Resolution.ResetViewport();
//start a new loop
screenManager.SpriteBatchBegin();
}
catch (Exception ex)
{
throw;
}
}
public override void DrawBackground(IScreen screen, GameClock gameTime)
{
DrawStuff(screen, gameTime, base.DrawBackground, true);
}
public override void Draw(IScreen screen, GameClock gameTime)
{
DrawStuff(screen, gameTime, base.Draw, false);
//render the texture
var rect = CalculateRect();
screen.ScreenManager.SpriteBatch.Draw(_renderTarget,
TransitionObject.Position(screen, rect.Location),
Color.White);
//Draw the scroll bars if the mouse pointer or a touch is inside the layout
if (ShowScrollBars && DrawScrollbars)
{
if (ShowVerticalScrollBars && DrawVerticalScrollBar)
{
screen.ScreenManager.DrawHelper.DrawRect(screen, StyleSheet.HighlightedBackgroundColor, VerticalScrollBar, TransitionObject);
}
if (ShowHorizontalScrollBars && DrawHorizontalScrollBar)
{
screen.ScreenManager.DrawHelper.DrawRect(screen, StyleSheet.HighlightedBackgroundColor, HorizontalScrollBar, TransitionObject);
}
}
}
public void UpdateMinMaxScroll()
{
//get the total rectangle
var total = TotalRect;
//get the layout rectangle
var current = Rect;
//set the min and max to be the diff between the two
var leftDelta = total.Left - current.Left + ScrollPosition.X;
var rightDelta = total.Right - current.Right + ScrollPosition.X;
var topDelta = total.Top - current.Top + ScrollPosition.Y;
var bottomDelta = total.Bottom - current.Bottom + ScrollPosition.Y;
_minScroll = new Vector2(leftDelta, topDelta);
_maxScroll = new Vector2(rightDelta, bottomDelta);
}
private Vector2 ConstrainScroll(Vector2 value)
{
//set the x value
if (value.X < _minScroll.X)
{
value.X = _minScroll.X;
}
else if (value.X > _maxScroll.X)
{
value.X = _maxScroll.X;
}
//set the y value
if (value.Y < _minScroll.Y)
{
value.Y = _minScroll.Y;
}
else if (value.Y > _maxScroll.Y)
{
value.Y = _maxScroll.Y;
}
return value;
}
public void UpdateScrollBars()
{
//get the window size
var windowSize = Size;
//get the total size
var totalRect = TotalRect;
var totalSize = new Vector2(totalRect.Width, totalRect.Height);
//get the size ratio
var ratio = new Vector2()
{
X = (totalSize.X != 0f) ? windowSize.X / totalSize.X : 0f,
Y = (totalSize.Y != 0f) ? windowSize.Y / totalSize.Y : 0f,
};
//Do we even need to draw these things?
DrawHorizontalScrollBar = ((0f < ratio.X) && (ratio.X < 1f));
DrawVerticalScrollBar = ((0f < ratio.Y) && (ratio.Y < 1f));
//get the scroll bar sizes
var scrollbarSize = windowSize * ratio;
//get the scroll delta
var scrollDelta = (MaxScroll - MinScroll);
var deltaRatio = new Vector2()
{
X = (scrollDelta.X != 0f) ? (ScrollPosition.X - MinScroll.X) / scrollDelta.X : 0f,
Y = (scrollDelta.Y != 0f) ? (ScrollPosition.Y - MinScroll.Y) / scrollDelta.Y : 0f,
};
//Get the max number of pixels to add to the scroll bar position
var maxScrollDelta = windowSize - scrollbarSize;
//get the delta to add to the window pos
var delta = maxScrollDelta * deltaRatio;
//set the scrollbar rectangles
var rect = Rect;
_verticalScrollBar = new Rectangle((int)(rect.Right - ScrollBarWidth),
(int)(rect.Top + delta.Y),
(int)(ScrollBarWidth),
(int)(scrollbarSize.Y));
_horizScrollBar = new Rectangle((int)(rect.Left + delta.X),
(int)(rect.Bottom - ScrollBarWidth),
(int)(scrollbarSize.X),
(int)(ScrollBarWidth));
}
public override bool CheckHighlight(HighlightEventArgs highlight)
{
if (Rect.Contains(highlight.Position))
{
DrawScrollbars = true;
base.CheckHighlight(highlight);
}
return DrawScrollbars;
}
public override bool CheckDrag(DragEventArgs drag)
{
var result = false;
if (CurrentlyDragging)
{
result = true;
//Set the position to the current drag position
DragOperation(drag);
}
else
{
//Check if the user has started a drag operation
result = Rect.Contains(drag.Start);
if (result)
{
//check if any of the widgets inside want the drag
if (!base.CheckDrag(drag))
{
if (!CurrentlyDragging)
{
//Set the start rectangle
CurrentlyDragging = true;
}
DragOperation(drag);
}
}
}
return result;
}
private void DragOperation(DragEventArgs drag)
{
//else add the delta to the scroll position
#if ANDROID || __IOS__
ScrollPosition = ScrollPosition - (drag.Delta * 0.5f);
#else
ScrollPosition = ScrollPosition + drag.Delta;
#endif
DrawScrollbars = true;
}
public override bool CheckDrop(DropEventArgs drop)
{
//check if we are currently dragging
if (CurrentlyDragging)
{
//don't respond to anymore drop events
CurrentlyDragging = false;
return true;
}
else
{
//drop.Drop = drop.Drop;
return base.CheckDrop(drop);
}
}
#endregion //Methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata.Ecma335
{
public static class MetadataTokens
{
/// <summary>
/// Maximum number of tables that can be present in Ecma335 metadata.
/// </summary>
public static readonly int TableCount = TableIndexExtensions.Count;
/// <summary>
/// Maximum number of tables that can be present in Ecma335 metadata.
/// </summary>
public static readonly int HeapCount = HeapIndexExtensions.Count;
/// <summary>
/// Returns the row number of a metadata table entry that corresponds
/// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>One based row number.</returns>
/// <exception cref="ArgumentException">The <paramref name="handle"/> is not a valid metadata table handle.</exception>
public static int GetRowNumber(this MetadataReader reader, Handle handle)
{
if (handle.IsHeapHandle)
{
ThrowTableHandleRequired();
}
if (handle.IsVirtual)
{
return MapVirtualHandleRowId(reader, handle);
}
return (int)handle.RowId;
}
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>Zero based offset, or -1 if <paramref name="handle"/> isn't a metadata heap handle.</returns>
/// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception>
/// <exception cref="ArgumentException">The <paramref name="handle"/> is invalid.</exception>
public static int GetHeapOffset(this MetadataReader reader, Handle handle)
{
if (!handle.IsHeapHandle)
{
ThrowHeapHandleRequired();
}
if (handle.IsVirtual)
{
return MapVirtualHandleRowId(reader, handle);
}
return (int)handle.RowId;
}
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>.
/// </summary>
/// <returns>Metadata token.</returns>
/// <exception cref="ArgumentException">
/// Handle represents a metadata entity that doesn't have a token.
/// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>.
/// </exception>
public static int GetToken(this MetadataReader reader, Handle handle)
{
if (!TokenTypeIds.IsEcmaToken(handle.value))
{
ThrowTableHandleOrUserStringRequired();
}
if (handle.IsVirtual)
{
return MapVirtualHandleRowId(reader, handle) | (int)(handle.value & TokenTypeIds.TokenTypeMask);
}
return (int)handle.value;
}
private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle)
{
switch (handle.Kind)
{
case HandleKind.AssemblyReference:
// pretend that virtual rows immediately follow real rows:
return (int)(reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId);
case HandleKind.String:
case HandleKind.Blob:
// We could precalculate offsets for virtual strings and blobs as we are creating them
// if we wanted to implement this.
throw new NotSupportedException(MetadataResources.CantGetOffsetForVirtualHeapHandle);
default:
throw new ArgumentException(MetadataResources.InvalidHandle, "handle");
}
}
/// <summary>
/// Returns the row number of a metadata table entry that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// One based row number, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetRowNumber(MetadataReader, Handle)"/>.
/// </returns>
public static int GetRowNumber(Handle handle)
{
if (handle.IsHeapHandle)
{
ThrowTableHandleRequired();
}
if (handle.IsVirtual)
{
return -1;
}
return (int)handle.RowId;
}
/// <summary>
/// Returns the offset of metadata heap data that corresponds
/// to the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>.
/// </returns>
public static int GetHeapOffset(Handle handle)
{
if (!handle.IsHeapHandle)
{
ThrowHeapHandleRequired();
}
if (handle.IsVirtual)
{
return -1;
}
return (int)handle.RowId;
}
/// <summary>
/// Returns the metadata token of the specified <paramref name="handle"/>.
/// </summary>
/// <returns>
/// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>.
/// See <see cref="GetToken(MetadataReader, Handle)"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// Handle represents a metadata entity that doesn't have a token.
/// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>.
/// </exception>
public static int GetToken(Handle handle)
{
if (!TokenTypeIds.IsEcmaToken(handle.value))
{
ThrowTableHandleOrUserStringRequired();
}
if (handle.IsVirtual)
{
return 0;
}
return (int)handle.value;
}
/// <summary>
/// Gets the <see cref="TableIndex"/> of the table corresponding to the specified <see cref="HandleKind"/>.
/// </summary>
/// <param name="type">Handle type.</param>
/// <param name="index">Table index.</param>
/// <returns>True if the handle type corresponds to an Ecma335 table, false otherwise.</returns>
public static bool TryGetTableIndex(HandleKind type, out TableIndex index)
{
if ((int)type < TableIndexExtensions.Count)
{
index = (TableIndex)type;
return true;
}
index = 0;
return false;
}
/// <summary>
/// Gets the <see cref="HeapIndex"/> of the heap corresponding to the specified <see cref="HandleKind"/>.
/// </summary>
/// <param name="type">Handle type.</param>
/// <param name="index">Heap index.</param>
/// <returns>True if the handle type corresponds to an Ecma335 heap, false otherwise.</returns>
public static bool TryGetHeapIndex(HandleKind type, out HeapIndex index)
{
switch (type)
{
case HandleKind.UserString:
index = HeapIndex.UserString;
return true;
case HandleKind.String:
case HandleKind.NamespaceDefinition:
index = HeapIndex.String;
return true;
case HandleKind.Blob:
index = HeapIndex.Blob;
return true;
case HandleKind.Guid:
index = HeapIndex.Guid;
return true;
default:
index = 0;
return false;
}
}
#region Handle Factories
/// <summary>
/// Creates a handle from a token value.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="token"/> is not a valid metadata token.
/// It must encode a metadata table entity or an offset in <see cref="HandleKind.UserString"/> heap.
/// </exception>
public static Handle Handle(int token)
{
if (!TokenTypeIds.IsEcmaToken(unchecked((uint)token)))
{
ThrowInvalidToken();
}
return new Handle((uint)token);
}
/// <summary>
/// Creates a handle from a token value.
/// </summary>
/// <exception cref="ArgumentException">
/// <paramref name="tableIndex"/> is not a valid table index.</exception>
public static Handle Handle(TableIndex tableIndex, int rowNumber)
{
int token = ((int)tableIndex << TokenTypeIds.RowIdBitCount) | rowNumber;
if (!TokenTypeIds.IsEcmaToken(unchecked((uint)token)))
{
ThrowInvalidTableIndex();
}
return new Handle((uint)token);
}
public static MethodDefinitionHandle MethodDefinitionHandle(int rowNumber)
{
return Metadata.MethodDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static MethodImplementationHandle MethodImplementationHandle(int rowNumber)
{
return Metadata.MethodImplementationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static MethodSpecificationHandle MethodSpecificationHandle(int rowNumber)
{
return Metadata.MethodSpecificationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static TypeDefinitionHandle TypeDefinitionHandle(int rowNumber)
{
return Metadata.TypeDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static ExportedTypeHandle ExpoortedTypeHandle(int rowNumber)
{
return Metadata.ExportedTypeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static TypeReferenceHandle TypeReferenceHandle(int rowNumber)
{
return Metadata.TypeReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static TypeSpecificationHandle TypeSpecificationHandle(int rowNumber)
{
return Metadata.TypeSpecificationHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static MemberReferenceHandle MemberReferenceHandle(int rowNumber)
{
return Metadata.MemberReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static FieldDefinitionHandle FieldDefinitionHandle(int rowNumber)
{
return Metadata.FieldDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static EventDefinitionHandle EventDefinitionHandle(int rowNumber)
{
return Metadata.EventDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static PropertyDefinitionHandle PropertyDefinitionHandle(int rowNumber)
{
return Metadata.PropertyDefinitionHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static StandaloneSignatureHandle StandaloneSignatureHandle(int rowNumber)
{
return Metadata.StandaloneSignatureHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static ParameterHandle ParameterHandle(int rowNumber)
{
return Metadata.ParameterHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static GenericParameterHandle GenericParameterHandle(int rowNumber)
{
return Metadata.GenericParameterHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static GenericParameterConstraintHandle GenericParameterConstraintHandle(int rowNumber)
{
return Metadata.GenericParameterConstraintHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static ModuleReferenceHandle ModuleReferenceHandle(int rowNumber)
{
return Metadata.ModuleReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static AssemblyReferenceHandle AssemblyReferenceHandle(int rowNumber)
{
return Metadata.AssemblyReferenceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static CustomAttributeHandle CustomAttributeHandle(int rowNumber)
{
return Metadata.CustomAttributeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static DeclarativeSecurityAttributeHandle DeclarativeSecurityAttributeHandle(int rowNumber)
{
return Metadata.DeclarativeSecurityAttributeHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static ConstantHandle ConstantHandle(int rowNumber)
{
return Metadata.ConstantHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static ManifestResourceHandle ManifestResourceHandle(int rowNumber)
{
return Metadata.ManifestResourceHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static AssemblyFileHandle AssemblyFileHandle(int rowNumber)
{
return Metadata.AssemblyFileHandle.FromRowId((uint)(rowNumber & TokenTypeIds.RIDMask));
}
public static UserStringHandle UserStringHandle(int offset)
{
return Metadata.UserStringHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask));
}
public static StringHandle StringHandle(int offset)
{
return Metadata.StringHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask));
}
public static BlobHandle BlobHandle(int offset)
{
return Metadata.BlobHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask));
}
public static GuidHandle GuidHandle(int offset)
{
return Metadata.GuidHandle.FromIndex((uint)(offset & TokenTypeIds.RIDMask));
}
#endregion
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowTableHandleRequired()
{
throw new ArgumentException(MetadataResources.NotMetadataTableHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowHeapHandleRequired()
{
throw new ArgumentException(MetadataResources.NotMetadataHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowTableHandleOrUserStringRequired()
{
throw new ArgumentException(MetadataResources.NotMetadataTableOrUserStringHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidToken()
{
throw new ArgumentException(MetadataResources.InvalidToken, "token");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidTableIndex()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
}
}
| |
namespace CWDev.SLNTools.UIKit
{
partial class MergeSolutionsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.Panel mainpanel;
System.Windows.Forms.GroupBox groupBoxDifferencesFoundInSourceBranch;
System.Windows.Forms.GroupBox groupBoxDifferencesFoundInDestinationBranch;
System.Windows.Forms.GroupBox groupboxConflicts;
System.Windows.Forms.GroupBox groupboxAcceptedDifferences;
this.m_splitContainerDifferencesFoundAndWorkArea = new System.Windows.Forms.SplitContainer();
this.m_splitContainerDifferencesFound = new System.Windows.Forms.SplitContainer();
this.m_differencesInSourceBranchControl = new CWDev.SLNTools.UIKit.DifferencesControl();
this.m_differencesInDestinationBranchControl = new CWDev.SLNTools.UIKit.DifferencesControl();
this.m_splitContainerConflictAndResult = new System.Windows.Forms.SplitContainer();
this.m_conflictsControl = new CWDev.SLNTools.UIKit.ConflictsControl();
this.m_buttonResolveAll = new System.Windows.Forms.Button();
this.m_acceptedDifferencesControl = new CWDev.SLNTools.UIKit.DifferencesControl();
this.m_buttonSave = new System.Windows.Forms.Button();
this.m_buttonCancel = new System.Windows.Forms.Button();
mainpanel = new System.Windows.Forms.Panel();
groupBoxDifferencesFoundInSourceBranch = new System.Windows.Forms.GroupBox();
groupBoxDifferencesFoundInDestinationBranch = new System.Windows.Forms.GroupBox();
groupboxConflicts = new System.Windows.Forms.GroupBox();
groupboxAcceptedDifferences = new System.Windows.Forms.GroupBox();
mainpanel.SuspendLayout();
this.m_splitContainerDifferencesFoundAndWorkArea.Panel1.SuspendLayout();
this.m_splitContainerDifferencesFoundAndWorkArea.Panel2.SuspendLayout();
this.m_splitContainerDifferencesFoundAndWorkArea.SuspendLayout();
this.m_splitContainerDifferencesFound.Panel1.SuspendLayout();
this.m_splitContainerDifferencesFound.Panel2.SuspendLayout();
this.m_splitContainerDifferencesFound.SuspendLayout();
groupBoxDifferencesFoundInSourceBranch.SuspendLayout();
groupBoxDifferencesFoundInDestinationBranch.SuspendLayout();
this.m_splitContainerConflictAndResult.Panel1.SuspendLayout();
this.m_splitContainerConflictAndResult.Panel2.SuspendLayout();
this.m_splitContainerConflictAndResult.SuspendLayout();
groupboxConflicts.SuspendLayout();
groupboxAcceptedDifferences.SuspendLayout();
this.SuspendLayout();
//
// mainpanel
//
mainpanel.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)));
mainpanel.Controls.Add(this.m_splitContainerDifferencesFoundAndWorkArea);
mainpanel.Location = new System.Drawing.Point(12, 12);
mainpanel.Name = "mainpanel";
mainpanel.Size = new System.Drawing.Size(806, 584);
mainpanel.TabIndex = 0;
//
// m_splitContainerDifferencesFoundAndWorkArea
//
this.m_splitContainerDifferencesFoundAndWorkArea.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_splitContainerDifferencesFoundAndWorkArea.Location = new System.Drawing.Point(0, 0);
this.m_splitContainerDifferencesFoundAndWorkArea.Name = "m_splitContainerDifferencesFoundAndWorkArea";
this.m_splitContainerDifferencesFoundAndWorkArea.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// m_splitContainerDifferencesFoundAndWorkArea.Panel1
//
this.m_splitContainerDifferencesFoundAndWorkArea.Panel1.Controls.Add(this.m_splitContainerDifferencesFound);
//
// m_splitContainerDifferencesFoundAndWorkArea.Panel2
//
this.m_splitContainerDifferencesFoundAndWorkArea.Panel2.Controls.Add(this.m_splitContainerConflictAndResult);
this.m_splitContainerDifferencesFoundAndWorkArea.Size = new System.Drawing.Size(806, 584);
this.m_splitContainerDifferencesFoundAndWorkArea.SplitterDistance = 157;
this.m_splitContainerDifferencesFoundAndWorkArea.TabIndex = 1;
//
// m_splitContainerDifferencesFound
//
this.m_splitContainerDifferencesFound.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_splitContainerDifferencesFound.Location = new System.Drawing.Point(0, 0);
this.m_splitContainerDifferencesFound.Name = "m_splitContainerDifferencesFound";
//
// m_splitContainerDifferencesFound.Panel1
//
this.m_splitContainerDifferencesFound.Panel1.Controls.Add(groupBoxDifferencesFoundInSourceBranch);
//
// m_splitContainerDifferencesFound.Panel2
//
this.m_splitContainerDifferencesFound.Panel2.Controls.Add(groupBoxDifferencesFoundInDestinationBranch);
this.m_splitContainerDifferencesFound.Size = new System.Drawing.Size(806, 157);
this.m_splitContainerDifferencesFound.SplitterDistance = 403;
this.m_splitContainerDifferencesFound.TabIndex = 0;
//
// groupBoxDifferencesFoundInSourceBranch
//
groupBoxDifferencesFoundInSourceBranch.Controls.Add(this.m_differencesInSourceBranchControl);
groupBoxDifferencesFoundInSourceBranch.Dock = System.Windows.Forms.DockStyle.Fill;
groupBoxDifferencesFoundInSourceBranch.Location = new System.Drawing.Point(0, 0);
groupBoxDifferencesFoundInSourceBranch.Name = "groupBoxDifferencesFoundInSourceBranch";
groupBoxDifferencesFoundInSourceBranch.Size = new System.Drawing.Size(403, 157);
groupBoxDifferencesFoundInSourceBranch.TabIndex = 0;
groupBoxDifferencesFoundInSourceBranch.TabStop = false;
groupBoxDifferencesFoundInSourceBranch.Text = "Differences found in the source branch";
//
// m_differencesInSourceBranchControl
//
this.m_differencesInSourceBranchControl.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.m_differencesInSourceBranchControl.Location = new System.Drawing.Point(6, 19);
this.m_differencesInSourceBranchControl.Name = "m_differencesInSourceBranchControl";
this.m_differencesInSourceBranchControl.Size = new System.Drawing.Size(391, 132);
this.m_differencesInSourceBranchControl.TabIndex = 0;
//
// groupBoxDifferencesFoundInDestinationBranch
//
groupBoxDifferencesFoundInDestinationBranch.Controls.Add(this.m_differencesInDestinationBranchControl);
groupBoxDifferencesFoundInDestinationBranch.Dock = System.Windows.Forms.DockStyle.Fill;
groupBoxDifferencesFoundInDestinationBranch.Location = new System.Drawing.Point(0, 0);
groupBoxDifferencesFoundInDestinationBranch.Name = "groupBoxDifferencesFoundInDestinationBranch";
groupBoxDifferencesFoundInDestinationBranch.Size = new System.Drawing.Size(399, 157);
groupBoxDifferencesFoundInDestinationBranch.TabIndex = 0;
groupBoxDifferencesFoundInDestinationBranch.TabStop = false;
groupBoxDifferencesFoundInDestinationBranch.Text = "Differences found in the destination branch";
//
// m_differencesInDestinationBranchControl
//
this.m_differencesInDestinationBranchControl.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.m_differencesInDestinationBranchControl.Location = new System.Drawing.Point(6, 19);
this.m_differencesInDestinationBranchControl.Name = "m_differencesInDestinationBranchControl";
this.m_differencesInDestinationBranchControl.Size = new System.Drawing.Size(387, 132);
this.m_differencesInDestinationBranchControl.TabIndex = 0;
//
// m_splitContainerConflictAndResult
//
this.m_splitContainerConflictAndResult.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_splitContainerConflictAndResult.Location = new System.Drawing.Point(0, 0);
this.m_splitContainerConflictAndResult.Name = "m_splitContainerConflictAndResult";
this.m_splitContainerConflictAndResult.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// m_splitContainerConflictAndResult.Panel1
//
this.m_splitContainerConflictAndResult.Panel1.Controls.Add(groupboxConflicts);
//
// m_splitContainerConflictAndResult.Panel2
//
this.m_splitContainerConflictAndResult.Panel2.Controls.Add(groupboxAcceptedDifferences);
this.m_splitContainerConflictAndResult.Size = new System.Drawing.Size(806, 423);
this.m_splitContainerConflictAndResult.SplitterDistance = 237;
this.m_splitContainerConflictAndResult.TabIndex = 0;
//
// groupboxConflicts
//
groupboxConflicts.Controls.Add(this.m_conflictsControl);
groupboxConflicts.Controls.Add(this.m_buttonResolveAll);
groupboxConflicts.Dock = System.Windows.Forms.DockStyle.Fill;
groupboxConflicts.Location = new System.Drawing.Point(0, 0);
groupboxConflicts.Name = "groupboxConflicts";
groupboxConflicts.Size = new System.Drawing.Size(806, 237);
groupboxConflicts.TabIndex = 0;
groupboxConflicts.TabStop = false;
groupboxConflicts.Text = "Conficts";
//
// m_conflictsControl
//
this.m_conflictsControl.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.m_conflictsControl.Location = new System.Drawing.Point(6, 19);
this.m_conflictsControl.Name = "m_conflictsControl";
this.m_conflictsControl.Size = new System.Drawing.Size(794, 183);
this.m_conflictsControl.TabIndex = 0;
//
// m_buttonResolveAll
//
this.m_buttonResolveAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_buttonResolveAll.Location = new System.Drawing.Point(708, 208);
this.m_buttonResolveAll.Name = "m_buttonResolveAll";
this.m_buttonResolveAll.Size = new System.Drawing.Size(92, 23);
this.m_buttonResolveAll.TabIndex = 1;
this.m_buttonResolveAll.Text = "&Resolve all...";
this.m_buttonResolveAll.UseVisualStyleBackColor = true;
this.m_buttonResolveAll.Click += new System.EventHandler(this.m_buttonResolveAll_Click);
//
// groupboxAcceptedDifferences
//
groupboxAcceptedDifferences.Controls.Add(this.m_acceptedDifferencesControl);
groupboxAcceptedDifferences.Controls.Add(this.m_buttonSave);
groupboxAcceptedDifferences.Controls.Add(this.m_buttonCancel);
groupboxAcceptedDifferences.Dock = System.Windows.Forms.DockStyle.Fill;
groupboxAcceptedDifferences.Location = new System.Drawing.Point(0, 0);
groupboxAcceptedDifferences.Name = "groupboxAcceptedDifferences";
groupboxAcceptedDifferences.Size = new System.Drawing.Size(806, 182);
groupboxAcceptedDifferences.TabIndex = 0;
groupboxAcceptedDifferences.TabStop = false;
groupboxAcceptedDifferences.Text = "Accepted differences";
//
// m_acceptedDifferencesControl
//
this.m_acceptedDifferencesControl.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.m_acceptedDifferencesControl.Location = new System.Drawing.Point(6, 19);
this.m_acceptedDifferencesControl.Name = "m_acceptedDifferencesControl";
this.m_acceptedDifferencesControl.Size = new System.Drawing.Size(794, 127);
this.m_acceptedDifferencesControl.TabIndex = 0;
//
// m_buttonSave
//
this.m_buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_buttonSave.DialogResult = System.Windows.Forms.DialogResult.OK;
this.m_buttonSave.Location = new System.Drawing.Point(644, 152);
this.m_buttonSave.Name = "m_buttonSave";
this.m_buttonSave.Size = new System.Drawing.Size(75, 23);
this.m_buttonSave.TabIndex = 1;
this.m_buttonSave.Text = "&Save";
this.m_buttonSave.UseVisualStyleBackColor = true;
//
// m_buttonCancel
//
this.m_buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.m_buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_buttonCancel.Location = new System.Drawing.Point(725, 152);
this.m_buttonCancel.Name = "m_buttonCancel";
this.m_buttonCancel.Size = new System.Drawing.Size(75, 23);
this.m_buttonCancel.TabIndex = 2;
this.m_buttonCancel.Text = "&Cancel";
this.m_buttonCancel.UseVisualStyleBackColor = true;
//
// MergeSolutionsForm
//
this.AcceptButton = this.m_buttonSave;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.m_buttonCancel;
this.ClientSize = new System.Drawing.Size(830, 608);
this.Controls.Add(mainpanel);
this.MaximumSize = new System.Drawing.Size(10000, 10000);
this.MinimumSize = new System.Drawing.Size(700, 500);
this.Name = "MergeSolutionsForm";
this.Text = "Solution Merger";
this.Load += new System.EventHandler(this.MergeSolutionsForm_Load);
mainpanel.ResumeLayout(false);
this.m_splitContainerDifferencesFoundAndWorkArea.Panel1.ResumeLayout(false);
this.m_splitContainerDifferencesFoundAndWorkArea.Panel2.ResumeLayout(false);
this.m_splitContainerDifferencesFoundAndWorkArea.ResumeLayout(false);
this.m_splitContainerDifferencesFound.Panel1.ResumeLayout(false);
this.m_splitContainerDifferencesFound.Panel2.ResumeLayout(false);
this.m_splitContainerDifferencesFound.ResumeLayout(false);
groupBoxDifferencesFoundInSourceBranch.ResumeLayout(false);
groupBoxDifferencesFoundInDestinationBranch.ResumeLayout(false);
this.m_splitContainerConflictAndResult.Panel1.ResumeLayout(false);
this.m_splitContainerConflictAndResult.Panel2.ResumeLayout(false);
this.m_splitContainerConflictAndResult.ResumeLayout(false);
groupboxConflicts.ResumeLayout(false);
groupboxAcceptedDifferences.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button m_buttonSave;
private System.Windows.Forms.Button m_buttonCancel;
private DifferencesControl m_differencesInSourceBranchControl;
private DifferencesControl m_differencesInDestinationBranchControl;
private DifferencesControl m_acceptedDifferencesControl;
private System.Windows.Forms.Button m_buttonResolveAll;
private ConflictsControl m_conflictsControl;
private System.Windows.Forms.SplitContainer m_splitContainerConflictAndResult;
private System.Windows.Forms.SplitContainer m_splitContainerDifferencesFound;
private System.Windows.Forms.SplitContainer m_splitContainerDifferencesFoundAndWorkArea;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.CodeTools
{
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell.Interop;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.IO;
// Action without arguments
internal delegate void Procedure();
// Common static helper functions
static internal class Common
{
#region Private fields
static private IServiceProvider serviceProvider;
static private IVsSolution solution;
static private ISynchronizeInvoke syncInvoke;
#endregion
#region Construction
static public void Initialize(IServiceProvider provider)
{
serviceProvider = provider;
solution = GetService(typeof(SVsSolution)) as IVsSolution;
// we must be called from the main UI thread
syncInvoke = null;
Form marshalingForm = new Form();
if (marshalingForm != null)
{
marshalingForm.Visible = false;
IntPtr handle = marshalingForm.Handle; // forces creation
syncInvoke = marshalingForm;
}
else
{
Log("Unable to create a synchronization context for safe thread calls.");
}
}
static public void Release()
{
solution = null;
serviceProvider = null;
}
#endregion
#region Utilities
[Conditional("TRACE")]
static public void Trace(string message)
{
System.Diagnostics.Debugger.Log(1, "Trace", "TaskManager: " + message + "\n");
}
static public void Log(string message)
{
System.Diagnostics.Debugger.Log(1, "Error", "TaskManager: " + message + "\n");
}
static public object GetService(Type serviceType)
{
if (serviceProvider != null)
return serviceProvider.GetService(serviceType);
else
return null;
}
static private string VsRoot = null;
static public String GetLocalRegistryRoot()
{
// Get the visual studio root key
if (VsRoot == null)
{
ILocalRegistry2 localReg = GetService(typeof(SLocalRegistry)) as ILocalRegistry2;
if (localReg != null)
{
localReg.GetLocalRegistryRoot(out VsRoot);
}
if (VsRoot == null)
{
VsRoot = @"Software\Microsoft\VisualStudio\10.0"; // Guess on failure
}
}
return VsRoot;
}
static public String GetCodeToolsRegistryRoot()
{
return (GetLocalRegistryRoot() + "\\CodeTools");
}
static public void ShowHelp(string helpKeyword)
{
if (helpKeyword != null && helpKeyword.Length > 0)
{
IVsHelpSystem help = GetService(typeof(SVsHelpService)) as IVsHelpSystem;
if (help != null)
{
help.KeywordSearch(helpKeyword, 0, 0);
help.ActivateHelpSystem(0);
}
}
}
static public void ThreadSafeInvoke(Procedure action)
{
if (syncInvoke != null && syncInvoke.InvokeRequired)
{
// Common.Trace("Use ISynchronized.Invoke");
syncInvoke.Invoke(action, null);
}
else
{
action();
}
}
static public void ThreadSafeASync(Procedure action)
{
if (syncInvoke != null && syncInvoke.InvokeRequired)
{
// Common.Trace("Use ISynchronized.Invoke");
syncInvoke.BeginInvoke(action, null);
}
else
{
action();
}
}
#endregion
#region Projects
static public Guid GetProjectType(IVsHierarchy hierarchy)
{
Guid projectType = Guid.Empty;
if (hierarchy != null)
{
hierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_TypeGuid, out projectType);
}
return projectType;
}
static public string GetProjectName(IVsHierarchy hierarchy)
{
object name = null;
if (hierarchy != null)
{
hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Name, out name);
}
if (name != null)
{
return name as String;
}
else
{
return null;
}
}
static public IVsHierarchy GetProjectByName(string projectName)
{
if (projectName != null && projectName.Length > 0 && solution != null)
{
foreach (IVsHierarchy project in GetProjects())
{
if (String.Compare(projectName, GetProjectName(project), StringComparison.OrdinalIgnoreCase) == 0)
{
return project;
}
}
}
return null;
}
static public IEnumerable<IVsHierarchy> GetProjects()
{
if (solution != null)
{
IEnumHierarchies hiers;
Guid emptyGuid = Guid.Empty;
int hr = solution.GetProjectEnum((uint)__VSENUMPROJFLAGS.EPF_ALLPROJECTS, ref emptyGuid, out hiers);
if (hr == 0 && hiers != null)
{
uint fetched;
do
{
IVsHierarchy[] hier = { null };
hr = hiers.Next(1, hier, out fetched);
if (hr == 0 && fetched == 1)
{
yield return (hier[0]);
}
}
while (fetched == 1);
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2013 Calvin Rien
*
* Based on the JSON parser by Patrick van Bergen
* http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
*
* Simplified it so that it doesn't throw exceptions
* and can be used in Unity iPhone with maximum code stripping.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace MiniJSON {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WORD_BREAK = "{}[],:\"";
public static bool IsWordBreak(char c) {
return Char.IsWhiteSpace(c) || WORD_BREAK.IndexOf(c) != -1;
}
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new char[4];
for (int i=0; i< 4; i++) {
hex[i] = NextChar;
}
s.Append((char) Convert.ToInt32(new string(hex), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (Char.IsWhiteSpace(PeekChar)) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
int c = json.Peek();
try {
return Convert.ToChar(c);
}
catch (Exception e)
{
Debug.Log("Error peeking char: " + c);
}
throw new Exception("Derr");
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (!IsWordBreak(PeekChar)) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
switch (PeekChar) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
switch (NextWord) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
} else if ((asStr = value as string) != null) {
SerializeString(asStr);
} else if (value is bool) {
builder.Append((bool) value ? "true" : "false");
} else if ((asList = value as IList) != null) {
SerializeArray(asList);
} else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
} else if (value is char) {
SerializeString(new string((char) value, 1));
} else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u");
builder.Append(codepoint.ToString("x4"));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R"));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R"));
} else {
SerializeString(value.ToString());
}
}
}
}
}
| |
/*
Copyright 2018 Esri
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.Threading.Tasks;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Framework.Threading.Tasks;
namespace SDKExamples
{
/// <summary>
/// Illustrates how to create a Feature in a FeatureClass.
/// </summary>
///
/// <remarks>
/// <para>
/// While it is true classes that are derived from the <see cref="ArcGIS.Core.CoreObjectsBase"/> super class
/// consumes native resources (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>),
/// you can rest assured that the garbage collector will properly dispose of the unmanaged resources during
/// finalization. However, there are certain workflows that require a <b>deterministic</b> finalization of the
/// <see cref="ArcGIS.Core.Data.Geodatabase"/>. Consider the case of a file geodatabase that needs to be deleted
/// on the fly at a particular moment. Because of the <b>indeterministic</b> nature of garbage collection, we can't
/// count on the garbage collector to dispose of the Geodatabase object, thereby removing the <b>lock(s)</b> at the
/// moment we want. To ensure a deterministic finalization of important native resources such as a
/// <see cref="ArcGIS.Core.Data.Geodatabase"/> or <see cref="ArcGIS.Core.Data.FeatureClass"/>, you should declare
/// and instantiate said objects in a <b>using</b> statement. Alternatively, you can achieve the same result by
/// putting the object inside a try block and then calling Dispose() in a finally block.
/// </para>
/// <para>
/// In general, you should always call Dispose() on the following types of objects:
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Datastore"/> (e.g., <see cref="ArcGIS.Core.Data.Geodatabase"/>).
/// </para>
/// <para>
/// - Those that are derived from <see cref="ArcGIS.Core.Data.Dataset"/> (e.g., <see cref="ArcGIS.Core.Data.Table"/>).
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.RowCursor"/> and <see cref="ArcGIS.Core.Data.RowBuffer"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Row"/> and <see cref="ArcGIS.Core.Data.Feature"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.Selection"/>.
/// </para>
/// <para>
/// - <see cref="ArcGIS.Core.Data.VersionManager"/> and <see cref="ArcGIS.Core.Data.Version"/>.
/// </para>
/// </remarks>
public class FeatureClassCreateRow
{
/// <summary>
/// In order to illustrate that Geodatabase calls have to be made on the MCT
/// </summary>
/// <returns></returns>
public async Task MainMethodCode()
{
await QueuedTask.Run(async () =>
{
await EnterpriseGeodabaseWorkFlow();
await FileGeodatabaseWorkFlow();
});
}
private static async Task EnterpriseGeodabaseWorkFlow()
{
// Opening a Non-Versioned SQL Server instance.
DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
{
AuthenticationMode = AuthenticationMode.DBMS,
// Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
Instance = @"testMachine\testInstance",
// Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
Database = "LocalGovernment",
// Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
User = "gdb",
Password = "password",
Version = "dbo.DEFAULT"
};
using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.FacilitySite"))
{
EditOperation editOperation = new EditOperation();
editOperation.Callback(context =>
{
RowBuffer rowBuffer = null;
Feature feature = null;
try
{
FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();
int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID");
rowBuffer = enterpriseFeatureClass.CreateRowBuffer();
// Either the field index or the field name can be used in the indexer.
rowBuffer[facilityIdIndex] = "FAC-400";
rowBuffer["NAME"] = "Griffith Park";
rowBuffer["OWNTYPE"] = "Municipal";
rowBuffer["FCODE"] = "Park";
// Add it to Public Attractions Subtype.
rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820;
List<Coordinate2D> newCoordinates = new List<Coordinate2D>
{
new Coordinate2D(1021570, 1880583),
new Coordinate2D(1028730, 1880994),
new Coordinate2D(1029718, 1875644),
new Coordinate2D(1021405, 1875397)
};
rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(newCoordinates).ToGeometry();
feature = enterpriseFeatureClass.CreateRow(rowBuffer);
//To Indicate that the Map has to draw this feature and/or the attribute table to be updated
context.Invalidate(feature);
long objectID = feature.GetObjectID();
Polygon polygon = feature.GetShape() as Polygon;
// Do some other processing with the newly-created feature.
}
catch (GeodatabaseException exObj)
{
Console.WriteLine(exObj);
}
finally
{
if (rowBuffer != null)
rowBuffer.Dispose();
if (feature != null)
feature.Dispose();
}
}, enterpriseFeatureClass);
bool editResult = editOperation.Execute();
// If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted.
bool saveResult = await Project.Current.SaveEditsAsync();
}
}
// Illustrates creating a feature in a File GDB.
private static async Task FileGeodatabaseWorkFlow()
{
using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
using (FeatureClass featureClass = fileGeodatabase.OpenDataset<FeatureClass>("PollingPlace"))
{
RowBuffer rowBuffer = null;
Feature feature = null;
try
{
EditOperation editOperation = new EditOperation();
editOperation.Callback(context =>
{
FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();
int nameIndex = featureClassDefinition.FindField("NAME");
rowBuffer = featureClass.CreateRowBuffer();
// Either the field index or the field name can be used in the indexer.
rowBuffer[nameIndex] = "New School";
rowBuffer["POLLINGID"] = "260";
rowBuffer["FULLADD"] = "100 New Street";
rowBuffer["CITY"] = "Naperville";
rowBuffer["STATE"] = "IL";
rowBuffer["OPERHOURS"] = "Yes";
rowBuffer["HANDICAP"] = "6.00am=7.00pm";
rowBuffer["NEXTELECT"] = "11/6/2012";
rowBuffer["REGDATE"] = "8/6/2012";
rowBuffer["PHONE"] = "815-740-4782";
rowBuffer["EMAIL"] = "elections@willcounty.gov";
rowBuffer[featureClassDefinition.GetShapeField()] = new MapPointBuilder(1028367, 1809789).ToGeometry();
feature = featureClass.CreateRow(rowBuffer);
//To Indicate that the Map has to draw this feature and/or the attribute table to be updated
context.Invalidate(feature);
// Do some other processing with the newly-created feature.
}, featureClass);
bool editResult = editOperation.Execute();
// At this point the changes are visible in the process, but not persisted/visible outside.
long objectID = feature.GetObjectID();
MapPoint mapPoint = feature.GetShape() as MapPoint;
// If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted.
bool saveResult = await Project.Current.SaveEditsAsync();
}
catch (GeodatabaseException exObj)
{
Console.WriteLine(exObj);
throw;
}
finally
{
if (rowBuffer != null)
rowBuffer.Dispose();
if (feature != null)
feature.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using FluentNHibernate.Testing.Values;
using FluentNHibernate.Utils;
using FluentNHibernate.Utils.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
namespace FluentNHibernate.Testing.Testing.Values
{
public abstract class With_list_entity : Specification
{
private Accessor property;
protected ListEntity target;
protected List<ListEntity, string> sut;
protected string[] listItems;
public override void establish_context()
{
property = ReflectionHelper.GetAccessor (GetPropertyExpression ());
target = new ListEntity();
listItems = new[] {"foo", "bar", "baz"};
sut = new List<ListEntity, string>(property, listItems);
}
protected abstract Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression();
}
public abstract class When_a_list_property_with_is_set_successfully : With_list_entity
{
public override void because()
{
sut.SetValue(target);
}
[Test]
public abstract void should_set_the_list_items();
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_a_list_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.GetterAndSetter;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.GetterAndSetter.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_a_list_property_with_a_private_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.GetterAndPrivateSetter;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.GetterAndPrivateSetter.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_a_list_property_is_set_with_a_custom_setter : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void establish_context()
{
base.establish_context();
sut.ValueSetter = (entity, propertyInfo, value) =>
{
foreach (var listItem in value)
{
entity.AddListItem(listItem);
}
};
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.BackingField.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_a_set_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.Set;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.Set.Contains(listItem).ShouldBeTrue();
}
}
}
[TestFixture]
public class When_a_typed_set_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.TypedSet;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.TypedSet.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_a_collection_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.Collection;
}
[Test]
public override void should_set_the_list_items()
{
string[] array = new string[target.Collection.Count];
target.Collection.CopyTo(array, 0);
foreach (var listItem in listItems)
{
array.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_an_array_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.Array;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.Array.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_an_list_property_with_a_public_setter_is_set : When_a_list_property_with_is_set_successfully
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.List;
}
[Test]
public override void should_set_the_list_items()
{
foreach (var listItem in listItems)
{
target.List.ShouldContain(listItem);
}
}
}
[TestFixture]
public class When_a_list_property_with_a_backing_field_is_set : With_list_entity
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void because()
{
sut.SetValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_which_property_failed_to_be_set()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Error while trying to set property BackingField");
}
}
[TestFixture]
public class When_a_list_property_is_set_with_a_custom_setter_that_fails : With_list_entity
{
protected override Expression<Func<ListEntity, IEnumerable>> GetPropertyExpression()
{
return x => x.BackingField;
}
public override void establish_context()
{
base.establish_context();
sut.ValueSetter = (entity, propertyInfo, value) => { throw new Exception(); };
}
public override void because()
{
sut.SetValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_which_property_failed_to_be_set()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Error while trying to set property BackingField");
}
}
public abstract class With_initialized_list : Specification
{
protected Accessor property;
protected ListEntity target;
protected List<ListEntity, string> sut;
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable<string>>>)(x => x.GetterAndSetter));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
}
}
[TestFixture]
public class When_the_checked_list_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = new[] {"foo", "bar", "baz"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_checked_list_has_transposed_items_of_the_expected_list : With_initialized_list
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = new[] {"baz", "bar", "foo"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_that_the_list_element_count_does_not_match()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Expected 'foo' but got 'baz' at position 0");
}
}
[TestFixture]
public class When_the_checked_list_does_not_have_the_same_number_of_elements_as_the_expected_list : With_initialized_list
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = new[] {"foo"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ApplicationException>();
}
[Test]
public void should_tell_that_the_list_element_count_does_not_match()
{
var exception = (ApplicationException)thrown_exception;
exception.Message.ShouldEqual("Actual count (1) does not equal expected count (3)");
}
}
[TestFixture]
public class When_the_checked_list_is_null : With_initialized_list
{
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = null;
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ArgumentNullException>();
}
[Test]
public void should_tell_that_actual_list_is_null()
{
var exception = (ArgumentNullException)thrown_exception;
exception.Message.ShouldStartWith("Actual and expected are not equal (actual was null).");
}
}
[TestFixture]
public class When_the_expected_list_is_null : With_initialized_list
{
public override void establish_context()
{
base.establish_context();
sut = new List<ListEntity, string>(property, null);
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail()
{
thrown_exception.ShouldBeOfType<ArgumentNullException>();
}
[Test]
public void should_tell_that_actual_list_is_null()
{
var exception = (ArgumentNullException)thrown_exception;
exception.Message.ShouldStartWith("Actual and expected are not equal (expected was null).");
}
}
public class When_the_checked_list_is_equal_to_the_expected_list_with_a_custom_equality_comparer : When_the_checked_list_is_equal_to_the_expected_list
{
public override void establish_context()
{
base.establish_context();
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer
.Stub(x => x.Equals(null, null))
.IgnoreArguments()
.Return(true);
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_perform_the_check_with_the_custom_equality_comparer()
{
sut.EntityEqualityComparer.AssertWasCalled(x => x.Equals(null, null),
o => o.IgnoreArguments().Repeat.Times(3));
}
}
public class When_the_checked_list_has_transposed_items_of_the_expected_list_with_a_custom_equality_comparer : When_the_checked_list_has_transposed_items_of_the_expected_list
{
public override void establish_context()
{
base.establish_context();
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer
.Stub(x => x.Equals(null, null))
.IgnoreArguments()
.Return(false);
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_perform_the_check_with_the_custom_equality_comparer()
{
sut.EntityEqualityComparer.AssertWasCalled(x => x.Equals(null, null),
o => o.IgnoreArguments().Repeat.Once());
}
}
[TestFixture]
public class When_a_list_is_checked_with_a_custom_equality_comparer_that_fails : With_initialized_list
{
private InvalidOperationException exception;
public override void establish_context()
{
base.establish_context();
target.GetterAndSetter = new[] {"foo", "bar", "baz"};
exception = new InvalidOperationException();
sut.EntityEqualityComparer = MockRepository.GenerateStub<IEqualityComparer>();
sut.EntityEqualityComparer
.Stub(x => x.Equals(null, null))
.IgnoreArguments()
.Throw(exception);
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_fail_with_the_exception_from_the_equality_comparer()
{
thrown_exception.ShouldBeTheSameAs(exception);
}
}
[TestFixture]
public class When_the_checked_typed_set_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable<string>>>)(x => x.TypedSet));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
target.TypedSet.AddAll(new[] {"foo", "bar", "baz"});
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_checked_set_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable>>)(x => x.Set));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
target.Set.AddAll(new[] {"foo", "bar", "baz"});
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_collection_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable>>)(x => x.Collection));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
target.Collection = new List<string> {"foo", "bar", "baz"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_typed_list_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable>>)(x => x.List));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
target.List = new List<string> {"foo", "bar", "baz"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
[TestFixture]
public class When_the_checked_array_is_equal_to_the_expected_list : With_initialized_list
{
public override void establish_context()
{
property = ReflectionHelper.GetAccessor((Expression<Func<ListEntity, IEnumerable<string>>>)(x => x.Array));
target = new ListEntity();
sut = new List<ListEntity, string>(property, new[] {"foo", "bar", "baz"});
target.Array = new[] {"foo", "bar", "baz"};
}
public override void because()
{
sut.CheckValue(target);
}
[Test]
public void should_succeed()
{
thrown_exception.ShouldBeNull();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
//
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Common\Shared
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Common\Shared\ValidationHelpers.cs
*********************************************************************/
namespace System.Workflow.Activities.Common
{
#region Imports
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel;
#endregion
internal static class ValidationHelpers
{
#region Validation & helpers for ID and Type
internal static void ValidateIdentifier(IServiceProvider serviceProvider, string identifier)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(serviceProvider);
CodeDomProvider provider = CompilerHelpers.GetCodeDomProvider(language);
if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
!provider.IsValidIdentifier(identifier))
{
throw new Exception(SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier));
}
}
internal static ValidationError ValidateIdentifier(string propName, IServiceProvider context, string identifier)
{
if (context == null)
throw new ArgumentNullException("context");
ValidationError error = null;
if (identifier == null || identifier.Length == 0)
error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
else
{
try
{
ValidationHelpers.ValidateIdentifier(context, identifier);
}
catch (Exception e)
{
error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, e.Message), ErrorNumbers.Error_InvalidIdentifier);
}
}
if (error != null)
error.PropertyName = propName;
return error;
}
internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
{
if (context == null)
throw new ArgumentNullException("context");
ValidationError error = null;
if (identifier == null || identifier.Length == 0)
error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
else
{
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(context);
CodeDomProvider provider = CompilerHelpers.GetCodeDomProvider(language);
if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
!provider.IsValidIdentifier(provider.CreateEscapedIdentifier(identifier)))
{
error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier)), ErrorNumbers.Error_InvalidIdentifier);
}
}
if (error != null)
error.PropertyName = propName;
return error;
}
internal static ValidationErrorCollection ValidateUniqueIdentifiers(Activity rootActivity)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
Hashtable identifiers = new Hashtable();
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
Queue activities = new Queue();
activities.Enqueue(rootActivity);
while (activities.Count > 0)
{
Activity activity = (Activity)activities.Dequeue();
if (activity.Enabled)
{
if (identifiers.ContainsKey(activity.QualifiedName))
{
ValidationError duplicateError = new ValidationError(SR.GetString(SR.Error_DuplicatedActivityID, activity.QualifiedName), ErrorNumbers.Error_DuplicatedActivityID);
duplicateError.PropertyName = "Name";
duplicateError.UserData[typeof(Activity)] = activity;
validationErrors.Add(duplicateError);
}
else
identifiers.Add(activity.QualifiedName, activity);
if (activity is CompositeActivity && ((activity.Parent == null) || !Helpers.IsCustomActivity(activity as CompositeActivity)))
{
foreach (Activity child in Helpers.GetAllEnabledActivities((CompositeActivity)activity))
activities.Enqueue(child);
}
}
}
return validationErrors;
}
#endregion
#region Validation for Activity Ref order
internal static bool IsActivitySourceInOrder(Activity request, Activity response)
{
if (request.Parent == null)
return true;
List<Activity> responsePath = new List<Activity>();
responsePath.Add(response);
Activity responseParent = response is CompositeActivity ? (CompositeActivity)response : response.Parent;
while (responseParent != null)
{
responsePath.Add(responseParent);
responseParent = responseParent.Parent;
}
Activity requestChild = request;
CompositeActivity requestParent = request is CompositeActivity ? (CompositeActivity)request : request.Parent;
while (requestParent != null && !responsePath.Contains(requestParent))
{
requestChild = requestParent;
requestParent = requestParent.Parent;
}
if (requestParent == requestChild)
return true;
bool incorrectOrder = false;
int index = (responsePath.IndexOf(requestParent) - 1);
index = (index < 0) ? 0 : index; //sometimes parent gets added to the collection twice which causes index to be -1
Activity responseChild = responsePath[index];
if (requestParent == null || Helpers.IsAlternateFlowActivity(requestChild) || Helpers.IsAlternateFlowActivity(responseChild))
incorrectOrder = true;
else
{
for (int i = 0; i < requestParent.EnabledActivities.Count; i++)
{
if (requestParent.EnabledActivities[i] == requestChild)
break;
else if (requestParent.EnabledActivities[i] == responseChild)
{
incorrectOrder = true;
break;
}
}
}
return !incorrectOrder;
}
#endregion
internal static ValidationErrorCollection ValidateObject(ValidationManager manager, object obj)
{
ValidationErrorCollection errors = new ValidationErrorCollection();
if (obj == null)
return errors;
Type objType = obj.GetType();
if (!objType.IsPrimitive && (objType != typeof(string)))
{
bool removeValidatedObjectCollection = false;
Dictionary<int, object> validatedObjects = manager.Context[typeof(Dictionary<int, object>)] as Dictionary<int, object>;
if (validatedObjects == null)
{
validatedObjects = new Dictionary<int, object>();
manager.Context.Push(validatedObjects);
removeValidatedObjectCollection = true;
}
try
{
if (!validatedObjects.ContainsKey(obj.GetHashCode()))
{
validatedObjects.Add(obj.GetHashCode(), obj);
try
{
Validator[] validators = manager.GetValidators(objType);
foreach (Validator validator in validators)
errors.AddRange(validator.Validate(manager, obj));
}
finally
{
validatedObjects.Remove(obj.GetHashCode());
}
}
}
finally
{
if (removeValidatedObjectCollection)
manager.Context.Pop();
}
}
return errors;
}
internal static ValidationErrorCollection ValidateActivity(ValidationManager manager, Activity activity)
{
ValidationErrorCollection errors = ValidationHelpers.ValidateObject(manager, activity);
foreach (ValidationError error in errors)
{
if (!error.UserData.Contains(typeof(Activity)))
error.UserData[typeof(Activity)] = activity;
}
return errors;
}
internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext)
{
return ValidateProperty(manager, activity, obj, propertyValidationContext, null);
}
internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext, object extendedPropertyContext)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (obj == null)
throw new ArgumentNullException("obj");
if (propertyValidationContext == null)
throw new ArgumentNullException("propertyValidationContext");
ValidationErrorCollection errors = new ValidationErrorCollection();
manager.Context.Push(activity);
manager.Context.Push(propertyValidationContext);
if (extendedPropertyContext != null)
manager.Context.Push(extendedPropertyContext);
try
{
errors.AddRange(ValidationHelpers.ValidateObject(manager, obj));
}
finally
{
manager.Context.Pop();
manager.Context.Pop();
if (extendedPropertyContext != null)
manager.Context.Pop();
}
return errors;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using ExcelDna.Integration;
using ExcelFormulaParser;
namespace AsyncDNA
{
/// <summary>
/// Calculates all precedents for specified reference.
/// </summary>
public class Precedents
{
private readonly ExcelReference src_;
public Precedents(ExcelReference src)
{
src_ = src;
}
public IEnumerable<ExcelReference> GetRefs()
{
return GetPrecedents(src_).Select(_ => _.Reference).Distinct();
}
public IEnumerable<ReferenceFunc> GetFormulas()
{
return
GetPrecedents(src_)
.Where(_ => !src_.Equals(_.ParentReference))
.Select(_ => new
{
Token = _.ParentFormula
.FirstOrDefault(
f =>
f.Type == ExcelFormulaTokenType.Function &&
f.Subtype == ExcelFormulaTokenSubtype.Start),
Ref = _.ParentReference
})
.Where(_ => _.Token != null)
.Select(_ => new ReferenceFunc(_.Ref, _.Token.Value))
.Distinct();
}
private static readonly Regex rangeRegex_ =
new Regex(
@"^(?:(?<Sheet>[^!]+)!)?(?:\$?(?<Col1>[a-z]+)\$?(?<Row1>\d+))(?:\:\$?(?<Col2>[a-z]+)\$?(?<Row2>\d+))?$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly IDictionary<ExcelReference, List<ExcelPrecedent>> cache_ =
new Dictionary<ExcelReference, List<ExcelPrecedent>>();
// TODO Handle INDIRECT, etc.
// TODO Static cache (string-ExcelFormula).
// TODO Fix for R1C1 mode.
// TODO Fix external references.
private IEnumerable<ExcelPrecedent> GetPrecedents(ExcelReference reference)
{
List<ExcelPrecedent> items;
if (cache_.TryGetValue(reference, out items))
{
foreach (var item in items)
{
yield return item;
foreach (var p in GetPrecedents(item.Reference))
yield return p;
}
}
else
{
bool isFormula = (bool) XlCall.Excel(XlCall.xlfGetCell, 48, reference);
if (isFormula)
{
string formula = (string) XlCall.Excel(XlCall.xlfGetCell, 6, reference);
ExcelFormula excelFormula = new ExcelFormula(formula);
foreach (var token in excelFormula)
{
if (token.Type == ExcelFormulaTokenType.Operand &&
token.Subtype == ExcelFormulaTokenSubtype.Range)
{
//if (isRCmode)
//{
// var regex = new Regex(
// @"^=(?:(?<Sheet>[^!]+)!)?(?:R((?<RAbs>\d+)|(?<RRel>\[-?\d+\]))C((?<CAbs>\d+)|(?<CRel>\[-?\d+\]))){1,2}$",
// RegexOptions.Compiled | RegexOptions.IgnoreCase);
// if (regex.IsMatch(formula))
// {
// throw new NotSupportedException();
// }
//}
var range = token.Value;
Match rangeMatch = rangeRegex_.Match(range);
var col1 = ExcelAColumnToInt(rangeMatch.Groups["Col1"].Value) - 1;
var row1 = Int32.Parse(rangeMatch.Groups["Row1"].Value) - 1;
Group sheetGroup = rangeMatch.Groups["Sheet"];
var sheetName = sheetGroup.Success ? sheetGroup.Value : null;
int col2 = col1;
int row2 = row1;
if (rangeMatch.Groups["Col2"].Success)
{
col2 = ExcelAColumnToInt(rangeMatch.Groups["Col2"].Value) - 1;
row2 = Int32.Parse(rangeMatch.Groups["Row2"].Value) - 1;
}
for (int col = col1; col <= col2; col++)
{
for (int row = row1; row <= row2; row++)
{
ExcelReference precedantRef;
if (sheetName == null)
{
precedantRef = new ExcelReference(row, row, col, col, reference.SheetId);
}
else
{
precedantRef = new ExcelReference(row, row, col, col, sheetName);
}
ExcelPrecedent newPrecedent = new ExcelPrecedent(
precedantRef, excelFormula, formula, reference);
AddToCache(reference, newPrecedent);
yield return newPrecedent;
foreach (var nestedPrecedant in GetPrecedents(precedantRef))
yield return nestedPrecedant;
}
}
}
}
}
}
}
private void AddToCache(ExcelReference reference, ExcelPrecedent newPrecedent)
{
List<ExcelPrecedent> cachedItems;
if (!cache_.TryGetValue(reference, out cachedItems))
{
cachedItems = new List<ExcelPrecedent>();
cache_[reference] = cachedItems;
}
cachedItems.Add(newPrecedent);
}
private static int ExcelAColumnToInt(string strCol)
{
var strColUpperCase = strCol.ToUpper(CultureInfo.InvariantCulture);
int result = 0;
int pBase = 1;
for (int i = strColUpperCase.Length - 1; i >= 0; i--)
{
int digit = strColUpperCase[i] - 'A' + 1;
result += pBase * digit;
pBase = pBase * 26;
}
return result;
}
//private static string GetExcelAColumnName(int columnNumber)
//{
// int dividend = columnNumber;
// string columnName = String.Empty;
// int modulo;
// while (dividend > 0)
// {
// modulo = (dividend - 1) % ('Z' - 'A');
// columnName = Convert.ToChar('A' + modulo) + columnName;
// dividend = (int)((dividend - modulo) / 26);
// }
// return columnName;
//}
private class ExcelPrecedent
{
private readonly ExcelReference reference_;
private readonly ExcelReference parentReference_;
private readonly ExcelFormula parentFormula_;
private readonly string parentFormulaSrc_;
public ExcelPrecedent(ExcelReference reference, ExcelFormula parentFormula, string parentFormulaSrc, ExcelReference parentReference)
{
reference_ = reference;
parentFormula_ = parentFormula;
parentFormulaSrc_ = parentFormulaSrc;
parentReference_ = parentReference;
}
public ExcelReference Reference
{
get { return reference_; }
}
public ExcelFormula ParentFormula
{
get { return parentFormula_; }
}
public string ParentFormulaSrc
{
get { return parentFormulaSrc_; }
}
public ExcelReference ParentReference
{
get { return parentReference_; }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Internal.TypeSystem
{
/// <summary>
/// Represents an array type - either a multidimensional array, or a vector
/// (a one-dimensional array with a zero lower bound).
/// </summary>
public sealed partial class ArrayType : ParameterizedType
{
private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays
internal ArrayType(TypeDesc elementType, int rank)
: base(elementType)
{
_rank = rank;
}
public override int GetHashCode()
{
// ComputeArrayTypeHashCode expects -1 for an SzArray
return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank);
}
public override DefType BaseType
{
get
{
return this.Context.GetWellKnownType(WellKnownType.Array);
}
}
/// <summary>
/// Gets the type of the element of this array.
/// </summary>
public TypeDesc ElementType
{
get
{
return this.ParameterType;
}
}
internal MethodDesc[] _methods;
/// <summary>
/// Gets a value indicating whether this type is a vector.
/// </summary>
public new bool IsSzArray
{
get
{
return _rank < 0;
}
}
/// <summary>
/// Gets a value indicating whether this type is an mdarray.
/// </summary>
public new bool IsMdArray
{
get
{
return _rank > 0;
}
}
/// <summary>
/// Gets the rank of this array. Note this returns "1" for both vectors, and
/// for general arrays of rank 1. Use <see cref="IsSzArray"/> to disambiguate.
/// </summary>
public int Rank
{
get
{
return (_rank < 0) ? 1 : _rank;
}
}
private void InitializeMethods()
{
int numCtors;
if (IsSzArray)
{
numCtors = 1;
// Jagged arrays have constructor for each possible depth
var t = this.ElementType;
while (t.IsSzArray)
{
t = ((ArrayType)t).ElementType;
numCtors++;
}
}
else
{
// Multidimensional arrays have two ctors, one with and one without lower bounds
numCtors = 2;
}
MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors];
for (int i = 0; i < methods.Length; i++)
methods[i] = new ArrayMethod(this, (ArrayMethodKind)i);
Interlocked.CompareExchange(ref _methods, methods, null);
}
public override IEnumerable<MethodDesc> GetMethods()
{
if (_methods == null)
InitializeMethods();
return _methods;
}
public MethodDesc GetArrayMethod(ArrayMethodKind kind)
{
if (_methods == null)
InitializeMethods();
return _methods[(int)kind];
}
public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc elementType = this.ElementType;
TypeDesc instantiatedElementType = elementType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (instantiatedElementType != elementType)
return Context.GetArrayType(instantiatedElementType, _rank);
return this;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array;
flags |= TypeFlags.HasGenericVarianceComputed;
flags |= TypeFlags.HasFinalizerComputed;
return flags;
}
public override string ToString()
{
return this.ElementType.ToString() + "[" + new String(',', Rank - 1) + "]";
}
}
public enum ArrayMethodKind
{
Get,
Set,
Address,
AddressWithHiddenArg,
Ctor
}
/// <summary>
/// Represents one of the methods on array types. While array types are not typical
/// classes backed by metadata, they do have methods that can be referenced from the IL
/// and the type system needs to provide a way to represent them.
/// </summary>
/// <remarks>
/// There are two array Address methods (<see cref="ArrayMethodKind.Address"/> and
/// <see cref="ArrayMethodKind.AddressWithHiddenArg"/>). One is used when referencing Address
/// method from IL, the other is used when *compiling* the method body.
/// The reason we need to do this is that the Address method is required to do a type check using a type
/// that is only known at the callsite. The trick we use is that we tell codegen that the
/// <see cref="ArrayMethodKind.Address"/> method requires a hidden instantiation parameter (even though it doesn't).
/// The instantiation parameter is where we capture the type at the callsite.
/// When we compile the method body, we compile it as <see cref="ArrayMethodKind.AddressWithHiddenArg"/> that
/// has the hidden argument explicitly listed in it's signature and is available as a regular parameter.
/// </remarks>
public sealed partial class ArrayMethod : MethodDesc
{
private ArrayType _owningType;
private ArrayMethodKind _kind;
internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind)
{
_owningType = owningType;
_kind = kind;
}
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _owningType;
}
}
public ArrayType OwningArray
{
get
{
return _owningType;
}
}
public ArrayMethodKind Kind
{
get
{
return _kind;
}
}
private MethodSignature _signature;
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
switch (_kind)
{
case ArrayMethodKind.Get:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType, parameters);
break;
}
case ArrayMethodKind.Set:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
parameters[_owningType.Rank] = _owningType.ElementType;
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters);
break;
}
case ArrayMethodKind.Address:
{
var parameters = new TypeDesc[_owningType.Rank];
for (int i = 0; i < _owningType.Rank; i++)
parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
case ArrayMethodKind.AddressWithHiddenArg:
{
var parameters = new TypeDesc[_owningType.Rank + 1];
parameters[0] = Context.SystemModule.GetType("System", "EETypePtr");
for (int i = 0; i < _owningType.Rank; i++)
parameters[i + 1] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters);
}
break;
default:
{
int numArgs;
if (_owningType.IsSzArray)
{
numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor;
}
else
{
numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank;
}
var argTypes = new TypeDesc[numArgs];
for (int i = 0; i < argTypes.Length; i++)
argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes);
}
break;
}
}
return _signature;
}
}
public override string Name
{
get
{
switch (_kind)
{
case ArrayMethodKind.Get:
return "Get";
case ArrayMethodKind.Set:
return "Set";
case ArrayMethodKind.Address:
case ArrayMethodKind.AddressWithHiddenArg:
return "Address";
default:
return ".ctor";
}
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation)
{
TypeDesc owningType = this.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind);
else
return this;
}
public override string ToString()
{
return _owningType.ToString() + "." + Name;
}
}
}
| |
// 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.
/*============================================================
**
** Interface: IAppDomain
**
**
**
**
** Purpose: Properties and methods exposed to COM
**
**
===========================================================*/
namespace System {
using System.Reflection;
using System.Runtime.CompilerServices;
using SecurityManager = System.Security.SecurityManager;
using System.Security.Permissions;
using IEvidenceFactory = System.Security.IEvidenceFactory;
#if FEATURE_IMPERSONATION
using System.Security.Principal;
#endif
using System.Security.Policy;
using System.Security;
using System.Security.Util;
using System.Collections;
using System.Text;
using System.Configuration.Assemblies;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Reflection.Emit;
using CultureInfo = System.Globalization.CultureInfo;
using System.IO;
using System.Runtime.Versioning;
[GuidAttribute("05F696DC-2B29-3663-AD8B-C4389CF2A713")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface _AppDomain
{
#if !FEATURE_CORECLR
void GetTypeInfoCount(out uint pcTInfo);
void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo);
void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId);
void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr);
String ToString();
bool Equals (Object other);
int GetHashCode ();
Type GetType ();
#if FEATURE_REMOTING
[System.Security.SecurityCritical] // auto-generated_required
Object InitializeLifetimeService ();
[System.Security.SecurityCritical] // auto-generated_required
Object GetLifetimeService ();
#endif // FEATURE_REMOTING
#if FEATURE_CAS_POLICY
Evidence Evidence { get; }
#endif // FEATURE_CAS_POLICY
event EventHandler DomainUnload;
[method:System.Security.SecurityCritical]
event AssemblyLoadEventHandler AssemblyLoad;
event EventHandler ProcessExit;
[method:System.Security.SecurityCritical]
event ResolveEventHandler TypeResolve;
[method:System.Security.SecurityCritical]
event ResolveEventHandler ResourceResolve;
[method:System.Security.SecurityCritical]
event ResolveEventHandler AssemblyResolve;
[method:System.Security.SecurityCritical]
event UnhandledExceptionEventHandler UnhandledException;
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
String dir);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
Evidence evidence);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPermissions);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
String dir,
Evidence evidence);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
String dir,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPermissions);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
Evidence evidence,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPermissions);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
String dir,
Evidence evidence,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPermissions);
AssemblyBuilder DefineDynamicAssembly(AssemblyName name,
AssemblyBuilderAccess access,
String dir,
Evidence evidence,
PermissionSet requiredPermissions,
PermissionSet optionalPermissions,
PermissionSet refusedPermissions,
bool isSynchronized);
ObjectHandle CreateInstance(String assemblyName,
String typeName);
ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName);
ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes);
ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
Object[] activationAttributes);
ObjectHandle CreateInstance(String assemblyName,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes);
ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes);
Assembly Load(AssemblyName assemblyRef);
Assembly Load(String assemblyString);
Assembly Load(byte[] rawAssembly);
Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore);
Assembly Load(byte[] rawAssembly,
byte[] rawSymbolStore,
Evidence securityEvidence);
Assembly Load(AssemblyName assemblyRef,
Evidence assemblySecurity);
Assembly Load(String assemblyString,
Evidence assemblySecurity);
int ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity);
int ExecuteAssembly(String assemblyFile);
int ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity,
String[] args);
String FriendlyName
{ get; }
#if FEATURE_FUSION
String BaseDirectory
{
get;
}
String RelativeSearchPath
{ get; }
bool ShadowCopyFiles
{ get; }
#endif
Assembly[] GetAssemblies();
#if FEATURE_FUSION
[System.Security.SecurityCritical] // auto-generated_required
void AppendPrivatePath(String path);
[System.Security.SecurityCritical] // auto-generated_required
void ClearPrivatePath();
[System.Security.SecurityCritical] // auto-generated_required
void SetShadowCopyPath (String s);
[System.Security.SecurityCritical] // auto-generated_required
void ClearShadowCopyPath ( );
[System.Security.SecurityCritical] // auto-generated_required
void SetCachePath (String s);
#endif //FEATURE_FUSION
[System.Security.SecurityCritical] // auto-generated_required
void SetData(String name, Object data);
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
Object GetData(string name);
#if FEATURE_CAS_POLICY
[System.Security.SecurityCritical] // auto-generated_required
void SetAppDomainPolicy(PolicyLevel domainPolicy);
#if FEATURE_IMPERSONATION
void SetThreadPrincipal(IPrincipal principal);
#endif // FEATURE_IMPERSONATION
void SetPrincipalPolicy(PrincipalPolicy policy);
#endif
#if FEATURE_REMOTING
void DoCallBack(CrossAppDomainDelegate theDelegate);
#endif
String DynamicDirectory
{ get; }
#endif
}
}
| |
namespace IdSharp.Inspection
{
using System;
using System.Runtime.InteropServices;
internal sealed class DescriptiveLameTagReader
{
public DescriptiveLameTagReader(string path)
{
this.m_Mpeg = new MpegAudio(path);
this.m_BasicReader = new BasicLameTagReader(path);
this.DeterminePresetRelatedValues();
}
private string DeterminePreset(out IdSharp.Inspection.UsePresetGuess usePresetGuess)
{
string text1;
usePresetGuess = IdSharp.Inspection.UsePresetGuess.NotNeeded;
int num1 = this.m_BasicReader.Preset;
if ((num1 >= 8) && (num1 <= 320))
{
text1 = num1.ToString();
if (this.m_BasicReader.EncodingMethod == 1)
{
text1 = "cbr " + text1;
}
usePresetGuess = IdSharp.Inspection.UsePresetGuess.UseGuess;
}
else
{
switch (num1)
{
case 0x3e8:
text1 = "r3mix";
goto Label_0208;
case 0x3e9:
text1 = "--alt-preset standard";
goto Label_0208;
case 0x3ea:
text1 = "--alt-preset extreme";
goto Label_0208;
case 0x3eb:
text1 = "--alt-preset insane";
goto Label_0208;
case 0x3ec:
text1 = "--alt-preset fast standard";
goto Label_0208;
case 0x3ed:
text1 = "--alt-preset fast extreme";
goto Label_0208;
case 0x3ee:
text1 = "preset medium";
goto Label_0208;
case 0x3ef:
text1 = "preset fast medium";
goto Label_0208;
case 0x3f2:
text1 = "preset portable";
goto Label_0208;
case 0x3f7:
text1 = "preset radio";
goto Label_0208;
case 500:
text1 = "V0: preset extreme";
goto Label_0208;
case 490:
text1 = "V1";
goto Label_0208;
case 460:
text1 = "V4: preset medium";
goto Label_0208;
case 470:
text1 = "V3";
goto Label_0208;
case 480:
text1 = "V2: preset standard";
goto Label_0208;
case 430:
text1 = "V7";
goto Label_0208;
case 440:
text1 = "V6";
goto Label_0208;
case 450:
text1 = "V5";
goto Label_0208;
case 0:
text1 = "<not stored>";
usePresetGuess = IdSharp.Inspection.UsePresetGuess.UseGuess;
goto Label_0208;
case 410:
text1 = "V9";
goto Label_0208;
case 420:
text1 = "V8";
goto Label_0208;
}
text1 = string.Format("<unrecognised value {0}>", num1);
usePresetGuess = IdSharp.Inspection.UsePresetGuess.UseGuess;
}
Label_0208:
if ((this.m_BasicReader.EncodingMethod != 4) || ((((num1 != 410) && (num1 != 420)) && ((num1 != 430) && (num1 != 440))) && ((((num1 != 450) && (num1 != 460)) && ((num1 != 470) && (num1 != 480))) && ((num1 != 490) && (num1 != 500)))))
{
return text1;
}
return (text1 + " (fast mode)");
}
private string DeterminePresetGuess(ref IdSharp.Inspection.UsePresetGuess usePresetGuess)
{
switch (this.m_BasicReader.PresetGuess)
{
case LamePreset.Insane:
return "--alt-preset insane";
case LamePreset.Extreme:
return "--alt-preset extreme";
case LamePreset.FastExtreme:
return "--alt-preset fast extreme";
case LamePreset.Standard:
return "--alt-preset standard";
case LamePreset.FastStandard:
return "--alt-preset fast standard";
case LamePreset.Medium:
return "preset medium";
case LamePreset.FastMedium:
return "preset fast medium";
case LamePreset.R3mix:
return "r3mix";
case LamePreset.Studio:
return "preset studio";
case LamePreset.CD:
return "preset cd";
case LamePreset.Hifi:
return "preset hifi";
case LamePreset.Tape:
return "preset tape";
case LamePreset.Radio:
return "preset radio";
case LamePreset.FM:
return "preset fm";
case LamePreset.TapeRadioFM:
return "preset tape OR preset radio OR preset fm";
case LamePreset.Voice:
return "preset voice";
case LamePreset.MWUS:
return "preset mw-us";
case LamePreset.MWEU:
return "preset phon+ OR preset lw OR preset mw-eu OR preset sw";
case LamePreset.Phone:
return "preset phone";
}
string text1 = "";
if (this.m_BasicReader.Preset == 0)
{
usePresetGuess = IdSharp.Inspection.UsePresetGuess.UnableToGuess;
return text1;
}
usePresetGuess = IdSharp.Inspection.UsePresetGuess.NotNeeded;
return text1;
}
private void DeterminePresetRelatedValues()
{
this.m_Preset = this.DeterminePreset(out this.m_UsePresetGuess);
if (this.m_UsePresetGuess == IdSharp.Inspection.UsePresetGuess.NotNeeded)
{
this.m_PresetGuess = "";
}
else
{
this.m_PresetGuess = this.DeterminePresetGuess(ref this.m_UsePresetGuess);
if (this.m_BasicReader.IsPresetGuessNonBitrate)
{
this.m_PresetGuess = this.m_PresetGuess + string.Format(" -b {0}", this.m_BasicReader.Bitrate);
}
}
}
public bool IsLameTagFound
{
get
{
return this.m_BasicReader.IsLameTagFound;
}
}
public bool IsPresetGuessNonBitrate
{
get
{
return this.m_BasicReader.IsPresetGuessNonBitrate;
}
}
public string LameTagInfoEncoder
{
get
{
if (!this.IsLameTagFound)
{
return this.m_Mpeg.Encoder;
}
string text1 = "LAME";
if (string.Compare(this.VersionString, "3.90") < 0)
{
if (!string.IsNullOrEmpty(this.VersionStringNonLameTag) && (this.VersionStringNonLameTag[1] == '.'))
{
text1 = text1 + " " + this.VersionStringNonLameTag;
}
return text1;
}
if (!string.IsNullOrEmpty(this.VersionString))
{
text1 = text1 + " " + this.VersionString;
}
return text1;
}
}
public string LameTagInfoPreset
{
get
{
string text1 = "";
if (!this.IsLameTagFound || (string.Compare(this.VersionString, "3.90") < 0))
{
return text1;
}
text1 = this.Preset;
if (this.UsePresetGuess != IdSharp.Inspection.UsePresetGuess.UseGuess)
{
return text1;
}
if (this.IsPresetGuessNonBitrate)
{
return (this.PresetGuess + " (modified)");
}
return (this.PresetGuess + " (guessed)");
}
}
public string LameTagInfoVersion
{
get
{
return (this.m_Mpeg.Version + " " + this.m_Mpeg.Layer);
}
}
public string Preset
{
get
{
return this.m_Preset;
}
}
public string PresetGuess
{
get
{
return this.m_PresetGuess;
}
}
public IdSharp.Inspection.UsePresetGuess UsePresetGuess
{
get
{
return this.m_UsePresetGuess;
}
}
public string VersionString
{
get
{
return this.m_BasicReader.VersionString;
}
}
public string VersionStringNonLameTag
{
get
{
return this.m_BasicReader.VersionStringNonLameTag;
}
}
private BasicLameTagReader m_BasicReader;
private MpegAudio m_Mpeg;
private string m_Preset;
private string m_PresetGuess;
private IdSharp.Inspection.UsePresetGuess m_UsePresetGuess;
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using BTDB.IL;
using BTDB.ODBLayer;
namespace BTDB.IOC.CRegs
{
class SingletonImpl : ICReg, ICRegILGen, ICRegFuncOptimized
{
readonly Type _implementationType;
readonly ICRegILGen _wrapping;
readonly int _singletonIndex;
IBuildContext? _buildCtx;
public SingletonImpl(Type implementationType, ICRegILGen wrapping, int singletonIndex)
{
_implementationType = implementationType;
_wrapping = wrapping;
_singletonIndex = singletonIndex;
}
public object? BuildFuncOfT(ContainerImpl container, Type funcType)
{
var obj = container.Singletons[_singletonIndex];
return obj == null ? null : ClosureOfObjBuilder.Build(funcType, obj);
}
string ICRegILGen.GenFuncName(IGenerationContext context)
{
return "Singleton_" + _implementationType.ToSimpleName();
}
public void GenInitialization(IGenerationContext context)
{
var backupCtx = context.BuildContext;
context.BuildContext = _buildCtx!;
_wrapping.GenInitialization(context);
context.GetSpecific<SingletonsLocal>().Prepare();
context.BuildContext = backupCtx;
}
internal class BuildCRegLocals
{
Dictionary<ICReg, IILLocal> _map = new Dictionary<ICReg, IILLocal>(ReferenceEqualityComparer<ICReg>.Instance);
readonly Stack<Dictionary<ICReg, IILLocal>> _stack = new Stack<Dictionary<ICReg, IILLocal>>();
internal void Push()
{
_stack.Push(_map);
_map = new Dictionary<ICReg, IILLocal>(_map, ReferenceEqualityComparer<ICReg>.Instance);
}
internal void Pop()
{
_map = _stack.Pop();
}
internal IILLocal? Get(ICReg key)
{
return _map.TryGetValue(key, out var result) ? result : null;
}
public void Add(ICReg key, IILLocal local)
{
_map.Add(key, local);
}
}
class SingletonsLocal : IGenerationContextSetter
{
IGenerationContext? _context;
public void Set(IGenerationContext context)
{
_context = context;
}
internal void Prepare()
{
if (MainLocal != null) return;
MainLocal = _context!.IL.DeclareLocal(typeof(object[]), "singletons");
_context.PushToILStack(Need.ContainerNeed);
_context.IL
.Castclass(typeof(ContainerImpl))
.Ldfld(() => default(ContainerImpl).Singletons)
.Stloc(MainLocal);
}
internal IILLocal? MainLocal { get; private set; }
}
public bool IsCorruptingILStack(IGenerationContext context)
{
var buildCRegLocals = context.GetSpecific<BuildCRegLocals>();
var localSingleton = buildCRegLocals.Get(this);
if (localSingleton != null) return false;
var obj = context.Container.Singletons[_singletonIndex];
if (obj != null) return false;
return true;
}
public IILLocal GenMain(IGenerationContext context)
{
var backupCtx = context.BuildContext;
context.BuildContext = _buildCtx!;
var il = context.IL;
var buildCRegLocals = context.GetSpecific<BuildCRegLocals>();
var localSingleton = buildCRegLocals.Get(this);
if (localSingleton != null)
{
return localSingleton;
}
var localSingletons = context.GetSpecific<SingletonsLocal>().MainLocal;
var safeImplementationType = _implementationType.IsPublic ? _implementationType : typeof (object);
localSingleton = il.DeclareLocal(safeImplementationType, "singleton");
var obj = context.Container.Singletons[_singletonIndex];
if (obj != null)
{
il
.Ldloc(localSingletons!)
.LdcI4(_singletonIndex)
.LdelemRef()
.Castclass(_implementationType)
.Stloc(localSingleton);
return localSingleton;
}
var localLockTaken = il.DeclareLocal(typeof(bool), "lockTaken");
var localLock = il.DeclareLocal(typeof(object), "lock");
var labelNull1 = il.DefineLabel();
var labelNotNull2 = il.DefineLabel();
var labelNotTaken = il.DefineLabel();
bool boolPlaceholder = false;
il
.Ldloc(localSingletons!)
.LdcI4(_singletonIndex)
.LdelemRef()
.Dup()
.Castclass(safeImplementationType)
.Stloc(localSingleton)
.Brtrue(labelNull1)
.LdcI4(0)
.Stloc(localLockTaken);
context.PushToILStack(Need.ContainerNeed);
il
.Castclass(typeof(ContainerImpl))
.Ldfld(() => default(ContainerImpl).SingletonLocks)
.LdcI4(_singletonIndex)
.LdelemRef()
.Stloc(localLock)
.Try()
.Ldloc(localLock)
.Ldloca(localLockTaken)
.Call(() => Monitor.Enter(null, ref boolPlaceholder))
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.LdelemRef()
.Dup()
.Castclass(safeImplementationType)
.Stloc(localSingleton)
.Brtrue(labelNotNull2);
buildCRegLocals.Push();
var nestedLocal = _wrapping.GenMain(context);
if (nestedLocal != null)
{
il.Ldloc(nestedLocal);
}
buildCRegLocals.Pop();
il
.Stloc(localSingleton)
.Ldloc(localSingletons)
.LdcI4(_singletonIndex)
.Ldloc(localSingleton)
.StelemRef()
.Mark(labelNotNull2)
.Finally()
.Ldloc(localLockTaken)
.BrfalseS(labelNotTaken)
.Ldloc(localLock)
.Call(() => Monitor.Exit(null))
.Mark(labelNotTaken)
.EndTry()
.Mark(labelNull1);
buildCRegLocals.Add(this, localSingleton);
context.BuildContext = backupCtx;
return localSingleton;
}
public IEnumerable<INeed> GetNeeds(IGenerationContext context)
{
var backupCtx = context.BuildContext;
_buildCtx = backupCtx.FreezeMulti();
context.BuildContext = _buildCtx;
yield return new Need
{
Kind = NeedKind.CReg,
Key = _wrapping
};
yield return Need.ContainerNeed;
context.BuildContext = backupCtx;
}
}
}
| |
// 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.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Platform;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.IO.Archives;
using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Scoring
{
public class ScoreManager : IModelManager<ScoreInfo>, IModelImporter<ScoreInfo>
{
private readonly RealmAccess realm;
private readonly Scheduler scheduler;
private readonly Func<BeatmapDifficultyCache> difficulties;
private readonly OsuConfigManager configManager;
private readonly ScoreModelManager scoreModelManager;
public ScoreManager(RulesetStore rulesets, Func<BeatmapManager> beatmaps, Storage storage, RealmAccess realm, Scheduler scheduler,
Func<BeatmapDifficultyCache> difficulties = null, OsuConfigManager configManager = null)
{
this.realm = realm;
this.scheduler = scheduler;
this.difficulties = difficulties;
this.configManager = configManager;
scoreModelManager = new ScoreModelManager(rulesets, beatmaps, storage, realm);
}
public Score GetScore(ScoreInfo score) => scoreModelManager.GetScore(score);
/// <summary>
/// Perform a lookup query on available <see cref="ScoreInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public ScoreInfo Query(Expression<Func<ScoreInfo, bool>> query)
{
return realm.Run(r => r.All<ScoreInfo>().FirstOrDefault(query)?.Detach());
}
/// <summary>
/// Orders an array of <see cref="ScoreInfo"/>s by total score.
/// </summary>
/// <param name="scores">The array of <see cref="ScoreInfo"/>s to reorder.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to cancel the process.</param>
/// <returns>The given <paramref name="scores"/> ordered by decreasing total score.</returns>
public async Task<ScoreInfo[]> OrderByTotalScoreAsync(ScoreInfo[] scores, CancellationToken cancellationToken = default)
{
var difficultyCache = difficulties?.Invoke();
if (difficultyCache != null)
{
// Compute difficulties asynchronously first to prevent blocking via the GetTotalScore() call below.
foreach (var s in scores)
{
await difficultyCache.GetDifficultyAsync(s.BeatmapInfo, s.Ruleset, s.Mods, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
}
}
long[] totalScores = await Task.WhenAll(scores.Select(s => GetTotalScoreAsync(s, cancellationToken: cancellationToken))).ConfigureAwait(false);
return scores.Select((score, index) => (score, totalScore: totalScores[index]))
.OrderByDescending(g => g.totalScore)
.ThenBy(g => g.score.OnlineID)
.Select(g => g.score)
.ToArray();
}
/// <summary>
/// Retrieves a bindable that represents the total score of a <see cref="ScoreInfo"/>.
/// </summary>
/// <remarks>
/// Responds to changes in the currently-selected <see cref="ScoringMode"/>.
/// </remarks>
/// <param name="score">The <see cref="ScoreInfo"/> to retrieve the bindable for.</param>
/// <returns>The bindable containing the total score.</returns>
public Bindable<long> GetBindableTotalScore([NotNull] ScoreInfo score)
{
var bindable = new TotalScoreBindable(score, this);
configManager?.BindWith(OsuSetting.ScoreDisplayMode, bindable.ScoringMode);
return bindable;
}
/// <summary>
/// Retrieves a bindable that represents the formatted total score string of a <see cref="ScoreInfo"/>.
/// </summary>
/// <remarks>
/// Responds to changes in the currently-selected <see cref="ScoringMode"/>.
/// </remarks>
/// <param name="score">The <see cref="ScoreInfo"/> to retrieve the bindable for.</param>
/// <returns>The bindable containing the formatted total score string.</returns>
public Bindable<string> GetBindableTotalScoreString([NotNull] ScoreInfo score) => new TotalScoreStringBindable(GetBindableTotalScore(score));
/// <summary>
/// Retrieves the total score of a <see cref="ScoreInfo"/> in the given <see cref="ScoringMode"/>.
/// The score is returned in a callback that is run on the update thread.
/// </summary>
/// <param name="score">The <see cref="ScoreInfo"/> to calculate the total score of.</param>
/// <param name="callback">The callback to be invoked with the total score.</param>
/// <param name="mode">The <see cref="ScoringMode"/> to return the total score as.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to cancel the process.</param>
public void GetTotalScore([NotNull] ScoreInfo score, [NotNull] Action<long> callback, ScoringMode mode = ScoringMode.Standardised, CancellationToken cancellationToken = default)
{
GetTotalScoreAsync(score, mode, cancellationToken)
.ContinueWith(task => scheduler.Add(() => callback(task.GetResultSafely())), TaskContinuationOptions.OnlyOnRanToCompletion);
}
/// <summary>
/// Retrieves the total score of a <see cref="ScoreInfo"/> in the given <see cref="ScoringMode"/>.
/// </summary>
/// <param name="score">The <see cref="ScoreInfo"/> to calculate the total score of.</param>
/// <param name="mode">The <see cref="ScoringMode"/> to return the total score as.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> to cancel the process.</param>
/// <returns>The total score.</returns>
public async Task<long> GetTotalScoreAsync([NotNull] ScoreInfo score, ScoringMode mode = ScoringMode.Standardised, CancellationToken cancellationToken = default)
{
// TODO: This is required for playlist aggregate scores. They should likely not be getting here in the first place.
if (string.IsNullOrEmpty(score.BeatmapInfo.MD5Hash))
return score.TotalScore;
int beatmapMaxCombo;
double accuracy = score.Accuracy;
if (score.IsLegacyScore)
{
if (score.RulesetID == 3)
{
// In osu!stable, a full-GREAT score has 100% accuracy in mania. Along with a full combo, the score becomes indistinguishable from a full-PERFECT score.
// To get around this, recalculate accuracy based on the hit statistics.
// Note: This cannot be applied universally to all legacy scores, as some rulesets (e.g. catch) group multiple judgements together.
double maxBaseScore = score.Statistics.Select(kvp => kvp.Value).Sum() * Judgement.ToNumericResult(HitResult.Perfect);
double baseScore = score.Statistics.Select(kvp => Judgement.ToNumericResult(kvp.Key) * kvp.Value).Sum();
if (maxBaseScore > 0)
accuracy = baseScore / maxBaseScore;
}
// This score is guaranteed to be an osu!stable score.
// The combo must be determined through either the beatmap's max combo value or the difficulty calculator, as lazer's scoring has changed and the score statistics cannot be used.
if (score.BeatmapInfo.MaxCombo != null)
beatmapMaxCombo = score.BeatmapInfo.MaxCombo.Value;
else
{
if (difficulties == null)
return score.TotalScore;
// We can compute the max combo locally after the async beatmap difficulty computation.
var difficulty = await difficulties().GetDifficultyAsync(score.BeatmapInfo, score.Ruleset, score.Mods, cancellationToken).ConfigureAwait(false);
// Something failed during difficulty calculation. Fall back to provided score.
if (difficulty == null)
return score.TotalScore;
beatmapMaxCombo = difficulty.Value.MaxCombo;
}
}
else
{
// This is guaranteed to be a non-legacy score.
// The combo must be determined through the score's statistics, as both the beatmap's max combo and the difficulty calculator will provide osu!stable combo values.
beatmapMaxCombo = Enum.GetValues(typeof(HitResult)).OfType<HitResult>().Where(r => r.AffectsCombo()).Select(r => score.Statistics.GetValueOrDefault(r)).Sum();
}
if (beatmapMaxCombo == 0)
return 0;
var ruleset = score.Ruleset.CreateInstance();
var scoreProcessor = ruleset.CreateScoreProcessor();
scoreProcessor.Mods.Value = score.Mods;
return (long)Math.Round(scoreProcessor.GetScore(mode, accuracy, (double)score.MaxCombo / beatmapMaxCombo, score.Statistics));
}
/// <summary>
/// Provides the total score of a <see cref="ScoreInfo"/>. Responds to changes in the currently-selected <see cref="ScoringMode"/>.
/// </summary>
private class TotalScoreBindable : Bindable<long>
{
public readonly Bindable<ScoringMode> ScoringMode = new Bindable<ScoringMode>();
private readonly ScoreInfo score;
private readonly ScoreManager scoreManager;
private CancellationTokenSource difficultyCalculationCancellationSource;
/// <summary>
/// Creates a new <see cref="TotalScoreBindable"/>.
/// </summary>
/// <param name="score">The <see cref="ScoreInfo"/> to provide the total score of.</param>
/// <param name="scoreManager">The <see cref="ScoreManager"/>.</param>
public TotalScoreBindable(ScoreInfo score, ScoreManager scoreManager)
{
this.score = score;
this.scoreManager = scoreManager;
ScoringMode.BindValueChanged(onScoringModeChanged, true);
}
private void onScoringModeChanged(ValueChangedEvent<ScoringMode> mode)
{
difficultyCalculationCancellationSource?.Cancel();
difficultyCalculationCancellationSource = new CancellationTokenSource();
scoreManager.GetTotalScore(score, s => Value = s, mode.NewValue, difficultyCalculationCancellationSource.Token);
}
}
/// <summary>
/// Provides the total score of a <see cref="ScoreInfo"/> as a formatted string. Responds to changes in the currently-selected <see cref="ScoringMode"/>.
/// </summary>
private class TotalScoreStringBindable : Bindable<string>
{
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable (need to hold a reference)
private readonly IBindable<long> totalScore;
public TotalScoreStringBindable(IBindable<long> totalScore)
{
this.totalScore = totalScore;
this.totalScore.BindValueChanged(v => Value = v.NewValue.ToString("N0"), true);
}
}
#region Implementation of IPostNotifications
public Action<Notification> PostNotification
{
set => scoreModelManager.PostNotification = value;
}
#endregion
#region Implementation of IModelManager<ScoreInfo>
public bool Delete(ScoreInfo item)
{
return scoreModelManager.Delete(item);
}
public void Delete([CanBeNull] Expression<Func<ScoreInfo, bool>> filter = null, bool silent = false)
{
realm.Run(r =>
{
var items = r.All<ScoreInfo>()
.Where(s => !s.DeletePending);
if (filter != null)
items = items.Where(filter);
scoreModelManager.Delete(items.ToList(), silent);
});
}
public void Delete(BeatmapInfo beatmap, bool silent = false)
{
realm.Run(r =>
{
var beatmapScores = r.Find<BeatmapInfo>(beatmap.ID).Scores.ToList();
scoreModelManager.Delete(beatmapScores, silent);
});
}
public void Delete(List<ScoreInfo> items, bool silent = false)
{
scoreModelManager.Delete(items, silent);
}
public void Undelete(List<ScoreInfo> items, bool silent = false)
{
scoreModelManager.Undelete(items, silent);
}
public void Undelete(ScoreInfo item)
{
scoreModelManager.Undelete(item);
}
public Task Import(params string[] paths)
{
return scoreModelManager.Import(paths);
}
public Task Import(params ImportTask[] tasks)
{
return scoreModelManager.Import(tasks);
}
public IEnumerable<string> HandledExtensions => scoreModelManager.HandledExtensions;
public Task<IEnumerable<Live<ScoreInfo>>> Import(ProgressNotification notification, params ImportTask[] tasks)
{
return scoreModelManager.Import(notification, tasks);
}
public Task<Live<ScoreInfo>> Import(ImportTask task, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return scoreModelManager.Import(task, lowPriority, cancellationToken);
}
public Task<Live<ScoreInfo>> Import(ArchiveReader archive, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return scoreModelManager.Import(archive, lowPriority, cancellationToken);
}
public Live<ScoreInfo> Import(ScoreInfo item, ArchiveReader archive = null, bool lowPriority = false, CancellationToken cancellationToken = default)
{
return scoreModelManager.Import(item, archive, lowPriority, cancellationToken);
}
public bool IsAvailableLocally(ScoreInfo model)
{
return scoreModelManager.IsAvailableLocally(model);
}
#endregion
#region Implementation of IPresentImports<ScoreInfo>
public Action<IEnumerable<Live<ScoreInfo>>> PostImport
{
set => scoreModelManager.PostImport = value;
}
#endregion
}
}
| |
namespace TBag.BloomFilters.Estimators
{
using Configurations;
using Invertible.Configurations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
/// <summary>
/// A b-bits min hash estimator.
/// </summary>
/// <typeparam name="TEntity">The entity type</typeparam>
/// <typeparam name="TId">The entity identifier type</typeparam>
/// <typeparam name="TCount">The type of occurence count.</typeparam>
public class BitMinwiseHashEstimator<TEntity, TId, TCount> : IBitMinwiseHashEstimator<TEntity, TId, TCount>
where TCount : struct
where TId : struct
{
#region Fields
private int _hashCount;
private readonly Func<int, IEnumerable<int>> _hashFunctions;
private readonly Func<TEntity, int> _entityHash;
private byte _bitSize;
private long _capacity;
private Lazy<int[]> _slots ;
private long _itemCount;
private readonly IInvertibleBloomFilterConfiguration<TEntity,TId, int, TCount> _configuration;
#endregion
#region Properties
/// <summary>
/// The number of items in the estimator.
/// </summary>
public virtual long ItemCount => _itemCount;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="configuration">The configuration</param>
/// <param name="bitSize">The number of bits to store per hash</param>
/// <param name="hashCount">The number of hash functions to use.</param>
/// <param name="capacity">The capacity (should be a close approximation of the number of elements added)</param>
/// <remarks>By using bitSize = 1 or bitSize = 2, the accuracy is decreased, thus the hashCount needs to be increased. However, when resemblance is not too small, for example > 0.5, bitSize = 1 can yield similar results as bitSize = 64 with only 3 times the hash count.</remarks>
public BitMinwiseHashEstimator(
IInvertibleBloomFilterConfiguration<TEntity, TId, int, TCount> configuration,
byte bitSize,
int hashCount,
long capacity)
{
_hashCount = hashCount;
_configuration = configuration;
_hashFunctions = GenerateHashes();
_bitSize = bitSize;
_capacity = _configuration.FoldingStrategy?.ComputeFoldableSize(capacity, 0) ?? capacity;
_entityHash = e => unchecked((int)(ulong)(_configuration.EntityHash(e)+configuration.IdHash(_configuration.GetId(e))));
_slots = new Lazy<int[]>(()=> GetMinHashSlots(_hashCount, _capacity));
}
#endregion
#region Implementation of estimator
/// <summary>
/// Determine similarity.
/// </summary>
/// <param name="estimator">The estimator to compare against.</param>
/// <returns>Similarity (percentage similar, zero is completely different, one is completely the same)</returns>
/// <remarks>Zero is no similarity, one is completely similar.</remarks>
public double? Similarity(IBitMinwiseHashEstimator<TEntity, TId, TCount> estimator)
{
if (estimator == null) return 0.0D;
return Extract()
.Similarity(estimator.Extract());
}
/// <summary>
/// Determine the similarity between this estimator and the provided estimator data,
/// </summary>
/// <param name="estimatorData">The estimator data to compare against.</param>
/// <returns></returns>
public double? Similarity(IBitMinwiseHashEstimatorData estimatorData)
{
if (estimatorData == null) return 0.0D;
return Extract()
.Similarity(estimatorData);
}
/// <summary>
/// Add the item to estimator.
/// </summary>
/// <param name="item">The entity to add</param>
public void Add(TEntity item)
{
Debug.Assert(item != null);
ComputeMinHash(item);
}
/// <summary>
/// Add an estimator
/// </summary>
/// <param name="estimator">The estimator to add.</param>
/// <returns></returns>
public void Add(IBitMinwiseHashEstimator<TEntity, TId, TCount> estimator)
{
Rehydrate(
FullExtract()
.Add(
estimator?.FullExtract(),
_configuration.FoldingStrategy,
true));
}
/// <summary>
/// Add an estimator
/// </summary>
/// <param name="estimator">The estimator to add.</param>
/// <returns></returns>
public void Add(IBitMinwiseHashEstimatorFullData estimator)
{
Rehydrate(FullExtract().Add(estimator, _configuration.FoldingStrategy, true));
}
/// <summary>
/// Intersect an estimator
/// </summary>
/// <param name="estimator">The estimator to add.</param>
/// <returns></returns>
public void Intersect(IBitMinwiseHashEstimator<TEntity, TId, TCount> estimator)
{
Rehydrate(FullExtract().Intersect(estimator?.FullExtract(), _configuration.FoldingStrategy));
}
/// <summary>
/// Add an estimator
/// </summary>
/// <param name="estimator">The estimator to add.</param>
/// <returns></returns>
public void Intersect(IBitMinwiseHashEstimatorFullData estimator)
{
Rehydrate(FullExtract().Intersect(estimator, _configuration.FoldingStrategy));
}
/// <summary>
/// Extract the estimator data in a serializable format.
/// </summary>
/// <returns></returns>
public BitMinwiseHashEstimatorData Extract()
{
return new BitMinwiseHashEstimatorData
{
BitSize = _bitSize,
Capacity = _capacity,
HashCount = _hashCount,
Values = !_slots.IsValueCreated ? null : _slots.Value.ConvertToBitArray(_bitSize).ToBytes(),
ItemCount = _itemCount
};
}
/// <summary>
/// Extract the full data from the b-bit inwise estimator
/// </summary>
/// <returns></returns>
/// <remarks>Not for sending across the wire, but good for rehydrating.</remarks>
public BitMinwiseHashEstimatorFullData FullExtract()
{
return new BitMinwiseHashEstimatorFullData
{
BitSize = _bitSize,
Capacity = _capacity,
HashCount = _hashCount,
Values = !_slots.IsValueCreated ? null : _slots.Value,
ItemCount = _itemCount
};
}
/// <summary>
/// Compress the estimator.
/// </summary>
/// <param name="inPlace"></param>
/// <returns></returns>
public IBitMinwiseHashEstimator<TEntity, TId, TCount> Compress(bool inPlace = false)
{
var res = FullExtract().Compress<TId,int>(_configuration);
if (inPlace)
{
Rehydrate(res);
return this;
}
var estimatorRes = new BitMinwiseHashEstimator<TEntity, TId, TCount>(
_configuration,
_bitSize,
_hashCount,
_capacity);
estimatorRes.Rehydrate(res);
return estimatorRes;
}
/// <summary>
/// Fold the estimator.
/// </summary>
/// <param name="factor">Factor to fold by.</param>
/// <param name="inPlace">When <c>true</c> the estimator will be replaced by a folded estimator, else <c>false</c>.</param>
/// <returns></returns>
public BitMinwiseHashEstimator<TEntity, TId, TCount> Fold(uint factor, bool inPlace = false)
{
var res = FullExtract().Fold(factor);
if (inPlace)
{
Rehydrate(res);
return this;
}
var estimator = new BitMinwiseHashEstimator<TEntity, TId, TCount>(
_configuration,
res.BitSize,
res.HashCount,
res.Capacity);
estimator.Rehydrate(res);
return estimator;
}
/// <summary>
/// Explicit implementation of the interface for folding.
/// </summary>
/// <param name="factor"></param>
/// <param name="inPlace"></param>
/// <returns></returns>
IBitMinwiseHashEstimator<TEntity, TId, TCount> IBitMinwiseHashEstimator<TEntity, TId, TCount>.Fold(uint factor, bool inPlace)
{
return Fold(factor, inPlace);
}
/// <summary>
/// Rehydrate the given data.
/// </summary>
/// <param name="data"></param>
public void Rehydrate(IBitMinwiseHashEstimatorFullData data)
{
if (data == null) return;
_capacity = data.Capacity;
_hashCount = data.HashCount;
_bitSize = data.BitSize;
_itemCount = data.ItemCount;
_slots = data.Values == null
? new Lazy<int[]>(() => GetMinHashSlots(_hashCount, _capacity))
: new Lazy<int[]>(() => data.Values);
}
#endregion
#region Methods
/// <summary>
/// Bit minwise estimator requires this specific hash function.
/// </summary>
/// <returns></returns>
private Func<int, IEnumerable<int>> GenerateHashes()
{
const int universeSize = int.MaxValue;
var bound = (uint)universeSize;
var r = new Random(11);
var hashFuncs = new Func<int, int>[_hashCount];
for (var i = 0; i < _hashCount; i++)
{
var a = unchecked((uint)r.Next(universeSize));
var b = unchecked((uint)r.Next(universeSize));
var c = unchecked((uint)r.Next(universeSize));
hashFuncs[i] = hash => QHash(hash, a, b, c, bound);
}
return hash => hashFuncs.Select(f => f(hash));
}
/// <summary>
/// Compute the hash for the given element.
/// </summary>
/// <param name="element">Entity to calculate a hash for.</param>
private void ComputeMinHash(TEntity element)
{
var entityHash =_entityHash(element);
var entityHashes = _hashFunctions(entityHash).ToArray();
var idx = 0L;
var idhash = Math.Abs(entityHash % _capacity);
for (var i = 0L; i < entityHashes.LongLength; i++)
{
if (entityHashes[i] < _slots.Value[idx+idhash])
{
_slots.Value[idx + idhash] = entityHashes[i];
}
idx += _capacity;
}
_itemCount++;
}
/// <summary>
/// Create an array of the correct size.
/// </summary>
/// <param name="numHashFunctions"></param>
/// <param name="setSize"></param>
/// <returns></returns>
private static int[] GetMinHashSlots(int numHashFunctions, long setSize)
{
var minHashValues = new int[numHashFunctions*setSize];
for (var i = 0L; i < minHashValues.LongLength; i++)
{
minHashValues[i] = int.MaxValue;
}
return minHashValues;
}
/// <summary>
/// QHash.
/// </summary>
/// <param name="id"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="bound"></param>
/// <returns></returns>
private static int QHash(int id, uint a, uint b, uint c, uint bound)
{
//Modify the hash family as per the size of possible elements in a Set
return unchecked((int) (Math.Abs((int) ((a*(id >> 4) + b*id + c) & 131071))%bound));
}
#endregion
}
}
| |
/*
This file is licensed to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml;
using net.sf.xmlunit.util;
namespace net.sf.xmlunit.diff {
/// <summary>
/// Common ElementSelector implementations.
/// </summary>
public sealed class ElementSelectors {
private ElementSelectors() { }
/// <summary>
/// Always returns true, i.e. each element can be compared to each
/// other element.
/// </summary>
/// <remarks>
/// Generally this means elements will be compared in document
/// order.
/// </remarks>
public static bool Default(XmlElement controlElement,
XmlElement testElement) {
return true;
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// can be compared.
/// </summary>
public static bool ByName(XmlElement controlElement,
XmlElement testElement) {
return controlElement != null && testElement != null
&& BothNullOrEqual(Nodes.GetQName(controlElement),
Nodes.GetQName(testElement));
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and nested text (if any) can be compared.
/// </summary>
public static bool ByNameAndText(XmlElement controlElement,
XmlElement testElement) {
return ByName(controlElement, testElement)
&& BothNullOrEqual(Nodes.GetMergedNestedText(controlElement),
Nodes.GetMergedNestedText(testElement));
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and attribute values for the given attribute names can be
/// compared.
/// </summary>
/// <remarks>Attributes are only searched for in the null
/// namespace.</remarks>
public static ElementSelector
ByNameAndAttributes(params string[] attribs) {
if (attribs == null) {
throw new ArgumentNullException("attribs");
}
XmlQualifiedName[] qs = new XmlQualifiedName[attribs.Length];
for (int i = 0; i < attribs.Length; i++) {
qs[i] = new XmlQualifiedName(attribs[i]);
}
return ByNameAndAttributes(qs);
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and attribute values for the given attribute names can be
/// compared.
/// </summary>
public static ElementSelector
ByNameAndAttributes(params XmlQualifiedName[] attribs) {
if (attribs == null) {
throw new ArgumentNullException("attribs");
}
XmlQualifiedName[] qs = new XmlQualifiedName[attribs.Length];
Array.Copy(attribs, 0, qs, 0, qs.Length);
return delegate(XmlElement controlElement, XmlElement testElement) {
if (!ByName(controlElement, testElement)) {
return false;
}
return MapsEqualForKeys(Nodes.GetAttributes(controlElement),
Nodes.GetAttributes(testElement),
qs);
};
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and attribute values for the given attribute names can be
/// compared.
/// </summary>
/// <remarks>
/// Namespace URIs of attributes are those of the attributes on
/// the control element or the null namespace if the don't
/// exist.
/// </remarks>
public static ElementSelector
ByNameAndAttributesControlNS(params string[] attribs) {
if (attribs == null) {
throw new ArgumentNullException("attribs");
}
List<string> ats = new List<string>(attribs);
return delegate(XmlElement controlElement, XmlElement testElement) {
if (!ByName(controlElement, testElement)) {
return false;
}
IDictionary<XmlQualifiedName, string> cAttrs =
Nodes.GetAttributes(controlElement);
IDictionary<string, XmlQualifiedName> qNameByLocalName =
new Dictionary<string, XmlQualifiedName>();
foreach (XmlQualifiedName q in cAttrs.Keys) {
string local = q.Name;
if (ats.Contains(local)) {
qNameByLocalName[local] = q;
}
}
foreach (string a in ats) {
if (!qNameByLocalName.ContainsKey(a)) {
qNameByLocalName[a] = new XmlQualifiedName(a);
}
}
return MapsEqualForKeys(cAttrs,
Nodes.GetAttributes(testElement),
qNameByLocalName.Values);
};
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and attribute values for all attributes can be compared.
/// </summary>
public static bool ByNameAndAllAttributes(XmlElement controlElement,
XmlElement testElement) {
if (!ByName(controlElement, testElement)) {
return false;
}
IDictionary<XmlQualifiedName, string> cAttrs =
Nodes.GetAttributes(controlElement);
IDictionary<XmlQualifiedName, string> tAttrs =
Nodes.GetAttributes(testElement);
if (cAttrs.Count != tAttrs.Count) {
return false;
}
return MapsEqualForKeys(cAttrs, tAttrs, cAttrs.Keys);
}
/// <summary>
/// Elements with the same local name (and namespace URI - if any)
/// and child elements and nested text at each level (if any) can
/// be compared.
/// </summary>
public static bool ByNameAndTextRec(XmlElement controlElement,
XmlElement testElement) {
if (!ByNameAndText(controlElement, testElement)) {
return false;
}
XmlNodeList controlChildren = controlElement.ChildNodes;
XmlNodeList testChildren = testElement.ChildNodes;
int controlLen = controlChildren.Count;
int testLen = testChildren.Count;
int controlIndex, testIndex;
for (controlIndex = testIndex = 0;
controlIndex < controlLen && testIndex < testLen;
) {
// find next non-text child nodes
XmlNode c = controlChildren[controlIndex];
while (IsText(c) && ++controlIndex < controlLen) {
c = controlChildren[controlIndex];
}
if (IsText(c)) {
break;
}
XmlNode t = testChildren[testIndex];
while (IsText(t) && ++testIndex < testLen) {
t = testChildren[testIndex];
}
if (IsText(t)) {
break;
}
// different types of children make elements
// non-comparable
if (c.NodeType != t.NodeType) {
return false;
}
// recurse for child elements
if (c is XmlElement
&& !ByNameAndTextRec(c as XmlElement, t as XmlElement)) {
return false;
}
controlIndex++;
testIndex++;
}
// child lists exhausted?
if (controlIndex < controlLen) {
XmlNode n = controlChildren[controlIndex];
while (IsText(n) && ++controlIndex < controlLen) {
n = controlChildren[controlIndex];
}
// some non-Text children remained
if (controlIndex < controlLen) {
return false;
}
}
if (testIndex < testLen) {
XmlNode n = testChildren[testIndex];
while (IsText(n) && ++testIndex < testLen) {
n = testChildren[testIndex];
}
// some non-Text children remained
if (testIndex < testLen) {
return false;
}
}
return true;
}
private static bool BothNullOrEqual(object o1, object o2) {
return o1 == null ? o2 == null : o1.Equals(o2);
}
private static bool
MapsEqualForKeys(IDictionary<XmlQualifiedName, string> control,
IDictionary<XmlQualifiedName, string> test,
IEnumerable<XmlQualifiedName> keys) {
foreach (XmlQualifiedName q in keys) {
string c, t;
if (control.TryGetValue(q, out c) != test.TryGetValue(q, out t)) {
return false;
}
if (!BothNullOrEqual(c, t)) {
return false;
}
}
return true;
}
private static bool IsText(XmlNode n) {
return n is XmlText || n is XmlCDataSection;
}
}
}
| |
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Render model of associated tracked object
//
//=============================================================================
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Valve.VR;
namespace Valve.VR
{
[ExecuteInEditMode]
public class SteamVR_RenderModel : MonoBehaviour
{
public SteamVR_TrackedObject.EIndex index = SteamVR_TrackedObject.EIndex.None;
protected SteamVR_Input_Sources inputSource;
public const string modelOverrideWarning = "Model override is really only meant to be used in " +
"the scene view for lining things up; using it at runtime is discouraged. Use tracked device " +
"index instead to ensure the correct model is displayed for all users.";
[Tooltip(modelOverrideWarning)]
public string modelOverride;
[Tooltip("Shader to apply to model.")]
public Shader shader;
[Tooltip("Enable to print out when render models are loaded.")]
public bool verbose = false;
[Tooltip("If available, break down into separate components instead of loading as a single mesh.")]
public bool createComponents = true;
[Tooltip("Update transforms of components at runtime to reflect user action.")]
public bool updateDynamically = true;
// Additional controller settings for showing scrollwheel, etc.
public RenderModel_ControllerMode_State_t controllerModeState;
// Name of the sub-object which represents the "local" coordinate space for each component.
public const string k_localTransformName = "attach";
// Cached name of this render model for updating component transforms at runtime.
public string renderModelName { get; private set; }
public bool initializedAttachPoints { get; set; }
private Dictionary<string, Transform> componentAttachPoints = new Dictionary<string, Transform>();
private List<MeshRenderer> meshRenderers = new List<MeshRenderer>();
// If someone knows how to keep these from getting cleaned up every time
// you exit play mode, let me know. I've tried marking the RenderModel
// class below as [System.Serializable] and switching to normal public
// variables for mesh and material to get them to serialize properly,
// as well as tried marking the mesh and material objects as
// DontUnloadUnusedAsset, but Unity was still unloading them.
// The hashtable is preserving its entries, but the mesh and material
// variables are going null.
public class RenderModel
{
public RenderModel(Mesh mesh, Material material)
{
this.mesh = mesh;
this.material = material;
}
public Mesh mesh { get; private set; }
public Material material { get; private set; }
}
public static Hashtable models = new Hashtable();
public static Hashtable materials = new Hashtable();
// Helper class to load render models interface on demand and clean up when done.
public sealed class RenderModelInterfaceHolder : System.IDisposable
{
private bool needsShutdown, failedLoadInterface;
private CVRRenderModels _instance;
public CVRRenderModels instance
{
get
{
if (_instance == null && !failedLoadInterface)
{
if (Application.isEditor && Application.isPlaying == false)
needsShutdown = SteamVR.InitializeTemporarySession();
_instance = OpenVR.RenderModels;
if (_instance == null)
{
Debug.LogError("<b>[SteamVR]</b> Failed to load IVRRenderModels interface version " + OpenVR.IVRRenderModels_Version);
failedLoadInterface = true;
}
}
return _instance;
}
}
public void Dispose()
{
if (needsShutdown)
SteamVR.ExitTemporarySession();
}
}
private void OnModelSkinSettingsHaveChanged(VREvent_t vrEvent)
{
if (!string.IsNullOrEmpty(renderModelName))
{
renderModelName = "";
UpdateModel();
}
}
public void SetMeshRendererState(bool state)
{
for (int rendererIndex = 0; rendererIndex < meshRenderers.Count; rendererIndex++)
{
MeshRenderer renderer = meshRenderers[rendererIndex];
if (renderer != null)
renderer.enabled = state;
}
}
private void OnHideRenderModels(bool hidden)
{
SetMeshRendererState(!hidden);
}
private void OnDeviceConnected(int i, bool connected)
{
if (i != (int)index)
return;
if (connected)
{
UpdateModel();
}
}
public void UpdateModel()
{
var system = OpenVR.System;
if (system == null || index == SteamVR_TrackedObject.EIndex.None)
return;
var error = ETrackedPropertyError.TrackedProp_Success;
var capacity = system.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, null, 0, ref error);
if (capacity <= 1)
{
Debug.LogError("<b>[SteamVR]</b> Failed to get render model name for tracked object " + index);
return;
}
var buffer = new System.Text.StringBuilder((int)capacity);
system.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, buffer, capacity, ref error);
var s = buffer.ToString();
if (renderModelName != s)
{
StartCoroutine(SetModelAsync(s));
}
}
IEnumerator SetModelAsync(string newRenderModelName)
{
meshRenderers.Clear();
if (string.IsNullOrEmpty(newRenderModelName))
yield break;
// Preload all render models before asking for the data to create meshes.
using (RenderModelInterfaceHolder holder = new RenderModelInterfaceHolder())
{
CVRRenderModels renderModels = holder.instance;
if (renderModels == null)
yield break;
// Gather names of render models to preload.
string[] renderModelNames;
uint count = renderModels.GetComponentCount(newRenderModelName);
if (count > 0)
{
renderModelNames = new string[count];
for (int componentIndex = 0; componentIndex < count; componentIndex++)
{
uint capacity = renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, null, 0);
if (capacity == 0)
continue;
var componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
if (renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, componentNameStringBuilder, capacity) == 0)
continue;
string componentName = componentNameStringBuilder.ToString();
capacity = renderModels.GetComponentRenderModelName(newRenderModelName, componentName, null, 0);
if (capacity == 0)
continue;
var nameStringBuilder = new System.Text.StringBuilder((int)capacity);
if (renderModels.GetComponentRenderModelName(newRenderModelName, componentName, nameStringBuilder, capacity) == 0)
continue;
var s = nameStringBuilder.ToString();
// Only need to preload if not already cached.
RenderModel model = models[s] as RenderModel;
if (model == null || model.mesh == null)
{
renderModelNames[componentIndex] = s;
}
}
}
else
{
// Only need to preload if not already cached.
RenderModel model = models[newRenderModelName] as RenderModel;
if (model == null || model.mesh == null)
{
renderModelNames = new string[] { newRenderModelName };
}
else
{
renderModelNames = new string[0];
}
}
// Keep trying every 100ms until all components finish loading.
while (true)
{
var loading = false;
for (int renderModelNameIndex = 0; renderModelNameIndex < renderModelNames.Length; renderModelNameIndex++)
{
if (string.IsNullOrEmpty(renderModelNames[renderModelNameIndex]))
continue;
var pRenderModel = System.IntPtr.Zero;
var error = renderModels.LoadRenderModel_Async(renderModelNames[renderModelNameIndex], ref pRenderModel);
//Debug.Log("<b>[SteamVR]</b> renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());
if (error == EVRRenderModelError.Loading)
{
loading = true;
}
else if (error == EVRRenderModelError.None)
{
// Preload textures as well.
var renderModel = MarshalRenderModel(pRenderModel);
// Check the cache first.
var material = materials[renderModel.diffuseTextureId] as Material;
if (material == null || material.mainTexture == null)
{
var pDiffuseTexture = System.IntPtr.Zero;
error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
//Debug.Log("<b>[SteamVR]</b> renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());
if (error == EVRRenderModelError.Loading)
{
loading = true;
}
}
}
}
if (loading)
{
yield return new WaitForSecondsRealtime(0.1f);
}
else
{
break;
}
}
}
bool success = SetModel(newRenderModelName);
this.renderModelName = newRenderModelName;
SteamVR_Events.RenderModelLoaded.Send(this, success);
}
private bool SetModel(string renderModelName)
{
StripMesh(gameObject);
using (var holder = new RenderModelInterfaceHolder())
{
if (createComponents)
{
componentAttachPoints.Clear();
if (LoadComponents(holder, renderModelName))
{
UpdateComponents(holder.instance);
return true;
}
Debug.Log("<b>[SteamVR]</b> [" + gameObject.name + "] Render model does not support components, falling back to single mesh.");
}
if (!string.IsNullOrEmpty(renderModelName))
{
var model = models[renderModelName] as RenderModel;
if (model == null || model.mesh == null)
{
var renderModels = holder.instance;
if (renderModels == null)
return false;
if (verbose)
Debug.Log("<b>[SteamVR]</b> Loading render model " + renderModelName);
model = LoadRenderModel(renderModels, renderModelName, renderModelName);
if (model == null)
return false;
models[renderModelName] = model;
}
gameObject.AddComponent<MeshFilter>().mesh = model.mesh;
MeshRenderer newRenderer = gameObject.AddComponent<MeshRenderer>();
newRenderer.sharedMaterial = model.material;
meshRenderers.Add(newRenderer);
return true;
}
}
return false;
}
RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
{
var pRenderModel = System.IntPtr.Zero;
EVRRenderModelError error;
while (true)
{
error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
if (error != EVRRenderModelError.None)
{
Debug.LogError(string.Format("<b>[SteamVR]</b> Failed to load render model {0} - {1}", renderModelName, error.ToString()));
return null;
}
var renderModel = MarshalRenderModel(pRenderModel);
var vertices = new Vector3[renderModel.unVertexCount];
var normals = new Vector3[renderModel.unVertexCount];
var uv = new Vector2[renderModel.unVertexCount];
var type = typeof(RenderModel_Vertex_t);
for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
{
var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);
vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
}
int indexCount = (int)renderModel.unTriangleCount * 3;
var indices = new short[indexCount];
Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);
var triangles = new int[indexCount];
for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
{
triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
}
var mesh = new Mesh();
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uv;
mesh.triangles = triangles;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
mesh.Optimize();
#endif
//mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;
// Check cache before loading texture.
var material = materials[renderModel.diffuseTextureId] as Material;
if (material == null || material.mainTexture == null)
{
var pDiffuseTexture = System.IntPtr.Zero;
while (true)
{
error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
if (error == EVRRenderModelError.None)
{
var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
{
texture.Apply();
System.IntPtr texturePointer = texture.GetNativeTexturePtr();
while (true)
{
error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
if (error != EVRRenderModelError.Loading)
break;
Sleep();
}
}
else
{
var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);
var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
int iColor = 0;
for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
{
for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
{
var r = textureMapData[iColor++];
var g = textureMapData[iColor++];
var b = textureMapData[iColor++];
var a = textureMapData[iColor++];
colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
}
}
texture.SetPixels32(colors);
texture.Apply();
}
material = new Material(shader != null ? shader : Shader.Find("Standard"));
material.mainTexture = texture;
//material.hideFlags = HideFlags.DontUnloadUnusedAsset;
materials[renderModel.diffuseTextureId] = material;
renderModels.FreeTexture(pDiffuseTexture);
}
else
{
Debug.Log("<b>[SteamVR]</b> Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
}
}
// Delay freeing when we can since we'll often get multiple requests for the same model right
// after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
if (!Application.isPlaying)
renderModels.FreeRenderModel(pRenderModel);
else
#endif
StartCoroutine(FreeRenderModel(pRenderModel));
return new RenderModel(mesh, material);
}
IEnumerator FreeRenderModel(System.IntPtr pRenderModel)
{
yield return new WaitForSeconds(1.0f);
using (var holder = new RenderModelInterfaceHolder())
{
var renderModels = holder.instance;
renderModels.FreeRenderModel(pRenderModel);
}
}
public Transform FindTransformByName(string componentName, Transform inTransform = null)
{
if (inTransform == null)
inTransform = this.transform;
for (int childIndex = 0; childIndex < inTransform.childCount; childIndex++)
{
Transform child = inTransform.GetChild(childIndex);
if (child.name == componentName)
return child;
}
return null;
}
public Transform GetComponentTransform(string componentName)
{
if (componentName == null)
return this.transform;
if (componentAttachPoints.ContainsKey(componentName))
return componentAttachPoints[componentName];
return null;
}
private void StripMesh(GameObject go)
{
var meshRenderer = go.GetComponent<MeshRenderer>();
if (meshRenderer != null)
DestroyImmediate(meshRenderer);
var meshFilter = go.GetComponent<MeshFilter>();
if (meshFilter != null)
DestroyImmediate(meshFilter);
}
private bool LoadComponents(RenderModelInterfaceHolder holder, string renderModelName)
{
// Disable existing components (we will re-enable them if referenced by this new model).
// Also strip mesh filter and renderer since these will get re-added if the new component needs them.
var t = transform;
for (int childIndex = 0; childIndex < t.childCount; childIndex++)
{
var child = t.GetChild(childIndex);
child.gameObject.SetActive(false);
StripMesh(child.gameObject);
}
// If no model specified, we're done; return success.
if (string.IsNullOrEmpty(renderModelName))
return true;
var renderModels = holder.instance;
if (renderModels == null)
return false;
var count = renderModels.GetComponentCount(renderModelName);
if (count == 0)
return false;
for (int i = 0; i < count; i++)
{
var capacity = renderModels.GetComponentName(renderModelName, (uint)i, null, 0);
if (capacity == 0)
continue;
System.Text.StringBuilder componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
if (renderModels.GetComponentName(renderModelName, (uint)i, componentNameStringBuilder, capacity) == 0)
continue;
string componentName = componentNameStringBuilder.ToString();
// Create (or reuse) a child object for this component (some components are dynamic and don't have meshes).
t = FindTransformByName(componentName);
if (t != null)
{
t.gameObject.SetActive(true);
componentAttachPoints[componentName] = FindTransformByName(k_localTransformName, t);
}
else
{
t = new GameObject(componentName).transform;
t.parent = transform;
t.gameObject.layer = gameObject.layer;
// Also create a child 'attach' object for attaching things.
var attach = new GameObject(k_localTransformName).transform;
attach.parent = t;
attach.localPosition = Vector3.zero;
attach.localRotation = Quaternion.identity;
attach.localScale = Vector3.one;
attach.gameObject.layer = gameObject.layer;
componentAttachPoints[componentName] = attach;
}
// Reset transform.
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
capacity = renderModels.GetComponentRenderModelName(renderModelName, componentName, null, 0);
if (capacity == 0)
continue;
var componentRenderModelNameStringBuilder = new System.Text.StringBuilder((int)capacity);
if (renderModels.GetComponentRenderModelName(renderModelName, componentName, componentRenderModelNameStringBuilder, capacity) == 0)
continue;
string componentRenderModelName = componentRenderModelNameStringBuilder.ToString();
// Check the cache or load into memory.
var model = models[componentRenderModelName] as RenderModel;
if (model == null || model.mesh == null)
{
if (verbose)
Debug.Log("<b>[SteamVR]</b> Loading render model " + componentRenderModelName);
model = LoadRenderModel(renderModels, componentRenderModelName, renderModelName);
if (model == null)
continue;
models[componentRenderModelName] = model;
}
t.gameObject.AddComponent<MeshFilter>().mesh = model.mesh;
MeshRenderer newRenderer = t.gameObject.AddComponent<MeshRenderer>();
newRenderer.sharedMaterial = model.material;
meshRenderers.Add(newRenderer);
}
return true;
}
SteamVR_Events.Action deviceConnectedAction, hideRenderModelsAction, modelSkinSettingsHaveChangedAction;
SteamVR_RenderModel()
{
deviceConnectedAction = SteamVR_Events.DeviceConnectedAction(OnDeviceConnected);
hideRenderModelsAction = SteamVR_Events.HideRenderModelsAction(OnHideRenderModels);
modelSkinSettingsHaveChangedAction = SteamVR_Events.SystemAction(EVREventType.VREvent_ModelSkinSettingsHaveChanged, OnModelSkinSettingsHaveChanged);
}
void OnEnable()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
return;
#endif
if (!string.IsNullOrEmpty(modelOverride))
{
Debug.Log("<b>[SteamVR]</b> " + modelOverrideWarning);
enabled = false;
return;
}
var system = OpenVR.System;
if (system != null && system.IsTrackedDeviceConnected((uint)index))
{
UpdateModel();
}
deviceConnectedAction.enabled = true;
hideRenderModelsAction.enabled = true;
modelSkinSettingsHaveChangedAction.enabled = true;
}
void OnDisable()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
return;
#endif
deviceConnectedAction.enabled = false;
hideRenderModelsAction.enabled = false;
modelSkinSettingsHaveChangedAction.enabled = false;
}
#if UNITY_EDITOR
Hashtable values;
#endif
void Update()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
// See if anything has changed since this gets called whenever anything gets touched.
var fields = GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
bool modified = false;
if (values == null)
{
modified = true;
}
else
{
foreach (var f in fields)
{
if (!values.Contains(f))
{
modified = true;
break;
}
var v0 = values[f];
var v1 = f.GetValue(this);
if (v1 != null)
{
if (!v1.Equals(v0))
{
modified = true;
break;
}
}
else if (v0 != null)
{
modified = true;
break;
}
}
}
if (modified)
{
if (renderModelName != modelOverride)
{
renderModelName = modelOverride;
SetModel(modelOverride);
}
values = new Hashtable();
foreach (var f in fields)
values[f] = f.GetValue(this);
}
return; // Do not update transforms (below) when not playing in Editor (to avoid keeping OpenVR running all the time).
}
#endif
// Update component transforms dynamically.
if (updateDynamically)
UpdateComponents(OpenVR.RenderModels);
}
Dictionary<int, string> nameCache;
public void UpdateComponents(CVRRenderModels renderModels)
{
if (renderModels == null)
return;
if (transform.childCount == 0)
return;
if (nameCache == null)
nameCache = new Dictionary<int, string>();
for (int childIndex = 0; childIndex < transform.childCount; childIndex++)
{
Transform child = transform.GetChild(childIndex);
// Cache names since accessing an object's name allocate memory.
string componentName;
if (!nameCache.TryGetValue(child.GetInstanceID(), out componentName))
{
componentName = child.name;
nameCache.Add(child.GetInstanceID(), componentName);
}
var componentState = new RenderModel_ComponentState_t();
if (!renderModels.GetComponentStateForDevicePath(renderModelName, componentName, SteamVR_Input_Source.GetHandle(inputSource), ref controllerModeState, ref componentState))
continue;
child.localPosition = SteamVR_Utils.GetPosition(componentState.mTrackingToComponentRenderModel);
child.localRotation = SteamVR_Utils.GetRotation(componentState.mTrackingToComponentRenderModel);
Transform attach = null;
for (int childChildIndex = 0; childChildIndex < child.childCount; childChildIndex++)
{
Transform childChild = child.GetChild(childChildIndex);
int childInstanceID = childChild.GetInstanceID();
string childName;
if (!nameCache.TryGetValue(childInstanceID, out childName))
{
childName = childChild.name;
nameCache.Add(childInstanceID, componentName);
}
if (childName == SteamVR_RenderModel.k_localTransformName)
attach = childChild;
}
if (attach != null)
{
attach.position = transform.TransformPoint(SteamVR_Utils.GetPosition(componentState.mTrackingToComponentLocal));
attach.rotation = transform.rotation * SteamVR_Utils.GetRotation(componentState.mTrackingToComponentLocal);
initializedAttachPoints = true;
}
bool visible = (componentState.uProperties & (uint)EVRComponentProperty.IsVisible) != 0;
if (visible != child.gameObject.activeSelf)
{
child.gameObject.SetActive(visible);
}
}
}
public void SetDeviceIndex(int newIndex)
{
this.index = (SteamVR_TrackedObject.EIndex)newIndex;
modelOverride = "";
if (enabled)
{
UpdateModel();
}
}
public void SetInputSource(SteamVR_Input_Sources newInputSource)
{
inputSource = newInputSource;
}
private static void Sleep()
{
#if !UNITY_METRO
//System.Threading.Thread.SpinWait(1); //faster napping
System.Threading.Thread.Sleep(1);
#endif
}
/// <summary>
/// Helper function to handle the inconvenient fact that the packing for RenderModel_t is
/// different on Linux/OSX (4) than it is on Windows (8)
/// </summary>
/// <param name="pRenderModel">native pointer to the RenderModel_t</param>
/// <returns></returns>
private RenderModel_t MarshalRenderModel(System.IntPtr pRenderModel)
{
if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
(System.Environment.OSVersion.Platform == System.PlatformID.Unix))
{
var packedModel = (RenderModel_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t_Packed));
RenderModel_t model = new RenderModel_t();
packedModel.Unpack(ref model);
return model;
}
else
{
return (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
}
}
/// <summary>
/// Helper function to handle the inconvenient fact that the packing for RenderModel_TextureMap_t is
/// different on Linux/OSX (4) than it is on Windows (8)
/// </summary>
/// <param name="pRenderModel">native pointer to the RenderModel_TextureMap_t</param>
/// <returns></returns>
private RenderModel_TextureMap_t MarshalRenderModel_TextureMap(System.IntPtr pRenderModel)
{
if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
(System.Environment.OSVersion.Platform == System.PlatformID.Unix))
{
var packedModel = (RenderModel_TextureMap_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t_Packed));
RenderModel_TextureMap_t model = new RenderModel_TextureMap_t();
packedModel.Unpack(ref model);
return model;
}
else
{
return (RenderModel_TextureMap_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t));
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class SessionOpenEventDecoder
{
public const ushort BLOCK_LENGTH = 36;
public const ushort TEMPLATE_ID = 21;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private SessionOpenEventDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public SessionOpenEventDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public SessionOpenEventDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdId()
{
return 1;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int ClusterSessionIdId()
{
return 3;
}
public static int ClusterSessionIdSinceVersion()
{
return 0;
}
public static int ClusterSessionIdEncodingOffset()
{
return 16;
}
public static int ClusterSessionIdEncodingLength()
{
return 8;
}
public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ClusterSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ClusterSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ClusterSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ClusterSessionId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int TimestampId()
{
return 4;
}
public static int TimestampSinceVersion()
{
return 0;
}
public static int TimestampEncodingOffset()
{
return 24;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static string TimestampMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public long Timestamp()
{
return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian);
}
public static int ResponseStreamIdId()
{
return 6;
}
public static int ResponseStreamIdSinceVersion()
{
return 0;
}
public static int ResponseStreamIdEncodingOffset()
{
return 32;
}
public static int ResponseStreamIdEncodingLength()
{
return 4;
}
public static string ResponseStreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseStreamIdNullValue()
{
return -2147483648;
}
public static int ResponseStreamIdMinValue()
{
return -2147483647;
}
public static int ResponseStreamIdMaxValue()
{
return 2147483647;
}
public int ResponseStreamId()
{
return _buffer.GetInt(_offset + 32, ByteOrder.LittleEndian);
}
public static int ResponseChannelId()
{
return 7;
}
public static int ResponseChannelSinceVersion()
{
return 0;
}
public static string ResponseChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ResponseChannelHeaderLength()
{
return 4;
}
public int ResponseChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetResponseChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetResponseChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string ResponseChannel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public static int EncodedPrincipalId()
{
return 8;
}
public static int EncodedPrincipalSinceVersion()
{
return 0;
}
public static string EncodedPrincipalMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int EncodedPrincipalHeaderLength()
{
return 4;
}
public int EncodedPrincipalLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetEncodedPrincipal(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetEncodedPrincipal(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[SessionOpenEvent](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ClusterSessionId=");
builder.Append(ClusterSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timestamp', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Timestamp=");
builder.Append(Timestamp());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='responseStreamId', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=32, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ResponseStreamId=");
builder.Append(ResponseStreamId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='responseChannel', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=36, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ResponseChannel=");
builder.Append(ResponseChannel());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='encodedPrincipal', referencedName='null', description='null', id=8, version=0, deprecated=0, encodedLength=0, offset=-1, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("EncodedPrincipal=");
builder.Append(EncodedPrincipalLength() + " raw bytes");
Limit(originalLimit);
return builder;
}
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using FluentMigrator.Builders.Create.Table;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.SqlServer;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.SqlServer2000
{
[TestFixture]
public class SqlServer2000TableTests : BaseTableTests
{
protected SqlServer2000Generator Generator;
[SetUp]
public void Setup()
{
Generator = new SqlServer2000Generator();
}
[Test]
public void CanCreateTableWithIgnoredRowGuidCol()
{
var expression = new CreateTableExpression()
{
TableName = "TestTable1",
};
var serviceProvider = new ServiceCollection().BuildServiceProvider();
var querySchema = new Mock<IQuerySchema>();
new CreateTableExpressionBuilder(expression, new MigrationContext(querySchema.Object, serviceProvider, null, null))
.WithColumn("Id").AsGuid().PrimaryKey().RowGuid();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([Id] UNIQUEIDENTIFIER NOT NULL, PRIMARY KEY ([Id]))");
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "[timestamp]";
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] [timestamp] NOT NULL, PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanCreateTableWithCustomColumnTypeWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "[timestamp]";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] [timestamp] NOT NULL, PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanCreateTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL CONSTRAINT [DF_TestTable1_TestColumn1] DEFAULT NULL, [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueExplicitlySetToNullWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL CONSTRAINT [DF_TestTable1_TestColumn1] DEFAULT NULL, [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL CONSTRAINT [DF_TestTable1_TestColumn1] DEFAULT N'Default', [TestColumn2] INT NOT NULL CONSTRAINT [DF_TestTable1_TestColumn2] DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithDefaultValueWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL CONSTRAINT [DF_TestTable1_TestColumn1] DEFAULT N'Default', [TestColumn2] INT NOT NULL CONSTRAINT [DF_TestTable1_TestColumn2] DEFAULT 0)");
}
[Test]
public override void CanCreateTableWithIdentityWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] INT NOT NULL IDENTITY(1,1), [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithIdentityWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] INT NOT NULL IDENTITY(1,1), [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, PRIMARY KEY ([TestColumn1], [TestColumn2]))");
}
[Test]
public override void CanCreateTableWithMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, PRIMARY KEY ([TestColumn1], [TestColumn2]))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, CONSTRAINT [TestKey] PRIMARY KEY ([TestColumn1], [TestColumn2]))");
}
[Test]
public override void CanCreateTableWithNamedMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, CONSTRAINT [TestKey] PRIMARY KEY ([TestColumn1], [TestColumn2]))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, CONSTRAINT [TestKey] PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanCreateTableWithNamedPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, CONSTRAINT [TestKey] PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanCreateTableWithNullableFieldWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsNullable = true;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255), [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithNullableFieldWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsNullable = true;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255), [TestColumn2] INT NOT NULL)");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanCreateTableWithPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE [TestTable1] ([TestColumn1] NVARCHAR(255) NOT NULL, [TestColumn2] INT NOT NULL, PRIMARY KEY ([TestColumn1]))");
}
[Test]
public override void CanDropTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE [TestTable1]");
}
[Test]
public override void CanDropTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("DROP TABLE [TestTable1]");
}
[Test]
public override void CanRenameTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("sp_rename N'[TestTable1]', N'TestTable2'");
}
[Test]
public override void CanRenameTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetRenameTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("sp_rename N'[TestTable1]', N'TestTable2'");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.