context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace System.Net.NetworkInformation
{
internal class SystemNetworkInterface : NetworkInterface
{
private readonly string _name;
private readonly string _id;
private readonly string _description;
private readonly byte[] _physicalAddress;
private readonly uint _addressLength;
private readonly NetworkInterfaceType _type;
private readonly OperationalStatus _operStatus;
private readonly long _speed;
// Any interface can have two completely different valid indexes for ipv4 and ipv6.
private readonly uint _index = 0;
private readonly uint _ipv6Index = 0;
private readonly Interop.IpHlpApi.AdapterFlags _adapterFlags;
private readonly SystemIPInterfaceProperties _interfaceProperties = null;
internal static int InternalLoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.Loopback);
}
}
internal static int InternalIPv6LoopbackInterfaceIndex
{
get
{
return GetBestInterfaceForAddress(IPAddress.IPv6Loopback);
}
}
private static int GetBestInterfaceForAddress(IPAddress addr)
{
int index;
Internals.SocketAddress address = new Internals.SocketAddress(addr);
int error = (int)Interop.IpHlpApi.GetBestInterfaceEx(address.Buffer, out index);
if (error != 0)
{
throw new NetworkInformationException(error);
}
return index;
}
internal static bool InternalGetIsNetworkAvailable()
{
try
{
NetworkInterface[] networkInterfaces = GetNetworkInterfaces();
foreach (NetworkInterface netInterface in networkInterfaces)
{
if (netInterface.OperationalStatus == OperationalStatus.Up && netInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel
&& netInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
return true;
}
}
}
catch (NetworkInformationException nie)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "SystemNetworkInterface", "InternalGetIsNetworkAvailable", nie);
}
}
return false;
}
internal static NetworkInterface[] GetNetworkInterfaces()
{
Contract.Ensures(Contract.Result<NetworkInterface[]>() != null);
AddressFamily family = AddressFamily.Unspecified;
uint bufferSize = 0;
SafeLocalAllocHandle buffer = null;
// TODO: #2485: This will probably require changes in the PAL for HostInformation.
Interop.IpHlpApi.FIXED_INFO fixedInfo = HostInformationPal.GetFixedInfo();
List<SystemNetworkInterface> interfaceList = new List<SystemNetworkInterface>();
Interop.IpHlpApi.GetAdaptersAddressesFlags flags =
Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeGateways
| Interop.IpHlpApi.GetAdaptersAddressesFlags.IncludeWins;
// Figure out the right buffer size for the adapter information.
uint result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, SafeLocalAllocHandle.Zero, ref bufferSize);
while (result == Interop.IpHlpApi.ERROR_BUFFER_OVERFLOW)
{
// Allocate the buffer and get the adapter info.
using (buffer = SafeLocalAllocHandle.LocalAlloc((int)bufferSize))
{
result = Interop.IpHlpApi.GetAdaptersAddresses(
family, (uint)flags, IntPtr.Zero, buffer, ref bufferSize);
// If succeeded, we're going to add each new interface.
if (result == Interop.IpHlpApi.ERROR_SUCCESS)
{
// Linked list of interfaces.
IntPtr ptr = buffer.DangerousGetHandle();
while (ptr != IntPtr.Zero)
{
// Traverse the list, marshal in the native structures, and create new NetworkInterfaces.
Interop.IpHlpApi.IpAdapterAddresses adapterAddresses = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterAddresses>(ptr);
interfaceList.Add(new SystemNetworkInterface(fixedInfo, adapterAddresses));
ptr = adapterAddresses.next;
}
}
}
}
// If we don't have any interfaces detected, return empty.
if (result == Interop.IpHlpApi.ERROR_NO_DATA || result == Interop.IpHlpApi.ERROR_INVALID_PARAMETER)
{
return new SystemNetworkInterface[0];
}
// Otherwise we throw on an error.
if (result != Interop.IpHlpApi.ERROR_SUCCESS)
{
throw new NetworkInformationException((int)result);
}
return interfaceList.ToArray();
}
internal SystemNetworkInterface(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses)
{
// Store the common API information.
_id = ipAdapterAddresses.AdapterName;
_name = ipAdapterAddresses.friendlyName;
_description = ipAdapterAddresses.description;
_index = ipAdapterAddresses.index;
_physicalAddress = ipAdapterAddresses.address;
_addressLength = ipAdapterAddresses.addressLength;
_type = ipAdapterAddresses.type;
_operStatus = ipAdapterAddresses.operStatus;
_speed = (long)ipAdapterAddresses.receiveLinkSpeed;
// API specific info.
_ipv6Index = ipAdapterAddresses.ipv6Index;
_adapterFlags = ipAdapterAddresses.flags;
_interfaceProperties = new SystemIPInterfaceProperties(fixedInfo, ipAdapterAddresses);
}
public override string Id { get { return _id; } }
public override string Name { get { return _name; } }
public override string Description { get { return _description; } }
public override PhysicalAddress GetPhysicalAddress()
{
byte[] newAddr = new byte[_addressLength];
// Array.Copy only supports int and long while addressLength is uint (see IpAdapterAddresses).
// Will throw OverflowException if addressLength > Int32.MaxValue.
Array.Copy(_physicalAddress, 0, newAddr, 0, checked((int)_addressLength));
return new PhysicalAddress(newAddr);
}
public override NetworkInterfaceType NetworkInterfaceType { get { return _type; } }
public override IPInterfaceProperties GetIPProperties()
{
return _interfaceProperties;
}
public override IPInterfaceStatistics GetIPStatistics()
{
return new SystemIPInterfaceStatistics(_index);
}
public override bool Supports(NetworkInterfaceComponent networkInterfaceComponent)
{
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv6
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0))
{
return true;
}
if (networkInterfaceComponent == NetworkInterfaceComponent.IPv4
&& ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0))
{
return true;
}
return false;
}
// We cache this to be consistent across all platforms.
public override OperationalStatus OperationalStatus
{
get
{
return _operStatus;
}
}
public override long Speed
{
get
{
return _speed;
}
}
public override bool IsReceiveOnly
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.ReceiveOnly) > 0);
}
}
/// <summary>The interface doesn't allow multicast.</summary>
public override bool SupportsMulticast
{
get
{
return ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.NoMulticast) == 0);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace Microsoft.Framework.WebEncoders
{
public class HtmlEncoderTests
{
[Fact]
public void TestSurrogate()
{
Assert.Equal("💩", System.Text.Encodings.Web.HtmlEncoder.Default.Encode("\U0001f4a9"));
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.HtmlEncoder.Default.Encode(writer, "\U0001f4a9");
Assert.Equal("💩", writer.GetStringBuilder().ToString());
}
}
[Fact]
public void Ctor_WithTextEncoderSettings()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
HtmlEncoder encoder = new HtmlEncoder(filter);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("b", encoder.HtmlEncode("b"));
Assert.Equal("c", encoder.HtmlEncode("c"));
Assert.Equal("d", encoder.HtmlEncode("d"));
Assert.Equal("�", encoder.HtmlEncode("\0")); // we still always encode control chars
Assert.Equal("&", encoder.HtmlEncode("&")); // we still always encode HTML-special chars
Assert.Equal("", encoder.HtmlEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("\u00E9", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Ctor_WithNoParameters_DefaultsToBasicLatin()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("é", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("☁", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Default_EquivalentToBasicLatin()
{
// Arrange
HtmlEncoder controlEncoder = new HtmlEncoder(UnicodeRanges.BasicLatin);
HtmlEncoder testEncoder = HtmlEncoder.Default;
// Act & assert
for (int i = 0; i <= char.MaxValue; i++)
{
if (!IsSurrogateCodePoint(i))
{
string input = new string((char)i, 1);
Assert.Equal(controlEncoder.HtmlEncode(input), testEncoder.HtmlEncode(input));
}
}
}
[Theory]
[InlineData("<", "<")]
[InlineData(">", ">")]
[InlineData("&", "&")]
[InlineData("'", "'")]
[InlineData("\"", """)]
[InlineData("+", "+")]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new string((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
if (input == "<") { expected = "<"; }
else if (input == ">") { expected = ">"; }
else if (input == "&") { expected = "&"; }
else if (input == "\"") { expected = """; }
else
{
bool mustEncode = false;
if (i == '\'' || i == '+')
{
mustEncode = true; // apostrophe, plus
}
else if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
}
else
{
expected = input; // no encoding
}
}
}
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = char.ConvertFromUtf32(i);
string expected = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void HtmlEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD𐏿e\uFFFD";
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("", encoder.HtmlEncode(""));
}
[Fact]
public void HtmlEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.HtmlEncode(input));
}
[Fact]
public void HtmlEncode_NullInput_Throws()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
Assert.Throws<ArgumentNullException>(() => { encoder.HtmlEncode(null); });
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal("&Hello, there!", new HtmlEncoder().HtmlEncode("&Hello, there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal("Hello, there!&", new HtmlEncoder().HtmlEncode("Hello, there!&"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal("Hello, &there!", new HtmlEncoder().HtmlEncode("Hello, &there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal("Hello, <there>!", new HtmlEncoder().HtmlEncode("Hello, <there>!"));
}
[Fact]
public void HtmlEncode_CharArray()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!".ToCharArray(), 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
[Fact]
public void HtmlEncode_StringSubstring()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!", 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
[Fact]
public void HtmlEncode_AstralWithTextWriter()
{
byte[] buffer = new byte[10];
MemoryStream ms = new MemoryStream(buffer);
using (StreamWriter sw = new StreamWriter(ms))
{
string input = "\U0010FFFF";
System.Text.Encodings.Web.HtmlEncoder.Default.Encode(sw, input);
}
Assert.Equal("", System.Text.Encoding.UTF8.GetString(buffer));
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
}
}
| |
using System;
using System.Security.Cryptography;
namespace Foundation.Services.Security
{
public class PasswordGenerator
{
const int defaultMaximumPasswordLength = 12;
const int defaultMinimumPasswordLength = 8;
public PasswordGenerator()
{
LowercaseCharacters = "abcdefgijkmnopqrstwxyz";
NumericCharacters = "23456789";
UppercaseCharacters = "ABCDEFGHJKLMNPQRSTWXYZ";
MinimumPasswordLength = defaultMinimumPasswordLength;
MaximumPasswordLength = defaultMaximumPasswordLength;
}
/// <summary>
/// Lower-case characters to use when generating passwords
/// </summary>
public string LowercaseCharacters { get; set; }
/// <summary>
/// Numeric characters to use when generating passwords
/// </summary>
public string NumericCharacters { get; set; }
/// <summary>
/// Upper-case characters to use when generating passwords
/// </summary>
public string UppercaseCharacters { get; set; }
/// <summary>
/// The maximum length for generated passwords
/// </summary>
public int? MaximumPasswordLength { get; set; }
/// <summary>
/// The minimum length for generated passwords
/// </summary>
public int? MinimumPasswordLength { get; set; }
/// <summary>
/// Generates a random password of a random length using generator defaults
/// </summary>
/// <returns></returns>
public string Generate()
{
return Generate(MinimumPasswordLength ?? defaultMinimumPasswordLength,
MaximumPasswordLength ?? defaultMaximumPasswordLength);
}
/// <summary>
/// Generates a random password of the specified length
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password or a random length within the specified range
/// </summary>
/// <param name="minLength"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public string Generate(int minLength, int maxLength)
{
// Make sure that input parameters are valid.
ThrowException.IfTrue(minLength <= 0, "The minimum password length must be at least 1");
ThrowException.IfTrue(maxLength <= 0, "The maximum password length must be at least 1");
ThrowException.IfFalse(maxLength >= minLength,
"The minimum password length can't be more than the maximum password length");
// Create a local array containing supported password characters
// grouped by types.
var charGroups = new[]
{
LowercaseCharacters.ToCharArray(), UppercaseCharacters.ToCharArray(),
NumericCharacters.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
var charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for( var i = 0; i < charsLeftInGroup.Length; i++ )
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
var leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for( var i = 0; i < leftGroupsOrder.Length; i++ )
leftGroupsOrder[i] = i;
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
var randomBytes = new byte[4];
// Generate 4 random bytes.
using( var rng = new RNGCryptoServiceProvider() )
{
rng.GetBytes(randomBytes);
}
// Convert 4 bytes into a 32-bit integer value.
var seed = (randomBytes[0] & 0x7f) << 24 | randomBytes[1] << 16 | randomBytes[2] << 8 |
randomBytes[3];
// Now, this is real randomization.
var random = new Random(seed);
// This array will hold password characters.
char[] password;
// Allocate appropriate memory for the password.
if( minLength < maxLength )
{
password = new char[random.Next(minLength, maxLength + 1)];
}
else
{
password = new char[minLength];
}
// Index of the next character to be added to password.
int nextCharIdx;
// Index of the next character group to be processed.
int nextGroupIdx;
// Index which will be used to track not processed character groups.
int nextLeftGroupsOrderIdx;
// Index of the last non-processed character in a group.
int lastCharIdx;
// Index of the last non-processed group. Initially, we will skip
// special characters.
var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for( var i = 0; i < password.Length; i++ )
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list.
if( lastLeftGroupsOrderIdx == 0 )
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0, lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
if( lastCharIdx == 0 )
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if( lastCharIdx == 0 )
charsLeftInGroup[nextGroupIdx] = charGroups[nextGroupIdx].Length;
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if( lastCharIdx != nextCharIdx )
{
var temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] = charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if( lastLeftGroupsOrderIdx == 0 )
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if( lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx )
{
var temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] = leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
}
}
| |
using J2N.Threading;
using J2N.Threading.Atomic;
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using FakeIOException = Lucene.Net.Store.FakeIOException;
using Field = Field;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using InfoStream = Lucene.Net.Util.InfoStream;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using Query = Lucene.Net.Search.Query;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
using TopDocs = Lucene.Net.Search.TopDocs;
[TestFixture]
[Deadlock]
public class TestIndexWriterReader : LuceneTestCase
{
private readonly int numThreads = TestNightly ? 5 : 3;
public static int Count(Term t, IndexReader r)
{
int count = 0;
DocsEnum td = TestUtil.Docs(Random, r, t.Field, new BytesRef(t.Text()), MultiFields.GetLiveDocs(r), null, 0);
if (td != null)
{
while (td.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
var _ = td.DocID;
count++;
}
}
return count;
}
#if FEATURE_INDEXWRITER_TESTS
[Test]
public virtual void TestAddCloseOpen()
{
// Can't use assertNoDeletes: this test pulls a non-NRT
// reader in the end:
Directory dir1 = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
IndexWriter writer = new IndexWriter(dir1, iwc);
for (int i = 0; i < 97; i++)
{
DirectoryReader reader = writer.GetReader();
if (i == 0)
{
writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random.Next(5)));
}
else
{
int previous = Random.Next(i);
// a check if the reader is current here could fail since there might be
// merges going on.
switch (Random.Next(5))
{
case 0:
case 1:
case 2:
writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random.Next(5)));
break;
case 3:
writer.UpdateDocument(new Term("id", "" + previous), DocHelper.CreateDocument(previous, "x", 1 + Random.Next(5)));
break;
case 4:
writer.DeleteDocuments(new Term("id", "" + previous));
break;
}
}
Assert.IsFalse(reader.IsCurrent());
reader.Dispose();
}
writer.ForceMerge(1); // make sure all merging is done etc.
DirectoryReader dirReader = writer.GetReader();
writer.Commit(); // no changes that are not visible to the reader
Assert.IsTrue(dirReader.IsCurrent());
writer.Dispose();
Assert.IsTrue(dirReader.IsCurrent()); // all changes are visible to the reader
iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
writer = new IndexWriter(dir1, iwc);
Assert.IsTrue(dirReader.IsCurrent());
writer.AddDocument(DocHelper.CreateDocument(1, "x", 1 + Random.Next(5)));
Assert.IsTrue(dirReader.IsCurrent()); // segments in ram but IW is different to the readers one
writer.Dispose();
Assert.IsFalse(dirReader.IsCurrent()); // segments written
dirReader.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestUpdateDocument()
{
bool doFullMerge = true;
Directory dir1 = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random.NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
if (Verbose)
{
Console.WriteLine("TEST: make index");
}
IndexWriter writer = new IndexWriter(dir1, iwc);
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
// writer.Flush(false, true, true);
// get a reader
DirectoryReader r1 = writer.GetReader();
Assert.IsTrue(r1.IsCurrent());
string id10 = r1.Document(10).GetField("id").GetStringValue();
Document newDoc = r1.Document(10);
newDoc.RemoveField("id");
newDoc.Add(NewStringField("id", Convert.ToString(8000), Field.Store.YES));
writer.UpdateDocument(new Term("id", id10), newDoc);
Assert.IsFalse(r1.IsCurrent());
DirectoryReader r2 = writer.GetReader();
Assert.IsTrue(r2.IsCurrent());
Assert.AreEqual(0, Count(new Term("id", id10), r2));
if (Verbose)
{
Console.WriteLine("TEST: verify id");
}
Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r2));
r1.Dispose();
Assert.IsTrue(r2.IsCurrent());
writer.Dispose();
Assert.IsTrue(r2.IsCurrent());
DirectoryReader r3 = DirectoryReader.Open(dir1);
Assert.IsTrue(r3.IsCurrent());
Assert.IsTrue(r2.IsCurrent());
Assert.AreEqual(0, Count(new Term("id", id10), r3));
Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r3));
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
writer.AddDocument(doc);
Assert.IsTrue(r2.IsCurrent());
Assert.IsTrue(r3.IsCurrent());
writer.Dispose();
Assert.IsFalse(r2.IsCurrent());
Assert.IsTrue(!r3.IsCurrent());
r2.Dispose();
r3.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestIsCurrent()
{
Directory dir = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
IndexWriter writer = new IndexWriter(dir, iwc);
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
writer.AddDocument(doc);
writer.Dispose();
iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
writer = new IndexWriter(dir, iwc);
doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
DirectoryReader nrtReader = writer.GetReader();
Assert.IsTrue(nrtReader.IsCurrent());
writer.AddDocument(doc);
Assert.IsFalse(nrtReader.IsCurrent()); // should see the changes
writer.ForceMerge(1); // make sure we don't have a merge going on
Assert.IsFalse(nrtReader.IsCurrent());
nrtReader.Dispose();
DirectoryReader dirReader = DirectoryReader.Open(dir);
nrtReader = writer.GetReader();
Assert.IsTrue(dirReader.IsCurrent());
Assert.IsTrue(nrtReader.IsCurrent()); // nothing was committed yet so we are still current
Assert.AreEqual(2, nrtReader.MaxDoc); // sees the actual document added
Assert.AreEqual(1, dirReader.MaxDoc);
writer.Dispose(); // close is actually a commit both should see the changes
Assert.IsTrue(nrtReader.IsCurrent());
Assert.IsFalse(dirReader.IsCurrent()); // this reader has been opened before the writer was closed / committed
dirReader.Dispose();
nrtReader.Dispose();
dir.Dispose();
}
/// <summary>
/// Test using IW.addIndexes
/// </summary>
[Test]
public virtual void TestAddIndexes()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random.NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
IndexWriter writer = new IndexWriter(dir1, iwc);
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Flush(false, true);
// create a 2nd index
Directory dir2 = NewDirectory();
IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
CreateIndexNoClose(!doFullMerge, "index2", writer2);
writer2.Dispose();
DirectoryReader r0 = writer.GetReader();
Assert.IsTrue(r0.IsCurrent());
writer.AddIndexes(dir2);
Assert.IsFalse(r0.IsCurrent());
r0.Dispose();
DirectoryReader r1 = writer.GetReader();
Assert.IsTrue(r1.IsCurrent());
writer.Commit();
Assert.IsTrue(r1.IsCurrent()); // we have seen all changes - no change after opening the NRT reader
Assert.AreEqual(200, r1.MaxDoc);
int index2df = r1.DocFreq(new Term("indexname", "index2"));
Assert.AreEqual(100, index2df);
// verify the docs are from different indexes
Document doc5 = r1.Document(5);
Assert.AreEqual("index1", doc5.Get("indexname"));
Document doc150 = r1.Document(150);
Assert.AreEqual("index2", doc150.Get("indexname"));
r1.Dispose();
writer.Dispose();
dir1.Dispose();
dir2.Dispose();
}
[Test]
public virtual void ExposeCompTermVR()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random.NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
IndexWriter writer = new IndexWriter(dir1, iwc);
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestAddIndexes2()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
// create a 2nd index
Directory dir2 = NewDirectory();
IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
CreateIndexNoClose(!doFullMerge, "index2", writer2);
writer2.Dispose();
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
IndexReader r1 = writer.GetReader();
Assert.AreEqual(500, r1.MaxDoc);
r1.Dispose();
writer.Dispose();
dir1.Dispose();
dir2.Dispose();
}
/// <summary>
/// Deletes using IW.deleteDocuments
/// </summary>
[Test]
public virtual void TestDeleteFromIndexWriter()
{
bool doFullMerge = true;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetReaderTermsIndexDivisor(2));
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Flush(false, true);
// get a reader
IndexReader r1 = writer.GetReader();
string id10 = r1.Document(10).GetField("id").GetStringValue();
// deleted IW docs should not show up in the next getReader
writer.DeleteDocuments(new Term("id", id10));
IndexReader r2 = writer.GetReader();
Assert.AreEqual(1, Count(new Term("id", id10), r1));
Assert.AreEqual(0, Count(new Term("id", id10), r2));
string id50 = r1.Document(50).GetField("id").GetStringValue();
Assert.AreEqual(1, Count(new Term("id", id50), r1));
writer.DeleteDocuments(new Term("id", id50));
IndexReader r3 = writer.GetReader();
Assert.AreEqual(0, Count(new Term("id", id10), r3));
Assert.AreEqual(0, Count(new Term("id", id50), r3));
string id75 = r1.Document(75).GetField("id").GetStringValue();
writer.DeleteDocuments(new TermQuery(new Term("id", id75)));
IndexReader r4 = writer.GetReader();
Assert.AreEqual(1, Count(new Term("id", id75), r3));
Assert.AreEqual(0, Count(new Term("id", id75), r4));
r1.Dispose();
r2.Dispose();
r3.Dispose();
r4.Dispose();
writer.Dispose();
// reopen the writer to verify the delete made it to the directory
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
IndexReader w2r1 = writer.GetReader();
Assert.AreEqual(0, Count(new Term("id", id10), w2r1));
w2r1.Dispose();
writer.Dispose();
dir1.Dispose();
}
[Test]
[Slow]
public virtual void TestAddIndexesAndDoDeletesThreads()
{
const int numIter = 2;
int numDirs = 3;
Directory mainDir = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter mainWriter = new IndexWriter(mainDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
TestUtil.ReduceOpenFiles(mainWriter);
AddDirectoriesThreads addDirThreads = new AddDirectoriesThreads(this, numIter, mainWriter);
addDirThreads.LaunchThreads(numDirs);
addDirThreads.JoinThreads();
//Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads
// * addDirThreads.NUM_INIT_DOCS, addDirThreads.mainWriter.NumDocs);
Assert.AreEqual(addDirThreads.count, addDirThreads.mainWriter.NumDocs);
addDirThreads.Close(true);
Assert.IsTrue(addDirThreads.failures.Count == 0);
TestUtil.CheckIndex(mainDir);
IndexReader reader = DirectoryReader.Open(mainDir);
Assert.AreEqual(addDirThreads.count, reader.NumDocs);
//Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads
// * addDirThreads.NUM_INIT_DOCS, reader.NumDocs);
reader.Dispose();
addDirThreads.CloseDir();
mainDir.Dispose();
}
private class AddDirectoriesThreads
{
private readonly TestIndexWriterReader outerInstance;
internal Directory addDir;
internal const int NUM_INIT_DOCS = 100;
internal int numDirs;
internal ThreadJob[] threads;
internal IndexWriter mainWriter;
internal readonly IList<Exception> failures = new List<Exception>();
internal IndexReader[] readers;
internal bool didClose = false;
internal AtomicInt32 count = new AtomicInt32(0);
internal AtomicInt32 numaddIndexes = new AtomicInt32(0);
public AddDirectoriesThreads(TestIndexWriterReader outerInstance, int numDirs, IndexWriter mainWriter)
{
this.outerInstance = outerInstance;
threads = new ThreadJob[outerInstance.numThreads];
this.numDirs = numDirs;
this.mainWriter = mainWriter;
addDir = NewDirectory();
IndexWriter writer = new IndexWriter(addDir, NewIndexWriterConfig(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
outerInstance,
#endif
TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2));
TestUtil.ReduceOpenFiles(writer);
for (int i = 0; i < NUM_INIT_DOCS; i++)
{
Document doc = DocHelper.CreateDocument(i, "addindex", 4);
writer.AddDocument(doc);
}
writer.Dispose();
readers = new IndexReader[numDirs];
for (int i = 0; i < numDirs; i++)
{
readers[i] = DirectoryReader.Open(addDir);
}
}
internal virtual void JoinThreads()
{
for (int i = 0; i < outerInstance.numThreads; i++)
{
//#if FEATURE_THREAD_INTERRUPT
// try
// {
//#endif
threads[i].Join();
//#if FEATURE_THREAD_INTERRUPT
// }
// catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// {
// throw new ThreadInterruptedException("Thread Interrupted Exception", ie);
// }
//#endif
}
}
internal virtual void Close(bool doWait)
{
didClose = true;
if (doWait)
{
mainWriter.WaitForMerges();
}
mainWriter.Dispose(doWait);
}
internal virtual void CloseDir()
{
for (int i = 0; i < numDirs; i++)
{
readers[i].Dispose();
}
addDir.Dispose();
}
internal virtual void Handle(Exception t)
{
Console.WriteLine(t.StackTrace);
lock (failures)
{
failures.Add(t);
}
}
internal virtual void LaunchThreads(int numIter)
{
for (int i = 0; i < outerInstance.numThreads; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper(this, numIter);
}
for (int i = 0; i < outerInstance.numThreads; i++)
{
threads[i].Start();
}
}
private class ThreadAnonymousInnerClassHelper : ThreadJob
{
private readonly AddDirectoriesThreads outerInstance;
private readonly int numIter;
public ThreadAnonymousInnerClassHelper(AddDirectoriesThreads outerInstance, int numIter)
{
this.outerInstance = outerInstance;
this.numIter = numIter;
}
public override void Run()
{
try
{
Directory[] dirs = new Directory[outerInstance.numDirs];
for (int k = 0; k < outerInstance.numDirs; k++)
{
dirs[k] = new MockDirectoryWrapper(Random, new RAMDirectory(outerInstance.addDir, NewIOContext(Random)));
}
//int j = 0;
//while (true) {
// System.out.println(Thread.currentThread().getName() + ": iter
// j=" + j);
for (int x = 0; x < numIter; x++)
{
// only do addIndexes
outerInstance.DoBody(x, dirs);
}
//if (numIter > 0 && j == numIter)
// break;
//doBody(j++, dirs);
//doBody(5, dirs);
//}
}
catch (Exception t)
{
outerInstance.Handle(t);
}
}
}
internal virtual void DoBody(int j, Directory[] dirs)
{
switch (j % 4)
{
case 0:
mainWriter.AddIndexes(dirs);
mainWriter.ForceMerge(1);
break;
case 1:
mainWriter.AddIndexes(dirs);
numaddIndexes.IncrementAndGet();
break;
case 2:
mainWriter.AddIndexes(readers);
break;
case 3:
mainWriter.Commit();
break;
}
count.AddAndGet(dirs.Length * NUM_INIT_DOCS);
}
}
[Test]
public virtual void TestIndexWriterReopenSegmentFullMerge()
{
DoTestIndexWriterReopenSegment(true);
}
[Test]
public virtual void TestIndexWriterReopenSegment()
{
DoTestIndexWriterReopenSegment(false);
}
/// <summary>
/// Tests creating a segment, then check to insure the segment can be seen via
/// IW.getReader
/// </summary>
public virtual void DoTestIndexWriterReopenSegment(bool doFullMerge)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
IndexReader r1 = writer.GetReader();
Assert.AreEqual(0, r1.MaxDoc);
CreateIndexNoClose(false, "index1", writer);
writer.Flush(!doFullMerge, true);
IndexReader iwr1 = writer.GetReader();
Assert.AreEqual(100, iwr1.MaxDoc);
IndexReader r2 = writer.GetReader();
Assert.AreEqual(r2.MaxDoc, 100);
// add 100 documents
for (int x = 10000; x < 10000 + 100; x++)
{
Document d = DocHelper.CreateDocument(x, "index1", 5);
writer.AddDocument(d);
}
writer.Flush(false, true);
// verify the reader was reopened internally
IndexReader iwr2 = writer.GetReader();
Assert.IsTrue(iwr2 != r1);
Assert.AreEqual(200, iwr2.MaxDoc);
// should have flushed out a segment
IndexReader r3 = writer.GetReader();
Assert.IsTrue(r2 != r3);
Assert.AreEqual(200, r3.MaxDoc);
// dec ref the readers rather than close them because
// closing flushes changes to the writer
r1.Dispose();
iwr1.Dispose();
r2.Dispose();
r3.Dispose();
iwr2.Dispose();
writer.Dispose();
// test whether the changes made it to the directory
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
IndexReader w2r1 = writer.GetReader();
// insure the deletes were actually flushed to the directory
Assert.AreEqual(200, w2r1.MaxDoc);
w2r1.Dispose();
writer.Dispose();
dir1.Dispose();
}
#endif
/*
* Delete a document by term and return the doc id
*
* public static int deleteDocument(Term term, IndexWriter writer) throws
* IOException { IndexReader reader = writer.GetReader(); TermDocs td =
* reader.termDocs(term); int doc = -1; //if (td.Next()) { // doc = td.Doc();
* //} //writer.DeleteDocuments(term); td.Dispose(); return doc; }
*/
public void CreateIndex(Random random, Directory dir1, string indexName, bool multiSegment)
{
IndexWriter w = new IndexWriter(dir1, NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 100; i++)
{
w.AddDocument(DocHelper.CreateDocument(i, indexName, 4));
}
if (!multiSegment)
{
w.ForceMerge(1);
}
w.Dispose();
}
public static void CreateIndexNoClose(bool multiSegment, string indexName, IndexWriter w)
{
for (int i = 0; i < 100; i++)
{
w.AddDocument(DocHelper.CreateDocument(i, indexName, 4));
}
if (!multiSegment)
{
w.ForceMerge(1);
}
}
#if FEATURE_INDEXWRITER_TESTS
private class MyWarmer : IndexWriter.IndexReaderWarmer
{
internal int warmCount;
public override void Warm(AtomicReader reader)
{
warmCount++;
}
}
[Test]
[Slow]
public virtual void TestMergeWarmer([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
// Enroll warmer
MyWarmer warmer = new MyWarmer();
var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))
.SetMaxBufferedDocs(2)
.SetMergedSegmentWarmer(warmer)
.SetMergeScheduler(newScheduler())
.SetMergePolicy(NewLogMergePolicy());
IndexWriter writer = new IndexWriter(dir1, config);
// create the index
CreateIndexNoClose(false, "test", writer);
// get a reader to put writer into near real-time mode
IndexReader r1 = writer.GetReader();
((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 2;
//int num = AtLeast(100);
int num = 101;
for (int i = 0; i < num; i++)
{
writer.AddDocument(DocHelper.CreateDocument(i, "test", 4));
}
((IConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync();
Assert.IsTrue(warmer.warmCount > 0);
Console.WriteLine("Count {0}", warmer.warmCount);
int count = warmer.warmCount;
var newDocument = DocHelper.CreateDocument(17, "test", 4);
writer.AddDocument(newDocument);
writer.ForceMerge(1);
Assert.IsTrue(warmer.warmCount > count);
writer.Dispose();
r1.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestAfterCommit([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergeScheduler(newScheduler());
IndexWriter writer = new IndexWriter(dir1, config);
writer.Commit();
// create the index
CreateIndexNoClose(false, "test", writer);
// get a reader to put writer into near real-time mode
DirectoryReader r1 = writer.GetReader();
TestUtil.CheckIndex(dir1);
writer.Commit();
TestUtil.CheckIndex(dir1);
Assert.AreEqual(100, r1.NumDocs);
for (int i = 0; i < 10; i++)
{
writer.AddDocument(DocHelper.CreateDocument(i, "test", 4));
}
((IConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync();
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r1);
if (r2 != null)
{
r1.Dispose();
r1 = r2;
}
Assert.AreEqual(110, r1.NumDocs);
writer.Dispose();
r1.Dispose();
dir1.Dispose();
}
// Make sure reader remains usable even if IndexWriter closes
[Test]
public virtual void TestAfterClose()
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
// create the index
CreateIndexNoClose(false, "test", writer);
DirectoryReader r = writer.GetReader();
writer.Dispose();
TestUtil.CheckIndex(dir1);
// reader should remain usable even after IndexWriter is closed:
Assert.AreEqual(100, r.NumDocs);
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
Assert.AreEqual(100, searcher.Search(q, 10).TotalHits);
try
{
DirectoryReader.OpenIfChanged(r);
Assert.Fail("failed to hit ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ace)
#pragma warning restore 168
{
// expected
}
r.Dispose();
dir1.Dispose();
}
// Stress test reopen during addIndexes
[Test]
[Slow]
public virtual void TestDuringAddIndexes()
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(
dir1,
NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))
.SetMergePolicy(NewLogMergePolicy(2)));
// create the index
CreateIndexNoClose(false, "test", writer);
writer.Commit();
Directory[] dirs = new Directory[10];
for (int i = 0; i < 10; i++)
{
dirs[i] = new MockDirectoryWrapper(Random, new RAMDirectory(dir1, NewIOContext(Random)));
}
DirectoryReader r = writer.GetReader();
const float SECONDS = 0.5f;
long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS);
ConcurrentQueue<Exception> excs = new ConcurrentQueue<Exception>();
// Only one thread can addIndexes at a time, because
// IndexWriter acquires a write lock in each directory:
var threads = new ThreadJob[1];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper(writer, dirs, endTime, excs);
threads[i].IsBackground = (true);
threads[i].Start();
}
int lastCount = 0;
while (Environment.TickCount < endTime)
{
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
if (r2 != null)
{
r.Dispose();
r = r2;
}
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
int count = searcher.Search(q, 10).TotalHits;
Assert.IsTrue(count >= lastCount);
lastCount = count;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// final check
DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r);
if (dr2 != null)
{
r.Dispose();
r = dr2;
}
Query q2 = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher_ = NewSearcher(r);
int count_ = searcher_.Search(q2, 10).TotalHits;
Assert.IsTrue(count_ >= lastCount);
Assert.AreEqual(0, excs.Count);
r.Dispose();
if (dir1 is MockDirectoryWrapper)
{
ICollection<string> openDeletedFiles = ((MockDirectoryWrapper)dir1).GetOpenDeletedFiles();
Assert.AreEqual(0, openDeletedFiles.Count, "openDeleted=" + openDeletedFiles);
}
writer.Dispose();
dir1.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadJob
{
private readonly IndexWriter writer;
private readonly Directory[] dirs;
private readonly long endTime;
private readonly ConcurrentQueue<Exception> excs;
public ThreadAnonymousInnerClassHelper(IndexWriter writer, Directory[] dirs, long endTime, ConcurrentQueue<Exception> excs)
{
this.writer = writer;
this.dirs = dirs;
this.endTime = endTime;
this.excs = excs;
}
public override void Run()
{
do
{
try
{
writer.AddIndexes(dirs);
writer.MaybeMerge();
}
catch (Exception t)
{
excs.Enqueue(t);
throw new Exception(t.Message, t);
}
} while (Environment.TickCount < endTime);
}
}
private Directory GetAssertNoDeletesDirectory(Directory directory)
{
if (directory is MockDirectoryWrapper)
{
((MockDirectoryWrapper)directory).AssertNoDeleteOpenFile = true;
}
return directory;
}
// Stress test reopen during add/delete
[Test]
[Slow]
public virtual void TestDuringAddDelete()
{
Directory dir1 = NewDirectory();
var writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy(2)));
// create the index
CreateIndexNoClose(false, "test", writer);
writer.Commit();
DirectoryReader r = writer.GetReader();
const float SECONDS = 0.5f;
long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS);
ConcurrentQueue<Exception> excs = new ConcurrentQueue<Exception>();
var threads = new ThreadJob[numThreads];
for (int i = 0; i < numThreads; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper2(writer, endTime, excs);
threads[i].IsBackground = (true);
threads[i].Start();
}
int sum = 0;
while (Environment.TickCount < endTime)
{
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
if (r2 != null)
{
r.Dispose();
r = r2;
}
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
sum += searcher.Search(q, 10).TotalHits;
}
for (int i = 0; i < numThreads; i++)
{
threads[i].Join();
}
// at least search once
DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r);
if (dr2 != null)
{
r.Dispose();
r = dr2;
}
Query q2 = new TermQuery(new Term("indexname", "test"));
IndexSearcher indSearcher = NewSearcher(r);
sum += indSearcher.Search(q2, 10).TotalHits;
Assert.IsTrue(sum > 0, "no documents found at all");
Assert.AreEqual(0, excs.Count);
writer.Dispose();
r.Dispose();
dir1.Dispose();
}
private class ThreadAnonymousInnerClassHelper2 : ThreadJob
{
private readonly IndexWriter writer;
private readonly long endTime;
private readonly ConcurrentQueue<Exception> excs;
public ThreadAnonymousInnerClassHelper2(IndexWriter writer, long endTime, ConcurrentQueue<Exception> excs)
{
this.writer = writer;
this.endTime = endTime;
this.excs = excs;
rand = new Random(Random.Next());
}
internal readonly Random rand;
public override void Run()
{
int count = 0;
do
{
try
{
for (int docUpto = 0; docUpto < 10; docUpto++)
{
writer.AddDocument(DocHelper.CreateDocument(10 * count + docUpto, "test", 4));
}
count++;
int limit = count * 10;
for (int delUpto = 0; delUpto < 5; delUpto++)
{
int x = rand.Next(limit);
writer.DeleteDocuments(new Term("field3", "b" + x));
}
}
catch (Exception t)
{
excs.Enqueue(t);
throw new Exception(t.Message, t);
}
} while (Environment.TickCount < endTime);
}
}
[Test]
public virtual void TestForceMergeDeletes()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy()));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
Field id = NewStringField("id", "", Field.Store.NO);
doc.Add(id);
id.SetStringValue("0");
w.AddDocument(doc);
id.SetStringValue("1");
w.AddDocument(doc);
w.DeleteDocuments(new Term("id", "0"));
IndexReader r = w.GetReader();
w.ForceMergeDeletes();
w.Dispose();
r.Dispose();
r = DirectoryReader.Open(dir);
Assert.AreEqual(1, r.NumDocs);
Assert.IsFalse(r.HasDeletions);
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDeletesNumDocs()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
Field id = NewStringField("id", "", Field.Store.NO);
doc.Add(id);
id.SetStringValue("0");
w.AddDocument(doc);
id.SetStringValue("1");
w.AddDocument(doc);
IndexReader r = w.GetReader();
Assert.AreEqual(2, r.NumDocs);
r.Dispose();
w.DeleteDocuments(new Term("id", "0"));
r = w.GetReader();
Assert.AreEqual(1, r.NumDocs);
r.Dispose();
w.DeleteDocuments(new Term("id", "1"));
r = w.GetReader();
Assert.AreEqual(0, r.NumDocs);
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestEmptyIndex()
{
// Ensures that getReader works on an empty index, which hasn't been committed yet.
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
IndexReader r = w.GetReader();
Assert.AreEqual(0, r.NumDocs);
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestSegmentWarmer()
{
Directory dir = NewDirectory();
AtomicBoolean didWarm = new AtomicBoolean();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetReaderPooling(true).SetMergedSegmentWarmer(new IndexReaderWarmerAnonymousInnerClassHelper(didWarm)).
SetMergePolicy(NewLogMergePolicy(10)));
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
for (int i = 0; i < 20; i++)
{
w.AddDocument(doc);
}
w.WaitForMerges();
w.Dispose();
dir.Dispose();
Assert.IsTrue(didWarm);
}
private class IndexReaderWarmerAnonymousInnerClassHelper : IndexWriter.IndexReaderWarmer
{
private readonly AtomicBoolean didWarm;
public IndexReaderWarmerAnonymousInnerClassHelper(AtomicBoolean didWarm)
{
this.didWarm = didWarm;
}
public override void Warm(AtomicReader r)
{
IndexSearcher s = NewSearcher(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
outerInstance,
#endif
r);
TopDocs hits = s.Search(new TermQuery(new Term("foo", "bar")), 10);
Assert.AreEqual(20, hits.TotalHits);
didWarm.Value = (true);
}
}
[Test]
public virtual void TestSimpleMergedSegmentWramer()
{
Directory dir = NewDirectory();
AtomicBoolean didWarm = new AtomicBoolean();
InfoStream infoStream = new InfoStreamAnonymousInnerClassHelper(didWarm);
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2).SetReaderPooling(true).SetInfoStream(infoStream).SetMergedSegmentWarmer(new SimpleMergedSegmentWarmer(infoStream)).SetMergePolicy(NewLogMergePolicy(10)));
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
for (int i = 0; i < 20; i++)
{
w.AddDocument(doc);
}
w.WaitForMerges();
w.Dispose();
dir.Dispose();
Assert.IsTrue(didWarm);
}
private class InfoStreamAnonymousInnerClassHelper : InfoStream
{
private readonly AtomicBoolean didWarm;
public InfoStreamAnonymousInnerClassHelper(AtomicBoolean didWarm)
{
this.didWarm = didWarm;
}
protected override void Dispose(bool disposing)
{
}
public override void Message(string component, string message)
{
if ("SMSW".Equals(component, StringComparison.Ordinal))
{
didWarm.Value = (true);
}
}
public override bool IsEnabled(string component)
{
return true;
}
}
[Test]
public virtual void TestNoTermsIndex()
{
// Some Codecs don't honor the ReaderTermsIndexDivisor, so skip the test if
// they're picked.
AssumeFalse("PreFlex codec does not support ReaderTermsIndexDivisor!", "Lucene3x".Equals(Codec.Default.Name, StringComparison.Ordinal));
IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetReaderTermsIndexDivisor(-1);
// Don't proceed if picked Codec is in the list of illegal ones.
string format = TestUtil.GetPostingsFormat("f");
AssumeFalse("Format: " + format + " does not support ReaderTermsIndexDivisor!",
(format.Equals("FSTPulsing41", StringComparison.Ordinal) ||
format.Equals("FSTOrdPulsing41", StringComparison.Ordinal) ||
format.Equals("FST41", StringComparison.Ordinal) ||
format.Equals("FSTOrd41", StringComparison.Ordinal) ||
format.Equals("SimpleText", StringComparison.Ordinal) ||
format.Equals("Memory", StringComparison.Ordinal) ||
format.Equals("MockRandom", StringComparison.Ordinal) ||
format.Equals("Direct", StringComparison.Ordinal)));
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, conf);
Document doc = new Document();
doc.Add(new TextField("f", "val", Field.Store.NO));
w.AddDocument(doc);
SegmentReader r = GetOnlySegmentReader(DirectoryReader.Open(w, true));
try
{
TestUtil.Docs(Random, r, "f", new BytesRef("val"), null, null, DocsFlags.NONE);
Assert.Fail("should have failed to seek since terms index was not loaded.");
}
#pragma warning disable 168
catch (InvalidOperationException e)
#pragma warning restore 168
{
// expected - we didn't load the term index
}
finally
{
r.Dispose();
w.Dispose();
dir.Dispose();
}
}
[Test]
public virtual void TestReopenAfterNoRealChange()
{
Directory d = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
DirectoryReader r = w.GetReader(); // start pooling readers
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
Assert.IsNull(r2);
w.AddDocument(new Document());
DirectoryReader r3 = DirectoryReader.OpenIfChanged(r);
Assert.IsNotNull(r3);
Assert.IsTrue(r3.Version != r.Version);
Assert.IsTrue(r3.IsCurrent());
// Deletes nothing in reality...:
w.DeleteDocuments(new Term("foo", "bar"));
// ... but IW marks this as not current:
Assert.IsFalse(r3.IsCurrent());
DirectoryReader r4 = DirectoryReader.OpenIfChanged(r3);
Assert.IsNull(r4);
// Deletes nothing in reality...:
w.DeleteDocuments(new Term("foo", "bar"));
DirectoryReader r5 = DirectoryReader.OpenIfChanged(r3, w, true);
Assert.IsNull(r5);
r3.Dispose();
w.Dispose();
d.Dispose();
}
[Test]
public virtual void TestNRTOpenExceptions()
{
// LUCENE-5262: test that several failed attempts to obtain an NRT reader
// don't leak file handles.
MockDirectoryWrapper dir = (MockDirectoryWrapper)GetAssertNoDeletesDirectory(NewMockDirectory());
AtomicBoolean shouldFail = new AtomicBoolean();
dir.FailOn(new FailureAnonymousInnerClassHelper(shouldFail));
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
conf.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); // prevent merges from getting in the way
IndexWriter writer = new IndexWriter(dir, conf);
// create a segment and open an NRT reader
writer.AddDocument(new Document());
writer.GetReader().Dispose();
// add a new document so a new NRT reader is required
writer.AddDocument(new Document());
// try to obtain an NRT reader twice: first time it fails and closes all the
// other NRT readers. second time it fails, but also fails to close the
// other NRT reader, since it is already marked closed!
for (int i = 0; i < 2; i++)
{
shouldFail.Value = (true);
try
{
writer.GetReader().Dispose();
}
#pragma warning disable 168
catch (FakeIOException e)
#pragma warning restore 168
{
// expected
if (Verbose)
{
Console.WriteLine("hit expected fake IOE");
}
}
}
writer.Dispose();
dir.Dispose();
}
private class FailureAnonymousInnerClassHelper : Failure
{
private readonly AtomicBoolean shouldFail;
public FailureAnonymousInnerClassHelper(AtomicBoolean shouldFail)
{
this.shouldFail = shouldFail;
}
public override void Eval(MockDirectoryWrapper dir)
{
// LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
// to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
if (shouldFail && StackTraceHelper.DoesStackTraceContainMethod("GetReadOnlyClone"))
{
if (Verbose)
{
Console.WriteLine("TEST: now fail; exc:");
Console.WriteLine((new Exception()).StackTrace);
}
shouldFail.Value = (false);
throw new FakeIOException();
}
}
}
/// <summary>
/// Make sure if all we do is open NRT reader against
/// writer, we don't see merge starvation.
/// </summary>
[Test]
[Slow]
public virtual void TestTooManySegments()
{
Directory dir = GetAssertNoDeletesDirectory(NewDirectory());
// Don't use newIndexWriterConfig, because we need a
// "sane" mergePolicy:
IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
IndexWriter w = new IndexWriter(dir, iwc);
// Create 500 segments:
for (int i = 0; i < 500; i++)
{
Document doc = new Document();
doc.Add(NewStringField("id", "" + i, Field.Store.NO));
w.AddDocument(doc);
IndexReader r = DirectoryReader.Open(w, true);
// Make sure segment count never exceeds 100:
Assert.IsTrue(r.Leaves.Count < 100);
r.Dispose();
}
w.Dispose();
dir.Dispose();
}
#endif
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CheckBox.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Security.Permissions;
using System.Windows.Forms.ButtonInternal;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Layout;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using System.Globalization;
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox"]/*' />
/// <devdoc>
/// <para> Represents a Windows
/// check box.</para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
DefaultProperty("Checked"),
DefaultEvent("CheckedChanged"),
DefaultBindingProperty("CheckState"),
ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem," + AssemblyRef.SystemDesign),
SRDescription(SR.DescriptionCheckBox)
]
public class CheckBox : ButtonBase {
private static readonly object EVENT_CHECKEDCHANGED = new object();
private static readonly object EVENT_CHECKSTATECHANGED = new object();
private static readonly object EVENT_APPEARANCECHANGED = new object();
static readonly ContentAlignment anyRight = ContentAlignment.TopRight | ContentAlignment.MiddleRight | ContentAlignment.BottomRight;
private bool autoCheck;
private bool threeState;
private bool accObjDoDefaultAction = false;
private ContentAlignment checkAlign = ContentAlignment.MiddleLeft;
private CheckState checkState;
private Appearance appearance;
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBox"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.CheckBox'/> class.
/// </para>
/// </devdoc>
public CheckBox()
: base() {
// Checkboxes shouldn't respond to right clicks, so we need to do all our own click logic
SetStyle(ControlStyles.StandardClick |
ControlStyles.StandardDoubleClick, false);
SetAutoSizeMode(AutoSizeMode.GrowAndShrink);
autoCheck = true;
TextAlign = ContentAlignment.MiddleLeft;
}
private bool AccObjDoDefaultAction {
get {
return this.accObjDoDefaultAction;
}
set {
this.accObjDoDefaultAction = value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.Appearance"]/*' />
/// <devdoc>
/// <para>Gets
/// or sets the value that determines the appearance of a
/// check box control.</para>
/// </devdoc>
[
DefaultValue(Appearance.Normal),
Localizable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.CheckBoxAppearanceDescr)
]
public Appearance Appearance {
get {
return appearance;
}
set {
//valid values are 0x0 to 0x1
if (!ClientUtils.IsEnumValid(value, (int)value, (int)Appearance.Normal, (int)Appearance.Button)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(Appearance));
}
if (appearance != value) {
using (LayoutTransaction.CreateTransactionIf(AutoSize, this.ParentInternal, this, PropertyNames.Appearance)) {
appearance = value;
if (OwnerDraw) {
Refresh();
}
else {
UpdateStyles();
}
OnAppearanceChanged(EventArgs.Empty);
}
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.AppearanceChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SRCategory(SR.CatPropertyChanged), SRDescription(SR.CheckBoxOnAppearanceChangedDescr)]
public event EventHandler AppearanceChanged {
add {
Events.AddHandler(EVENT_APPEARANCECHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_APPEARANCECHANGED, value);
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.AutoCheck"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Windows.Forms.CheckBox.Checked'/> or <see cref='System.Windows.Forms.CheckBox.CheckState'/>
/// value and the check box's appearance are automatically
/// changed when it is clicked.</para>
/// </devdoc>
[
DefaultValue(true),
SRCategory(SR.CatBehavior),
SRDescription(SR.CheckBoxAutoCheckDescr)
]
public bool AutoCheck {
get {
return autoCheck;
}
set {
autoCheck = value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckAlign"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets
/// the horizontal and vertical alignment of a check box on a check box
/// control.
///
/// </para>
/// </devdoc>
[
Bindable(true),
Localizable(true),
SRCategory(SR.CatAppearance),
DefaultValue(ContentAlignment.MiddleLeft),
SRDescription(SR.CheckBoxCheckAlignDescr)
]
public ContentAlignment CheckAlign {
get {
return checkAlign;
}
set {
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) {
throw new InvalidEnumArgumentException("value", (int)value, typeof(ContentAlignment));
}
if (checkAlign != value) {
checkAlign = value;
LayoutTransaction.DoLayoutIf(AutoSize, ParentInternal, this, PropertyNames.CheckAlign);
if (OwnerDraw) {
Invalidate();
}
else {
UpdateStyles();
}
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.Checked"]/*' />
/// <devdoc>
/// <para>
/// Gets
/// or sets a value indicating whether the
/// check box
/// is checked.
/// </para>
/// </devdoc>
[
Bindable(true),
SettingsBindable(true),
DefaultValue(false),
SRCategory(SR.CatAppearance),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.CheckBoxCheckedDescr)
]
public bool Checked {
get {
return checkState != CheckState.Unchecked;
}
set {
if (value != Checked) {
CheckState = value ? CheckState.Checked : CheckState.Unchecked;
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckState"]/*' />
/// <devdoc>
/// <para>Gets
/// or sets a value indicating whether the check box is checked.</para>
/// </devdoc>
[
Bindable(true),
SRCategory(SR.CatAppearance),
DefaultValue(CheckState.Unchecked),
RefreshProperties(RefreshProperties.All),
SRDescription(SR.CheckBoxCheckStateDescr)
]
public CheckState CheckState {
get {
return checkState;
}
set {
// valid values are 0-2 inclusive.
if (!ClientUtils.IsEnumValid(value, (int)value, (int)CheckState.Unchecked, (int)CheckState.Indeterminate)){
throw new InvalidEnumArgumentException("value", (int)value, typeof(CheckState));
}
if (checkState != value) {
bool oldChecked = Checked;
checkState = value;
if (IsHandleCreated) {
SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0);
}
if (oldChecked != Checked) {
OnCheckedChanged(EventArgs.Empty);
}
OnCheckStateChanged(EventArgs.Empty);
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.DoubleClick"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler DoubleClick {
add {
base.DoubleClick += value;
}
remove {
base.DoubleClick -= value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.MouseDoubleClick"]/*' />
/// <internalonly/><hideinheritance/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event MouseEventHandler MouseDoubleClick {
add {
base.MouseDoubleClick += value;
}
remove {
base.MouseDoubleClick -= value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CreateParams"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Gets the information used to create the handle for the
/// <see cref='System.Windows.Forms.CheckBox'/>
/// control.
/// </para>
/// </devdoc>
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
cp.ClassName = "BUTTON";
if (OwnerDraw) {
cp.Style |= NativeMethods.BS_OWNERDRAW;
}
else {
cp.Style |= NativeMethods.BS_3STATE;
if (Appearance == Appearance.Button) {
cp.Style |= NativeMethods.BS_PUSHLIKE;
}
// Determine the alignment of the check box
//
ContentAlignment align = RtlTranslateContent(CheckAlign);
if ((int)(align & anyRight) != 0) {
cp.Style |= NativeMethods.BS_RIGHTBUTTON;
}
}
return cp;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(104, 24);
}
}
internal override Size GetPreferredSizeCore(Size proposedConstraints) {
if (Appearance == Appearance.Button) {
ButtonStandardAdapter adapter = new ButtonStandardAdapter(this);
return adapter.GetPreferredSizeCore(proposedConstraints);
}
if(FlatStyle != FlatStyle.System) {
return base.GetPreferredSizeCore(proposedConstraints);
}
Size textSize = TextRenderer.MeasureText(this.Text, this.Font);
Size size = SizeFromClientSize(textSize);
size.Width += 25;
size.Height += 5;
return size + Padding.Size;
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OverChangeRectangle"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
internal override Rectangle OverChangeRectangle {
get {
if (Appearance == Appearance.Button) {
return base.OverChangeRectangle;
}
else {
if (FlatStyle == FlatStyle.Standard) {
// this Rectangle will cause no Invalidation
// can't use Rectangle.Empty because it will cause Invalidate(ClientRectangle)
return new Rectangle(-1, -1, 1, 1);
}
else {
// Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle
return Adapter.CommonLayout().Layout().checkBounds;
}
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.DownChangeRectangle"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
internal override Rectangle DownChangeRectangle {
get {
if (Appearance == Appearance.Button || FlatStyle == FlatStyle.System) {
return base.DownChangeRectangle;
}
else {
// Popup mouseover rectangle is actually bigger than GetCheckmarkRectangle()
return Adapter.CommonLayout().Layout().checkBounds;
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.TextAlign"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Gets or sets a value indicating the alignment of the
/// text on the checkbox control.
///
/// </para>
/// </devdoc>
[
Localizable(true),
DefaultValue(ContentAlignment.MiddleLeft)
]
public override ContentAlignment TextAlign {
get {
return base.TextAlign;
}
set {
base.TextAlign = value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.ThreeState"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating
/// whether the check box will allow three check states rather than two.</para>
/// </devdoc>
[
DefaultValue(false),
SRCategory(SR.CatBehavior),
SRDescription(SR.CheckBoxThreeStateDescr)
]
public bool ThreeState {
get {
return threeState;
}
set {
threeState = value;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckedChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.Checked'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckedChangedDescr)]
public event EventHandler CheckedChanged {
add {
Events.AddHandler(EVENT_CHECKEDCHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_CHECKEDCHANGED, value);
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckStateChanged"]/*' />
/// <devdoc>
/// <para>Occurs when the
/// value of the <see cref='System.Windows.Forms.CheckBox.CheckState'/>
/// property changes.</para>
/// </devdoc>
[SRDescription(SR.CheckBoxOnCheckStateChangedDescr)]
public event EventHandler CheckStateChanged {
add {
Events.AddHandler(EVENT_CHECKSTATECHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_CHECKSTATECHANGED, value);
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CreateAccessibilityInstance"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Constructs the new instance of the accessibility object for this control. Subclasses
/// should not call base.CreateAccessibilityObject.
/// </para>
/// </devdoc>
protected override AccessibleObject CreateAccessibilityInstance() {
return new CheckBoxAccessibleObject(this);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnAppearanceChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected virtual void OnAppearanceChanged(EventArgs e) {
EventHandler eh = Events[EVENT_APPEARANCECHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnCheckedChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.CheckBox.CheckedChanged'/>
/// event.</para>
/// </devdoc>
protected virtual void OnCheckedChanged(EventArgs e) {
// accessibility stuff
if (this.FlatStyle == FlatStyle.System) {
AccessibilityNotifyClients(AccessibleEvents.SystemCaptureStart, -1);
}
AccessibilityNotifyClients(AccessibleEvents.StateChange, -1);
AccessibilityNotifyClients(AccessibleEvents.NameChange, -1);
if (this.FlatStyle == FlatStyle.System) {
AccessibilityNotifyClients(AccessibleEvents.SystemCaptureEnd, -1);
}
EventHandler handler = (EventHandler)Events[EVENT_CHECKEDCHANGED];
if (handler != null) handler(this,e);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnCheckStateChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.CheckBox.CheckStateChanged'/> event.</para>
/// </devdoc>
protected virtual void OnCheckStateChanged(EventArgs e) {
if (OwnerDraw) {
Refresh();
}
EventHandler handler = (EventHandler)Events[EVENT_CHECKSTATECHANGED];
if (handler != null) handler(this,e);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnClick"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Fires the event indicating that the control has been clicked.
/// Inheriting controls should use this in favour of actually listening to
/// the event, but should not forget to call base.onClicked() to
/// ensure that the event is still fired for external listeners.
///
/// </para>
/// </devdoc>
protected override void OnClick(EventArgs e) {
if (autoCheck) {
switch (CheckState) {
case CheckState.Unchecked:
CheckState = CheckState.Checked;
break;
case CheckState.Checked:
if (threeState) {
CheckState = CheckState.Indeterminate;
// If the check box is clicked as a result of AccObj::DoDefaultAction
// then the native check box does not fire OBJ_STATE_CHANGE event when going to Indeterminate state.
// So the [....] layer fires the OBJ_STATE_CHANGE event.
// vsw 543351.
if (this.AccObjDoDefaultAction) {
AccessibilityNotifyClients(AccessibleEvents.StateChange, -1);
}
}
else {
CheckState = CheckState.Unchecked;
}
break;
default:
CheckState = CheckState.Unchecked;
break;
}
}
base.OnClick(e);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnHandleCreated"]/*' />
/// <devdoc>
/// We override this to ensure that the control's click values are set up
/// correctly.
/// </devdoc>
/// <internalonly/>
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
// Since this is a protected override...
// this can be directly called in by a overriden class..
// and the Handle need not be created...
// So Check for the handle
if (IsHandleCreated) {
SendMessage(NativeMethods.BM_SETCHECK, (int)checkState, 0);
}
}
/// <devdoc>
/// We override this to ensure that press '+' or '=' checks the box,
/// while pressing '-' unchecks the box
/// </devdoc>
/// <internalonly/>
protected override void OnKeyDown(KeyEventArgs e) {
//this fixes bug 235019, but it will be a breaking change from Everett
//see the comments attached to bug 235019
/*
if (Enabled) {
if (e.KeyCode == Keys.Oemplus || e.KeyCode == Keys.Add) {
CheckState = CheckState.Checked;
}
if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract) {
CheckState = CheckState.Unchecked;
}
}
*/
base.OnKeyDown(e);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.OnMouseUp"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Raises the <see cref='System.Windows.Forms.ButtonBase.OnMouseUp'/> event.
///
/// </para>
/// </devdoc>
protected override void OnMouseUp(MouseEventArgs mevent) {
if (mevent.Button == MouseButtons.Left && MouseIsPressed) {
// It's best not to have the mouse captured while running Click events
if (base.MouseIsDown) {
Point pt = PointToScreen(new Point(mevent.X, mevent.Y));
if (UnsafeNativeMethods.WindowFromPoint(pt.X, pt.Y) == Handle) {
//Paint in raised state...
ResetFlagsandPaint();
if (!ValidationCancelled) {
if (this.Capture) {
OnClick(mevent);
}
OnMouseClick(mevent);
}
}
}
}
base.OnMouseUp(mevent);
}
internal override ButtonBaseAdapter CreateFlatAdapter() {
return new CheckBoxFlatAdapter(this);
}
internal override ButtonBaseAdapter CreatePopupAdapter() {
return new CheckBoxPopupAdapter(this);
}
internal override ButtonBaseAdapter CreateStandardAdapter() {
return new CheckBoxStandardAdapter(this);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.ProcessMnemonic"]/*' />
/// <devdoc>
/// Overridden to handle mnemonics properly.
/// </devdoc>
/// <internalonly/>
[UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)]
protected internal override bool ProcessMnemonic(char charCode) {
if (UseMnemonic && IsMnemonic(charCode, Text) && CanSelect) {
if (FocusInternal()) {
//Paint in raised state...
//
ResetFlagsandPaint();
if (!ValidationCancelled) {
OnClick(EventArgs.Empty);
}
}
return true;
}
return false;
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.ToString"]/*' />
/// <devdoc>
/// Provides some interesting information for the CheckBox control in
/// String form.
/// </devdoc>
/// <internalonly/>
public override string ToString() {
string s = base.ToString();
// C#R cpb: 14744 ([....]) We shouldn't need to convert the enum to int -- EE M10 workitem.
int checkState = (int)CheckState;
return s + ", CheckState: " + checkState.ToString(CultureInfo.InvariantCulture);
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[System.Runtime.InteropServices.ComVisible(true)]
public class CheckBoxAccessibleObject : ButtonBaseAccessibleObject {
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject.CheckBoxAccessibleObject"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CheckBoxAccessibleObject(Control owner) : base(owner) {
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject.DefaultAction"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string DefaultAction {
get {
string defaultAction = Owner.AccessibleDefaultActionDescription;
if (defaultAction != null) {
return defaultAction;
}
if (((CheckBox)Owner).Checked) {
return SR.GetString(SR.AccessibleActionUncheck);
}
else {
return SR.GetString(SR.AccessibleActionCheck);
}
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject.Role"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleRole Role {
get {
AccessibleRole role = Owner.AccessibleRole;
if (role != AccessibleRole.Default) {
return role;
}
return AccessibleRole.CheckButton;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject.State"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override AccessibleStates State {
get {
switch (((CheckBox)Owner).CheckState) {
case CheckState.Checked:
return AccessibleStates.Checked | base.State;
case CheckState.Indeterminate:
return AccessibleStates.Indeterminate | base.State;
}
return base.State;
}
}
/// <include file='doc\CheckBox.uex' path='docs/doc[@for="CheckBox.CheckBoxAccessibleObject.DoDefaultAction"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public override void DoDefaultAction() {
CheckBox cb = this.Owner as CheckBox;
if (cb != null) {
cb.AccObjDoDefaultAction = true;
}
try {
base.DoDefaultAction();
} finally {
if (cb != null) {
cb.AccObjDoDefaultAction = false;
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.WsatConfig
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
// NET_FIREWALL_IP_VERSION
enum NetFirewallIPVersion
{
V4 = 0,
V6 = 1,
Any = 2,
Max = 3,
}
// NET_FIREWALL_SCOPE
enum NetFirewallScope
{
All = 0,
Subnet = 1,
Custom = 2,
Max = 3,
}
// NET_FIREWALL_IP_PROTOCOL
enum NetFirewallIPProtocol
{
Tcp = 6,
Udp = 17,
}
// NET_FIREWALL_SERVICE_TYPE
enum NetFirewallServiceType
{
FileAndPrint = 0,
Upnp = 1,
RemoteDesktop = 2,
None = 3,
Max = 4,
}
// NET_FIREWALL_PROFILE_TYPE
enum NetFirewallProfileType
{
Domain = 0,
Standard = 1,
Current = 2,
Max = 3,
}
// INetFwRemoteAdminSettings
[ComImport, TypeLibType(4160), Guid("D4BECDDF-6F73-4A83-B832-9C66874CD20E")]
interface INetFirewallRemoteAdminSettings
{
[DispId(1)]
NetFirewallIPVersion IPVersion { get; set; }
[DispId(2)]
NetFirewallScope Scope { get; set; }
[DispId(3)]
string RemoteAddresses { get; set; }
[DispId(4)]
bool Enabled { get; set; }
}
// INetFwIcmpSettings
[ComImport, TypeLibType(4160), Guid("A6207B2E-7CDD-426A-951E-5E1CBC5AFEAD")]
interface INetFirewallIcmpSettings
{
[DispId(1)]
bool AllowOutboundDestinationUnreachable { get; set; }
[DispId(2)]
bool AllowRedirect { get; set; }
[DispId(3)]
bool AllowInboundEchoRequest { get; set; }
[DispId(4)]
bool AllowOutboundTimeExceeded { get; set; }
[DispId(5)]
bool AllowOutboundParameterProblem { get; set; }
[DispId(6)]
bool AllowOutboundSourceQuench { get; set; }
[DispId(7)]
bool AllowInboundRouterRequest { get; set; }
[DispId(8)]
bool AllowInboundTimestampRequest { get; set; }
[DispId(9)]
bool AllowInboundMaskRequest { get; set; }
[DispId(10)]
bool AllowOutboundPacketTooBig { get; set; }
}
// INetFwOpenPort
[ComImport, TypeLibType(4160), Guid("E0483BA0-47FF-4D9C-A6D6-7741D0B195F7")]
interface INetFirewallOpenPort
{
[DispId(1)]
string Name { get; set; }
[DispId(2)]
NetFirewallIPVersion IPVersion { get; set; }
[DispId(3)]
NetFirewallIPProtocol Protocol { get; set; }
[DispId(4)]
int Port { get; set; }
[DispId(5)]
NetFirewallScope Scope { get; set; }
[DispId(6)]
string RemoteAddresses { get; set; }
[DispId(7)]
bool Enabled { get; set; }
[DispId(8)]
bool BuiltIn { get; }
}
// INetFwOpenPorts
[ComImport, TypeLibType(4160), Guid("C0E9D7FA-E07E-430A-B19A-090CE82D92E2")]
interface INetFirewallOpenPortsCollection : IEnumerable
{
[DispId(1)]
int Count { get; }
[DispId(2)]
void Add([MarshalAs(UnmanagedType.Interface)] INetFirewallOpenPort port);
[DispId(3)]
void Remove(int portNumber, NetFirewallIPProtocol ipProtocol);
[DispId(4)]
INetFirewallOpenPort Item([MarshalAs(UnmanagedType.Interface)] int port, NetFirewallIPProtocol portNumber);
[DispId(-4)]
[TypeLibFunc(1)]
new IEnumerator GetEnumerator();
}
// INetFwService
[ComImport, TypeLibType(4160), Guid("79FD57C8-908E-4A36-9888-D5B3F0A444CF")]
interface INetFirewallService
{
[DispId(1)]
string Name { get; }
[DispId(2)]
NetFirewallServiceType Type { get; }
[DispId(3)]
bool Customized { get; }
[DispId(4)]
NetFirewallIPVersion IPVersion { get; set; }
[DispId(5)]
NetFirewallScope Scope { get; set; }
[DispId(6)]
string RemoteAddresses { get; set; }
[DispId(7)]
bool Enabled { get; set; }
[DispId(8)]
INetFirewallOpenPortsCollection GloballyOpenPorts { get; }
}
// INetFwServices
[ComImport, TypeLibType(4160), Guid("79649BB4-903E-421B-94C9-79848E79F6EE")]
interface INetFirewallServicesCollection : IEnumerable
{
[DispId(1)]
int Count { get; }
[DispId(2)]
INetFirewallService Item([MarshalAs(UnmanagedType.Interface)] NetFirewallServiceType serviceType);
[TypeLibFunc(1)]
[DispId(-4)]
new IEnumerator GetEnumerator();
}
// INetFwAuthorizedApplication
[ComImport, TypeLibType(4160), Guid("B5E64FFA-C2C5-444E-A301-FB5E00018050")]
interface INetFirewallAuthorizedApplication
{
[DispId(1)]
string Name { get; set; }
[DispId(2)]
string ProcessImageFileName { get; set; }
[DispId(3)]
NetFirewallIPVersion IPVersion { get; set; }
[DispId(4)]
NetFirewallScope Scope { get; set; }
[DispId(5)]
string RemoteAddresses { get; set; }
[DispId(6)]
bool Enabled { get; set; }
}
// INetFwAuthorizedApplications
[ComImport, TypeLibType(4160), Guid("644EFD52-CCF9-486C-97A2-39F352570B30")]
interface INetFirewallAuthorizedApplicationsCollection : IEnumerable
{
[DispId(1)]
int Count { get; }
[DispId(2)]
void Add([MarshalAs(UnmanagedType.Interface)] INetFirewallAuthorizedApplication app);
[DispId(3)]
void Remove([MarshalAs(UnmanagedType.BStr)] string imageFileName);
[DispId(4)]
INetFirewallAuthorizedApplication Item([MarshalAs(UnmanagedType.Interface)] string name);
[DispId(-4)]
[TypeLibFunc(1)]
new IEnumerator GetEnumerator();
}
// INetFwProfile
[ComImport, TypeLibType(4160), Guid("174A0DDA-E9F9-449D-993B-21AB667CA456")]
interface INetFirewallProfile
{
[DispId(1)]
NetFirewallProfileType Type { get; }
[DispId(2)]
bool FirewallEnabled { get; set; }
[DispId(3)]
bool ExceptionsNotAllowed { get; set; }
[DispId(4)]
bool NotificationsDisabled { get; set; }
[DispId(5)]
bool UnicastResponsesToMulticastBroadcastDisabled { get; set; }
[DispId(6)]
INetFirewallRemoteAdminSettings RemoteAdminSettings { get; }
[DispId(7)]
INetFirewallIcmpSettings IcmpSettings { get; }
[DispId(8)]
INetFirewallOpenPortsCollection GloballyOpenPorts { get; }
[DispId(9)]
INetFirewallServicesCollection Services { get; }
[DispId(10)]
INetFirewallAuthorizedApplicationsCollection AuthorizedApplications { get; }
}
// INetFwPolicy
[ComImport, TypeLibType(4160), Guid("D46D2478-9AC9-4008-9DC7-5563CE5536CC")]
interface INetFirewallPolicy
{
[DispId(1)]
INetFirewallProfile CurrentProfile { get; }
[DispId(2)]
INetFirewallProfile GetProfileByType([MarshalAs(UnmanagedType.Interface)] NetFirewallProfileType profileType);
}
// INetFwMgr
[ComImport, TypeLibType(4160), Guid("F7898AF5-CAC4-4632-A2EC-DA06E5111AF2")]
interface INetFirewallMgr
{
[DispId(1)]
INetFirewallPolicy LocalPolicy { get; }
[DispId(2)]
NetFirewallProfileType CurrentProfileType { get; }
[DispId(3)]
void RestoreDefaults();
[DispId(4)]
void IsPortAllowed([MarshalAs(UnmanagedType.BStr)] string imageFileName, NetFirewallIPVersion ipVersion, int portNumber, [MarshalAs(UnmanagedType.BStr)] string localAddress, NetFirewallIPProtocol ipProtocol, [MarshalAs(UnmanagedType.Struct)] ref object allowed, [MarshalAs(UnmanagedType.Struct)] ref object restricted);
[DispId(5)]
void IsIcmpTypeAllowed(NetFirewallIPVersion ipVersion, [MarshalAs(UnmanagedType.BStr)] string localAddress, byte type, [MarshalAs(UnmanagedType.Struct)] ref INetFirewallIcmpSettings allowed, [MarshalAs(UnmanagedType.Struct)] ref object restricted);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Transactions
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading.Tasks;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Cache transaction proxy which supports only implicit rollback operations and getters.
/// <para/>
/// Does not support the following operations:
/// <list type="bullet">
/// <item><description><see cref="Commit"/>.</description></item>
/// <item><description><see cref="CommitAsync"/>.</description></item>
/// <item><description>Get <see cref="Meta{TV}"/>.</description></item>
/// <item><description>Get <see cref="AddMeta{TV}"/>.</description></item>
/// <item><description>Get <see cref="RemoveMeta{TV}"/>.</description></item>
/// <item><description>Get <see cref="StartTime"/>.</description></item>
/// <item><description>Get <see cref="ThreadId"/>.</description></item>
/// </list>
/// </summary>
internal class TransactionRollbackOnlyProxy : ITransaction
{
/** Transactions facade. */
private readonly TransactionsImpl _txs;
/** Unique transaction view ID. */
private readonly long _id;
/** Is closed. */
private volatile bool _isClosed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="id">ID.</param>
/// <param name="txs">Transactions.</param>
/// <param name="concurrency">TX concurrency.</param>
/// <param name="isolation">TX isolation.</param>
/// <param name="timeout">Timeout.</param>
/// <param name="label">TX label.</param>
/// <param name="nodeId">The originating node identifier.</param>
public TransactionRollbackOnlyProxy(
TransactionsImpl txs,
long id,
TransactionConcurrency concurrency,
TransactionIsolation isolation,
TimeSpan timeout,
string label,
Guid nodeId)
{
_txs = txs;
_id = id;
NodeId = nodeId;
Isolation = isolation;
Concurrency = concurrency;
Timeout = timeout;
Label = label;
}
/** <inheritdoc /> */
public Guid NodeId { get; private set; }
/** <inheritdoc /> */
public long ThreadId
{
get { throw GetInvalidOperationException(); }
}
/** <inheritdoc /> */
public DateTime StartTime
{
get { throw GetInvalidOperationException(); }
}
/** <inheritdoc /> */
public TransactionIsolation Isolation { get; private set; }
/** <inheritdoc /> */
public TransactionConcurrency Concurrency { get; private set; }
/** <inheritdoc /> */
public TransactionState State
{
get
{
lock (this)
{
ThrowIfClosed();
return _txs.TxState(this);
}
}
}
/** <inheritdoc /> */
public TimeSpan Timeout { get; private set; }
/** <inheritdoc /> */
public string Label { get; private set; }
/** <inheritdoc /> */
public bool IsRollbackOnly
{
get { return true; }
}
/** <inheritDoc /> */
public bool SetRollbackonly()
{
return true;
}
/** <inheritDoc /> */
public void Commit()
{
throw GetInvalidOperationException();
}
/** <inheritDoc /> */
public Task CommitAsync()
{
throw GetInvalidOperationException();
}
/** <inheritDoc /> */
public void Rollback()
{
lock (this)
{
ThrowIfClosed();
try
{
_txs.TxRollback(this);
}
finally
{
_isClosed = true;
}
}
}
/** <inheritDoc /> */
public Task RollbackAsync()
{
lock (this)
{
ThrowIfClosed();
return _txs.TxRollbackAsync(this)
.ContWith(t =>
{
try
{
_txs.TxClose(this);
}
finally
{
_isClosed = true;
}
});
}
}
/** <inheritDoc /> */
public void AddMeta<TV>(string name, TV val)
{
throw GetInvalidOperationException();
}
/** <inheritdoc /> */
public TV Meta<TV>(string name)
{
throw GetInvalidOperationException();
}
/** <inheritDoc /> */
public TV RemoveMeta<TV>(string name)
{
throw GetInvalidOperationException();
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Dispose should not throw.")]
public void Dispose()
{
if (!_isClosed)
{
try
{
_txs.TxRemove(this);
}
catch(IgniteIllegalStateException)
{
// No-op. Dispose should not throw.
}
finally
{
_isClosed = true;
GC.SuppressFinalize(this);
}
}
}
/// <summary>
/// Unique transaction view ID.
/// </summary>
internal long Id
{
get { return _id; }
}
/// <summary>
/// Throws and exception if transaction is closed.
/// </summary>
private void ThrowIfClosed()
{
if (_isClosed)
throw GetClosedException();
}
/// <summary>
/// Gets the closed exception.
/// </summary>
private InvalidOperationException GetClosedException()
{
return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Transaction {0} is closed", Id));
}
/// <summary>
/// Gets invalid operation exception.
/// </summary>
private static InvalidOperationException GetInvalidOperationException()
{
return new InvalidOperationException("Operation is not supported by rollback only transaction.");
}
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using Microsoft.Research.DryadLinq;
using Microsoft.Research.Peloponnese.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
namespace DryadLinqTests
{
public static class MiscBugFixTests
{
public static void Run(DryadLinqContext context, string matchPattern)
{
TestLog.Message(" **********************");
TestLog.Message(" MiscBugFixTests ");
TestLog.Message(" **********************");
var tests = new Dictionary<string, Action>()
{
{"Bug11447_GroupByWithComparer", () => Bug11447_GroupByWithComparer(context) },
{"Bug12584_HashPartitionOutputCount", () => Bug12584_HashPartitionOutputCount(context) },
{"Bug13108_DisableSequenceEquals", () => Bug13108_DisableSequenceEquals(context) },
{"Bug13529_and_Bug13593_IndexedOperatorCompilation", () => Bug13529_and_Bug13593_IndexedOperatorCompilation(context) },
{"Bug13130_ReverseOperator", () => Bug13130_ReverseOperator(context) },
{"Bug13736_IndexedTakeWhile", () => Bug13736_IndexedTakeWhile(context) },
{"Bug13534_HashPartitionNegIndexIsError", () => Bug13534_HashPartitionNegIndexIsError(context) },
{"Bug13474_and_Bug13483_FromDscOnBadFileSet", () => Bug13474_and_Bug13483_FromDscOnBadFileSet(context) },
{"Bug13637_EmptyFilesInFilesets", () => Bug13637_EmptyFilesInFilesets(context) },
{"Bug13637_LocalDebugProducingZeroRecords", () => Bug13637_LocalDebugProducingZeroRecords(context) },
{"Bug13245_FromDsc_Submit_throws", () => Bug13245_FromDsc_Submit_throws(context) },
{"Bug13245_QueryUsingNonHpcLinqOperator", () => Bug13245_QueryUsingNonHpcLinqOperator(context) },
{"Bug13302_ConfigEnvironmentCleanup", () => Bug13302_ConfigEnvironmentCleanup(context) },
{"Bug13970_MismatchedDataTypes", () => Bug13970_MismatchedDataTypes(context) },
{"Bug14010_AlreadyDisposedContext", () => Bug14010_AlreadyDisposedContext(context) },
{"Bug14256_LeaseOnTempDscFileset", () => Bug14256_LeaseOnTempDscFileset(context) },
{"Bug14189_OrderPreservation", () => Bug14189_OrderPreservation(context) },
{"Bug14190_MergeJoin_DecreasingOrder", () => Bug14190_MergeJoin_DecreasingOrder(context) },
{"Bug14192_MultiApplySubExpressionReuse", () => Bug14192_MultiApplySubExpressionReuse(context) },
{"Bug14870_LongIndexTakeWhile", () => Bug14870_LongIndexTakeWhile(context) },
{"Bug15159_NotOperatorForNullableBool", () => Bug15159_NotOperatorForNullableBool(context) },
{"Bug15371_NoDataMembersForSerialization", () => Bug15371_NoDataMembersForSerialization(context) },
{"Bug15570_GetHashCodeAndEqualsForNullableFieldsOfAnonymousTypes", () => Bug15570_GetHashCodeAndEqualsForNullableFieldsOfAnonymousTypes(context) },
};
foreach (var test in tests)
{
if (Regex.IsMatch(test.Key, matchPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
test.Value.Invoke();
}
}
}
public static bool Bug11447_GroupByWithComparer(DryadLinqContext context)
{
string testName = "Bug11447_GroupByWithComparer";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var a = pt1.GroupBy(x => x, EqualityComparer<int>.Default).SelectMany(x => x).ToList();
result[0] = a;
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var a = pt1.GroupBy(x => x, EqualityComparer<int>.Default).SelectMany(x => x).ToList();
result[1] = a;
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug12584_HashPartitionOutputCount(DryadLinqContext context) // ToDo
{
string testName = "Bug12584_HashPartitionOutputCount";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
string outFile = "unittest/output/Bug12584_HashPartitionOutputCount";
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var info = pt1.HashPartition(x => x).ToStore(AzureUtils.ToAzureUri(Config.accountName, Config.containerName, outFile), true).Submit();
info.Wait();
//// partition verification are only valid for cluster execution..
//// check that nOutputPartitions == nInputPartitions.
//// Note: this is today's behavior, but we don't strictly guarantee this and the rules may change.
//var inFS = context.DscService.GetFileSet(DataGenerators.SIMPLE_FILESET_NAME);
//var inPCount = inFS.GetFiles().Count();
//var outFS = context.DscService.GetFileSet("DevUnitTest/Bug12584_out");
//var outPCount = outFS.GetFiles().Count();
//passed &= TestUtils.Assert(outPCount == inPCount, "Output nPartitions should be equal to input nPartitions.");
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13108_DisableSequenceEquals(DryadLinqContext context)
{
string testName = "Bug13108_DisableSequenceEquals";
TestLog.TestStart(testName);
bool passed = true;
try
{
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
IQueryable<int> pt2 = DataGenerator.GetSimpleFileSets(context);
bool result = pt1.Select(x => x).SequenceEqual(pt2.Select(x => x));
passed &= false; // NotSupportedException should have been thrown
}
}
catch (Exception Ex)
{
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13529_and_Bug13593_IndexedOperatorCompilation(DryadLinqContext context)
{
string testName = "Bug13529_and_Bug13593_IndexedOperatorCompilation";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
result[0] = pt1.Select((x, i) => x)
.LongSelect((x, i) => x)
.LongSelectMany((x, i) => new[] { x })
.SelectMany((x, i) => new[] { x })
.Where((x, i) => true)
.LongWhere((x, i) => true)
.TakeWhile((x, i) => true)
.LongTakeWhile((x, i) => true)
.SkipWhile((x, i) => false)
.LongSkipWhile((x, i) => false)
.ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
result[1] = pt1.Select((x, i) => x)
.LongSelect((x, i) => x)
.LongSelectMany((x, i) => new[] { x })
.SelectMany((x, i) => new[] { x })
.Where((x, i) => true)
.LongWhere((x, i) => true)
.TakeWhile((x, i) => true)
.LongTakeWhile((x, i) => true)
.SkipWhile((x, i) => false)
.LongSkipWhile((x, i) => false)
.ToArray();
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13130_ReverseOperator(DryadLinqContext context)
{
string testName = "Bug13130_ReverseOperator";
TestLog.TestStart(testName);
bool passed = true;
//data set #1
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
result[0] = pt1.Reverse().ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
result[1] = pt1.Reverse().ToArray();
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
//data set #2 ToDo
//data set #3 ToDo
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13736_IndexedTakeWhile(DryadLinqContext context)
{
string testName = "Bug13736_IndexedTakeWhile";
TestLog.TestStart(testName);
bool passed = true;
// dataset #1
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var pt2 = pt1.TakeWhile((x, i) => i < 6).ToArray();
result[0] = pt1.AsEnumerable().TakeWhile((x, i) => i < 6).ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var pt2 = pt1.TakeWhile((x, i) => i < 6).ToArray();
result[1] = pt1.AsEnumerable().TakeWhile((x, i) => i < 6).ToArray();
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
// dataset #2
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var pt2 = pt1.TakeWhile((x, i) => i < 125).ToArray();
result[0] = pt1.AsEnumerable().TakeWhile((x, i) => i < 125).ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context);
var pt2 = pt1.TakeWhile((x, i) => i < 125).ToArray();
result[0] = pt1.AsEnumerable().TakeWhile((x, i) => i < 125).ToArray();
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception)
{
passed &= false;
}
}
catch (Exception)
{
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13534_HashPartitionNegIndexIsError(DryadLinqContext context)
{
string testName = "Bug13534_HashPartitionNegIndexIsError";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
pt1.HashPartition(x => x, 0); // exception should be thrown
passed &= false;
}
}
catch (Exception)
{
}
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
pt1.HashPartition(x => x, -1); // exception should be thrown
passed &= false;
}
}
catch (Exception)
{
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13474_and_Bug13483_FromDscOnBadFileSet(DryadLinqContext context)
{
// ToDo
return false;
}
public static bool Bug13637_EmptyFilesInFilesets(DryadLinqContext context)
{
// ToDo
return false;
}
public static bool Bug13637_LocalDebugProducingZeroRecords(DryadLinqContext context)
{
string testName = "Bug13637_LocalDebugProducingZeroRecords";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
string outFile = "unittest/output/Bug13637_LocalDebugProducingZeroRecords";
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
IQueryable<int> pt2 = pt1.Where(x => false).ToStore(AzureUtils.ToAzureUri(Config.accountName, Config.containerName, outFile), true);
var queryInfo2 = pt2.Submit();
queryInfo2.Wait();
int[] data2 = pt2.ToArray();
passed &= (data2.Length == 0);
// query producing no records -> anonymous output
IQueryable<int> pt3 = pt1.Where(x => false);
var queryInfo3 = pt3.Submit();
queryInfo3.Wait();
int[] data3 = pt3.ToArray();
passed &= (data3.Length == 0);
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13245_FromDsc_Submit_throws(DryadLinqContext context)
{
string testName = "Bug13245_FromDsc_Submit_throws";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var info = pt1.Submit();
passed &= false; // should throw ArgEx as the input isn't well formed
}
}
catch (ArgumentException)
{
}
catch (Exception)
{
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static IQueryable<int> Blah(this IQueryable<int> source)
{
return Enumerable.Range(1, 1).AsQueryable();
}
public static bool Bug13245_QueryUsingNonHpcLinqOperator(DryadLinqContext context)
{
string testName = "Bug13245_QueryUsingNonHpcLinqOperator";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var info = pt1.Blah().Submit();
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static IEnumerable<int> CheckEnvVar(IEnumerable<int> en)
{
if (Environment.GetEnvironmentVariable("DummyEnvVar") == null)
throw new Exception("the expected environment variable is not defined");
return en;
}
public static bool Bug13302_ConfigEnvironmentCleanup(DryadLinqContext context)
{
string testName = "Bug13302_ConfigEnvironmentCleanup";
TestLog.TestStart(testName);
bool passed = true;
try
{
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var info = pt1.Apply((en) => CheckEnvVar(en)).Submit();
info.Wait();
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug13970_MismatchedDataTypes(DryadLinqContext context)
{
string testName = "Bug13970_MismatchedDataTypes";
TestLog.TestStart(testName);
bool passed = true;
try
{
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetGroupByReduceDataSet(context);
double? output = pt1.AverageAsQuery().Single();
passed &= false;
}
}
catch (Exception)
{
passed &= true; // expected
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14010_AlreadyDisposedContext(DryadLinqContext context)
{
string testName = "Bug14010_AlreadyDisposedContext";
TestLog.TestStart(testName);
bool passed = true;
context.LocalDebug = false;
try
{
DryadLinqContext ctx = new DryadLinqContext(Config.cluster);
ctx.Dispose();
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(ctx);
int output = pt1.Select(x => x).First();
passed &= false;
}
catch (Exception)
{
passed &= true;
}
try
{
DryadLinqContext ctx = new DryadLinqContext(Config.cluster);
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(ctx);
ctx.Dispose();
int output = pt1.Select(x => x).First();
passed &= false;
}
catch (Exception)
{
passed &= true;
}
try
{
DryadLinqContext ctx = new DryadLinqContext(Config.cluster);
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(ctx);
ctx.Dispose();
IQueryable<int> query = pt1.Select(x => x).ToStore(AzureUtils.ToAzureUri(Config.accountName, Config.containerName, "abc"), true);
var info = DryadLinqQueryable.Submit(query);
passed &= false;
}
catch (Exception)
{
passed &= true;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14256_LeaseOnTempDscFileset(DryadLinqContext context) // TODO
{
string testName = "Bug14256_LeaseOnTempDscFileset";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14189_OrderPreservation(DryadLinqContext context)
{
string testName = "Bug14189_OrderPreservation";
TestLog.TestStart(testName);
bool passed = true;
try
{
IGrouping<int, int>[] clusterSorted, localSorted;
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetRangePartitionDataSet(context);
var output = pt1.OrderBy(x => x % 4)
.Select(x => x).Select(x => x).Where(x => true) // this pipeline was not preserving order correctly.
.GroupBy(x => x % 4)
.ToArray();
passed &= (output.Count() == output.Select(x => x.Key).Distinct().Count()); // "each group should have a distinct key");
// sort back on the key for deterministic output.
clusterSorted = output.OrderBy(x => x.Key).ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetRangePartitionDataSet(context);
var output = pt1.OrderBy(x => x % 4)
.Select(x => x).Select(x => x).Where(x => true) // this pipeline was not preserving order correctly.
.GroupBy(x => x % 4)
.ToArray();
passed &= (output.Count() == output.Select(x => x.Key).Distinct().Count()); // "each group should have a distinct key");
// sort back on the key for deterministic output.
localSorted = output.OrderBy(x => x.Key).ToArray();
}
// check that each group of output has the same elements as the LINQ groups.
for (int i = 0; i < 4; i++)
{
var a = clusterSorted[i].OrderBy(x => x);
var b = localSorted[i].OrderBy(x => x);
passed &= a.SequenceEqual(b); //the output should match linq. Error for group: + i);
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14190_MergeJoin_DecreasingOrder(DryadLinqContext context) // TODO
{
string testName = "Bug14190_MergeJoin_DecreasingOrder";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
string outFile = "unittest/output/Bug14190_MergeJoin_DecreasingOrder";
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14192_MultiApplySubExpressionReuse(DryadLinqContext context)
{
string testName = "Bug14192_MultiApplySubExpressionReuse";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
string outFile = "unittest/output/Bug14192_MultiApplySubExpressionReuse";
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var data = pt1.Select(x => x);
var info = pt1.Apply(new[] { pt1, pt1 }, (sources) => new int[] { 1, 2, 3 }).ToStore(AzureUtils.ToAzureUri(Config.accountName, Config.containerName, outFile), true).Submit();
info.Wait();
// ToDo
//string queryPlan = TestUtils.GetRecentQueryXmlAsText();
//int nVerticesInPlan = TestUtils.GetVertexStageCount(queryPlan);
//passed &= (nVerticesInPlan == 7); // "Only seven vertices should appear (before bug, there were 10 of which the last three were extraneous.");
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug14870_LongIndexTakeWhile(DryadLinqContext context)
{
string testName = "Bug14870_LongIndexTakeWhile";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
// ToDo - move to data generator
int[][] data = new[] {
new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, new int[] { }, new int[] { } };
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var output = pt1.LongTakeWhile((x, i) => i < 8).ToArray();
passed &= (output.Length == 8); // "Only eight items should be returned."
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug15159_NotOperatorForNullableBool(DryadLinqContext context)
{
string testName = "Bug15159_NotOperatorForNullableBool";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<bool?>[] result = new IEnumerable<bool?>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var output = pt1.Select<int, bool?>(x => x == 1 ? (bool?)null : true).Select(x => !x);
result[0] = output.ToArray();
}
// local
{
context.LocalDebug = true;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
var output = pt1.Select<int, bool?>(x => x == 1 ? (bool?)null : true).Select(x => !x);
result[1] = output.ToArray();
}
// compare result
try
{
Validate.Check(result);
}
catch (Exception ex)
{
TestLog.Message("Error: " + ex.Message);
passed &= false;
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public class NoDataMembersClass
{
}
public static bool Bug15371_NoDataMembersForSerialization(DryadLinqContext context)
{
string testName = "Bug15371_NoDataMembersForSerialization";
TestLog.TestStart(testName);
bool passed = true;
try
{
// cluster
{
context.LocalDebug = false;
string outFile = "unittest/output/Bug15371_NoDataMembersForSerialization";
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
IQueryable<NoDataMembersClass> output = pt1.Select(x => new NoDataMembersClass());
var jobInfo = output.ToStore(AzureUtils.ToAzureUri(Config.accountName, Config.containerName, outFile), true).Submit();
jobInfo.Wait();
var result = context.FromStore<NoDataMembersClass>(AzureUtils.ToAzureUri(Config.accountName, Config.storageKey, Config.containerName, outFile)).ToArray();
passed &= false;
}
}
catch (DryadLinqException Ex)
{
passed &= (Ex.ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("TypeMustHaveDataMembers") ||
Ex.InnerException != null && ((DryadLinqException)Ex.InnerException).ErrorCode == ReflectionHelper.GetDryadLinqErrorCode("TypeMustHaveDataMembers")); // "exception should have been thrown.
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
public static bool Bug15570_GetHashCodeAndEqualsForNullableFieldsOfAnonymousTypes(DryadLinqContext context)
{
string testName = "Bug15570_GetHashCodeAndEqualsForNullableFieldsOfAnonymousTypes";
TestLog.TestStart(testName);
bool passed = true;
try
{
IEnumerable<int>[] result = new IEnumerable<int>[2];
// cluster
{
context.LocalDebug = false;
IQueryable<int> pt1 = DataGenerator.GetSimpleFileSets(context);
// use an anonymous type with nullable fields, and make sure we at least have some null values in the stream
var output = pt1.Select(x => new { FirstField = (x % 2 == 0) ? new int?(x) : default(int?), SecondField = x.ToString() })
.GroupBy(x => x.FirstField, y => y.SecondField); // use of GB ensures we exercise the emitted GetHashCode() overload
passed &= (output.Count() != 0); // "Query return 0 length output"
}
}
catch (Exception Ex)
{
TestLog.Message("Error: " + Ex.Message);
passed &= false;
}
TestLog.LogResult(new TestResult(testName, context, passed));
return passed;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public enum MegaRubberType
{
Custom,
SoftRubber,
HardRubber,
Jelly,
SoftLatex
}
[System.Serializable]
public class VertexRubber
{
public Vector3 pos;
public Vector3 cpos;
public Vector3 force;
public Vector3 acc;
public Vector3 vel;
public int[] indices;
public float weight;
public float stiff;
public VertexRubber(Vector3 v_target, float w, float s) { pos = v_target; weight = w; stiff = s; }
}
[AddComponentMenu("Modifiers/Rubber")]
public class MegaRubber : MegaModifier
{
public override string ModName() { return "Rubber"; }
public override string GetHelpURL() { return "?page_id=1254"; }
// From other system
public MegaRubberType Presets = MegaRubberType.Custom;
public MegaWeightChannel channel = MegaWeightChannel.Red;
public MegaWeightChannel stiffchannel = MegaWeightChannel.None;
public Vector3 Intensity = Vector3.one;
public float gravity = 0.0f;
public float mass = 1.0f;
public Vector3 stiffness = new Vector3(0.2f, 0.2f, 0.2f);
public Vector3 damping = new Vector3(0.7f, 0.7f, 0.7f);
public float threshold = 0.0f;
public float size = 0.001f;
public bool showweights = true;
float oomass;
float grav;
bool defined = false;
public VertexRubber[] vr;
int[] notmoved;
public Transform target;
[ContextMenu("Reset Physics")]
public void ResetPhysics()
{
MegaModifiers mod = GetComponent<MegaModifiers>();
if ( mod )
Init(mod);
}
int[] FindVerts(Vector3[] vts, Vector3 p)
{
List<int> indices = new List<int>();
for ( int i = 0; i < vts.Length; i++ )
{
if ( p.x == vts[i].x && p.y == vts[i].y && p.z == vts[i].z )
indices.Add(i);
}
return indices.ToArray();
}
bool HavePoint(Vector3[] vts, List<int> points, Vector3 p)
{
for ( int i = 0; i < points.Count; i++ )
{
if ( p.x == vts[points[i]].x && p.y == vts[points[i]].y && p.z == vts[points[i]].z )
return true;
}
return false;
}
void Init(MegaModifiers mod)
{
if ( mod.verts == null )
return;
List<int> noweights = new List<int>();
List<int> ActiveVertex = new List<int>();
int wc = (int)channel;
for ( int i = 0; i < mod.verts.Length; i++ )
{
// Dont add if we have already
if ( channel == MegaWeightChannel.None || mod.cols == null || mod.cols.Length == 0 )
{
//if ( !HavePoint(mod.verts, ActiveVertex, mod.verts[i]) )
//ActiveVertex.Add(i);
}
else
{
if ( mod.cols[i][wc] > threshold )
{
if ( !HavePoint(mod.verts, ActiveVertex, mod.verts[i]) )
ActiveVertex.Add(i);
}
else
noweights.Add(i);
}
}
notmoved = noweights.ToArray();
if ( ActiveVertex.Count > 0 )
{
vr = new VertexRubber[ActiveVertex.Count];
for ( int i = 0; i < ActiveVertex.Count; i++ )
{
int ref_index = (int)ActiveVertex[i];
float stiff = 1.0f;
if ( stiffchannel != MegaWeightChannel.None && mod.cols != null && mod.cols.Length > 0 )
{
stiff = mod.cols[ref_index][(int)stiffchannel];
}
float intens = (mod.cols[ref_index][wc] - threshold) / (1.0f - threshold);
vr[i] = new VertexRubber(transform.TransformPoint(mod.verts[ref_index]), intens, stiff);
vr[i].indices = FindVerts(mod.verts, mod.verts[ref_index]);
}
}
else
vr = null;
defined = true;
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( weightsChanged )
{
ResetPhysics();
weightsChanged = false;
}
return Prepare(mc);
}
public override bool Prepare(MegaModContext mc)
{
if ( target )
{
tm = target.worldToLocalMatrix * transform.localToWorldMatrix;
invtm = tm.inverse; //target.worldToLocalMatrix;
}
else
{
tm = transform.localToWorldMatrix;
invtm = transform.worldToLocalMatrix;
}
oomass = 1.0f / mass;
grav = gravity * 0.1f;
if ( !defined )
Init(mc.mod);
if ( vr != null )
return true;
return false;
}
public override void Modify(MegaModifiers mc)
{
UpdateVerts(0, vr.Length);
for ( int i = 0; i < notmoved.Length; i++ )
sverts[notmoved[i]] = verts[notmoved[i]];
}
public void SetTarget(Transform target)
{
if ( target )
{
tm = target.worldToLocalMatrix * transform.localToWorldMatrix;
invtm = tm.inverse; //target.worldToLocalMatrix;
}
else
{
tm = transform.localToWorldMatrix;
invtm = transform.worldToLocalMatrix;
}
InitVerts(0, vr.Length);
}
void InitVerts(int start, int end)
{
for ( int i = start; i < end; i++ )
{
int ix = vr[i].indices[0];
Vector3 vp = verts[ix];
Vector3 v3_target = tm.MultiplyPoint(vp);
VertexRubber v = vr[i];
v.vel = Vector3.zero;
v.pos = v3_target;
}
}
void UpdateVerts(int start, int end)
{
Vector3 p = Vector3.zero;
for ( int i = start; i < end; i++ )
{
int ix = vr[i].indices[0];
Vector3 vp = verts[ix];
Vector3 v3_target = tm.MultiplyPoint(vp);
VertexRubber v = vr[i];
v.force.x = (v3_target.x - v.pos.x) * stiffness.x * v.stiff;
v.acc.x = v.force.x * oomass;
v.vel.x = damping.x * (v.vel.x + v.acc.x);
v.pos.x += v.vel.x; // * t;
v.force.y = (v3_target.y - v.pos.y) * stiffness.y * v.stiff;
v.force.y -= grav;
v.acc.y = v.force.y * oomass;
v.vel.y = damping.y * (v.vel.y + v.acc.y);
v.pos.y += v.vel.y; // * t;
v.force.z = (v3_target.z - v.pos.z) * stiffness.z * v.stiff;
v.acc.z = v.force.z * oomass;
v.vel.z = damping.z * (v.vel.z + v.acc.z);
v.pos.z += v.vel.z; // * t;
v3_target = invtm.MultiplyPoint(vr[i].pos);
p.x = vp.x + ((v3_target.x - vp.x) * v.weight * Intensity.x);
p.y = vp.y + ((v3_target.y - vp.y) * v.weight * Intensity.y);
p.z = vp.z + ((v3_target.z - vp.z) * v.weight * Intensity.z);
v.cpos = p;
for ( int v1 = 0; v1 < vr[i].indices.Length; v1++ )
{
int ix1 = vr[i].indices[v1];
sverts[ix1] = p;
}
}
}
public void ChangeMaterial()
{
switch ( Presets )
{
case MegaRubberType.HardRubber:
gravity = 0.0f;
mass = 8.0f;
stiffness = new Vector3(0.5f, 0.5f, 0.5f);
damping = new Vector3(0.9f, 0.9f, 0.9f);
Intensity = new Vector3(0.5f, 0.5f, 0.5f);
break;
case MegaRubberType.Jelly:
gravity = 0.0f;
mass = 1.0f;
stiffness = new Vector3(0.95f, 0.95f, 0.95f);
damping = new Vector3(0.95f, 0.95f, 0.95f);
Intensity = Vector3.one;
break;
case MegaRubberType.SoftRubber:
gravity = 0.0f;
mass = 2.0f;
stiffness = new Vector3(0.5f, 0.5f, 0.5f);
damping = new Vector3(0.85f, 0.85f, 0.85f);
Intensity = Vector3.one;
break;
case MegaRubberType.SoftLatex:
gravity = 1.0f;
mass = 0.9f;
stiffness = new Vector3(0.3f, 0.3f, 0.3f);
damping = new Vector3(0.25f, 0.25f, 0.25f);
Intensity = Vector3.one;
break;
}
}
public void ChangeChannel()
{
MegaModifiers mod = GetComponent<MegaModifiers>();
if ( mod )
Init(mod);
}
// Threaded
public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores)
{
ModifyCompressedMT(mc, index, cores);
}
public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores)
{
int step = notmoved.Length / cores;
int startvert = (tindex * step);
int endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = notmoved.Length;
if ( notmoved != null )
{
for ( int i = startvert; i < endvert; i++ )
{
int index = notmoved[i];
sverts[index] = verts[index];
}
}
step = vr.Length / cores;
startvert = (tindex * step);
endvert = startvert + step;
if ( tindex == cores - 1 )
endvert = vr.Length;
UpdateVerts(startvert, endvert);
}
bool weightsChanged = false;
MegaModifiers mods = null;
MegaModifiers GetMod()
{
if ( mods == null )
mods = GetComponent<MegaModifiers>();
return mods;
}
public void UpdateCols(int first, Color[] newcols)
{
GetMod();
if ( mods )
mods.UpdateCols(first, newcols);
weightsChanged = true;
}
public void UpdateCol(int i, Color col)
{
GetMod();
if ( mods )
mods.UpdateCol(i, col);
weightsChanged = true;
}
public void UpdateCols(Color[] newcols)
{
GetMod();
if ( mods )
mods.UpdateCols(newcols);
weightsChanged = true;
}
}
| |
// ***********************************************************************
// Copyright (c) 2014-2015 Charlie Poole
//
// 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.Reflection;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Builders
{
/// <summary>
/// NUnitTestFixtureBuilder is able to build a fixture given
/// a class marked with a TestFixtureAttribute or an unmarked
/// class containing test methods. In the first case, it is
/// called by the attribute and in the second directly by
/// NUnitSuiteBuilder.
/// </summary>
public class NUnitTestFixtureBuilder
{
#region Static Fields
static readonly string NO_TYPE_ARGS_MSG =
"Fixture type contains generic parameters. You must either provide " +
"Type arguments or specify constructor arguments that allow NUnit " +
"to deduce the Type arguments.";
#endregion
#region Instance Fields
private ITestCaseBuilder _testBuilder = new DefaultTestCaseBuilder();
#endregion
#region Public Methods
/// <summary>
/// Build a TestFixture from type provided. A non-null TestSuite
/// must always be returned, since the method is generally called
/// because the user has marked the target class as a fixture.
/// If something prevents the fixture from being used, it should
/// be returned nonetheless, labelled as non-runnable.
/// </summary>
/// <param name="type">The type of the fixture to be used.</param>
/// <returns>A TestSuite object or one derived from TestSuite.</returns>
// TODO: This should really return a TestFixture, but that requires changes to the Test hierarchy.
public TestSuite BuildFrom(Type type)
{
var fixture = new TestFixture(type);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(type);
AddTestCasesToFixture(fixture);
return fixture;
}
/// <summary>
/// Overload of BuildFrom called by tests that have arguments.
/// Builds a fixture using the provided type and information
/// in the ITestFixtureData object.
/// </summary>
/// <param name="type">The Type for which to construct a fixture.</param>
/// <param name="testFixtureData">An object implementing ITestFixtureData or null.</param>
/// <returns></returns>
public TestSuite BuildFrom(Type type, ITestFixtureData testFixtureData)
{
Guard.ArgumentNotNull(testFixtureData, "testFixtureData");
object[] arguments = testFixtureData.Arguments;
if (type.ContainsGenericParameters)
{
Type[] typeArgs = testFixtureData.TypeArgs;
if (typeArgs.Length == 0)
{
int cnt = 0;
foreach (object o in arguments)
if (o is Type) cnt++;
else break;
typeArgs = new Type[cnt];
for (int i = 0; i < cnt; i++)
typeArgs[i] = (Type)arguments[i];
if (cnt > 0)
{
object[] args = new object[arguments.Length - cnt];
for (int i = 0; i < args.Length; i++)
args[i] = arguments[cnt + i];
arguments = args;
}
}
if (typeArgs.Length > 0 ||
TypeHelper.CanDeduceTypeArgsFromArgs(type, arguments, ref typeArgs))
{
type = TypeHelper.MakeGenericType(type, typeArgs);
}
}
var fixture = new TestFixture(type);
if (arguments != null && arguments.Length > 0)
{
string name = fixture.Name = TypeHelper.GetDisplayName(type, arguments);
string nspace = type.Namespace;
fixture.FullName = nspace != null && nspace != ""
? nspace + "." + name
: name;
fixture.Arguments = arguments;
}
if (fixture.RunState != RunState.NotRunnable)
fixture.RunState = testFixtureData.RunState;
foreach (string key in testFixtureData.Properties.Keys)
foreach (object val in testFixtureData.Properties[key])
fixture.Properties.Add(key, val);
if (fixture.RunState != RunState.NotRunnable)
CheckTestFixtureIsValid(fixture);
fixture.ApplyAttributesToTest(type);
AddTestCasesToFixture(fixture);
return fixture;
}
#endregion
#region Helper Methods
/// <summary>
/// Method to add test cases to the newly constructed fixture.
/// </summary>
/// <param name="fixture">The fixture to which cases should be added</param>
private void AddTestCasesToFixture(TestFixture fixture)
{
Type fixtureType = fixture.FixtureType;
// TODO: Check this logic added from Neil's build.
if (fixtureType.ContainsGenericParameters)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
return;
}
IList methods = fixtureType.GetMethods(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (MethodInfo method in methods)
{
Test test = BuildTestCase(method, fixture);
if (test != null)
{
fixture.Add(test);
}
}
}
/// <summary>
/// Method to create a test case from a MethodInfo and add
/// it to the fixture being built. It first checks to see if
/// any global TestCaseBuilder addin wants to build the
/// test case. If not, it uses the internal builder
/// collection maintained by this fixture builder.
///
/// The default implementation has no test case builders.
/// Derived classes should add builders to the collection
/// in their constructor.
/// </summary>
/// <param name="method">The MethodInfo for which a test is to be created</param>
/// <param name="suite">The test suite being built.</param>
/// <returns>A newly constructed Test</returns>
private Test BuildTestCase(MethodInfo method, TestSuite suite)
{
return _testBuilder.CanBuildFrom(method, suite)
? _testBuilder.BuildFrom(method, suite)
: null;
}
private static void CheckTestFixtureIsValid(TestFixture fixture)
{
Type fixtureType = fixture.FixtureType;
if (fixtureType.ContainsGenericParameters)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, NO_TYPE_ARGS_MSG);
}
else if (!IsStaticClass(fixtureType))
{
object[] args = fixture.Arguments;
Type[] argTypes;
// Note: This could be done more simply using
// Type.EmptyTypes and Type.GetTypeArray() but
// they don't exist in all runtimes we support.
argTypes = new Type[args.Length];
int index = 0;
foreach (object arg in args)
argTypes[index++] = arg.GetType();
ConstructorInfo ctor = fixtureType.GetConstructor(argTypes);
if (ctor == null)
{
fixture.RunState = RunState.NotRunnable;
fixture.Properties.Set(PropertyNames.SkipReason, "No suitable constructor was found");
}
}
}
private static bool IsStaticClass(Type type)
{
return type.IsAbstract && type.IsSealed;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization
{
using System;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
// this[key] api throws KeyNotFoundException
using Hashtable = System.Collections.InternalHashtable;
// These classes define the abstract serialization model, e.g. the rules for WHAT is serialized.
// The answer of HOW the values are serialized is answered by a particular reflection importer
// by looking for a particular set of custom attributes specific to the serialization format
// and building an appropriate set of accessors/mappings.
internal class ModelScope
{
private TypeScope _typeScope;
private Hashtable _models = new Hashtable();
private Hashtable _arrayModels = new Hashtable();
internal ModelScope(TypeScope typeScope)
{
_typeScope = typeScope;
}
internal TypeScope TypeScope
{
get { return _typeScope; }
}
internal TypeModel GetTypeModel(Type type)
{
return GetTypeModel(type, true);
}
internal TypeModel GetTypeModel(Type type, bool directReference)
{
TypeModel model = (TypeModel)_models[type];
if (model != null) return model;
TypeDesc typeDesc = _typeScope.GetTypeDesc(type, null, directReference);
switch (typeDesc.Kind)
{
case TypeKind.Enum:
model = new EnumModel(type, typeDesc, this);
break;
case TypeKind.Primitive:
model = new PrimitiveModel(type, typeDesc, this);
break;
case TypeKind.Array:
case TypeKind.Collection:
case TypeKind.Enumerable:
model = new ArrayModel(type, typeDesc, this);
break;
case TypeKind.Root:
case TypeKind.Class:
case TypeKind.Struct:
model = new StructModel(type, typeDesc, this);
break;
default:
if (!typeDesc.IsSpecial) throw new NotSupportedException(SR.Format(SR.XmlUnsupportedTypeKind, type.FullName));
model = new SpecialModel(type, typeDesc, this);
break;
}
_models.Add(type, model);
return model;
}
internal ArrayModel GetArrayModel(Type type)
{
TypeModel model = (TypeModel)_arrayModels[type];
if (model == null)
{
model = GetTypeModel(type);
if (!(model is ArrayModel))
{
TypeDesc typeDesc = _typeScope.GetArrayTypeDesc(type);
model = new ArrayModel(type, typeDesc, this);
}
_arrayModels.Add(type, model);
}
return (ArrayModel)model;
}
}
internal abstract class TypeModel
{
private TypeDesc _typeDesc;
private Type _type;
private ModelScope _scope;
protected TypeModel(Type type, TypeDesc typeDesc, ModelScope scope)
{
_scope = scope;
_type = type;
_typeDesc = typeDesc;
}
internal Type Type
{
get { return _type; }
}
internal ModelScope ModelScope
{
get { return _scope; }
}
internal TypeDesc TypeDesc
{
get { return _typeDesc; }
}
}
internal class ArrayModel : TypeModel
{
internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal TypeModel Element
{
get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); }
}
}
internal class PrimitiveModel : TypeModel
{
internal PrimitiveModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class SpecialModel : TypeModel
{
internal SpecialModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
}
internal class StructModel : TypeModel
{
internal StructModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal MemberInfo[] GetMemberInfos()
{
// we use to return Type.GetMembers() here, the members were returned in a different order: fields first, properties last
// Current System.Reflection code returns members in oposite order: properties first, then fields.
// This code make sure that returns members in the Everett order.
MemberInfo[] members = Type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
MemberInfo[] fieldsAndProps = new MemberInfo[members.Length];
int cMember = 0;
// first copy all non-property members over
for (int i = 0; i < members.Length; i++)
{
if (!(members[i] is PropertyInfo))
{
fieldsAndProps[cMember++] = members[i];
}
}
// now copy all property members over
for (int i = 0; i < members.Length; i++)
{
if (members[i] is PropertyInfo)
{
fieldsAndProps[cMember++] = members[i];
}
}
return fieldsAndProps;
}
internal FieldModel GetFieldModel(MemberInfo memberInfo)
{
FieldModel model = null;
if (memberInfo is FieldInfo)
model = GetFieldModel((FieldInfo)memberInfo);
else if (memberInfo is PropertyInfo)
model = GetPropertyModel((PropertyInfo)memberInfo);
if (model != null)
{
if (model.ReadOnly && model.FieldTypeDesc.Kind != TypeKind.Collection && model.FieldTypeDesc.Kind != TypeKind.Enumerable)
return null;
}
return model;
}
private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
{
if (typeDesc == null)
return;
if (typeDesc.IsUnsupported)
{
if (typeDesc.Exception == null)
{
typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName));
}
throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception);
}
CheckSupportedMember(typeDesc.BaseTypeDesc, member, type);
CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type);
}
private FieldModel GetFieldModel(FieldInfo fieldInfo)
{
if (fieldInfo.IsStatic) return null;
if (fieldInfo.DeclaringType != Type) return null;
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(fieldInfo.FieldType, fieldInfo, true, false);
if (fieldInfo.IsInitOnly && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, fieldInfo, fieldInfo.FieldType);
return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc);
}
private FieldModel GetPropertyModel(PropertyInfo propertyInfo)
{
if (propertyInfo.DeclaringType != Type) return null;
if (CheckPropertyRead(propertyInfo))
{
TypeDesc typeDesc = ModelScope.TypeScope.GetTypeDesc(propertyInfo.PropertyType, propertyInfo, true, false);
// Fix for CSDMain 100492, please contact arssrvlt if you need to change this line
if (!propertyInfo.CanWrite && typeDesc.Kind != TypeKind.Collection && typeDesc.Kind != TypeKind.Enumerable)
return null;
CheckSupportedMember(typeDesc, propertyInfo, propertyInfo.PropertyType);
return new FieldModel(propertyInfo, propertyInfo.PropertyType, typeDesc);
}
return null;
}
//CheckProperty
internal static bool CheckPropertyRead(PropertyInfo propertyInfo)
{
if (!propertyInfo.CanRead) return false;
MethodInfo getMethod = propertyInfo.GetMethod;
if (getMethod.IsStatic) return false;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length > 0) return false;
return true;
}
}
internal enum SpecifiedAccessor
{
None,
ReadOnly,
ReadWrite,
}
internal class FieldModel
{
private SpecifiedAccessor _checkSpecified = SpecifiedAccessor.None;
private MemberInfo _memberInfo;
private MemberInfo _checkSpecifiedMemberInfo;
private MethodInfo _checkShouldPersistMethodInfo;
private bool _checkShouldPersist;
private bool _readOnly = false;
private bool _isProperty = false;
private Type _fieldType;
private string _name;
private TypeDesc _fieldTypeDesc;
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist) :
this(name, fieldType, fieldTypeDesc, checkSpecified, checkShouldPersist, false)
{
}
internal FieldModel(string name, Type fieldType, TypeDesc fieldTypeDesc, bool checkSpecified, bool checkShouldPersist, bool readOnly)
{
_fieldTypeDesc = fieldTypeDesc;
_name = name;
_fieldType = fieldType;
_checkSpecified = checkSpecified ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.None;
_checkShouldPersist = checkShouldPersist;
_readOnly = readOnly;
}
internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDesc)
{
_name = memberInfo.Name;
_fieldType = fieldType;
_fieldTypeDesc = fieldTypeDesc;
_memberInfo = memberInfo;
_checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty<Type>());
_checkShouldPersist = _checkShouldPersistMethodInfo != null;
FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified");
if (specifiedField != null)
{
if (specifiedField.FieldType != typeof(bool))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedField.Name, specifiedField.FieldType.FullName, typeof(bool).FullName));
}
_checkSpecified = specifiedField.IsInitOnly ? SpecifiedAccessor.ReadOnly : SpecifiedAccessor.ReadWrite;
_checkSpecifiedMemberInfo = specifiedField;
}
else
{
PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified");
if (specifiedProperty != null)
{
if (StructModel.CheckPropertyRead(specifiedProperty))
{
_checkSpecified = specifiedProperty.CanWrite ? SpecifiedAccessor.ReadWrite : SpecifiedAccessor.ReadOnly;
_checkSpecifiedMemberInfo = specifiedProperty;
}
if (_checkSpecified != SpecifiedAccessor.None && specifiedProperty.PropertyType != typeof(bool))
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidSpecifiedType, specifiedProperty.Name, specifiedProperty.PropertyType.FullName, typeof(bool).FullName));
}
}
}
if (memberInfo is PropertyInfo)
{
_readOnly = !((PropertyInfo)memberInfo).CanWrite;
_isProperty = true;
}
else if (memberInfo is FieldInfo)
{
_readOnly = ((FieldInfo)memberInfo).IsInitOnly;
}
}
internal string Name
{
get { return _name; }
}
internal Type FieldType
{
get { return _fieldType; }
}
internal TypeDesc FieldTypeDesc
{
get { return _fieldTypeDesc; }
}
internal bool CheckShouldPersist
{
get { return _checkShouldPersist; }
}
internal SpecifiedAccessor CheckSpecified
{
get { return _checkSpecified; }
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
}
internal MemberInfo CheckSpecifiedMemberInfo
{
get { return _checkSpecifiedMemberInfo; }
}
internal MethodInfo CheckShouldPersistMethodInfo
{
get { return _checkShouldPersistMethodInfo; }
}
internal bool ReadOnly
{
get { return _readOnly; }
}
internal bool IsProperty
{
get { return _isProperty; }
}
}
internal class ConstantModel
{
private FieldInfo _fieldInfo;
private long _value;
internal ConstantModel(FieldInfo fieldInfo, long value)
{
_fieldInfo = fieldInfo;
_value = value;
}
internal string Name
{
get { return _fieldInfo.Name; }
}
internal long Value
{
get { return _value; }
}
internal FieldInfo FieldInfo
{
get { return _fieldInfo; }
}
}
internal class EnumModel : TypeModel
{
private ConstantModel[] _constants;
internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { }
internal ConstantModel[] Constants
{
get
{
if (_constants == null)
{
ArrayList list = new ArrayList();
FieldInfo[] fields = Type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
ConstantModel constant = GetConstantModel(field);
if (constant != null) list.Add(constant);
}
_constants = (ConstantModel[])list.ToArray(typeof(ConstantModel));
}
return _constants;
}
}
private ConstantModel GetConstantModel(FieldInfo fieldInfo)
{
if (fieldInfo.IsSpecialName) return null;
return new ConstantModel(fieldInfo, (Convert.ToInt64(fieldInfo.GetValue(null), null)));
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Internal.Interop;
using Internal.Threading.Tasks;
namespace System
{
/// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br />
/// Currently contains:<br />
/// <ul>
/// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces
/// and <code>System.Threading.Tasks.Task</code>.</li>
/// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code>
/// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li>
/// </ul></summary>
[CLSCompliant(false)]
public static class WindowsRuntimeSystemExtensions
{
#region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Convenience Helpers
private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime)
{
Contract.Requires(sink != null);
CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); },
sink);
concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); },
ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info));
}
private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink)
{
// This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null.
source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info));
}
#endregion Convenience Helpers
#region Converters from IAsyncAction to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter(this IAsyncAction source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionAdapter;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created);
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Helpers.CompletedTask;
case AsyncStatus.Error:
return Helpers.TaskFromException<VoidValueTypeParameter>(source.ErrorCode.AttachRestrictedErrorInfo());
case AsyncStatus.Canceled:
return Helpers.TaskFromCancellation<VoidValueTypeParameter>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter>(cancellationToken);
try
{
source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction);
bridge.RegisterForCancellation(source);
}
catch
{
AsyncCausalitySupport.RemoveFromActiveTasks(bridge.Task);
}
return bridge.Task;
}
#endregion Converters from IAsyncAction to Task
#region Converters from IAsyncOperation<TResult> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source)
{
return AsTask(source, CancellationToken.None);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationAdapter<TResult>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatination is useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Helpers.TaskFromException<TResult>(source.ErrorCode.AttachRestrictedErrorInfo());
case AsyncStatus.Canceled:
return Helpers.TaskFromCancellation<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult>(cancellationToken);
try
{
source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation);
bridge.RegisterForCancellation(source);
}
catch
{
AsyncCausalitySupport.RemoveFromActiveTasks(bridge.Task);
}
return bridge.Task;
}
#endregion Converters from IAsyncOperation<TResult> to Task
#region Converters from IAsyncActionWithProgress<TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task innerTask = wrapper.Task;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed:
switch (source.Status)
{
case AsyncStatus.Completed:
return Helpers.CompletedTask;
case AsyncStatus.Error:
return Helpers.TaskFromException<VoidValueTypeParameter>(source.ErrorCode.AttachRestrictedErrorInfo());
case AsyncStatus.Canceled:
return Helpers.TaskFromCancellation<VoidValueTypeParameter>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter>(cancellationToken);
try
{
source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress);
bridge.RegisterForCancellation(source);
}
catch
{
AsyncCausalitySupport.RemoveFromActiveTasks(bridge.Task);
}
return bridge.Task;
}
#endregion Converters from IAsyncActionWithProgress<TProgress> to Task
#region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
/// <summary>Gets an awaiter used to await this asynchronous operation.</summary>
/// <returns>An awaiter instance.</returns>
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source).GetAwaiter();
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <returns>The Task representing the started asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source)
{
return AsTask(source, CancellationToken.None, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken)
{
return AsTask(source, cancellationToken, null);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
IProgress<TProgress> progress)
{
return AsTask(source, CancellationToken.None, progress);
}
/// <summary>Gets a Task to represent the asynchronous operation.</summary>
/// <param name="source">The asynchronous operation.</param>
/// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
/// <param name="progress">The progress object used to receive progress updates.</param>
/// <returns>The Task representing the asynchronous operation.</returns>
public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source,
CancellationToken cancellationToken, IProgress<TProgress> progress)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>;
if (wrapper != null && !wrapper.CompletedSynchronously)
{
Task<TResult> innerTask = wrapper.Task as Task<TResult>;
Debug.Assert(innerTask != null);
Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment?
if (!innerTask.IsCompleted)
{
// The race here is benign: If the task completes here, the concatinations are useless, but not damaging.
if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
if (progress != null)
ConcatenateProgress(source, progress);
}
return innerTask;
}
// Fast path to return a completed Task if the operation has already completed
switch (source.Status)
{
case AsyncStatus.Completed:
return Task.FromResult(source.GetResults());
case AsyncStatus.Error:
return Helpers.TaskFromException<TResult>(source.ErrorCode.AttachRestrictedErrorInfo());
case AsyncStatus.Canceled:
return Helpers.TaskFromCancellation<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
// Benign race: source may complete here. Things still work, just not taking the fast path.
// Forward progress reports:
if (progress != null)
ConcatenateProgress(source, progress);
// Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
var bridge = new AsyncInfoToTaskBridge<TResult>(cancellationToken);
try
{
source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
bridge.RegisterForCancellation(source);
}
catch
{
AsyncCausalitySupport.RemoveFromActiveTasks(bridge.Task);
}
return bridge.Task;
}
#endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task
#endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task
#region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
public static IAsyncAction AsAsyncAction(this Task source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null);
}
public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null);
}
#endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it)
} // class WindowsRuntimeSystemExtensions
} // namespace
// WindowsRuntimeExtensions.cs
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
// This class takes an EXPRMEMGRP and a set of arguments and binds the arguments
// to the best applicable method in the group.
// ----------------------------------------------------------------------------
internal sealed partial class ExpressionBinder
{
internal sealed class GroupToArgsBinder
{
private enum Result
{
Success,
Failure_SearchForExpanded,
Failure_NoSearchForExpanded
}
private readonly ExpressionBinder _pExprBinder;
private bool _fCandidatesUnsupported;
private readonly BindingFlag _fBindFlags;
private readonly ExprMemberGroup _pGroup;
private readonly ArgInfos _pArguments;
private readonly ArgInfos _pOriginalArguments;
private readonly bool _bHasNamedArguments;
private readonly AggregateType _pDelegate;
private AggregateType _pCurrentType;
private MethodOrPropertySymbol _pCurrentSym;
private TypeArray _pCurrentTypeArgs;
private TypeArray _pCurrentParameters;
private TypeArray _pBestParameters;
private int _nArgBest;
// Keep track of the first 20 or so syms with the wrong arg count.
private readonly SymWithType[] _swtWrongCount = new SymWithType[20];
private int _nWrongCount;
private bool _bIterateToEndOfNsList; // we have found an appliacable extension method only itereate to
// end of current namespaces extension method list
private bool _bBindingCollectionAddArgs; // Report parameter modifiers as error
private readonly GroupToArgsBinderResult _results;
private readonly List<CandidateFunctionMember> _methList;
private readonly MethPropWithInst _mpwiParamTypeConstraints;
private readonly MethPropWithInst _mpwiBogus;
private readonly MethPropWithInst _mpwiCantInferInstArg;
private readonly MethWithType _mwtBadArity;
private Name _pInvalidSpecifiedName;
private Name _pNameUsedInPositionalArgument;
private Name _pDuplicateSpecifiedName;
// When we find a type with an interface, then we want to mark all other interfaces that it
// implements as being hidden. We also want to mark object as being hidden. So stick them
// all in this list, and then for subsequent types, if they're in this list, then we
// ignore them.
private readonly List<CType> _HiddenTypes;
private bool _bArgumentsChangedForNamedOrOptionalArguments;
public GroupToArgsBinder(ExpressionBinder exprBinder, BindingFlag bindFlags, ExprMemberGroup grp, ArgInfos args, ArgInfos originalArgs, bool bHasNamedArguments, AggregateType atsDelegate)
{
Debug.Assert(grp != null);
Debug.Assert(exprBinder != null);
Debug.Assert(args != null);
_pExprBinder = exprBinder;
_fCandidatesUnsupported = false;
_fBindFlags = bindFlags;
_pGroup = grp;
_pArguments = args;
_pOriginalArguments = originalArgs;
_bHasNamedArguments = bHasNamedArguments;
_pDelegate = atsDelegate;
_pCurrentType = null;
_pCurrentSym = null;
_pCurrentTypeArgs = null;
_pCurrentParameters = null;
_pBestParameters = null;
_nArgBest = -1;
_nWrongCount = 0;
_bIterateToEndOfNsList = false;
_bBindingCollectionAddArgs = false;
_results = new GroupToArgsBinderResult();
_methList = new List<CandidateFunctionMember>();
_mpwiParamTypeConstraints = new MethPropWithInst();
_mpwiBogus = new MethPropWithInst();
_mpwiCantInferInstArg = new MethPropWithInst();
_mwtBadArity = new MethWithType();
_HiddenTypes = new List<CType>();
}
// ----------------------------------------------------------------------------
// This method does the actual binding.
// ----------------------------------------------------------------------------
public bool Bind(bool bReportErrors)
{
Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER));
// We need the Exprs for error reporting for non-delegates
Debug.Assert(_pDelegate != null || _pArguments.fHasExprs);
LookForCandidates();
if (!GetResultOfBind(bReportErrors))
{
if (bReportErrors)
{
ReportErrorsOnFailure();
}
return false;
}
return true;
}
public GroupToArgsBinderResult GetResultsOfBind()
{
return _results;
}
public bool BindCollectionAddArgs()
{
_bBindingCollectionAddArgs = true;
return Bind(true /* bReportErrors */);
}
private SymbolLoader GetSymbolLoader()
{
return _pExprBinder.GetSymbolLoader();
}
private CSemanticChecker GetSemanticChecker()
{
return _pExprBinder.GetSemanticChecker();
}
private ErrorHandling GetErrorContext()
{
return _pExprBinder.GetErrorContext();
}
private static CType GetTypeQualifier(ExprMemberGroup pGroup)
{
Debug.Assert(pGroup != null);
CType rval = null;
if (0 != (pGroup.Flags & EXPRFLAG.EXF_BASECALL))
{
rval = null;
}
else if (0 != (pGroup.Flags & EXPRFLAG.EXF_CTOR))
{
rval = pGroup.ParentType;
}
else if (pGroup.OptionalObject != null)
{
rval = pGroup.OptionalObject.Type;
}
else
{
rval = null;
}
return rval;
}
private void LookForCandidates()
{
bool fExpanded = false;
bool bSearchForExpanded = true;
int cswtMaxWrongCount = _swtWrongCount.Length;
bool allCandidatesUnsupported = true;
bool lookedAtCandidates = false;
// Calculate the mask based on the type of the sym we've found so far. This
// is to ensure that if we found a propsym (or methsym, or whatever) the
// iterator will only return propsyms (or methsyms, or whatever)
symbmask_t mask = (symbmask_t)(1 << (int)_pGroup.SymKind);
CType pTypeThrough = _pGroup.OptionalObject?.Type;
CMemberLookupResults.CMethodIterator iterator = _pGroup.MemberLookupResults.GetMethodIterator(GetSemanticChecker(), GetSymbolLoader(), pTypeThrough, GetTypeQualifier(_pGroup), _pExprBinder.ContextForMemberLookup(), true, // AllowBogusAndInaccessible
false, _pGroup.TypeArgs.Count, _pGroup.Flags, mask);
while (true)
{
bool bFoundExpanded;
bFoundExpanded = false;
if (bSearchForExpanded && !fExpanded)
{
bFoundExpanded = fExpanded = ConstructExpandedParameters();
}
// Get the next sym to search for.
if (!bFoundExpanded)
{
fExpanded = false;
if (!GetNextSym(iterator))
{
break;
}
// Get the parameters.
_pCurrentParameters = _pCurrentSym.Params;
bSearchForExpanded = true;
}
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
_bArgumentsChangedForNamedOrOptionalArguments = false;
CopyArgInfos(_pOriginalArguments, _pArguments);
}
// If we have named arguments, reorder them for this method.
if (_pArguments.fHasExprs)
{
// If we don't have Exprs, its because we're doing a method group conversion.
// In those scenarios, we never want to add named arguments or optional arguments.
if (_bHasNamedArguments)
{
if (!ReOrderArgsForNamedArguments())
{
continue;
}
}
else if (HasOptionalParameters())
{
if (!AddArgumentsForOptionalParameters())
{
continue;
}
}
}
if (!bFoundExpanded)
{
lookedAtCandidates = true;
allCandidatesUnsupported &= _pCurrentSym.getBogus();
// If we have the wrong number of arguments and still have room in our cache of 20,
// then store it in our cache and go to the next sym.
if (_pCurrentParameters.Count != _pArguments.carg)
{
if (_nWrongCount < cswtMaxWrongCount &&
(!_pCurrentSym.isParamArray || _pArguments.carg < _pCurrentParameters.Count - 1))
{
_swtWrongCount[_nWrongCount++] = new SymWithType(_pCurrentSym, _pCurrentType);
}
bSearchForExpanded = true;
continue;
}
}
// If we cant use the current symbol, then we've filtered it, so get the next one.
if (!iterator.CanUseCurrentSymbol())
{
continue;
}
// Get the current type args.
Result currentTypeArgsResult = DetermineCurrentTypeArgs();
if (currentTypeArgsResult != Result.Success)
{
bSearchForExpanded = (currentTypeArgsResult == Result.Failure_SearchForExpanded);
continue;
}
// Check access.
bool fCanAccess = !iterator.IsCurrentSymbolInaccessible();
if (!fCanAccess && (!_methList.IsEmpty() || _results.GetInaccessibleResult()))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check bogus.
bool fBogus = fCanAccess && iterator.IsCurrentSymbolBogus();
if (fBogus && (!_methList.IsEmpty() || _results.GetInaccessibleResult() || _mpwiBogus))
{
// We'll never use this one for error reporting anyway, so just skip it.
bSearchForExpanded = false;
continue;
}
// Check convertibility of arguments.
if (!ArgumentsAreConvertible())
{
bSearchForExpanded = true;
continue;
}
// We know we have the right number of arguments and they are all convertible.
if (!fCanAccess)
{
// In case we never get an accessible method, this will allow us to give
// a better error...
Debug.Assert(!_results.GetInaccessibleResult());
_results.GetInaccessibleResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else if (fBogus)
{
// In case we never get a good method, this will allow us to give
// a better error...
Debug.Assert(!_mpwiBogus);
_mpwiBogus.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
}
else
{
// This is a plausible method / property to call.
// Link it in at the end of the list.
_methList.Add(new CandidateFunctionMember(
new MethPropWithInst(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs),
_pCurrentParameters,
0,
fExpanded));
// When we find a method, we check if the type has interfaces. If so, mark the other interfaces
// as hidden, and object as well.
if (_pCurrentType.isInterfaceType())
{
TypeArray ifaces = _pCurrentType.GetIfacesAll();
for (int i = 0; i < ifaces.Count; i++)
{
AggregateType type = ifaces[i].AsAggregateType();
Debug.Assert(type.isInterfaceType());
_HiddenTypes.Add(type);
}
// Mark object.
AggregateType typeObject = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT, true);
_HiddenTypes.Add(typeObject);
}
}
// Don't look at the expanded form.
bSearchForExpanded = false;
}
_fCandidatesUnsupported = allCandidatesUnsupported && lookedAtCandidates;
// Restore the arguments to their original state if we changed them for named/optional arguments.
// ILGen will take care of putting the real arguments in there.
if (_bArgumentsChangedForNamedOrOptionalArguments)
{
// If we changed them last time, then we need to reset them.
CopyArgInfos(_pOriginalArguments, _pArguments);
}
}
private void CopyArgInfos(ArgInfos src, ArgInfos dst)
{
dst.carg = src.carg;
dst.types = src.types;
dst.fHasExprs = src.fHasExprs;
dst.prgexpr.Clear();
for (int i = 0; i < src.prgexpr.Count; i++)
{
dst.prgexpr.Add(src.prgexpr[i]);
}
}
private bool GetResultOfBind(bool bReportErrors)
{
// We looked at all the evidence, and we come to render the verdict:
if (!_methList.IsEmpty())
{
CandidateFunctionMember pmethBest;
if (_methList.Count == 1)
{
// We found the single best method to call.
pmethBest = _methList.Head();
}
else
{
// We have some ambiguities, lets sort them out.
CandidateFunctionMember pAmbig1 = null;
CandidateFunctionMember pAmbig2 = null;
CType pTypeThrough = _pGroup.OptionalObject?.Type;
pmethBest = _pExprBinder.FindBestMethod(_methList, pTypeThrough, _pArguments, out pAmbig1, out pAmbig2);
if (null == pmethBest)
{
// Arbitrarily use the first one, but make sure to report errors or give the ambiguous one
// back to the caller.
pmethBest = pAmbig1;
_results.AmbiguousResult = pAmbig2.mpwi;
if (bReportErrors)
{
if (pAmbig1.@params != pAmbig2.@params ||
pAmbig1.mpwi.MethProp().Params.Count != pAmbig2.mpwi.MethProp().Params.Count ||
pAmbig1.mpwi.TypeArgs != pAmbig2.mpwi.TypeArgs ||
pAmbig1.mpwi.GetType() != pAmbig2.mpwi.GetType() ||
pAmbig1.mpwi.MethProp().Params == pAmbig2.mpwi.MethProp().Params)
{
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi, pAmbig2.mpwi);
}
else
{
// The two signatures are identical so don't use the type args in the error message.
GetErrorContext().Error(ErrorCode.ERR_AmbigCall, pAmbig1.mpwi.MethProp(), pAmbig2.mpwi.MethProp());
}
}
}
}
// This is the "success" exit path.
Debug.Assert(pmethBest != null);
_results.BestResult = pmethBest.mpwi;
// Record our best match in the memgroup as well. This is temporary.
if (bReportErrors)
{
ReportErrorsOnSuccess();
}
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////
// This method returns true if we're able to match arguments to their names.
// If we either have too many arguments, or we cannot match their names, then
// we return false.
//
// Note that if we have not enough arguments, we still return true as long as
// we can find matching parameters for each named arguments, and all parameters
// that do not have a matching argument are optional parameters.
private bool ReOrderArgsForNamedArguments()
{
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
if (methprop == null)
{
return false;
}
int numParameters = _pCurrentParameters.Count;
// If we have no parameters, or fewer parameters than we have arguments, bail.
if (numParameters == 0 || numParameters < _pArguments.carg)
{
return false;
}
// Make sure all the names we specified are in the list and we don't have duplicates.
if (!NamedArgumentNamesAppearInParameterList(methprop))
{
return false;
}
_bArgumentsChangedForNamedOrOptionalArguments = ReOrderArgsForNamedArguments(
methprop,
_pCurrentParameters,
_pCurrentType,
_pGroup,
_pArguments,
_pExprBinder.GetTypes(),
_pExprBinder.GetExprFactory(),
GetSymbolLoader());
return _bArgumentsChangedForNamedOrOptionalArguments;
}
internal static bool ReOrderArgsForNamedArguments(
MethodOrPropertySymbol methprop,
TypeArray pCurrentParameters,
AggregateType pCurrentType,
ExprMemberGroup pGroup,
ArgInfos pArguments,
TypeManager typeManager,
ExprFactory exprFactory,
SymbolLoader symbolLoader)
{
// We use the param count from pCurrentParameters because they may have been resized
// for param arrays.
int numParameters = pCurrentParameters.Count;
Expr[] pExprArguments = new Expr[numParameters];
// Now go through the parameters. First set all positional arguments in the new argument
// set, then for the remainder, look for a named argument with a matching name.
int index = 0;
Expr paramArrayArgument = null;
TypeArray @params = typeManager.SubstTypeArray(
pCurrentParameters,
pCurrentType,
pGroup.TypeArgs);
foreach (Name name in methprop.ParameterNames)
{
// This can happen if we had expanded our param array to size 0.
if (index >= pCurrentParameters.Count)
{
break;
}
// If:
// (1) we have a param array method
// (2) we're on the last arg
// (3) the thing we have is an array init thats generated for param array
// then let us through.
if (methprop.isParamArray &&
index < pArguments.carg &&
pArguments.prgexpr[index] is ExprArrayInit arrayInit && arrayInit.GeneratedForParamArray)
{
paramArrayArgument = pArguments.prgexpr[index];
}
// Positional.
if (index < pArguments.carg &&
!(pArguments.prgexpr[index] is ExprNamedArgumentSpecification) &&
!(pArguments.prgexpr[index] is ExprArrayInit arrayInitPos && arrayInitPos.GeneratedForParamArray))
{
pExprArguments[index] = pArguments.prgexpr[index++];
continue;
}
// Look for names.
Expr pNewArg = FindArgumentWithName(pArguments, name);
if (pNewArg == null)
{
if (methprop.IsParameterOptional(index))
{
pNewArg = GenerateOptionalArgument(symbolLoader, exprFactory, methprop, @params[index], index);
}
else if (paramArrayArgument != null && index == methprop.Params.Count - 1)
{
// If we have a param array argument and we're on the last one, then use it.
pNewArg = paramArrayArgument;
}
else
{
// No name and no default value.
return false;
}
}
pExprArguments[index++] = pNewArg;
}
// Here we've found all the arguments, or have default values for them.
CType[] prgTypes = new CType[pCurrentParameters.Count];
for (int i = 0; i < numParameters; i++)
{
if (i < pArguments.prgexpr.Count)
{
pArguments.prgexpr[i] = pExprArguments[i];
}
else
{
pArguments.prgexpr.Add(pExprArguments[i]);
}
prgTypes[i] = pArguments.prgexpr[i].Type;
}
pArguments.carg = pCurrentParameters.Count;
pArguments.types = symbolLoader.getBSymmgr().AllocParams(pCurrentParameters.Count, prgTypes);
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static Expr GenerateOptionalArgument(
SymbolLoader symbolLoader,
ExprFactory exprFactory,
MethodOrPropertySymbol methprop,
CType type,
int index)
{
CType pParamType = type;
CType pRawParamType = type.IsNullableType() ? type.AsNullableType().GetUnderlyingType() : type;
Expr optionalArgument = null;
if (methprop.HasDefaultParameterValue(index))
{
CType pConstValType = methprop.GetDefaultParameterValueConstValType(index);
ConstVal cv = methprop.GetDefaultParameterValue(index);
if (pConstValType.isPredefType(PredefinedType.PT_DATETIME) &&
(pRawParamType.isPredefType(PredefinedType.PT_DATETIME) || pRawParamType.isPredefType(PredefinedType.PT_OBJECT) || pRawParamType.isPredefType(PredefinedType.PT_VALUE)))
{
// This is the specific case where we want to create a DateTime
// but the constval that stores it is a long.
AggregateType dateTimeType = symbolLoader.GetReqPredefType(PredefinedType.PT_DATETIME);
optionalArgument = exprFactory.CreateConstant(dateTimeType, ConstVal.Get(DateTime.FromBinary(cv.Int64Val)));
}
else if (pConstValType.isSimpleOrEnumOrString())
{
// In this case, the constval is a simple type (all the numerics, including
// decimal), or an enum or a string. This covers all the substantial values,
// and everything else that can be encoded is just null or default(something).
// For enum parameters, we create a constant of the enum type. For everything
// else, we create the appropriate constant.
if (pRawParamType.isEnumType() && pConstValType == pRawParamType.underlyingType())
{
optionalArgument = exprFactory.CreateConstant(pRawParamType, cv);
}
else
{
optionalArgument = exprFactory.CreateConstant(pConstValType, cv);
}
}
else if ((pParamType.IsRefType() || pParamType.IsNullableType()) && cv.IsNullRef)
{
// We have an "= null" default value with a reference type or a nullable type.
optionalArgument = exprFactory.CreateNull();
}
else
{
// We have a default value that is encoded as a nullref, and that nullref is
// interpreted as default(something). For instance, the pParamType could be
// a type parameter type or a non-simple value type.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
else
{
// There was no default parameter specified, so generally use default(T),
// except for some cases when the parameter type in metatdata is object.
if (pParamType.isPredefType(PredefinedType.PT_OBJECT))
{
if (methprop.MarshalAsObject(index))
{
// For [opt] parameters of type object, if we have marshal(iunknown),
// marshal(idispatch), or marshal(interface), then we emit a null.
optionalArgument = exprFactory.CreateNull();
}
else
{
// Otherwise, we generate Type.Missing
AggregateSymbol agg = symbolLoader.GetOptPredefAgg(PredefinedType.PT_MISSING);
Name name = NameManager.GetPredefinedName(PredefinedName.PN_CAP_VALUE);
FieldSymbol field = symbolLoader.LookupAggMember(name, agg, symbmask_t.MASK_FieldSymbol).AsFieldSymbol();
FieldWithType fwt = new FieldWithType(field, agg.getThisType());
ExprField exprField = exprFactory.CreateField(0, agg.getThisType(), null, fwt);
if (agg.getThisType() != type)
{
optionalArgument = exprFactory.CreateCast(0, type, exprField);
}
else
{
optionalArgument = exprField;
}
}
}
else
{
// Every type aside from object that doesn't have a default value gets
// its default value.
optionalArgument = exprFactory.CreateZeroInit(pParamType);
}
}
Debug.Assert(optionalArgument != null);
optionalArgument.IsOptionalArgument = true;
return optionalArgument;
}
/////////////////////////////////////////////////////////////////////////////////
private MethodOrPropertySymbol FindMostDerivedMethod(
MethodOrPropertySymbol pMethProp,
Expr pObject)
{
return FindMostDerivedMethod(GetSymbolLoader(), pMethProp, pObject?.Type);
}
/////////////////////////////////////////////////////////////////////////////////
public static MethodOrPropertySymbol FindMostDerivedMethod(
SymbolLoader symbolLoader,
MethodOrPropertySymbol pMethProp,
CType pType)
{
MethodSymbol method;
bool bIsIndexer = false;
if (pMethProp.IsMethodSymbol())
{
method = pMethProp.AsMethodSymbol();
}
else
{
PropertySymbol prop = pMethProp.AsPropertySymbol();
method = prop.methGet != null ? prop.methGet : prop.methSet;
if (method == null)
{
return null;
}
bIsIndexer = prop.isIndexer();
}
if (!method.isVirtual)
{
return method;
}
if (pType == null)
{
// This must be a static call.
return method;
}
// Now get the slot method.
var slotMethod = method.swtSlot?.Meth();
if (slotMethod != null)
{
method = slotMethod;
}
if (!pType.IsAggregateType())
{
// Not something that can have overrides anyway.
return method;
}
for (AggregateSymbol pAggregate = pType.AsAggregateType().GetOwningAggregate();
pAggregate != null && pAggregate.GetBaseAgg() != null;
pAggregate = pAggregate.GetBaseAgg())
{
for (MethodOrPropertySymbol meth = symbolLoader.LookupAggMember(method.name, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol();
meth != null;
meth = symbolLoader.LookupNextSym(meth, pAggregate, symbmask_t.MASK_MethodSymbol | symbmask_t.MASK_PropertySymbol).AsMethodOrPropertySymbol())
{
if (!meth.isOverride)
{
continue;
}
if (meth.swtSlot.Sym != null && meth.swtSlot.Sym == method)
{
if (bIsIndexer)
{
Debug.Assert(meth.IsMethodSymbol());
return meth.AsMethodSymbol().getProperty();
}
else
{
return meth;
}
}
}
}
// If we get here, it means we can have two cases: one is that we have
// a delegate. This is because the delegate invoke method is virtual and is
// an override, but we won't have the slots set up correctly, and will
// not find the base type in the inheritance hierarchy. The second is that
// we're calling off of the base itself.
Debug.Assert(method.parent.IsAggregateSymbol());
return method;
}
/////////////////////////////////////////////////////////////////////////////////
private bool HasOptionalParameters()
{
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
return methprop != null && methprop.HasOptionalParameters();
}
/////////////////////////////////////////////////////////////////////////////////
// Returns true if we can either add enough optional parameters to make the
// argument list match, or if we don't need to at all.
private bool AddArgumentsForOptionalParameters()
{
if (_pCurrentParameters.Count <= _pArguments.carg)
{
// If we have enough arguments, or too many, no need to add any optionals here.
return true;
}
// First we need to find the method that we're actually trying to call.
MethodOrPropertySymbol methprop = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
if (methprop == null)
{
return false;
}
// If we're here, we know we're not in a named argument case. As such, we can
// just generate defaults for every missing argument.
int i = _pArguments.carg;
int index = 0;
TypeArray @params = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters,
_pCurrentType,
_pGroup.TypeArgs);
Expr[] pArguments = new Expr[_pCurrentParameters.Count - i];
for (; i < @params.Count; i++, index++)
{
if (!methprop.IsParameterOptional(i))
{
// We don't have an optional here, but we need to fill it in.
return false;
}
pArguments[index] = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), methprop, @params[i], i);
}
// Success. Lets copy them in now.
for (int n = 0; n < index; n++)
{
_pArguments.prgexpr.Add(pArguments[n]);
}
CType[] prgTypes = new CType[@params.Count];
for (int n = 0; n < @params.Count; n++)
{
prgTypes[n] = _pArguments.prgexpr[n].Type;
}
_pArguments.types = GetSymbolLoader().getBSymmgr().AllocParams(@params.Count, prgTypes);
_pArguments.carg = @params.Count;
_bArgumentsChangedForNamedOrOptionalArguments = true;
return true;
}
/////////////////////////////////////////////////////////////////////////////////
private static Expr FindArgumentWithName(ArgInfos pArguments, Name pName)
{
List<Expr> prgexpr = pArguments.prgexpr;
for (int i = 0; i < pArguments.carg; i++)
{
Expr expr = prgexpr[i];
if (expr is ExprNamedArgumentSpecification named && named.Name == pName)
{
return expr;
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////
private bool NamedArgumentNamesAppearInParameterList(
MethodOrPropertySymbol methprop)
{
// Keep track of the current position in the parameter list so that we can check
// containment from this point onwards as well as complete containment. This is
// for error reporting. The user cannot specify a named argument for a parameter
// that has a fixed argument value.
List<Name> currentPosition = methprop.ParameterNames;
HashSet<Name> names = new HashSet<Name>();
for (int i = 0; i < _pArguments.carg; i++)
{
if (!(_pArguments.prgexpr[i] is ExprNamedArgumentSpecification named))
{
if (!currentPosition.IsEmpty())
{
currentPosition = currentPosition.Tail();
}
continue;
}
Name name = named.Name;
if (!methprop.ParameterNames.Contains(name))
{
if (_pInvalidSpecifiedName == null)
{
_pInvalidSpecifiedName = name;
}
return false;
}
else if (!currentPosition.Contains(name))
{
if (_pNameUsedInPositionalArgument == null)
{
_pNameUsedInPositionalArgument = name;
}
return false;
}
if (!names.Add(name))
{
if (_pDuplicateSpecifiedName == null)
{
_pDuplicateSpecifiedName = name;
}
return false;
}
}
return true;
}
// This method returns true if we have another sym to consider.
// If we've found a match in the current type, and have no more syms to consider in this type, then we
// return false.
private bool GetNextSym(CMemberLookupResults.CMethodIterator iterator)
{
if (!iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList))
{
return false;
}
_pCurrentSym = iterator.GetCurrentSymbol();
AggregateType type = iterator.GetCurrentType();
// If our current type is null, this is our first iteration, so set the type.
// If our current type is not null, and we've got a new type now, and we've already matched
// a symbol, then bail out.
if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
(!_methList.Head().mpwi.Sym.IsMethodSymbol() || !_methList.Head().mpwi.Meth().IsExtension()))
{
return false;
}
else if (_pCurrentType != type &&
_pCurrentType != null &&
!_methList.IsEmpty() &&
!_methList.Head().mpwi.GetType().isInterfaceType() &&
_methList.Head().mpwi.Sym.IsMethodSymbol() &&
_methList.Head().mpwi.Meth().IsExtension())
{
// we have found a applicable method that is an extension now we must move to the end of the NS list before quiting
if (_pGroup.OptionalObject != null)
{
// if we find this while looking for static methods we should ignore it
_bIterateToEndOfNsList = true;
}
}
_pCurrentType = type;
// We have a new type. If this type is hidden, we need another type.
while (_HiddenTypes.Contains(_pCurrentType))
{
// Move through this type and get the next one.
for (; iterator.GetCurrentType() == _pCurrentType; iterator.MoveNext(_methList.IsEmpty(), _bIterateToEndOfNsList)) ;
_pCurrentSym = iterator.GetCurrentSymbol();
_pCurrentType = iterator.GetCurrentType();
if (iterator.AtEnd())
{
return false;
}
}
return true;
}
private bool ConstructExpandedParameters()
{
// Deal with params.
if (_pCurrentSym == null || _pArguments == null || _pCurrentParameters == null)
{
return false;
}
if (0 != (_fBindFlags & BindingFlag.BIND_NOPARAMS))
{
return false;
}
if (!_pCurrentSym.isParamArray)
{
return false;
}
// Count the number of optionals in the method. If there are enough optionals
// and actual arguments, then proceed.
{
int numOptionals = 0;
for (int i = _pArguments.carg; i < _pCurrentSym.Params.Count; i++)
{
if (_pCurrentSym.IsParameterOptional(i))
{
numOptionals++;
}
}
if (_pArguments.carg + numOptionals < _pCurrentParameters.Count - 1)
{
return false;
}
}
Debug.Assert(_methList.IsEmpty() || _methList.Head().mpwi.MethProp() != _pCurrentSym);
// Construct the expanded params.
return _pExprBinder.TryGetExpandedParams(_pCurrentSym.Params, _pArguments.carg, out _pCurrentParameters);
}
private Result DetermineCurrentTypeArgs()
{
TypeArray typeArgs = _pGroup.TypeArgs;
// Get the type args.
if (_pCurrentSym.IsMethodSymbol() && _pCurrentSym.AsMethodSymbol().typeVars.Count != typeArgs.Count)
{
MethodSymbol methSym = _pCurrentSym.AsMethodSymbol();
// Can't infer if some type args are specified.
if (typeArgs.Count > 0)
{
if (!_mwtBadArity)
{
_mwtBadArity.Set(methSym, _pCurrentType);
}
return Result.Failure_NoSearchForExpanded;
}
Debug.Assert(methSym.typeVars.Count > 0);
// Try to infer. If we have an errorsym in the type arguments, we know we cant infer,
// but we want to attempt it anyway. We'll mark this as "cant infer" so that we can
// report the appropriate error, but we'll continue inferring, since we want
// error sym to go to any type.
bool inferenceSucceeded;
inferenceSucceeded = MethodTypeInferrer.Infer(
_pExprBinder, GetSymbolLoader(),
methSym, _pCurrentType.GetTypeArgsAll(), _pCurrentParameters,
_pArguments, out _pCurrentTypeArgs);
if (!inferenceSucceeded)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs))
{
TypeArray pTypeVars = methSym.typeVars;
if (pTypeVars != null && _pCurrentTypeArgs != null && pTypeVars.Count == _pCurrentTypeArgs.Count)
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, _pCurrentTypeArgs);
}
else
{
_mpwiCantInferInstArg.Set(_pCurrentSym.AsMethodSymbol(), _pCurrentType, pTypeVars);
}
}
return Result.Failure_SearchForExpanded;
}
}
else
{
_pCurrentTypeArgs = typeArgs;
}
return Result.Success;
}
private bool ArgumentsAreConvertible()
{
bool containsErrorSym = false;
bool bIsInstanceParameterConvertible = false;
if (_pArguments.carg != 0)
{
UpdateArguments();
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters[ivar];
bool constraintErrors = !TypeBind.CheckConstraints(GetSemanticChecker(), GetErrorContext(), var, CheckConstraintsFlags.NoErrors);
if (constraintErrors && !DoesTypeArgumentsContainErrorSym(var))
{
_mpwiParamTypeConstraints.Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
return false;
}
}
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pCurrentParameters[ivar];
containsErrorSym |= DoesTypeArgumentsContainErrorSym(var);
bool fresult;
if (_pArguments.fHasExprs)
{
Expr pArgument = _pArguments.prgexpr[ivar];
// If we have a named argument, strip it to do the conversion.
if (pArgument is ExprNamedArgumentSpecification named)
{
pArgument = named.Value;
}
fresult = _pExprBinder.canConvert(pArgument, var);
}
else
{
fresult = _pExprBinder.canConvert(_pArguments.types[ivar], var);
}
// Mark this as a legitimate error if we didn't have any error syms.
if (!fresult && !containsErrorSym)
{
if (ivar > _nArgBest)
{
_nArgBest = ivar;
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
else if (ivar == _nArgBest && _pArguments.types[ivar] != var)
{
// this is to eliminate the paranoid case of types that are equal but can't convert
// (think ErrorType != ErrorType)
// See if they just differ in out / ref.
CType argStripped = _pArguments.types[ivar].IsParameterModifierType() ?
_pArguments.types[ivar].AsParameterModifierType().GetParameterType() : _pArguments.types[ivar];
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
// If we already have best method for instance methods don't overwrite with extensions
if (!_results.GetBestResult())
{
_results.GetBestResult().Set(_pCurrentSym, _pCurrentType, _pCurrentTypeArgs);
_pBestParameters = _pCurrentParameters;
}
}
}
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
return false;
}
}
}
if (containsErrorSym)
{
if (_results.IsBetterUninferableResult(_pCurrentTypeArgs) && _pCurrentSym.IsMethodSymbol())
{
// If we're an instance method or we're an extension that has an inferable instance argument,
// then mark us down. Note that the extension may not need to infer type args,
// so check if we have any type variables at all to begin with.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() ||
_pCurrentSym.AsMethodSymbol().typeVars.Count == 0 ||
MethodTypeInferrer.CanObjectOfExtensionBeInferred(
_pExprBinder,
GetSymbolLoader(),
_pCurrentSym.AsMethodSymbol(),
_pCurrentType.GetTypeArgsAll(),
_pCurrentSym.AsMethodSymbol().Params,
_pArguments))
{
_results.GetUninferableResult().Set(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
else
{
if (_pCurrentSym.IsMethodSymbol())
{
// Do not store the result if we have an extension method and the instance
// parameter isn't convertible.
if (!_pCurrentSym.AsMethodSymbol().IsExtension() || bIsInstanceParameterConvertible)
{
_results.AddInconvertibleResult(
_pCurrentSym.AsMethodSymbol(),
_pCurrentType,
_pCurrentTypeArgs);
}
}
}
return !containsErrorSym;
}
private void UpdateArguments()
{
// Parameter types might have changed as a result of
// method type inference.
_pCurrentParameters = _pExprBinder.GetTypes().SubstTypeArray(
_pCurrentParameters, _pCurrentType, _pCurrentTypeArgs);
// It is also possible that an optional argument has changed its value
// as a result of method type inference. For example, when inferring
// from Foo(10) to Foo<T>(T t1, T t2 = default(T)), the fabricated
// argument list starts off as being (10, default(T)). After type
// inference has successfully inferred T as int, it needs to be
// transformed into (10, default(int)) before applicability checking
// notices that default(T) is not assignable to int.
if (_pArguments.prgexpr == null || _pArguments.prgexpr.Count == 0)
{
return;
}
MethodOrPropertySymbol pMethod = null;
for (int iParam = 0; iParam < _pCurrentParameters.Count; ++iParam)
{
Expr pArgument = _pArguments.prgexpr[iParam];
if (!pArgument.IsOptionalArgument)
{
continue;
}
CType pType = _pCurrentParameters[iParam];
if (pType == pArgument.Type)
{
continue;
}
// Argument has changed its type because of method type inference. Recompute it.
if (pMethod == null)
{
pMethod = FindMostDerivedMethod(_pCurrentSym, _pGroup.OptionalObject);
Debug.Assert(pMethod != null);
}
Debug.Assert(pMethod.IsParameterOptional(iParam));
Expr pArgumentNew = GenerateOptionalArgument(GetSymbolLoader(), _pExprBinder.GetExprFactory(), pMethod, _pCurrentParameters[iParam], iParam);
_pArguments.prgexpr[iParam] = pArgumentNew;
}
}
private bool DoesTypeArgumentsContainErrorSym(CType var)
{
if (!var.IsAggregateType())
{
return false;
}
TypeArray typeVars = var.AsAggregateType().GetTypeArgsAll();
for (int i = 0; i < typeVars.Count; i++)
{
CType type = typeVars[i];
if (type.IsErrorType())
{
return true;
}
else if (type.IsAggregateType())
{
// If we have an agg type sym, check if its type args have errors.
if (DoesTypeArgumentsContainErrorSym(type))
{
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
private void ReportErrorsOnSuccess()
{
// used for Methods and Indexers
Debug.Assert(_pGroup.SymKind == SYMKIND.SK_MethodSymbol || _pGroup.SymKind == SYMKIND.SK_PropertySymbol && 0 != (_pGroup.Flags & EXPRFLAG.EXF_INDEXER));
Debug.Assert(_pGroup.TypeArgs.Count == 0 || _pGroup.SymKind == SYMKIND.SK_MethodSymbol);
// if this is a binding to finalize on object, then complain:
if (_results.GetBestResult().MethProp().name == NameManager.GetPredefinedName(PredefinedName.PN_DTOR) &&
_results.GetBestResult().MethProp().getClass().isPredefAgg(PredefinedType.PT_OBJECT))
{
if (0 != (_pGroup.Flags & EXPRFLAG.EXF_BASECALL))
{
GetErrorContext().Error(ErrorCode.ERR_CallingBaseFinalizeDeprecated);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_CallingFinalizeDepracated);
}
}
Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_USERCALLABLE) || _results.GetBestResult().MethProp().isUserCallable());
if (_pGroup.SymKind == SYMKIND.SK_MethodSymbol)
{
Debug.Assert(_results.GetBestResult().MethProp().IsMethodSymbol());
if (_results.GetBestResult().TypeArgs.Count > 0)
{
// Check method type variable constraints.
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_results.GetBestResult()));
}
}
}
private void ReportErrorsOnFailure()
{
// First and foremost, report if the user specified a name more than once.
if (_pDuplicateSpecifiedName != null)
{
GetErrorContext().Error(ErrorCode.ERR_DuplicateNamedArgument, _pDuplicateSpecifiedName);
return;
}
Debug.Assert(_methList.IsEmpty());
// Report inaccessible.
if (_results.GetInaccessibleResult())
{
// We might have called this, but it is inaccessible...
GetSemanticChecker().ReportAccessError(_results.GetInaccessibleResult(), _pExprBinder.ContextForMemberLookup(), GetTypeQualifier(_pGroup));
return;
}
// Report bogus.
if (_mpwiBogus)
{
// We might have called this, but it is bogus...
GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, _mpwiBogus);
return;
}
bool bUseDelegateErrors = false;
Name nameErr = _pGroup.Name;
// Check for an invoke.
if (_pGroup.OptionalObject != null &&
_pGroup.OptionalObject.Type != null &&
_pGroup.OptionalObject.Type.isDelegateType() &&
_pGroup.Name == NameManager.GetPredefinedName(PredefinedName.PN_INVOKE))
{
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().MethProp().getClass().IsDelegate());
Debug.Assert(!_results.GetBestResult() || _results.GetBestResult().GetType().getAggregate().IsDelegate());
bUseDelegateErrors = true;
nameErr = _pGroup.OptionalObject.Type.getAggregate().name;
}
if (_results.GetBestResult())
{
// If we had some invalid arguments for best matching.
ReportErrorsForBestMatching(bUseDelegateErrors, nameErr);
}
else if (_results.GetUninferableResult() || _mpwiCantInferInstArg)
{
if (!_results.GetUninferableResult())
{
//copy the extension method for which instance argument type inference failed
_results.GetUninferableResult().Set(_mpwiCantInferInstArg.Sym.AsMethodSymbol(), _mpwiCantInferInstArg.GetType(), _mpwiCantInferInstArg.TypeArgs);
}
Debug.Assert(_results.GetUninferableResult().Sym.IsMethodSymbol());
MethodSymbol sym = _results.GetUninferableResult().Meth();
TypeArray pCurrentParameters = sym.Params;
// if we tried to bind to an extensionmethod and the instance argument Type Inference failed then the method does not exist
// on the type at all. this is treated as a lookup error
CType type = null;
if (_pGroup.OptionalObject != null)
{
type = _pGroup.OptionalObject.Type;
}
else if (_pGroup.OptionalLHS != null)
{
type = _pGroup.OptionalLHS.Type;
}
MethWithType mwtCantInfer = new MethWithType();
mwtCantInfer.Set(_results.GetUninferableResult().Meth(), _results.GetUninferableResult().GetType());
GetErrorContext().Error(ErrorCode.ERR_CantInferMethTypeArgs, mwtCantInfer);
}
else if (_mwtBadArity)
{
int cvar = _mwtBadArity.Meth().typeVars.Count;
GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _mwtBadArity, new ErrArgSymKind(_mwtBadArity.Meth()), _pArguments.carg);
}
else if (_mpwiParamTypeConstraints)
{
// This will always report an error
TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), new MethWithInst(_mpwiParamTypeConstraints));
}
else if (_pInvalidSpecifiedName != null)
{
// Give a better message for delegate invoke.
if (_pGroup.OptionalObject != null &&
_pGroup.OptionalObject.Type.IsAggregateType() &&
_pGroup.OptionalObject.Type.AsAggregateType().GetOwningAggregate().IsDelegate())
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgumentForDelegateInvoke, _pGroup.OptionalObject.Type.AsAggregateType().GetOwningAggregate().name, _pInvalidSpecifiedName);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadNamedArgument, _pGroup.Name, _pInvalidSpecifiedName);
}
}
else if (_pNameUsedInPositionalArgument != null)
{
GetErrorContext().Error(ErrorCode.ERR_NamedArgumentUsedInPositional, _pNameUsedInPositionalArgument);
}
else
{
CParameterizedError error;
if (_pDelegate != null)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate);
GetErrorContext().AddRelatedTypeLoc(error, _pDelegate);
}
else
{
// The number of arguments must be wrong.
if (_fCandidatesUnsupported)
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BindToBogus, nameErr);
}
else if (bUseDelegateErrors)
{
Debug.Assert(0 == (_pGroup.Flags & EXPRFLAG.EXF_CTOR));
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadDelArgCount, nameErr, _pArguments.carg);
}
else
{
if (0 != (_pGroup.Flags & EXPRFLAG.EXF_CTOR))
{
Debug.Assert(!_pGroup.ParentType.IsTypeParameterType());
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadCtorArgCount, _pGroup.ParentType, _pArguments.carg);
}
else
{
GetErrorContext().MakeError(out error, ErrorCode.ERR_BadArgCount, nameErr, _pArguments.carg);
}
}
}
// Report possible matches (same name and is accessible). We stored these in m_swtWrongCount.
for (int i = 0; i < _nWrongCount; i++)
{
if (GetSemanticChecker().CheckAccess(
_swtWrongCount[i].Sym,
_swtWrongCount[i].GetType(),
_pExprBinder.ContextForMemberLookup(),
GetTypeQualifier(_pGroup)))
{
GetErrorContext().AddRelatedSymLoc(error, _swtWrongCount[i].Sym);
}
}
GetErrorContext().SubmitError(error);
}
}
private void ReportErrorsForBestMatching(bool bUseDelegateErrors, Name nameErr)
{
// Best matching overloaded method 'name' had some invalid arguments.
if (_pDelegate != null)
{
GetErrorContext().ErrorRef(ErrorCode.ERR_MethDelegateMismatch, nameErr, _pDelegate, _results.GetBestResult());
return;
}
if (_bBindingCollectionAddArgs)
{
if (ReportErrorsForCollectionAdd())
{
return;
}
}
if (bUseDelegateErrors)
{
// Point to the Delegate, not the Invoke method
GetErrorContext().Error(ErrorCode.ERR_BadDelArgTypes, _results.GetBestResult().GetType());
}
else
{
if (_results.GetBestResult().Sym.IsMethodSymbol() && _results.GetBestResult().Sym.AsMethodSymbol().IsExtension() && _pGroup.OptionalObject != null)
{
GetErrorContext().Error(ErrorCode.ERR_BadExtensionArgTypes, _pGroup.OptionalObject.Type, _pGroup.Name, _results.GetBestResult().Sym);
}
else if (_bBindingCollectionAddArgs)
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypesForCollectionAdd, _results.GetBestResult());
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgTypes, _results.GetBestResult());
}
}
// Argument X: cannot convert type 'Y' to type 'Z'
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters[ivar];
if (!_pExprBinder.canConvert(_pArguments.prgexpr[ivar], var))
{
// See if they just differ in out / ref.
CType argStripped = _pArguments.types[ivar].IsParameterModifierType() ?
_pArguments.types[ivar].AsParameterModifierType().GetParameterType() : _pArguments.types[ivar];
CType varStripped = var.IsParameterModifierType() ? var.AsParameterModifierType().GetParameterType() : var;
if (argStripped == varStripped)
{
if (varStripped != var)
{
// The argument is wrong in ref / out-ness.
GetErrorContext().Error(ErrorCode.ERR_BadArgRef, ivar + 1, (var.IsParameterModifierType() && var.AsParameterModifierType().isOut) ? "out" : "ref");
}
else
{
CType argument = _pArguments.types[ivar];
// the argument is decorated, but doesn't needs a 'ref' or 'out'
GetErrorContext().Error(ErrorCode.ERR_BadArgExtraRef, ivar + 1, (argument.IsParameterModifierType() && argument.AsParameterModifierType().isOut) ? "out" : "ref");
}
}
else
{
// if we tried to bind to an extensionmethod and the instance argument conversion failed then the method does not exist
// on the type at all.
Symbol sym = _results.GetBestResult().Sym;
if (ivar == 0 && sym.IsMethodSymbol() && sym.AsMethodSymbol().IsExtension() && _pGroup.OptionalObject != null &&
!_pExprBinder.canConvertInstanceParamForExtension(_pGroup.OptionalObject, sym.AsMethodSymbol().Params[0]))
{
if (!_pGroup.OptionalObject.Type.getBogus())
{
GetErrorContext().Error(ErrorCode.ERR_BadInstanceArgType, _pGroup.OptionalObject.Type, var);
}
}
else
{
GetErrorContext().Error(ErrorCode.ERR_BadArgType, ivar + 1, new ErrArg(_pArguments.types[ivar], ErrArgFlags.Unique), new ErrArg(var, ErrArgFlags.Unique));
}
}
}
}
}
private bool ReportErrorsForCollectionAdd()
{
for (int ivar = 0; ivar < _pArguments.carg; ivar++)
{
CType var = _pBestParameters[ivar];
if (var.IsParameterModifierType())
{
GetErrorContext().ErrorRef(ErrorCode.ERR_InitializerAddHasParamModifiers, _results.GetBestResult());
return true;
}
}
return false;
}
}
}
}
| |
// <copyright file="CodingContext.cs" company="LeetABit">
// Copyright (c) Hubert Bukowski. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace LeetABit.Binary
{
using System;
using System.Collections.Generic;
/// <summary>
/// Base implementation of the binary coding context.
/// </summary>
public abstract class CodingContext : ICodingContext
{
/// <summary>
/// Variables storage.
/// </summary>
private readonly TransactionalStorage<string, object?> variables = new();
/// <summary>
/// Fields mapping storage.
/// </summary>
private readonly TransactionalStorage<LogicalPath, FieldMapping> fields = new();
/// <summary>
/// Block's data storage.
/// </summary>
private readonly TransactionalStorage<IDefinitionBlock, object> blocksData = new();
/// <summary>
/// Gets or sets a current logical path.
/// </summary>
public virtual LogicalPath Path
{
get;
protected set;
}
/// <summary>
/// Gets a current binary position.
/// </summary>
public abstract int Position
{
get;
}
/// <summary>
/// Changes the current logical path.
/// </summary>
/// <param name="path">
/// New logical path to be set.
/// </param>
public virtual void ChangePath(LogicalPath path)
{
this.Path /= path;
}
/// <summary>
/// Moves current binary position specified number of bits.
/// </summary>
/// <param name="offset">
/// Number of bits to move the current binary position.
/// </param>
/// <returns>
/// Operation result.
/// </returns>
public abstract Result Move(int offset);
/// <summary>
/// Gets a current value of the specified variable.
/// </summary>
/// <param name="variableName">
/// Name of the variable which value shall be obtained.
/// </param>
/// <returns>
/// Current value of the specified variable or error.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="variableName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="variableName"/> is composed of white spaces only.
/// </exception>
public virtual Result<object?> GetVariable(string variableName)
{
_ = Requires.ArgumentNotNullAndNotWhiteSpace(variableName, nameof(variableName));
return this.variables.Get(variableName);
}
/// <summary>
/// Sets a current value of the specified variable.
/// </summary>
/// <param name="variableName">
/// Name of the variable which value shall be obtained.
/// </param>
/// <param name="value">
/// A new variable value.
/// </param>
public virtual void SetVariable(string variableName, object? value)
{
_ = Requires.ArgumentNotNullAndNotWhiteSpace(variableName, nameof(variableName));
this.variables.Set(variableName, value);
}
/// <summary>
/// Gets a binary value mapped to the specified logical path.
/// </summary>
/// <param name="fieldPath">
/// Logical path which binary value shall be obtained.
/// </param>
/// <returns>
/// Information about mapped binary value or error.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="fieldPath"/> is a root path.
/// <para>-or-</para>
/// <paramref name="fieldPath"/> is a relative path.
/// </exception>
public virtual Result<FieldMapping> GetFieldMapping(LogicalPath fieldPath)
{
_ = Requires.ArgumentNotRootAbsolutePath(fieldPath, nameof(fieldPath));
return this.fields.Get(this.Path / fieldPath);
}
/// <summary>
/// Maps binary field value to current coding state.
/// </summary>
/// <param name="fieldPath">
/// Path of the field which value to be mapped.
/// </param>
/// <param name="length">
/// Binary field length.
/// </param>
/// <param name="converter">
/// Field's value converter.
/// </param>
/// <param name="defaultValue">
/// Field's default value.
/// </param>
/// <returns>
/// Operation result.
/// </returns>
public virtual Result MapField(LogicalPath fieldPath, int length, IBinaryValueConverter converter, object? defaultValue)
{
_ = Requires.ArgumentNotRootAbsolutePath(fieldPath, nameof(fieldPath));
_ = Requires.ArgumentGreaterThanZero(length, nameof(length));
return this.CreateFieldMapping(this.Path / fieldPath, length, converter, defaultValue)
.ContinueWith(mapping => this.fields.Add(mapping!.Path, mapping));
}
/// <summary>
/// Retrieves previously stored binary definition block's data.
/// </summary>
/// <param name="block">
/// Block which value to be retrieved.
/// </param>
/// <returns>
/// Retrieved block's data or error.
/// </returns>
public virtual Result<object> RetrieveBlockData(IDefinitionBlock block)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
return this.blocksData.Get(block);
}
/// <summary>
/// Stores binary definition block's data.
/// </summary>
/// <param name="block">
/// Block which value is to be stored.
/// </param>
/// <param name="data">
/// Value to be stored.
/// </param>
public virtual void StoreBlockData(IDefinitionBlock block, object? data)
{
_ = Requires.ArgumentNotNull(block, nameof(block));
this.blocksData.Set(block, data);
}
/// <summary>
/// Starts registering all the revertable changes and make them permanent or revert them on transaction disposition.
/// </summary>
/// <returns>
/// A transaction object that shall be used to control committment or rollback of the cahnges.
/// </returns>
public virtual Transaction BeginTransaction()
{
TransactionActions actions = this.PrepareTransaction();
return new Transaction(actions);
}
/// <summary>
/// Maps binary field value to current coding state.
/// </summary>
/// <param name="fieldPath">
/// Path of the field which value to be mapped.
/// </param>
/// <param name="length">
/// Binary field length.
/// </param>
/// <param name="converter">
/// Field's value converter.
/// </param>
/// <param name="defaultValue">
/// Field's default value.
/// </param>
/// <returns>
/// Field mapping or error.
/// </returns>
protected abstract Result<FieldMapping> CreateFieldMapping(LogicalPath fieldPath, int length, IBinaryValueConverter converter, object? defaultValue);
/// <summary>
/// Prepares actions for the transaction that is abaout to be started.
/// </summary>
/// <returns>
/// Transaction actions for the prepared transaction.
/// </returns>
protected virtual TransactionActions PrepareTransaction()
{
var result = new TransactionActions();
var disposables = new List<IDisposable>();
var pathClone = this.Path;
result.RegisterRolbackAction(() => this.Path = pathClone);
try
{
disposables.Add(RegisterTransaction(this.variables.BeginTransaction(), result));
disposables.Add(RegisterTransaction(this.fields.BeginTransaction(), result));
disposables.Add(RegisterTransaction(this.blocksData.BeginTransaction(), result));
}
catch
{
foreach (var disposable in disposables)
{
disposable.Dispose();
}
throw;
}
return result;
}
/// <summary>
/// Registers specfied trnsaction in a transaction actions.
/// </summary>
/// <param name="transaction">
/// Transaction to register.
/// </param>
/// <param name="actions">
/// Transaction actions in which the transaction shall be registered.
/// </param>
/// <returns>
/// <paramref name="transaction"/> parameter.
/// </returns>
private static Transaction RegisterTransaction(Transaction transaction, TransactionActions actions)
{
actions.RegisterTransaction(transaction);
return transaction;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace CodeGenerator.HttpUtilities
{
public class HttpUtilities
{
public static string GeneratedFile()
{
var httpMethods = new []
{
new Tuple<string, String>("CONNECT ", "Connect"),
new Tuple<string, String>("DELETE ", "Delete"),
new Tuple<string, String>("HEAD ", "Head"),
new Tuple<string, String>("PATCH ", "Patch"),
new Tuple<string, String>("POST ", "Post"),
new Tuple<string, String>("PUT ", "Put"),
new Tuple<string, String>("OPTIONS ", "Options"),
new Tuple<string, String>("TRACE ", "Trace"),
new Tuple<string, String>("GET ", "Get")
};
return GenerateFile(httpMethods);
}
private static string GenerateFile(Tuple<string, String>[] httpMethods)
{
var maskLength = (byte)Math.Ceiling(Math.Log(httpMethods.Length, 2));
var methodsInfo = httpMethods.Select(GetMethodStringAndUlongAndMaskLength).ToList();
var methodsInfoWithoutGet = methodsInfo.Where(m => m.HttpMethod != "Get".ToString()).ToList();
var methodsAsciiStringAsLong = methodsInfo.Select(m => m.AsciiStringAsLong).ToArray();
var mask = HttpUtilitiesGeneratorHelpers.SearchKeyByLookThroughMaskCombinations(methodsAsciiStringAsLong, 0, sizeof(ulong) * 8, maskLength);
if (mask.HasValue == false)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Generated {0} not found.", nameof(mask)));
}
var functionGetKnownMethodIndex = GetFunctionBodyGetKnownMethodIndex(mask.Value);
var methodsSection = GetMethodsSection(methodsInfoWithoutGet);
var masksSection = GetMasksSection(methodsInfoWithoutGet);
var setKnownMethodSection = GetSetKnownMethodSection(methodsInfoWithoutGet);
var methodNamesSection = GetMethodNamesSection(methodsInfo);
int knownMethodsArrayLength = (int)(Math.Pow(2, maskLength) + 1);
int methodNamesArrayLength = httpMethods.Length;
return string.Format(CultureInfo.InvariantCulture, @"// 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.Runtime.CompilerServices;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
#nullable enable
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure
{{
internal static partial class HttpUtilities
{{
// readonly primitive statics can be Jit'd to consts https://github.com/dotnet/coreclr/issues/1079
{0}
{1}
private static readonly Tuple<ulong, ulong, HttpMethod, int>[] _knownMethods =
new Tuple<ulong, ulong, HttpMethod, int>[{2}];
private static readonly string[] _methodNames = new string[{3}];
static HttpUtilities()
{{
{4}
FillKnownMethodsGaps();
{5}
}}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetKnownMethodIndex(ulong value)
{{
{6}
}}
}}
}}", methodsSection, masksSection, knownMethodsArrayLength, methodNamesArrayLength, setKnownMethodSection, methodNamesSection, functionGetKnownMethodIndex);
}
private static string GetMethodsSection(List<MethodInfo> methodsInfo)
{
var result = new StringBuilder();
for (var index = 0; index < methodsInfo.Count; index++)
{
var methodInfo = methodsInfo[index];
var httpMethodFieldName = GetHttpMethodFieldName(methodInfo);
result.AppendFormat(CultureInfo.InvariantCulture, " private static readonly ulong {0} = GetAsciiStringAsLong(\"{1}\");", httpMethodFieldName, methodInfo.MethodAsciiString.Replace("\0", "\\0"));
if (index < methodsInfo.Count - 1)
{
result.AppendLine();
}
}
return result.ToString();
}
private static string GetMasksSection(List<MethodInfo> methodsInfo)
{
var distinctLengths = methodsInfo.Select(m => m.MaskLength).Distinct().ToList();
distinctLengths.Sort((t1, t2) => -t1.CompareTo(t2));
var result = new StringBuilder();
for (var index = 0; index < distinctLengths.Count; index++)
{
var maskBytesLength = distinctLengths[index];
var maskArray = GetMaskArray(maskBytesLength);
var hexMaskString = HttpUtilitiesGeneratorHelpers.GeHexString(maskArray, "0x", ", ");
var maskFieldName = GetMaskFieldName(maskBytesLength);
result.AppendFormat(CultureInfo.InvariantCulture, " private static readonly ulong {0} = GetMaskAsLong(new byte[]\r\n {{{1}}});", maskFieldName, hexMaskString);
result.AppendLine();
if (index < distinctLengths.Count - 1)
{
result.AppendLine();
}
}
return result.ToString();
}
private static string GetSetKnownMethodSection(List<MethodInfo> methodsInfo)
{
methodsInfo = methodsInfo.ToList();
methodsInfo.Sort((t1, t2) => t1.MaskLength.CompareTo(t2.MaskLength));
var result = new StringBuilder();
for (var index = 0; index < methodsInfo.Count; index++)
{
var methodInfo = methodsInfo[index];
var maskFieldName = GetMaskFieldName(methodInfo.MaskLength);
var httpMethodFieldName = GetHttpMethodFieldName(methodInfo);
result.AppendFormat(CultureInfo.InvariantCulture, " SetKnownMethod({0}, {1}, HttpMethod.{3}, {4});", maskFieldName, httpMethodFieldName, typeof(String).Name, methodInfo.HttpMethod, methodInfo.MaskLength - 1);
if (index < methodsInfo.Count - 1)
{
result.AppendLine();
}
}
return result.ToString();
}
private static string GetMethodNamesSection(List<MethodInfo> methodsInfo)
{
methodsInfo = methodsInfo.ToList();
methodsInfo.Sort((t1, t2) => string.Compare(t1.HttpMethod, t2.HttpMethod, StringComparison.Ordinal));
var result = new StringBuilder();
for (var index = 0; index < methodsInfo.Count; index++)
{
var methodInfo = methodsInfo[index];
result.AppendFormat(CultureInfo.InvariantCulture, " _methodNames[(byte)HttpMethod.{1}] = {2}.{3};", typeof(String).Name, methodInfo.HttpMethod, typeof(HttpMethods).Name, methodInfo.HttpMethod);
if (index < methodsInfo.Count - 1)
{
result.AppendLine();
}
}
return result.ToString();
}
private static string GetFunctionBodyGetKnownMethodIndex(ulong mask)
{
var shifts = HttpUtilitiesGeneratorHelpers.GetShifts(mask);
var maskHexString = HttpUtilitiesGeneratorHelpers.MaskToHexString(mask);
string bodyString;
if (shifts.Length > 0)
{
var bitsCount = HttpUtilitiesGeneratorHelpers.CountBits(mask);
var tmpReturn = string.Empty;
foreach (var item in shifts)
{
if (tmpReturn.Length > 0)
{
tmpReturn += " | ";
}
tmpReturn += string.Format(CultureInfo.InvariantCulture, "(tmp >> {1})", HttpUtilitiesGeneratorHelpers.MaskToHexString(item.Mask), item.Shift);
}
var mask2 = (ulong)(Math.Pow(2, bitsCount) - 1);
string returnString = string.Format(CultureInfo.InvariantCulture, "return ({0}) & {1};", tmpReturn, HttpUtilitiesGeneratorHelpers.MaskToHexString(mask2));
bodyString = string.Format(CultureInfo.InvariantCulture, " const int magicNumer = {0};\r\n var tmp = (int)value & magicNumer;\r\n {1}", HttpUtilitiesGeneratorHelpers.MaskToHexString(mask), returnString);
}
else
{
bodyString = string.Format(CultureInfo.InvariantCulture, "return (int)(value & {0});", maskHexString);
}
return bodyString;
}
private static string GetHttpMethodFieldName(MethodInfo methodsInfo)
{
return string.Format(CultureInfo.InvariantCulture, "_http{0}MethodLong", methodsInfo.HttpMethod.ToString());
}
private static string GetMaskFieldName(int nBytes)
{
return string.Format(CultureInfo.InvariantCulture, "_mask{0}Chars", nBytes);
}
private static string GetMethodString(string method)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
const int length = sizeof(ulong);
if (method.Length > length)
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "MethodAsciiString {0} length is greather than {1}", method, length));
}
string result = method;
if (result.Length == length)
{
return result;
}
if (result.Length < length)
{
var count = length - result.Length;
for (int i = 0; i < count; i++)
{
result += "\0";
}
}
return result;
}
private class MethodInfo
{
public string MethodAsciiString;
public ulong AsciiStringAsLong;
public string HttpMethod;
public int MaskLength;
}
private static MethodInfo GetMethodStringAndUlongAndMaskLength(Tuple<string, string> method)
{
var methodString = GetMethodString(method.Item1);
var asciiAsLong = GetAsciiStringAsLong(methodString);
return new MethodInfo
{
MethodAsciiString = methodString,
AsciiStringAsLong = asciiAsLong,
HttpMethod = method.Item2.ToString(),
MaskLength = method.Item1.Length
};
}
private static byte[] GetMaskArray(int n, int length = sizeof(ulong))
{
var maskArray = new byte[length];
for (int i = 0; i < n; i++)
{
maskArray[i] = 0xff;
}
return maskArray;
}
private static ulong GetAsciiStringAsLong(string str)
{
Debug.Assert(str.Length == sizeof(ulong), string.Format(CultureInfo.InvariantCulture, "String must be exactly {0} (ASCII) characters long.", sizeof(ulong)));
var bytes = Encoding.ASCII.GetBytes(str);
return BinaryPrimitives.ReadUInt64LittleEndian(bytes);
}
}
}
| |
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Abp.Auditing;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.EntityFramework;
using Abp.Localization;
using Abp.Notifications;
using Abp.Organizations;
using Abp.EntityFramework.Extensions;
namespace Abp.Zero.EntityFramework
{
public abstract class AbpZeroCommonDbContext<TRole, TUser, TSelf> : AbpDbContext
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
where TSelf : AbpZeroCommonDbContext<TRole, TUser, TSelf>
{
/// <summary>
/// Roles.
/// </summary>
public virtual DbSet<TRole> Roles { get; set; }
/// <summary>
/// Users.
/// </summary>
public virtual DbSet<TUser> Users { get; set; }
/// <summary>
/// User logins.
/// </summary>
public virtual DbSet<UserLogin> UserLogins { get; set; }
/// <summary>
/// User login attempts.
/// </summary>
public virtual DbSet<UserLoginAttempt> UserLoginAttempts { get; set; }
/// <summary>
/// User roles.
/// </summary>
public virtual DbSet<UserRole> UserRoles { get; set; }
/// <summary>
/// User claims.
/// </summary>
public virtual DbSet<UserClaim> UserClaims { get; set; }
/// <summary>
/// User tokens.
/// </summary>
public virtual DbSet<UserToken> UserTokens { get; set; }
/// <summary>
/// Role claims.
/// </summary>
public virtual DbSet<RoleClaim> RoleClaims { get; set; }
/// <summary>
/// Permissions.
/// </summary>
public virtual DbSet<PermissionSetting> Permissions { get; set; }
/// <summary>
/// Role permissions.
/// </summary>
public virtual DbSet<RolePermissionSetting> RolePermissions { get; set; }
/// <summary>
/// User permissions.
/// </summary>
public virtual DbSet<UserPermissionSetting> UserPermissions { get; set; }
/// <summary>
/// Settings.
/// </summary>
public virtual DbSet<Setting> Settings { get; set; }
/// <summary>
/// Audit logs.
/// </summary>
public virtual DbSet<AuditLog> AuditLogs { get; set; }
/// <summary>
/// Languages.
/// </summary>
public virtual DbSet<ApplicationLanguage> Languages { get; set; }
/// <summary>
/// LanguageTexts.
/// </summary>
public virtual DbSet<ApplicationLanguageText> LanguageTexts { get; set; }
/// <summary>
/// OrganizationUnits.
/// </summary>
public virtual DbSet<OrganizationUnit> OrganizationUnits { get; set; }
/// <summary>
/// UserOrganizationUnits.
/// </summary>
public virtual DbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; }
/// <summary>
/// OrganizationUnitRoles.
/// </summary>
public virtual DbSet<OrganizationUnitRole> OrganizationUnitRoles { get; set; }
/// <summary>
/// Tenant notifications.
/// </summary>
public virtual DbSet<TenantNotificationInfo> TenantNotifications { get; set; }
/// <summary>
/// User notifications.
/// </summary>
public virtual DbSet<UserNotificationInfo> UserNotifications { get; set; }
/// <summary>
/// Notification subscriptions.
/// </summary>
public virtual DbSet<NotificationSubscriptionInfo> NotificationSubscriptions { get; set; }
/// <summary>
/// Default constructor.
/// Do not directly instantiate this class. Instead, use dependency injection!
/// </summary>
protected AbpZeroCommonDbContext()
{
}
/// <summary>
/// Constructor with connection string parameter.
/// </summary>
/// <param name="nameOrConnectionString">Connection string or a name in connection strings in configuration file</param>
protected AbpZeroCommonDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected AbpZeroCommonDbContext(DbCompiledModel model)
: base(model)
{
}
/// <summary>
/// This constructor can be used for unit tests.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected AbpZeroCommonDbContext(string nameOrConnectionString, DbCompiledModel model)
: base(nameOrConnectionString, model)
{
}
protected AbpZeroCommonDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
/// <summary>
/// Constructor.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{
}
/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region TUser.Set_ConcurrencyStamp
modelBuilder.Entity<TUser>()
.Property(e => e.ConcurrencyStamp)
.IsConcurrencyToken();
#endregion
#region TUser.Set_ForeignKeys
modelBuilder.Entity<TUser>()
.HasOptional(p => p.DeleterUser)
.WithMany()
.HasForeignKey(p => p.DeleterUserId);
modelBuilder.Entity<TUser>()
.HasOptional(p => p.CreatorUser)
.WithMany()
.HasForeignKey(p => p.CreatorUserId);
modelBuilder.Entity<TUser>()
.HasOptional(p => p.LastModifierUser)
.WithMany()
.HasForeignKey(p => p.LastModifierUserId);
#endregion
#region TRole.Set_ConcurrencyStamp
modelBuilder.Entity<TRole>()
.Property(e => e.ConcurrencyStamp)
.IsConcurrencyToken();
#endregion
#region AuditLog.IX_TenantId_UserId
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region AuditLog.IX_TenantId_ExecutionTime
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ExecutionTime", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ExecutionTime)
.CreateIndex("IX_TenantId_ExecutionTime", 2);
#endregion
#region AuditLog.IX_TenantId_ExecutionDuration
modelBuilder.Entity<AuditLog>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ExecutionDuration", 1);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ExecutionDuration)
.CreateIndex("IX_TenantId_ExecutionDuration", 2);
#endregion
#region ApplicationLanguage.IX_TenantId_Name
modelBuilder.Entity<ApplicationLanguage>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<ApplicationLanguage>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region ApplicationLanguageText.IX_TenantId_Source_LanguageName_Key
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 1);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.Source)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 2);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.LanguageName)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 3);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(e => e.Key)
.CreateIndex("IX_TenantId_Source_LanguageName_Key", 4);
#endregion
#region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.NotificationName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityTypeName)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4);
#endregion
#region NotificationSubscriptionInfo.IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 1);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.NotificationName)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 2);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityTypeName)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 3);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.EntityId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 4);
modelBuilder.Entity<NotificationSubscriptionInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 5);
#endregion
#region UserNotificationInfo.IX_UserId_State_CreationTime
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.UserId)
.CreateIndex("IX_UserId_State_CreationTime", 1);
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.State)
.CreateIndex("IX_UserId_State_CreationTime", 2);
modelBuilder.Entity<UserNotificationInfo>()
.Property(e => e.CreationTime)
.CreateIndex("IX_UserId_State_CreationTime", 3);
#endregion
#region OrganizationUnit.IX_TenantId_Code
modelBuilder.Entity<OrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Code", 1);
modelBuilder.Entity<OrganizationUnit>()
.Property(e => e.Code)
.CreateIndex("IX_TenantId_Code", 2);
#endregion
#region PermissionSetting.IX_TenantId_Name
modelBuilder.Entity<PermissionSetting>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<PermissionSetting>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region RoleClaim.IX_RoleId
modelBuilder.Entity<RoleClaim>()
.Property(e => e.RoleId)
.CreateIndex("IX_RoleId", 1);
#endregion
#region RoleClaim.IX_TenantId_ClaimType
modelBuilder.Entity<RoleClaim>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ClaimType", 1);
modelBuilder.Entity<RoleClaim>()
.Property(e => e.ClaimType)
.CreateIndex("IX_TenantId_ClaimType", 2);
#endregion
#region Role.IX_TenantId_NormalizedName
modelBuilder.Entity<TRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedName", 1);
modelBuilder.Entity<TRole>()
.Property(e => e.NormalizedName)
.CreateIndex("IX_TenantId_NormalizedName", 2);
#endregion
#region Setting.IX_TenantId_Name
modelBuilder.Entity<Setting>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<Setting>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region TenantNotificationInfo.IX_TenantId
modelBuilder.Entity<TenantNotificationInfo>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
#endregion
#region UserClaim.IX_TenantId_ClaimType
modelBuilder.Entity<UserClaim>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_ClaimType", 1);
modelBuilder.Entity<UserClaim>()
.Property(e => e.ClaimType)
.CreateIndex("IX_TenantId_ClaimType", 2);
#endregion
#region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.TenancyName)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.UserNameOrEmailAddress)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2);
modelBuilder.Entity<UserLoginAttempt>()
.Property(ula => ula.Result)
.CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3);
#endregion
#region UserLoginAttempt.IX_UserId_TenantId
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.UserId)
.CreateIndex("IX_UserId_TenantId", 1);
modelBuilder.Entity<UserLoginAttempt>()
.Property(e => e.TenantId)
.CreateIndex("IX_UserId_TenantId", 2);
#endregion
#region UserLogin.IX_TenantId_LoginProvider_ProviderKey
modelBuilder.Entity<UserLogin>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 1);
modelBuilder.Entity<UserLogin>()
.Property(e => e.LoginProvider)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 2);
modelBuilder.Entity<UserLogin>()
.Property(e => e.ProviderKey)
.CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 3);
#endregion
#region UserLogin.IX_TenantId_UserId
modelBuilder.Entity<UserLogin>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserLogin>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserOrganizationUnit.IX_TenantId_UserId
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserOrganizationUnit.IX_TenantId_OrganizationUnitId
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 1);
modelBuilder.Entity<UserOrganizationUnit>()
.Property(e => e.OrganizationUnitId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 2);
#endregion
#region OrganizationUnitRole.IX_TenantId_RoleId
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_RoleId", 1);
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.RoleId)
.CreateIndex("IX_TenantId_RoleId", 2);
#endregion
#region OrganizationUnitRole.IX_TenantId_OrganizationUnitId
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 1);
modelBuilder.Entity<OrganizationUnitRole>()
.Property(e => e.OrganizationUnitId)
.CreateIndex("IX_TenantId_OrganizationUnitId", 2);
#endregion
#region UserRole.IX_TenantId_UserId
modelBuilder.Entity<UserRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserRole>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserRole.IX_TenantId_RoleId
modelBuilder.Entity<UserRole>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_RoleId", 1);
modelBuilder.Entity<UserRole>()
.Property(e => e.RoleId)
.CreateIndex("IX_TenantId_RoleId", 2);
#endregion
#region TUser.IX_TenantId_NormalizedUserName
modelBuilder.Entity<TUser>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedUserName", 1);
modelBuilder.Entity<TUser>()
.Property(e => e.NormalizedUserName)
.CreateIndex("IX_TenantId_NormalizedUserName", 2);
#endregion
#region TUser.IX_TenantId_NormalizedEmailAddress
modelBuilder.Entity<TUser>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_NormalizedEmailAddress", 1);
modelBuilder.Entity<TUser>()
.Property(e => e.NormalizedEmailAddress)
.CreateIndex("IX_TenantId_NormalizedEmailAddress", 2);
#endregion
#region UserToken.IX_TenantId_UserId
modelBuilder.Entity<UserToken>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserToken>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.Engine.Network.Activation;
using Encog.MathUtil.Error;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural.Error;
using Encog.Neural.Flat;
using Encog.Util;
using Encog.Util.Concurrency;
namespace Encog.Neural.Networks.Training.Propagation
{
/// <summary>
/// Worker class for the mulithreaded training of flat networks.
/// </summary>
///
public class GradientWorker
{
/// <summary>
/// The actual values from the neural network.
/// </summary>
///
private readonly double[] _actual;
/// <summary>
/// The error calculation method.
/// </summary>
///
private readonly ErrorCalculation _errorCalculation;
/// <summary>
/// The gradients.
/// </summary>
///
private readonly double[] _gradients;
/// <summary>
/// The low end of the training.
/// </summary>
///
private readonly int _high;
/// <summary>
/// The neuron counts, per layer.
/// </summary>
///
private readonly int[] _layerCounts;
/// <summary>
/// The deltas for each layer.
/// </summary>
///
private readonly double[] _layerDelta;
/// <summary>
/// The feed counts, per layer.
/// </summary>
///
private readonly int[] _layerFeedCounts;
/// <summary>
/// The layer indexes.
/// </summary>
///
private readonly int[] _layerIndex;
/// <summary>
/// The output from each layer.
/// </summary>
///
private readonly double[] _layerOutput;
/// <summary>
/// The sum from each layer.
/// </summary>
///
private readonly double[] _layerSums;
/// <summary>
/// The high end of the training data.
/// </summary>
///
private readonly int _low;
/// <summary>
/// The network to train.
/// </summary>
///
private readonly FlatNetwork _network;
/// <summary>
/// The owner.
/// </summary>
///
private readonly Propagation _owner;
/// <summary>
/// The training data.
/// </summary>
///
private readonly IMLDataSet _training;
/// <summary>
/// The index to each layer's weights and thresholds.
/// </summary>
///
private readonly int[] _weightIndex;
/// <summary>
/// The weights and thresholds.
/// </summary>
///
private readonly double[] _weights;
/// <summary>
/// Derivative add constant. Used to combat flat spot.
/// </summary>
private readonly double[] _flatSpot;
/// <summary>
/// The error function.
/// </summary>
private readonly IErrorFunction _ef;
/// <summary>
/// Construct a gradient worker.
/// </summary>
///
/// <param name="theNetwork">The network to train.</param>
/// <param name="theOwner">The owner that is doing the training.</param>
/// <param name="theTraining">The training data.</param>
/// <param name="theLow">The low index to use in the training data.</param>
/// <param name="theHigh">The high index to use in the training data.</param>
/// <param name="theFlatSpots">Holds an array of flat spot constants.</param>
public GradientWorker(FlatNetwork theNetwork,
Propagation theOwner, IMLDataSet theTraining,
int theLow, int theHigh, double[] theFlatSpots, IErrorFunction ef)
{
_errorCalculation = new ErrorCalculation();
_network = theNetwork;
_training = theTraining;
_low = theLow;
_high = theHigh;
_owner = theOwner;
_flatSpot = theFlatSpots;
_layerDelta = new double[_network.LayerOutput.Length];
_gradients = new double[_network.Weights.Length];
_actual = new double[_network.OutputCount];
_weights = _network.Weights;
_layerIndex = _network.LayerIndex;
_layerCounts = _network.LayerCounts;
_weightIndex = _network.WeightIndex;
_layerOutput = _network.LayerOutput;
_layerSums = _network.LayerSums;
_layerFeedCounts = _network.LayerFeedCounts;
_ef = ef;
}
#region FlatGradientWorker Members
/// <inheritdoc/>
public FlatNetwork Network
{
get { return _network; }
}
/// <value>The weights for this network.</value>
public double[] Weights
{
get { return _weights; }
}
/// <summary>
/// Perform the gradient calculation for the specified index range.
/// </summary>
///
public void Run()
{
try
{
_errorCalculation.Reset();
for (int i = _low; i <= _high; i++)
{
var pair = _training[i];
Process(pair);
}
double error = _errorCalculation.Calculate();
_owner.Report(_gradients, error, null);
EngineArray.Fill(_gradients, 0);
}
catch (Exception ex)
{
_owner.Report(null, 0, ex);
}
}
#endregion
/// <summary>
/// Process one training set element.
/// </summary>
///
/// <param name="input">The network input.</param>
/// <param name="ideal">The ideal values.</param>
/// <param name="s">The significance of this error.</param>
private void Process(IMLDataPair pair)
{
_network.Compute(pair.Input, _actual);
_errorCalculation.UpdateError(_actual, pair.Ideal, pair.Significance);
_ef.CalculateError(pair.Ideal,_actual,_layerDelta);
for (int i = 0; i < _actual.Length; i++)
{
_layerDelta[i] = (_network.ActivationFunctions[0]
.DerivativeFunction(_layerSums[i],_layerOutput[i])+_flatSpot[0])
*_layerDelta[i] * pair.Significance;
}
for (int i = _network.BeginTraining; i < _network.EndTraining; i++)
{
ProcessLevel(i);
}
}
/// <summary>
/// The error calculation to use.
/// </summary>
public ErrorCalculation CalculateError { get { return _errorCalculation; }}
public void Run(int index)
{
IMLDataPair pair = _training[index];
Process(pair);
_owner.Report(_gradients, 0, null);
EngineArray.Fill(_gradients, 0);
}
/// <summary>
/// Process one level.
/// </summary>
///
/// <param name="currentLevel">The level.</param>
private void ProcessLevel(int currentLevel)
{
int fromLayerIndex = _layerIndex[currentLevel + 1];
int toLayerIndex = _layerIndex[currentLevel];
int fromLayerSize = _layerCounts[currentLevel + 1];
int toLayerSize = _layerFeedCounts[currentLevel];
int index = _weightIndex[currentLevel];
IActivationFunction activation = _network.ActivationFunctions[currentLevel + 1];
double currentFlatSpot = _flatSpot[currentLevel + 1];
// handle weights
int yi = fromLayerIndex;
for (int y = 0; y < fromLayerSize; y++)
{
double output = _layerOutput[yi];
double sum = 0;
int xi = toLayerIndex;
int wi = index + y;
for (int x = 0; x < toLayerSize; x++)
{
_gradients[wi] += output*_layerDelta[xi];
sum += _weights[wi]*_layerDelta[xi];
wi += fromLayerSize;
xi++;
}
_layerDelta[yi] = sum
*(activation.DerivativeFunction(_layerSums[yi],_layerOutput[yi])+currentFlatSpot);
yi++;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/*
* Each CipherSuite instance encodes a cipher suite and its parameters.
*
* Static methods are used to locate the relevant CipherSuite instance.
*/
class CipherSuite {
/*
* Get the suite identifier (16 bits).
*/
internal int Suite {
get {
return suite;
}
}
/*
* Get the suite name.
*/
internal string Name {
get {
return name;
}
}
/*
* Get the suite "encryption strength":
* 0 = no encryption
* 1 = weak (40 bits)
* 2 = medium (56 bits)
* 3 = strong (96 bits or more)
*
* "Medium" will deter low-level amateurs, because they won't
* get through it with a couple of PC (it can be done within a
* week or so, with a FPGA-based machine that costs a few
* thousands of dollars -- not a lot, but enough to make it not
* worth the effort is the target is something as trivial as a
* credit card number).
*
* "Strong" is beyond current technology, even with lots of billions
* of dollars thrown at the problem. Though I put the cut-off at
* 96 bits, there is no cipher suite between 57 and 111 bits.
*/
internal int Strength {
get {
return strength;
}
}
/*
* Set to true if the suite uses a block cipher in CBC mode.
*/
internal bool IsCBC {
get {
return isCBC;
}
}
/*
* Set to true if the suite uses RC4.
*/
internal bool IsRC4 {
get {
return isRC4;
}
}
/*
* This returned true if the suite provides forward secrecy (unless
* the server does something stupid like using very weak ephemeral
* parameters, or storing ephemeral keys).
*/
internal bool HasForwardSecrecy {
get {
return isDHE || isECDHE || isSRP;
}
}
/*
* This returned true if the suite does not ensure server
* authentication.
*/
internal bool IsAnonymous {
get {
return !(isSRP || isPSK) && serverKeyType == "none";
}
}
/*
* Set to true if the suite uses ephemeral Diffie-Hellman (classic).
*/
internal bool IsDHE {
get {
return isDHE;
}
}
/*
* Set to true if the suite uses ephemeral Diffie-Hellman (on
* elliptic curves).
*/
internal bool IsECDHE {
get {
return isECDHE;
}
}
/*
* Set to true if the suite may use an ephemeral RSA key pair
* (this is a weak RSA key pair for "export" cipher suites; its
* length will be no more than 512 bits).
*/
internal bool IsRSAExport {
get {
return isRSAExport;
}
}
/*
* Set to true if the suite uses SRP (hence a form of DH key
* exchange, but a different ServerKeyExchange message).
*/
internal bool IsSRP {
get {
return isSRP;
}
}
/*
* Set to true if the suite uses a pre-shared key. This modifies
* the ServerKeyExchange format, if any (coupled with IsDHE
* or IsECDHE).
*/
internal bool IsPSK {
get {
return isPSK;
}
}
/*
* Expected server key type. Defined types are:
* RSA
* DSA
* DH
* EC (for ECDH or ECDSA)
* none (anonymous cipher suites)
*/
internal string ServerKeyType {
get {
return serverKeyType;
}
}
int suite;
string name;
int strength;
bool isCBC;
bool isRC4;
bool isDHE;
bool isECDHE;
bool isRSAExport;
bool isSRP;
bool isPSK;
string serverKeyType;
CipherSuite(string descriptor)
{
string[] ww = descriptor.Split((char[])null,
StringSplitOptions.RemoveEmptyEntries);
if (ww.Length != 6) {
throw new ArgumentException(
"Bad cipher suite descriptor");
}
suite = ParseHex(ww[0]);
switch (ww[1]) {
case "0":
case "1":
case "2":
case "3":
strength = ww[1][0] - '0';
break;
default:
throw new ArgumentException(
"Bad encryption strength: " + ww[1]);
}
switch (ww[2].ToLowerInvariant()) {
case "c":
isCBC = true;
break;
case "r":
isRC4 = true;
break;
case "-":
break;
default:
throw new ArgumentException(
"Bad encryption flags: " + ww[2]);
}
switch (ww[3].ToLowerInvariant()) {
case "d":
isDHE = true;
break;
case "e":
isECDHE = true;
break;
case "s":
isSRP = true;
break;
case "x":
isRSAExport = true;
break;
case "-":
break;
default:
throw new ArgumentException(
"Bad key exchange flags: " + ww[3]);
}
switch (ww[4].ToLowerInvariant()) {
case "r":
serverKeyType = "RSA";
break;
case "d":
serverKeyType = "DSA";
break;
case "h":
serverKeyType = "DH";
break;
case "e":
serverKeyType = "EC";
break;
case "p":
isPSK = true;
serverKeyType = "none";
break;
case "q":
isPSK = true;
serverKeyType = "RSA";
break;
case "n":
serverKeyType = "none";
break;
default:
throw new ArgumentException(
"Bad server key type: " + ww[4]);
}
name = ww[5];
}
static int ParseHex(string s)
{
int acc = 0;
foreach (char c in s) {
int d;
if (c >= '0' && c <= '9') {
d = c - '0';
} else if (c >= 'A' && c <= 'F') {
d = c - ('A' - 10);
} else if (c >= 'a' && c <= 'f') {
d = c - ('a' - 10);
} else {
throw new ArgumentException("Not hex digit");
}
if (acc > 0x7FFFFFF) {
throw new ArgumentException("Hex overflow");
}
acc = (acc << 4) + d;
}
return acc;
}
/*
* A map of all cipher suites, indexed by identifier.
*/
internal static readonly IDictionary<int, CipherSuite> ALL =
new SortedDictionary<int, CipherSuite>();
/*
* Some constants for cipher strength.
*/
internal const int CLEAR = 0; // no encryption
internal const int WEAK = 1; // weak encryption: 40-bit key
internal const int MEDIUM = 2; // medium encryption: 56-bit key
internal const int STRONG = 3; // strong encryption
/*
* Convert strength to a human-readable string.
*/
internal static string ToStrength(int strength)
{
switch (strength) {
case CLEAR: return "no encryption";
case WEAK: return "weak encryption (40-bit)";
case MEDIUM: return "medium encryption (56-bit)";
case STRONG: return "strong encryption (96-bit or more)";
default:
throw new Exception("strange strength: " + strength);
}
}
/*
* Get cipher suite name. If the identifier is unknown, then a
* synthetic name is returned.
*/
internal static string ToName(int suite)
{
if (ALL.ContainsKey(suite)) {
return ALL[suite].name;
} else {
return string.Format("UNKNOWN_SUITE:0x{0:X4}", suite);
}
}
/*
* Some constants for SSLv2 cipher suites.
*/
internal const int SSL_CK_RC4_128_WITH_MD5 = 0x010080;
internal const int SSL_CK_RC4_128_EXPORT40_WITH_MD5 = 0x020080;
internal const int SSL_CK_RC2_128_CBC_WITH_MD5 = 0x030080;
internal const int SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 = 0x040080;
internal const int SSL_CK_IDEA_128_CBC_WITH_MD5 = 0x050080;
internal const int SSL_CK_DES_64_CBC_WITH_MD5 = 0x060040;
internal const int SSL_CK_DES_192_EDE3_CBC_WITH_MD5 = 0x0700C0;
/*
* The SSL 2.0 suites, in numerical order.
*/
internal static int[] SSL2_SUITES = {
SSL_CK_RC4_128_WITH_MD5,
SSL_CK_RC4_128_EXPORT40_WITH_MD5,
SSL_CK_RC2_128_CBC_WITH_MD5,
SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5,
SSL_CK_IDEA_128_CBC_WITH_MD5,
SSL_CK_DES_64_CBC_WITH_MD5,
SSL_CK_DES_192_EDE3_CBC_WITH_MD5
};
/*
* Get the name for a SSLv2 cipher suite. If the identifier is
* unknown, then a synthetic name is returned.
*/
internal static string ToNameV2(int suite)
{
switch (suite) {
case SSL_CK_RC4_128_WITH_MD5:
return "RC4_128_WITH_MD5";
case SSL_CK_RC4_128_EXPORT40_WITH_MD5:
return "RC4_128_EXPORT40_WITH_MD5";
case SSL_CK_RC2_128_CBC_WITH_MD5:
return "RC2_128_CBC_WITH_MD5";
case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5:
return "RC2_128_CBC_EXPORT40_WITH_MD5";
case SSL_CK_IDEA_128_CBC_WITH_MD5:
return "IDEA_128_CBC_WITH_MD5";
case SSL_CK_DES_64_CBC_WITH_MD5:
return "DES_64_CBC_WITH_MD5";
case SSL_CK_DES_192_EDE3_CBC_WITH_MD5:
return "DES_192_EDE3_CBC_WITH_MD5";
default:
return string.Format("UNKNOWN_SUITE:0x{0:X6}", suite);
}
}
static CipherSuite()
{
StringReader r = new StringReader(STD_SUITES);
for (;;) {
string line = r.ReadLine();
if (line == null) {
break;
}
line = line.Trim();
if (line.Length == 0 || line.StartsWith("#")) {
continue;
}
CipherSuite cs = new CipherSuite(line);
if (ALL.ContainsKey(cs.Suite)) {
throw new ArgumentException(string.Format(
"Duplicate suite: 0x{0:X4}", cs.Suite));
}
ALL[cs.Suite] = cs;
string name = cs.Name;
/*
* Consistency test: the strength and CBC status can
* normally be inferred from the name itself.
*/
bool inferredCBC = name.Contains("_CBC_");
bool inferredRC4 = name.Contains("RC4");
int inferredStrength;
if (name.Contains("_NULL_")) {
inferredStrength = CLEAR;
} else if (name.Contains("DES40")
|| name.Contains("_40_"))
{
inferredStrength = WEAK;
} else if (name.Contains("_DES_")) {
inferredStrength = MEDIUM;
} else {
inferredStrength = STRONG;
}
bool isDHE = false;
bool isECDHE = false;
bool isRSAExport = false;
bool isSRP = false;
bool isPSK = false;
string serverKeyType = "none";
if (name.StartsWith("RSA_PSK")) {
isPSK = true;
serverKeyType = "RSA";
} else if (name.StartsWith("RSA_EXPORT")) {
isRSAExport = true;
serverKeyType = "RSA";
} else if (name.StartsWith("RSA_")) {
serverKeyType = "RSA";
} else if (name.StartsWith("DHE_PSK")) {
isDHE = true;
isPSK = true;
} else if (name.StartsWith("DHE_DSS")) {
isDHE = true;
serverKeyType = "DSA";
} else if (name.StartsWith("DHE_RSA")) {
isDHE = true;
serverKeyType = "RSA";
} else if (name.StartsWith("DH_anon")) {
isDHE = true;
} else if (name.StartsWith("DH_")) {
serverKeyType = "DH";
} else if (name.StartsWith("ECDHE_PSK")) {
isECDHE = true;
isPSK = true;
} else if (name.StartsWith("ECDHE_ECDSA")) {
isECDHE = true;
serverKeyType = "EC";
} else if (name.StartsWith("ECDHE_RSA")) {
isECDHE = true;
serverKeyType = "RSA";
} else if (name.StartsWith("ECDH_anon")) {
isECDHE = true;
} else if (name.StartsWith("ECDH_")) {
serverKeyType = "EC";
} else if (name.StartsWith("PSK_DHE")) {
isDHE = true;
isPSK = true;
} else if (name.StartsWith("PSK_")) {
isPSK = true;
} else if (name.StartsWith("KRB5_")) {
isPSK = true;
} else if (name.StartsWith("SRP_")) {
isSRP = true;
} else {
throw new ArgumentException(
"Weird name: " + cs.Name);
}
if (inferredStrength != cs.Strength
|| inferredCBC != cs.IsCBC
|| inferredRC4 != cs.IsRC4
|| isDHE != cs.IsDHE
|| isECDHE != cs.IsECDHE
|| isRSAExport != cs.IsRSAExport
|| isSRP != cs.IsSRP
|| isPSK != cs.IsPSK
|| serverKeyType != cs.ServerKeyType)
{
Console.WriteLine("BAD: {0}", cs.Name);
Console.WriteLine("strength: {0} / {1}", inferredStrength, cs.Strength);
Console.WriteLine("RC4: {0} / {1}", inferredRC4, cs.IsRC4);
Console.WriteLine("DHE: {0} / {1}", isDHE, cs.IsDHE);
Console.WriteLine("ECDHE: {0} / {1}", isECDHE, cs.IsECDHE);
Console.WriteLine("SRP: {0} / {1}", isSRP, cs.IsSRP);
Console.WriteLine("PSK: {0} / {1}", isPSK, cs.IsPSK);
Console.WriteLine("keytype: {0} / {1}", serverKeyType, cs.ServerKeyType);
throw new ArgumentException(
"Wrong classification: " + cs.Name);
}
}
}
const string STD_SUITES =
/*
+------------- cipher suite identifier (hex)
| +---------- encryption strength (0=none, 1=weak, 2=medium, 3=strong)
| | +-------- encryption flags (c=block cipher in CBC mode, r=RC4)
| | | +------ key exchange flags (d=DHE, e=ECDHE, s=SRP, x=RSA/export)
| | | | +---- server key type (r=RSA, d=DSA, h=DH, e=EC, p=PSK,
| | | | | q=RSA+PSK, n=none)
| | | | | +-- suite name
| | | | | |
V V V V V V
*/
@"
0001 0 - - r RSA_WITH_NULL_MD5
0002 0 - - r RSA_WITH_NULL_SHA
0003 1 r x r RSA_EXPORT_WITH_RC4_40_MD5
0004 3 r - r RSA_WITH_RC4_128_MD5
0005 3 r - r RSA_WITH_RC4_128_SHA
0006 1 c x r RSA_EXPORT_WITH_RC2_CBC_40_MD5
0007 3 c - r RSA_WITH_IDEA_CBC_SHA
0008 1 c x r RSA_EXPORT_WITH_DES40_CBC_SHA
0009 2 c - r RSA_WITH_DES_CBC_SHA
000A 3 c - r RSA_WITH_3DES_EDE_CBC_SHA
000B 1 c - h DH_DSS_EXPORT_WITH_DES40_CBC_SHA
000C 2 c - h DH_DSS_WITH_DES_CBC_SHA
000D 3 c - h DH_DSS_WITH_3DES_EDE_CBC_SHA
000E 1 c - h DH_RSA_EXPORT_WITH_DES40_CBC_SHA
000F 2 c - h DH_RSA_WITH_DES_CBC_SHA
0010 3 c - h DH_RSA_WITH_3DES_EDE_CBC_SHA
0011 1 c d d DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
0012 2 c d d DHE_DSS_WITH_DES_CBC_SHA
0013 3 c d d DHE_DSS_WITH_3DES_EDE_CBC_SHA
0014 1 c d r DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
0015 2 c d r DHE_RSA_WITH_DES_CBC_SHA
0016 3 c d r DHE_RSA_WITH_3DES_EDE_CBC_SHA
0017 1 r d n DH_anon_EXPORT_WITH_RC4_40_MD5
0018 3 r d n DH_anon_WITH_RC4_128_MD5
0019 1 c d n DH_anon_EXPORT_WITH_DES40_CBC_SHA
001A 2 c d n DH_anon_WITH_DES_CBC_SHA
001B 3 c d n DH_anon_WITH_3DES_EDE_CBC_SHA
001E 2 c - p KRB5_WITH_DES_CBC_SHA
001F 3 c - p KRB5_WITH_3DES_EDE_CBC_SHA
0020 3 r - p KRB5_WITH_RC4_128_SHA
0021 3 c - p KRB5_WITH_IDEA_CBC_SHA
0022 2 c - p KRB5_WITH_DES_CBC_MD5
0023 3 c - p KRB5_WITH_3DES_EDE_CBC_MD5
0024 3 r - p KRB5_WITH_RC4_128_MD5
0025 3 c - p KRB5_WITH_IDEA_CBC_MD5
0026 1 c - p KRB5_EXPORT_WITH_DES_CBC_40_SHA
0027 1 c - p KRB5_EXPORT_WITH_RC2_CBC_40_SHA
0028 1 r - p KRB5_EXPORT_WITH_RC4_40_SHA
0029 1 c - p KRB5_EXPORT_WITH_DES_CBC_40_MD5
002A 1 c - p KRB5_EXPORT_WITH_RC2_CBC_40_MD5
002B 1 r - p KRB5_EXPORT_WITH_RC4_40_MD5
002C 0 - - p PSK_WITH_NULL_SHA
002D 0 - d p DHE_PSK_WITH_NULL_SHA
002E 0 - - q RSA_PSK_WITH_NULL_SHA
002F 3 c - r RSA_WITH_AES_128_CBC_SHA
0030 3 c - h DH_DSS_WITH_AES_128_CBC_SHA
0031 3 c - h DH_RSA_WITH_AES_128_CBC_SHA
0032 3 c d d DHE_DSS_WITH_AES_128_CBC_SHA
0033 3 c d r DHE_RSA_WITH_AES_128_CBC_SHA
0034 3 c d n DH_anon_WITH_AES_128_CBC_SHA
0035 3 c - r RSA_WITH_AES_256_CBC_SHA
0036 3 c - h DH_DSS_WITH_AES_256_CBC_SHA
0037 3 c - h DH_RSA_WITH_AES_256_CBC_SHA
0038 3 c d d DHE_DSS_WITH_AES_256_CBC_SHA
0039 3 c d r DHE_RSA_WITH_AES_256_CBC_SHA
003A 3 c d n DH_anon_WITH_AES_256_CBC_SHA
003B 0 - - r RSA_WITH_NULL_SHA256
003C 3 c - r RSA_WITH_AES_128_CBC_SHA256
003D 3 c - r RSA_WITH_AES_256_CBC_SHA256
003E 3 c - h DH_DSS_WITH_AES_128_CBC_SHA256
003F 3 c - h DH_RSA_WITH_AES_128_CBC_SHA256
0040 3 c d d DHE_DSS_WITH_AES_128_CBC_SHA256
0041 3 c - r RSA_WITH_CAMELLIA_128_CBC_SHA
0042 3 c - h DH_DSS_WITH_CAMELLIA_128_CBC_SHA
0043 3 c - h DH_RSA_WITH_CAMELLIA_128_CBC_SHA
0044 3 c d d DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
0045 3 c d r DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
0046 3 c d n DH_anon_WITH_CAMELLIA_128_CBC_SHA
0067 3 c d r DHE_RSA_WITH_AES_128_CBC_SHA256
0068 3 c - h DH_DSS_WITH_AES_256_CBC_SHA256
0069 3 c - h DH_RSA_WITH_AES_256_CBC_SHA256
006A 3 c d d DHE_DSS_WITH_AES_256_CBC_SHA256
006B 3 c d r DHE_RSA_WITH_AES_256_CBC_SHA256
006C 3 c d n DH_anon_WITH_AES_128_CBC_SHA256
006D 3 c d n DH_anon_WITH_AES_256_CBC_SHA256
0084 3 c - r RSA_WITH_CAMELLIA_256_CBC_SHA
0085 3 c - h DH_DSS_WITH_CAMELLIA_256_CBC_SHA
0086 3 c - h DH_RSA_WITH_CAMELLIA_256_CBC_SHA
0087 3 c d d DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
0088 3 c d r DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
0089 3 c d n DH_anon_WITH_CAMELLIA_256_CBC_SHA
008A 3 r - p PSK_WITH_RC4_128_SHA
008B 3 c - p PSK_WITH_3DES_EDE_CBC_SHA
008C 3 c - p PSK_WITH_AES_128_CBC_SHA
008D 3 c - p PSK_WITH_AES_256_CBC_SHA
008E 3 r d p DHE_PSK_WITH_RC4_128_SHA
008F 3 c d p DHE_PSK_WITH_3DES_EDE_CBC_SHA
0090 3 c d p DHE_PSK_WITH_AES_128_CBC_SHA
0091 3 c d p DHE_PSK_WITH_AES_256_CBC_SHA
0092 3 r - q RSA_PSK_WITH_RC4_128_SHA
0093 3 c - q RSA_PSK_WITH_3DES_EDE_CBC_SHA
0094 3 c - q RSA_PSK_WITH_AES_128_CBC_SHA
0095 3 c - q RSA_PSK_WITH_AES_256_CBC_SHA
0096 3 c - r RSA_WITH_SEED_CBC_SHA
0097 3 c - h DH_DSS_WITH_SEED_CBC_SHA
0098 3 c - h DH_RSA_WITH_SEED_CBC_SHA
0099 3 c d d DHE_DSS_WITH_SEED_CBC_SHA
009A 3 c d r DHE_RSA_WITH_SEED_CBC_SHA
009B 3 c d n DH_anon_WITH_SEED_CBC_SHA
009C 3 - - r RSA_WITH_AES_128_GCM_SHA256
009D 3 - - r RSA_WITH_AES_256_GCM_SHA384
009E 3 - d r DHE_RSA_WITH_AES_128_GCM_SHA256
009F 3 - d r DHE_RSA_WITH_AES_256_GCM_SHA384
00A0 3 - - h DH_RSA_WITH_AES_128_GCM_SHA256
00A1 3 - - h DH_RSA_WITH_AES_256_GCM_SHA384
00A2 3 - d d DHE_DSS_WITH_AES_128_GCM_SHA256
00A3 3 - d d DHE_DSS_WITH_AES_256_GCM_SHA384
00A4 3 - - h DH_DSS_WITH_AES_128_GCM_SHA256
00A5 3 - - h DH_DSS_WITH_AES_256_GCM_SHA384
00A6 3 - d n DH_anon_WITH_AES_128_GCM_SHA256
00A7 3 - d n DH_anon_WITH_AES_256_GCM_SHA384
00A8 3 - - p PSK_WITH_AES_128_GCM_SHA256
00A9 3 - - p PSK_WITH_AES_256_GCM_SHA384
00AA 3 - d p DHE_PSK_WITH_AES_128_GCM_SHA256
00AB 3 - d p DHE_PSK_WITH_AES_256_GCM_SHA384
00AC 3 - - q RSA_PSK_WITH_AES_128_GCM_SHA256
00AD 3 - - q RSA_PSK_WITH_AES_256_GCM_SHA384
00AE 3 c - p PSK_WITH_AES_128_CBC_SHA256
00AF 3 c - p PSK_WITH_AES_256_CBC_SHA384
00B0 0 - - p PSK_WITH_NULL_SHA256
00B1 0 - - p PSK_WITH_NULL_SHA384
00B2 3 c d p DHE_PSK_WITH_AES_128_CBC_SHA256
00B3 3 c d p DHE_PSK_WITH_AES_256_CBC_SHA384
00B4 0 - d p DHE_PSK_WITH_NULL_SHA256
00B5 0 - d p DHE_PSK_WITH_NULL_SHA384
00B6 3 c - q RSA_PSK_WITH_AES_128_CBC_SHA256
00B7 3 c - q RSA_PSK_WITH_AES_256_CBC_SHA384
00B8 0 - - q RSA_PSK_WITH_NULL_SHA256
00B9 0 - - q RSA_PSK_WITH_NULL_SHA384
00BA 3 c - r RSA_WITH_CAMELLIA_128_CBC_SHA256
00BB 3 c - h DH_DSS_WITH_CAMELLIA_128_CBC_SHA256
00BC 3 c - h DH_RSA_WITH_CAMELLIA_128_CBC_SHA256
00BD 3 c d d DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256
00BE 3 c d r DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
00BF 3 c d n DH_anon_WITH_CAMELLIA_128_CBC_SHA256
00C0 3 c - r RSA_WITH_CAMELLIA_256_CBC_SHA256
00C1 3 c - h DH_DSS_WITH_CAMELLIA_256_CBC_SHA256
00C2 3 c - h DH_RSA_WITH_CAMELLIA_256_CBC_SHA256
00C3 3 c d d DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256
00C4 3 c d r DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
00C5 3 c d n DH_anon_WITH_CAMELLIA_256_CBC_SHA256
C001 0 - - e ECDH_ECDSA_WITH_NULL_SHA
C002 3 r - e ECDH_ECDSA_WITH_RC4_128_SHA
C003 3 c - e ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
C004 3 c - e ECDH_ECDSA_WITH_AES_128_CBC_SHA
C005 3 c - e ECDH_ECDSA_WITH_AES_256_CBC_SHA
C006 0 - e e ECDHE_ECDSA_WITH_NULL_SHA
C007 3 r e e ECDHE_ECDSA_WITH_RC4_128_SHA
C008 3 c e e ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
C009 3 c e e ECDHE_ECDSA_WITH_AES_128_CBC_SHA
C00A 3 c e e ECDHE_ECDSA_WITH_AES_256_CBC_SHA
C00B 0 - - e ECDH_RSA_WITH_NULL_SHA
C00C 3 r - e ECDH_RSA_WITH_RC4_128_SHA
C00D 3 c - e ECDH_RSA_WITH_3DES_EDE_CBC_SHA
C00E 3 c - e ECDH_RSA_WITH_AES_128_CBC_SHA
C00F 3 c - e ECDH_RSA_WITH_AES_256_CBC_SHA
C010 0 - e r ECDHE_RSA_WITH_NULL_SHA
C011 3 r e r ECDHE_RSA_WITH_RC4_128_SHA
C012 3 c e r ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
C013 3 c e r ECDHE_RSA_WITH_AES_128_CBC_SHA
C014 3 c e r ECDHE_RSA_WITH_AES_256_CBC_SHA
C015 0 - e n ECDH_anon_WITH_NULL_SHA
C016 3 r e n ECDH_anon_WITH_RC4_128_SHA
C017 3 c e n ECDH_anon_WITH_3DES_EDE_CBC_SHA
C018 3 c e n ECDH_anon_WITH_AES_128_CBC_SHA
C019 3 c e n ECDH_anon_WITH_AES_256_CBC_SHA
C01A 3 c s n SRP_SHA_WITH_3DES_EDE_CBC_SHA
C01B 3 c s n SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA
C01C 3 c s n SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA
C01D 3 c s n SRP_SHA_WITH_AES_128_CBC_SHA
C01E 3 c s n SRP_SHA_RSA_WITH_AES_128_CBC_SHA
C01F 3 c s n SRP_SHA_DSS_WITH_AES_128_CBC_SHA
C020 3 c s n SRP_SHA_WITH_AES_256_CBC_SHA
C021 3 c s n SRP_SHA_RSA_WITH_AES_256_CBC_SHA
C022 3 c s n SRP_SHA_DSS_WITH_AES_256_CBC_SHA
C023 3 c e e ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
C024 3 c e e ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
C025 3 c - e ECDH_ECDSA_WITH_AES_128_CBC_SHA256
C026 3 c - e ECDH_ECDSA_WITH_AES_256_CBC_SHA384
C027 3 c e r ECDHE_RSA_WITH_AES_128_CBC_SHA256
C028 3 c e r ECDHE_RSA_WITH_AES_256_CBC_SHA384
C029 3 c - e ECDH_RSA_WITH_AES_128_CBC_SHA256
C02A 3 c - e ECDH_RSA_WITH_AES_256_CBC_SHA384
C02B 3 - e e ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
C02C 3 - e e ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
C02D 3 - - e ECDH_ECDSA_WITH_AES_128_GCM_SHA256
C02E 3 - - e ECDH_ECDSA_WITH_AES_256_GCM_SHA384
C02F 3 - e r ECDHE_RSA_WITH_AES_128_GCM_SHA256
C030 3 - e r ECDHE_RSA_WITH_AES_256_GCM_SHA384
C031 3 - - e ECDH_RSA_WITH_AES_128_GCM_SHA256
C032 3 - - e ECDH_RSA_WITH_AES_256_GCM_SHA384
C033 3 r e p ECDHE_PSK_WITH_RC4_128_SHA
C034 3 c e p ECDHE_PSK_WITH_3DES_EDE_CBC_SHA
C035 3 c e p ECDHE_PSK_WITH_AES_128_CBC_SHA
C036 3 c e p ECDHE_PSK_WITH_AES_256_CBC_SHA
C037 3 c e p ECDHE_PSK_WITH_AES_128_CBC_SHA256
C038 3 c e p ECDHE_PSK_WITH_AES_256_CBC_SHA384
C039 0 - e p ECDHE_PSK_WITH_NULL_SHA
C03A 0 - e p ECDHE_PSK_WITH_NULL_SHA256
C03B 0 - e p ECDHE_PSK_WITH_NULL_SHA384
C03C 3 c - r RSA_WITH_ARIA_128_CBC_SHA256
C03D 3 c - r RSA_WITH_ARIA_256_CBC_SHA384
C03E 3 c - h DH_DSS_WITH_ARIA_128_CBC_SHA256
C03F 3 c - h DH_DSS_WITH_ARIA_256_CBC_SHA384
C040 3 c - h DH_RSA_WITH_ARIA_128_CBC_SHA256
C041 3 c - h DH_RSA_WITH_ARIA_256_CBC_SHA384
C042 3 c d d DHE_DSS_WITH_ARIA_128_CBC_SHA256
C043 3 c d d DHE_DSS_WITH_ARIA_256_CBC_SHA384
C044 3 c d r DHE_RSA_WITH_ARIA_128_CBC_SHA256
C045 3 c d r DHE_RSA_WITH_ARIA_256_CBC_SHA384
C046 3 c d n DH_anon_WITH_ARIA_128_CBC_SHA256
C047 3 c d n DH_anon_WITH_ARIA_256_CBC_SHA384
C048 3 c e e ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256
C049 3 c e e ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384
C04A 3 c - e ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256
C04B 3 c - e ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384
C04C 3 c e r ECDHE_RSA_WITH_ARIA_128_CBC_SHA256
C04D 3 c e r ECDHE_RSA_WITH_ARIA_256_CBC_SHA384
C04E 3 c - e ECDH_RSA_WITH_ARIA_128_CBC_SHA256
C04F 3 c - e ECDH_RSA_WITH_ARIA_256_CBC_SHA384
C050 3 - - r RSA_WITH_ARIA_128_GCM_SHA256
C051 3 - - r RSA_WITH_ARIA_256_GCM_SHA384
C052 3 - d r DHE_RSA_WITH_ARIA_128_GCM_SHA256
C053 3 - d r DHE_RSA_WITH_ARIA_256_GCM_SHA384
C054 3 - - h DH_RSA_WITH_ARIA_128_GCM_SHA256
C055 3 - - h DH_RSA_WITH_ARIA_256_GCM_SHA384
C056 3 - d d DHE_DSS_WITH_ARIA_128_GCM_SHA256
C057 3 - d d DHE_DSS_WITH_ARIA_256_GCM_SHA384
C058 3 - - h DH_DSS_WITH_ARIA_128_GCM_SHA256
C059 3 - - h DH_DSS_WITH_ARIA_256_GCM_SHA384
C05A 3 - d n DH_anon_WITH_ARIA_128_GCM_SHA256
C05B 3 - d n DH_anon_WITH_ARIA_256_GCM_SHA384
C05C 3 - e e ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
C05D 3 - e e ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
C05E 3 - - e ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256
C05F 3 - - e ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384
C060 3 - e r ECDHE_RSA_WITH_ARIA_128_GCM_SHA256
C061 3 - e r ECDHE_RSA_WITH_ARIA_256_GCM_SHA384
C062 3 - - e ECDH_RSA_WITH_ARIA_128_GCM_SHA256
C063 3 - - e ECDH_RSA_WITH_ARIA_256_GCM_SHA384
C064 3 c - p PSK_WITH_ARIA_128_CBC_SHA256
C065 3 c - p PSK_WITH_ARIA_256_CBC_SHA384
C066 3 c d p DHE_PSK_WITH_ARIA_128_CBC_SHA256
C067 3 c d p DHE_PSK_WITH_ARIA_256_CBC_SHA384
C068 3 c - q RSA_PSK_WITH_ARIA_128_CBC_SHA256
C069 3 c - q RSA_PSK_WITH_ARIA_256_CBC_SHA384
C06A 3 - - p PSK_WITH_ARIA_128_GCM_SHA256
C06B 3 - - p PSK_WITH_ARIA_256_GCM_SHA384
C06C 3 - d p DHE_PSK_WITH_ARIA_128_GCM_SHA256
C06D 3 - d p DHE_PSK_WITH_ARIA_256_GCM_SHA384
C06E 3 - - q RSA_PSK_WITH_ARIA_128_GCM_SHA256
C06F 3 - - q RSA_PSK_WITH_ARIA_256_GCM_SHA384
C070 3 c e p ECDHE_PSK_WITH_ARIA_128_CBC_SHA256
C071 3 c e p ECDHE_PSK_WITH_ARIA_256_CBC_SHA384
C072 3 c e e ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
C073 3 c e e ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
C074 3 c - e ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
C075 3 c - e ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
C076 3 c e r ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
C077 3 c e r ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384
C078 3 c - e ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256
C079 3 c - e ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384
C07A 3 - - r RSA_WITH_CAMELLIA_128_GCM_SHA256
C07B 3 - - r RSA_WITH_CAMELLIA_256_GCM_SHA384
C07C 3 - d r DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
C07D 3 - d r DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
C07E 3 - - h DH_RSA_WITH_CAMELLIA_128_GCM_SHA256
C07F 3 - - h DH_RSA_WITH_CAMELLIA_256_GCM_SHA384
C080 3 - d d DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256
C081 3 - d d DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384
C082 3 - - h DH_DSS_WITH_CAMELLIA_128_GCM_SHA256
C083 3 - - h DH_DSS_WITH_CAMELLIA_256_GCM_SHA384
C084 3 - d n DH_anon_WITH_CAMELLIA_128_GCM_SHA256
C085 3 - d n DH_anon_WITH_CAMELLIA_256_GCM_SHA384
C086 3 - e e ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
C087 3 - e e ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
C088 3 - - e ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
C089 3 - - e ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
C08A 3 - e r ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
C08B 3 - e r ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
C08C 3 - - e ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256
C08D 3 - - e ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384
C08E 3 - - p PSK_WITH_CAMELLIA_128_GCM_SHA256
C08F 3 - - p PSK_WITH_CAMELLIA_256_GCM_SHA384
C090 3 - d p DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256
C091 3 - d p DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384
C092 3 - - q RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256
C093 3 - - q RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384
C094 3 c - p PSK_WITH_CAMELLIA_128_CBC_SHA256
C095 3 c - p PSK_WITH_CAMELLIA_256_CBC_SHA384
C096 3 c d p DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
C097 3 c d p DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
C098 3 c - q RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256
C099 3 c - q RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384
C09A 3 c e p ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
C09B 3 c e p ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
C09C 3 - - r RSA_WITH_AES_128_CCM
C09D 3 - - r RSA_WITH_AES_256_CCM
C09E 3 - d r DHE_RSA_WITH_AES_128_CCM
C09F 3 - d r DHE_RSA_WITH_AES_256_CCM
C0A0 3 - - r RSA_WITH_AES_128_CCM_8
C0A1 3 - - r RSA_WITH_AES_256_CCM_8
C0A2 3 - d r DHE_RSA_WITH_AES_128_CCM_8
C0A3 3 - d r DHE_RSA_WITH_AES_256_CCM_8
C0A4 3 - - p PSK_WITH_AES_128_CCM
C0A5 3 - - p PSK_WITH_AES_256_CCM
C0A6 3 - d p DHE_PSK_WITH_AES_128_CCM
C0A7 3 - d p DHE_PSK_WITH_AES_256_CCM
C0A8 3 - - p PSK_WITH_AES_128_CCM_8
C0A9 3 - - p PSK_WITH_AES_256_CCM_8
C0AA 3 - d p PSK_DHE_WITH_AES_128_CCM_8
C0AB 3 - d p PSK_DHE_WITH_AES_256_CCM_8
C0AC 3 - e e ECDHE_ECDSA_WITH_AES_128_CCM
C0AD 3 - e e ECDHE_ECDSA_WITH_AES_256_CCM
C0AE 3 - e e ECDHE_ECDSA_WITH_AES_128_CCM_8
C0AF 3 - e e ECDHE_ECDSA_WITH_AES_256_CCM_8
# These ones are from draft-mavrogiannopoulos-chacha-tls-01
# Apparently some servers (Google...) deployed them.
# We use the suffix '_OLD' to signify that they are not registered at
# the IANA (and probably will never be).
CC12 3 - - r RSA_WITH_CHACHA20_POLY1305_OLD
CC13 3 - e r ECDHE_RSA_WITH_CHACHA20_POLY1305_OLD
CC14 3 - e e ECDHE_ECDSA_WITH_CHACHA20_POLY1305_OLD
CC15 3 - d r DHE_RSA_WITH_CHACHA20_POLY1305_OLD
CC16 3 - d p DHE_PSK_WITH_CHACHA20_POLY1305_OLD
CC17 3 - - p PSK_WITH_CHACHA20_POLY1305_OLD
CC18 3 - e p ECDHE_PSK_WITH_CHACHA20_POLY1305_OLD
CC19 3 - - q RSA_PSK_WITH_CHACHA20_POLY1305_OLD
# Defined in RFC 7905.
CCA8 3 - e r ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
CCA9 3 - e e ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
CCAA 3 - d r DHE_RSA_WITH_CHACHA20_POLY1305_SHA256
CCAB 3 - - p PSK_WITH_CHACHA20_POLY1305_SHA256
CCAC 3 - e p ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256
CCAD 3 - d p DHE_PSK_WITH_CHACHA20_POLY1305_SHA256
CCAE 3 - - q RSA_PSK_WITH_CHACHA20_POLY1305_SHA256
";
/*
* We do not support FORTEZZA cipher suites, because the
* protocol is not published, and nobody uses it anyway.
* One of the FORTEZZA cipher suites conflicts with one
* of the Kerberos cipher suites (same ID: 0x001E).
*/
}
| |
using System;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading.Tasks;
using Stardust.Interstellar.Rest.Common;
using Stardust.Interstellar.Rest.Extensions;
namespace Stardust.Interstellar.Rest.Client
{
internal class ProxyBuilder
{
private readonly Type interfaceType;
/// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
public ProxyBuilder(Type interfaceType)
{
this.interfaceType = interfaceType;
}
private AssemblyBuilder myAssemblyBuilder;
/// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary>
public Type Build()
{
var myCurrentDomain = AppDomain.CurrentDomain;
var myAssemblyName = new AssemblyName();
myAssemblyName.Name = Guid.NewGuid().ToString().Replace("-", "") + "_RestWrapper";
ExtensionsFactory.GetService<ILogger>()?.Message("Creating dynamic assembly {0}", myAssemblyName.FullName);
myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.RunAndSave);
var myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule", "dyn.dll");
var type = ReflectionTypeBuilder(myModuleBuilder, interfaceType.Name + "_dynimp");
ctor(type);
foreach (var methodInfo in interfaceType.GetMethods().Length == 0 ? interfaceType.GetInterfaces().First().GetMethods() : interfaceType.GetMethods())
{
if (typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
BuildMethodAsync(type, methodInfo);
else if (methodInfo.ReturnType != typeof(void))
BuildMethod(type, methodInfo);
else
BuildVoidMethod(type, methodInfo);
}
var result = type.CreateType();
try
{
if (ConfigurationManager.AppSettings["stardust.saveGeneratedAssemblies"] == "true")
{
ExtensionsFactory.GetService<ILogger>().Message("Saveing generated assembly");
myAssemblyBuilder.Save("dyn.dll");
}
}
catch (Exception ex)
{
ExtensionsFactory.GetService<ILogger>()?.Error(ex);
}
return result;
}
private MethodBuilder BuildMethod(TypeBuilder type, MethodInfo serviceAction)
{
const MethodAttributes methodAttributes = MethodAttributes.Public
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
var method = type.DefineMethod(serviceAction.Name, methodAttributes);
// Preparing Reflection instances
var method1 = typeof(RestWrapper).GetMethod(
"GetParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new[]{
typeof(string),
typeof(object[])
},
null
);
MethodInfo method2 = typeof(RestWrapper).GetMethod(
"Invoke",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new[]{
typeof(string),
typeof(ParameterWrapper[])
},
null
).MakeGenericMethod(serviceAction.ReturnType);
// Setting return type
method.SetReturnType(serviceAction.ReturnType);
// Adding parameters
method.SetParameters(serviceAction.GetParameters().Select(p => p.ParameterType).ToArray());
var i = 1;
foreach (var parameterInfo in serviceAction.GetParameters())
{
var param = method.DefineParameter(i, ParameterAttributes.None, parameterInfo.Name);
i++;
}
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder par = gen.DeclareLocal(typeof(Object[]));
LocalBuilder parameters = gen.DeclareLocal(typeof(ParameterWrapper[]));
LocalBuilder result = gen.DeclareLocal(serviceAction.ReturnType);
LocalBuilder str = gen.DeclareLocal(serviceAction.ReturnType);
// Preparing labels
Label label55 = gen.DefineLabel();
// Writing body
var ps = serviceAction.GetParameters();
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j].ParameterType;
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, method1);
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Call, method2);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Br_S, label55);
gen.MarkLabel(label55);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private MethodBuilder BuildVoidMethod(TypeBuilder type, MethodInfo serviceAction)
{
const MethodAttributes methodAttributes = MethodAttributes.Public
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
var method = type.DefineMethod(serviceAction.Name, methodAttributes);
// Preparing Reflection instances
var method1 = typeof(RestWrapper).GetMethod(
"GetParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new[]{
typeof(string),
typeof(object[])
},
null
);
MethodInfo method2 = typeof(RestWrapper).GetMethod(
"InvokeVoid",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new[]{
typeof(string),
typeof(ParameterWrapper[])
},
null
);
// Adding parameters
method.SetParameters(serviceAction.GetParameters().Select(p => p.ParameterType).ToArray());
var i = 1;
foreach (var parameterInfo in serviceAction.GetParameters())
{
var param = method.DefineParameter(i, ParameterAttributes.None, parameterInfo.Name);
i++;
}
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder par = gen.DeclareLocal(typeof(Object[]));
LocalBuilder parameters = gen.DeclareLocal(typeof(ParameterWrapper[]));
// Preparing labels
Label label55 = gen.DefineLabel();
// Writing body
var ps = serviceAction.GetParameters();
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j].ParameterType;
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, method1);
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Call, method2);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private MethodBuilder BuildMethodAsync(TypeBuilder type, MethodInfo serviceAction)
{
const MethodAttributes methodAttributes = MethodAttributes.Public
| MethodAttributes.Virtual
| MethodAttributes.Final
| MethodAttributes.HideBySig
| MethodAttributes.NewSlot;
var method = type.DefineMethod(serviceAction.Name, methodAttributes);
// Preparing Reflection instances
var method1 = typeof(RestWrapper).GetMethod(
"GetParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new[]{
typeof(string),
typeof(object[])
},
null
);
var method2 = typeof(RestWrapper).GetMethod(serviceAction.ReturnType.GetGenericArguments().Length == 0 ? "InvokeVoidAsync" : "InvokeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(string), typeof(ParameterWrapper[]) }, null);
if (serviceAction.ReturnType.GenericTypeArguments.Any())
method2 = method2.MakeGenericMethod(serviceAction.ReturnType.GenericTypeArguments);
// Setting return type
method.SetReturnType(serviceAction.ReturnType);
// Adding parameters
method.SetParameters(serviceAction.GetParameters().Select(p => p.ParameterType).ToArray());
var i = 1;
foreach (var parameterInfo in serviceAction.GetParameters())
{
var param = method.DefineParameter(i, ParameterAttributes.None, parameterInfo.Name);
i++;
}
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder par = gen.DeclareLocal(typeof(Object[]));
LocalBuilder parameters = gen.DeclareLocal(typeof(ParameterWrapper[]));
LocalBuilder result = gen.DeclareLocal(serviceAction.ReturnType);
LocalBuilder str = gen.DeclareLocal(serviceAction.ReturnType);
// Preparing labels
Label label55 = gen.DefineLabel();
// Writing body
var ps = serviceAction.GetParameters();
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j].ParameterType;
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, method1);
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, serviceAction.Name);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Call, method2);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Br_S, label55);
gen.MarkLabel(label55);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
public ConstructorBuilder ctor(TypeBuilder type)
{
const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;
var method = type.DefineConstructor(methodAttributes, CallingConventions.Standard | CallingConventions.HasThis, new[] { typeof(IAuthenticationHandler), typeof(IHeaderHandlerFactory), typeof(TypeWrapper) });
var authenticationHandler = method.DefineParameter(1, ParameterAttributes.None, "authenticationHandler");
var headerHandlers = method.DefineParameter(2, ParameterAttributes.None, "headerHandlers");
var interfaceType = method.DefineParameter(3, ParameterAttributes.None, "interfaceType");
var ctor1 = typeof(RestWrapper).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(IAuthenticationHandler), typeof(IHeaderHandlerFactory), typeof(TypeWrapper) }, null);
var gen = method.GetILGenerator();
// Writing body
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Ldarg_2);
gen.Emit(OpCodes.Ldarg_3);
gen.Emit(OpCodes.Call, ctor1);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private TypeBuilder ReflectionTypeBuilder(ModuleBuilder module, string typeName)
{
var type = module.DefineType("TempModule." + typeName,
TypeAttributes.Public | TypeAttributes.Class,
typeof(RestWrapper),
new[] { interfaceType }
);
return type;
}
}
}
| |
using Moq;
using NUnit.Framework;
using LeanCloud;
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using LeanCloud.Core.Internal;
// TODO (hallucinogen): mock AVACL, AVObject, AVUser once we have their Interfaces
namespace ParseTest {
[TestFixture]
public class EncoderTests {
/// <summary>
/// A <see cref="ParseEncoder"/> that's used only for testing. This class is used to test
/// <see cref="ParseEncoder"/>'s base methods.
/// </summary>
private class ParseEncoderTestClass : AVEncoder {
private static readonly ParseEncoderTestClass instance = new ParseEncoderTestClass();
public static ParseEncoderTestClass Instance {
get {
return instance;
}
}
protected override IDictionary<string, object> EncodeParseObject(AVObject value) {
return null;
}
}
[Test]
public void TestIsValidType() {
var corgi = new AVObject("Corgi");
var corgiRelation = corgi.GetRelation<AVObject>("corgi");
Assert.IsTrue(AVEncoder.IsValidType(322));
Assert.IsTrue(AVEncoder.IsValidType(0.3f));
Assert.IsTrue(AVEncoder.IsValidType(new byte[]{ 1, 2, 3, 4 }));
Assert.IsTrue(AVEncoder.IsValidType("corgi"));
Assert.IsTrue(AVEncoder.IsValidType(corgi));
Assert.IsTrue(AVEncoder.IsValidType(new AVACL()));
Assert.IsTrue(AVEncoder.IsValidType(new AVFile("Corgi", new byte[0])));
Assert.IsTrue(AVEncoder.IsValidType(new AVGeoPoint(1, 2)));
Assert.IsTrue(AVEncoder.IsValidType(corgiRelation));
Assert.IsTrue(AVEncoder.IsValidType(new DateTime()));
Assert.IsTrue(AVEncoder.IsValidType(new List<object>()));
Assert.IsTrue(AVEncoder.IsValidType(new Dictionary<string, string>()));
Assert.IsTrue(AVEncoder.IsValidType(new Dictionary<string, object>()));
Assert.IsFalse(AVEncoder.IsValidType(new AVAddOperation(new List<object>())));
Assert.IsFalse(AVEncoder.IsValidType(Task<AVObject>.FromResult(new AVObject("Corgi"))));
Assert.Throws<MissingMethodException>(() => AVEncoder.IsValidType(new Dictionary<object, object>()));
Assert.Throws<MissingMethodException>(() => AVEncoder.IsValidType(new Dictionary<object, string>()));
}
[Test]
public void TestEncodeDate() {
DateTime dateTime = new DateTime(1990, 8, 30, 12, 3, 59);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dateTime) as IDictionary<string, object>;
Assert.AreEqual("Date", value["__type"]);
Assert.AreEqual("1990-08-30T12:03:59.000Z", value["iso"]);
}
[Test]
public void TestEncodeBytes() {
byte[] bytes = new byte[] { 1, 2, 3, 4 };
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(bytes) as IDictionary<string, object>;
Assert.AreEqual("Bytes", value["__type"]);
Assert.AreEqual(Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), value["base64"]);
}
[Test]
public void TestEncodeParseObjectWithNoObjectsEncoder() {
AVObject obj = new AVObject("Corgi");
Assert.Throws<ArgumentException>(() => NoObjectsEncoder.Instance.Encode(obj));
}
[Test]
public void TestEncodeParseObjectWithPointerOrLocalIdEncoder() {
// TODO (hallucinogen): we can't make an object with ID without saving for now. Let's revisit this after we make IParseObject
}
[Test]
public void TestEncodeParseFile() {
AVFile file1 = AVFileExtensions.Create("Corgi.png", new Uri("http://corgi.xyz/gogo.png"));
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(file1) as IDictionary<string, object>;
Assert.AreEqual("File", value["__type"]);
Assert.AreEqual("Corgi.png", value["name"]);
Assert.AreEqual("http://corgi.xyz/gogo.png", value["url"]);
AVFile file2 = new AVFile(null, new MemoryStream(new byte[] { 1, 2, 3, 4 }));
Assert.Throws<InvalidOperationException>(() => ParseEncoderTestClass.Instance.Encode(file2));
}
[Test]
public void TestEncodeParseGeoPoint() {
AVGeoPoint point = new AVGeoPoint(3.22, 32.2);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(point) as IDictionary<string, object>;
Assert.AreEqual("GeoPoint", value["__type"]);
Assert.AreEqual(3.22, value["latitude"]);
Assert.AreEqual(32.2, value["longitude"]);
}
[Test]
public void TestEncodeACL() {
AVACL acl1 = new AVACL();
IDictionary<string, object> value1 = ParseEncoderTestClass.Instance.Encode(acl1) as IDictionary<string, object>;
Assert.IsNotNull(value1);
Assert.AreEqual(0, value1.Keys.Count);
AVACL acl2 = new AVACL();
acl2.PublicReadAccess = true;
acl2.PublicWriteAccess = true;
IDictionary<string, object> value2 = ParseEncoderTestClass.Instance.Encode(acl2) as IDictionary<string, object>;
Assert.AreEqual(1, value2.Keys.Count);
IDictionary<string, object> publicAccess = value2["*"] as IDictionary<string, object>;
Assert.AreEqual(2, publicAccess.Keys.Count);
Assert.IsTrue((bool)publicAccess["read"]);
Assert.IsTrue((bool)publicAccess["write"]);
// TODO (hallucinogen): mock AVUser and test SetReadAccess and SetWriteAccess
}
[Test]
public void TestEncodeParseRelation() {
var obj = new AVObject("Corgi");
AVRelation<AVObject> relation = AVRelationExtensions.Create<AVObject>(obj, "nano", "Husky");
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(relation) as IDictionary<string, object>;
Assert.AreEqual("Relation", value["__type"]);
Assert.AreEqual("Husky", value["className"]);
}
[Test]
public void TestEncodeParseFieldOperation() {
var incOps = new AVIncrementOperation(1);
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(incOps) as IDictionary<string, object>;
Assert.AreEqual("Increment", value["__op"]);
Assert.AreEqual(1, value["amount"]);
// Other operations are tested in FieldOperationTests
}
[Test]
public void TestEncodeList() {
IList<object> list = new List<object>();
list.Add(new AVGeoPoint(0, 0));
list.Add("item");
list.Add(new byte[] { 1, 2, 3, 4 });
list.Add(new string[] { "hikaru", "hanatan", "ultimate" });
list.Add(new Dictionary<string, object>() {
{ "elements", new int[] { 1, 2, 3 } },
{ "mystic", "cage" },
{ "listAgain", new List<object>() { "xilia", "zestiria", "symphonia" } }
});
IList<object> value = ParseEncoderTestClass.Instance.Encode(list) as IList<object>;
var item0 = value[0] as IDictionary<string, object>;
Assert.AreEqual("GeoPoint", item0["__type"]);
Assert.AreEqual(0.0, item0["latitude"]);
Assert.AreEqual(0.0, item0["longitude"]);
Assert.AreEqual("item", value[1]);
var item2 = value[2] as IDictionary<string, object>;
Assert.AreEqual("Bytes", item2["__type"]);
var item3 = value[3] as IList<object>;
Assert.AreEqual("hikaru", item3[0]);
Assert.AreEqual("hanatan", item3[1]);
Assert.AreEqual("ultimate", item3[2]);
var item4 = value[4] as IDictionary<string, object>;
Assert.IsTrue(item4["elements"] is IList<object>);
Assert.AreEqual("cage", item4["mystic"]);
Assert.IsTrue(item4["listAgain"] is IList<object>);
}
[Test]
public void TestEncodeDictionary() {
IDictionary<string, object> dict = new Dictionary<string, object>() {
{ "item", "random" },
{ "list", new List<object>(){ "vesperia", "abyss", "legendia" } },
{ "array", new int[] { 1, 2, 3 } },
{ "geo", new AVGeoPoint(0, 0) },
{ "validDict", new Dictionary<string, object>(){ { "phantasia", "jbf" } } }
};
IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dict) as IDictionary<string, object>;
Assert.AreEqual("random", value["item"]);
Assert.IsTrue(value["list"] is IList<object>);
Assert.IsTrue(value["array"] is IList<object>);
Assert.IsTrue(value["geo"] is IDictionary<string, object>);
Assert.IsTrue(value["validDict"] is IDictionary<string, object>);
IDictionary<object, string> invalidDict = new Dictionary<object, string>();
Assert.Throws<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(invalidDict));
IDictionary<string, object> childInvalidDict = new Dictionary<string, object>() {
{ "validDict", new Dictionary<object, string>(){ { new AVACL(), "jbf" } } }
};
Assert.Throws<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(childInvalidDict));
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Responses/CheckCodenameAvailableResponse.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Responses {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/CheckCodenameAvailableResponse.proto</summary>
public static partial class CheckCodenameAvailableResponseReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Responses/CheckCodenameAvailableResponse.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CheckCodenameAvailableResponseReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkRQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL0NoZWNrQ29kZW5h",
"bWVBdmFpbGFibGVSZXNwb25zZS5wcm90bxIfUE9HT1Byb3Rvcy5OZXR3b3Jr",
"aW5nLlJlc3BvbnNlcyLCAgoeQ2hlY2tDb2RlbmFtZUF2YWlsYWJsZVJlc3Bv",
"bnNlEhAKCGNvZGVuYW1lGAEgASgJEhQKDHVzZXJfbWVzc2FnZRgCIAEoCRIV",
"Cg1pc19hc3NpZ25hYmxlGAMgASgIElYKBnN0YXR1cxgEIAEoDjJGLlBPR09Q",
"cm90b3MuTmV0d29ya2luZy5SZXNwb25zZXMuQ2hlY2tDb2RlbmFtZUF2YWls",
"YWJsZVJlc3BvbnNlLlN0YXR1cyKIAQoGU3RhdHVzEgkKBVVOU0VUEAASCwoH",
"U1VDQ0VTUxABEhoKFkNPREVOQU1FX05PVF9BVkFJTEFCTEUQAhIWChJDT0RF",
"TkFNRV9OT1RfVkFMSUQQAxIRCg1DVVJSRU5UX09XTkVSEAQSHwobQ09ERU5B",
"TUVfQ0hBTkdFX05PVF9BTExPV0VEEAViBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse), global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse.Parser, new[]{ "Codename", "UserMessage", "IsAssignable", "Status" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse.Types.Status) }, null)
}));
}
#endregion
}
#region Messages
public sealed partial class CheckCodenameAvailableResponse : pb::IMessage<CheckCodenameAvailableResponse> {
private static readonly pb::MessageParser<CheckCodenameAvailableResponse> _parser = new pb::MessageParser<CheckCodenameAvailableResponse>(() => new CheckCodenameAvailableResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CheckCodenameAvailableResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponseReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckCodenameAvailableResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckCodenameAvailableResponse(CheckCodenameAvailableResponse other) : this() {
codename_ = other.codename_;
userMessage_ = other.userMessage_;
isAssignable_ = other.isAssignable_;
status_ = other.status_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CheckCodenameAvailableResponse Clone() {
return new CheckCodenameAvailableResponse(this);
}
/// <summary>Field number for the "codename" field.</summary>
public const int CodenameFieldNumber = 1;
private string codename_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Codename {
get { return codename_; }
set {
codename_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "user_message" field.</summary>
public const int UserMessageFieldNumber = 2;
private string userMessage_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string UserMessage {
get { return userMessage_; }
set {
userMessage_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "is_assignable" field.</summary>
public const int IsAssignableFieldNumber = 3;
private bool isAssignable_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsAssignable {
get { return isAssignable_; }
set {
isAssignable_ = value;
}
}
/// <summary>Field number for the "status" field.</summary>
public const int StatusFieldNumber = 4;
private global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse.Types.Status status_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse.Types.Status Status {
get { return status_; }
set {
status_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CheckCodenameAvailableResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CheckCodenameAvailableResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Codename != other.Codename) return false;
if (UserMessage != other.UserMessage) return false;
if (IsAssignable != other.IsAssignable) return false;
if (Status != other.Status) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Codename.Length != 0) hash ^= Codename.GetHashCode();
if (UserMessage.Length != 0) hash ^= UserMessage.GetHashCode();
if (IsAssignable != false) hash ^= IsAssignable.GetHashCode();
if (Status != 0) hash ^= Status.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Codename.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Codename);
}
if (UserMessage.Length != 0) {
output.WriteRawTag(18);
output.WriteString(UserMessage);
}
if (IsAssignable != false) {
output.WriteRawTag(24);
output.WriteBool(IsAssignable);
}
if (Status != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) Status);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Codename.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Codename);
}
if (UserMessage.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(UserMessage);
}
if (IsAssignable != false) {
size += 1 + 1;
}
if (Status != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CheckCodenameAvailableResponse other) {
if (other == null) {
return;
}
if (other.Codename.Length != 0) {
Codename = other.Codename;
}
if (other.UserMessage.Length != 0) {
UserMessage = other.UserMessage;
}
if (other.IsAssignable != false) {
IsAssignable = other.IsAssignable;
}
if (other.Status != 0) {
Status = other.Status;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Codename = input.ReadString();
break;
}
case 18: {
UserMessage = input.ReadString();
break;
}
case 24: {
IsAssignable = input.ReadBool();
break;
}
case 32: {
status_ = (global::POGOProtos.Networking.Responses.CheckCodenameAvailableResponse.Types.Status) input.ReadEnum();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the CheckCodenameAvailableResponse message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
public enum Status {
[pbr::OriginalName("UNSET")] Unset = 0,
[pbr::OriginalName("SUCCESS")] Success = 1,
[pbr::OriginalName("CODENAME_NOT_AVAILABLE")] CodenameNotAvailable = 2,
[pbr::OriginalName("CODENAME_NOT_VALID")] CodenameNotValid = 3,
[pbr::OriginalName("CURRENT_OWNER")] CurrentOwner = 4,
[pbr::OriginalName("CODENAME_CHANGE_NOT_ALLOWED")] CodenameChangeNotAllowed = 5,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.Utils;
namespace FluentNHibernate.Mapping
{
/// <summary>
/// Defines a mapping for an entity subclass. Derive from this class to create a mapping,
/// and use the constructor to control how your entity is persisted.
/// </summary>
/// <example>
/// public class EmployeeMap : SubclassMap<Employee>
/// {
/// public EmployeeMap()
/// {
/// Map(x => x.Name);
/// Map(x => x.Age);
/// }
/// }
/// </example>
/// <typeparam name="T">Entity type to map</typeparam>
public class SubclassMap<T> : ClasslikeMapBase<T>, IIndeterminateSubclassMappingProvider
{
readonly MappingProviderStore providers;
readonly AttributeStore attributes = new AttributeStore();
// this is a bit weird, but we need a way of delaying the generation of the subclass mappings until we know
// what the parent subclass type is...
readonly IDictionary<Type, IIndeterminateSubclassMappingProvider> indetermineateSubclasses = new Dictionary<Type, IIndeterminateSubclassMappingProvider>();
bool nextBool = true;
readonly IList<JoinMapping> joins = new List<JoinMapping>();
public SubclassMap()
: this(new MappingProviderStore())
{}
protected SubclassMap(MappingProviderStore providers)
: base(providers)
{
this.providers = providers;
}
/// <summary>
/// Inverts the next boolean setting
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public SubclassMap<T> Not
{
get
{
nextBool = !nextBool;
return this;
}
}
/// <summary>
/// (optional) Specifies that this subclass is abstract
/// </summary>
public void Abstract()
{
attributes.Set("Abstract", Layer.UserSupplied, nextBool);
nextBool = true;
}
/// <summary>
/// Sets the dynamic insert behaviour
/// </summary>
public void DynamicInsert()
{
attributes.Set("DynamicInsert", Layer.UserSupplied, nextBool);
nextBool = true;
}
/// <summary>
/// Sets the dynamic update behaviour
/// </summary>
public void DynamicUpdate()
{
attributes.Set("DynamicUpdate", Layer.UserSupplied, nextBool);
nextBool = true;
}
/// <summary>
/// Specifies that this entity should be lazy loaded
/// </summary>
public void LazyLoad()
{
attributes.Set("Lazy", Layer.UserSupplied, nextBool);
nextBool = true;
}
/// <summary>
/// Specify a proxy type for this entity
/// </summary>
/// <typeparam name="TProxy">Proxy type</typeparam>
public void Proxy<TProxy>()
{
Proxy(typeof(TProxy));
}
/// <summary>
/// Specify a proxy type for this entity
/// </summary>
/// <param name="proxyType">Proxy type</param>
public void Proxy(Type proxyType)
{
attributes.Set("Proxy", Layer.UserSupplied, proxyType.AssemblyQualifiedName);
}
/// <summary>
/// Specify that a select should be performed before an update of this entity
/// </summary>
public void SelectBeforeUpdate()
{
attributes.Set("SelectBeforeUpdate", Layer.UserSupplied, nextBool);
nextBool = true;
}
[Obsolete("Use a new SubclassMap")]
public void Subclass<TSubclass>(Action<SubclassMap<TSubclass>> subclassDefinition)
{
var subclass = new SubclassMap<TSubclass>();
subclassDefinition(subclass);
indetermineateSubclasses[typeof(TSubclass)] = subclass;
}
/// <summary>
/// Set the discriminator value, if this entity is in a table-per-class-hierarchy
/// mapping strategy.
/// </summary>
/// <param name="discriminatorValue">Discriminator value</param>
public void DiscriminatorValue(object discriminatorValue)
{
attributes.Set("DiscriminatorValue", Layer.UserSupplied, discriminatorValue);
}
/// <summary>
/// Sets the table name
/// </summary>
/// <param name="table">Table name</param>
public void Table(string table)
{
attributes.Set("TableName", Layer.UserSupplied, table);
}
/// <summary>
/// Sets the schema
/// </summary>
/// <param name="schema">Schema</param>
public void Schema(string schema)
{
attributes.Set("Schema", Layer.UserSupplied, schema);
}
/// <summary>
/// Specifies a check constraint
/// </summary>
/// <param name="constraint">Constraint name</param>
public void Check(string constraint)
{
attributes.Set("Check", Layer.UserSupplied, constraint);
}
/// <summary>
/// Adds a column to the key for this subclass, if used
/// in a table-per-subclass strategy.
/// </summary>
/// <param name="column">Column name</param>
public void KeyColumn(string column)
{
KeyMapping key;
if (attributes.IsSpecified("Key"))
key = attributes.GetOrDefault<KeyMapping>("Key");
else
key = new KeyMapping();
key.AddColumn(Layer.UserSupplied, new ColumnMapping(column));
attributes.Set("Key", Layer.UserSupplied, key);
}
/// <summary>
/// Subselect query
/// </summary>
/// <param name="subselect">Subselect query</param>
public void Subselect(string subselect)
{
attributes.Set("Subselect", Layer.UserSupplied, subselect);
}
/// <summary>
/// Specifies a persister for this entity
/// </summary>
/// <typeparam name="TPersister">Persister type</typeparam>
public void Persister<TPersister>()
{
attributes.Set("Persister", Layer.UserSupplied, new TypeReference(typeof(TPersister)));
}
/// <summary>
/// Specifies a persister for this entity
/// </summary>
/// <param name="type">Persister type</param>
public void Persister(Type type)
{
attributes.Set("Persister", Layer.UserSupplied, new TypeReference(type));
}
/// <summary>
/// Specifies a persister for this entity
/// </summary>
/// <param name="type">Persister type</param>
public void Persister(string type)
{
attributes.Set("Persister", Layer.UserSupplied, new TypeReference(type));
}
/// <summary>
/// Set the query batch size
/// </summary>
/// <param name="batchSize">Batch size</param>
public void BatchSize(int batchSize)
{
attributes.Set("BatchSize", Layer.UserSupplied, batchSize);
}
/// <summary>
/// Specifies an entity-name.
/// </summary>
/// <remarks>See http://nhforge.org/blogs/nhibernate/archive/2008/10/21/entity-name-in-action-a-strongly-typed-entity.aspx</remarks>
public void EntityName(string entityname)
{
attributes.Set("EntityName", Layer.UserSupplied, entityname);
}
/// <summary>
/// Links this entity to another table, to create a composite entity from two or
/// more tables. This only works if you're in a table-per-inheritance-hierarchy
/// strategy.
/// </summary>
/// <param name="tableName">Joined table name</param>
/// <param name="action">Joined table mapping</param>
/// <example>
/// Join("another_table", join =>
/// {
/// join.Map(x => x.Name);
/// join.Map(x => x.Age);
/// });
/// </example>
public void Join(string tableName, Action<JoinPart<T>> action)
{
var join = new JoinPart<T>(tableName);
action(join);
joins.Add(((IJoinMappingProvider)join).GetJoinMapping());
}
/// <summary>
/// (optional) Specifies the entity from which this subclass descends/extends.
/// </summary>
/// <typeparam name="TOther">Type of the entity to extend</typeparam>
public void Extends<TOther>()
{
Extends(typeof(TOther));
}
/// <summary>
/// (optional) Specifies the entity from which this subclass descends/extends.
/// </summary>
/// <param name="type">Type of the entity to extend</param>
public void Extends(Type type)
{
attributes.Set("Extends", Layer.UserSupplied, type);
}
SubclassMapping IIndeterminateSubclassMappingProvider.GetSubclassMapping(SubclassType type)
{
var mapping = new SubclassMapping(type);
GenerateNestedSubclasses(mapping);
attributes.Set("Type", Layer.Defaults, typeof(T));
attributes.Set("Name", Layer.Defaults, typeof(T).AssemblyQualifiedName);
attributes.Set("DiscriminatorValue", Layer.Defaults, typeof(T).Name);
// TODO: un-hardcode this
var key = new KeyMapping();
key.AddColumn(Layer.Defaults, new ColumnMapping(typeof(T).BaseType.Name + "_id"));
attributes.Set("TableName", Layer.Defaults, GetDefaultTableName());
attributes.Set("Key", Layer.Defaults, key);
// TODO: this is nasty, we should find a better way
mapping.OverrideAttributes(attributes.Clone());
foreach (var join in joins)
mapping.AddJoin(join);
foreach (var property in providers.Properties)
mapping.AddProperty(property.GetPropertyMapping());
foreach (var component in providers.Components)
mapping.AddComponent(component.GetComponentMapping());
foreach (var oneToOne in providers.OneToOnes)
mapping.AddOneToOne(oneToOne.GetOneToOneMapping());
foreach (var collection in providers.Collections)
mapping.AddCollection(collection.GetCollectionMapping());
foreach (var reference in providers.References)
mapping.AddReference(reference.GetManyToOneMapping());
foreach (var any in providers.Anys)
mapping.AddAny(any.GetAnyMapping());
return mapping.DeepClone();
}
Type IIndeterminateSubclassMappingProvider.Extends
{
get { return attributes.GetOrDefault<Type>("Extends"); }
}
void GenerateNestedSubclasses(SubclassMapping mapping)
{
foreach (var subclassType in indetermineateSubclasses.Keys)
{
var subclassMapping = indetermineateSubclasses[subclassType].GetSubclassMapping(mapping.SubclassType);
mapping.AddSubclass(subclassMapping);
}
}
string GetDefaultTableName()
{
#pragma warning disable 612,618
var tableName = EntityType.Name;
if (EntityType.IsGenericType)
{
// special case for generics: GenericType_GenericParameterType
tableName = EntityType.Name.Substring(0, EntityType.Name.IndexOf('`'));
foreach (var argument in EntityType.GetGenericArguments())
{
tableName += "_";
tableName += argument.Name;
}
}
#pragma warning restore 612,618
return "`" + tableName + "`";
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System;
using System.Globalization;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public partial struct Guid : IFormattable, IComparable
#if GENERICS_WORK
, IComparable<Guid>, IEquatable<Guid>
#endif
{
public static readonly Guid Empty = new Guid();
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
private int _a;
private short _b;
private short _c;
private byte _d;
private byte _e;
private byte _f;
private byte _g;
private byte _h;
private byte _i;
private byte _j;
private byte _k;
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
//
public Guid(byte[] b)
{
if (b==null)
throw new ArgumentNullException("b");
if (b.Length != 16)
throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"));
Contract.EndContractBlock();
_a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
_b = (short)(((int)b[5] << 8) | b[4]);
_c = (short)(((int)b[7] << 8) | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
_g = b[11];
_h = b[12];
_i = b[13];
_j = b[14];
_k = b[15];
}
[CLSCompliant(false)]
public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
_c = (short)c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
{
if (d==null)
throw new ArgumentNullException("d");
// Check that array is not too big
if(d.Length != 8)
throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"));
Contract.EndContractBlock();
_a = a;
_b = b;
_c = c;
_d = d[0];
_e = d[1];
_f = d[2];
_g = d[3];
_h = d[4];
_i = d[5];
_j = d[6];
_k = d[7];
}
// Creates a new GUID initialized to the value represented by the
// arguments. The bytes are specified like this to avoid endianness issues.
//
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = a;
_b = b;
_c = c;
_d = d;
_e = e;
_f = f;
_g = g;
_h = h;
_i = i;
_j = j;
_k = k;
}
[Flags]
private enum GuidStyles {
None = 0x00000000,
AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
RequireDashes = 0x00000040, //Require the guid to contain dash group separators
RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
HexFormat = RequireBraces | RequireHexPrefix, /* X */
NumberFormat = None, /* N */
DigitFormat = RequireDashes, /* D */
BraceFormat = RequireBraces | RequireDashes, /* B */
ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
private enum GuidParseThrowStyle {
None = 0,
All = 1,
AllButOverflow = 2
}
private enum ParseFailureKind {
None = 0,
ArgumentNull = 1,
Format = 2,
FormatWithParameter = 3,
NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult {
internal Guid parsedGuid;
internal GuidParseThrowStyle throwStyle;
internal ParseFailureKind m_failure;
internal string m_failureMessageID;
internal object m_failureMessageFormatArgument;
internal string m_failureArgumentName;
internal Exception m_innerException;
internal void Init(GuidParseThrowStyle canThrow) {
parsedGuid = Guid.Empty;
throwStyle = canThrow;
}
internal void SetFailure(Exception nativeException) {
m_failure = ParseFailureKind.NativeException;
m_innerException = nativeException;
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID) {
SetFailure(failure, failureMessageID, null, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException) {
Contract.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
m_failureArgumentName = failureArgumentName;
m_innerException = innerException;
if (throwStyle != GuidParseThrowStyle.None) {
throw GetGuidParseException();
}
}
internal Exception GetGuidParseException() {
switch (m_failure) {
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID));
case ParseFailureKind.FormatWithInnerException:
return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException);
case ParseFailureKind.FormatWithParameter:
return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
case ParseFailureKind.Format:
return new FormatException(Environment.GetResourceString(m_failureMessageID));
case ParseFailureKind.NativeException:
return m_innerException;
default:
Contract.Assert(false, "Unknown GuidParseFailure: " + m_failure);
return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
}
}
}
// Creates a new guid based on the value in the string. The value is made up
// of hex digits speared by the dash ("-"). The string may begin and end with
// brackets ("{", "}").
//
// The string must be of the form dddddddd-dddd-dddd-dddd-dddddddddddd. where
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
public Guid(String g)
{
if (g==null) {
throw new ArgumentNullException("g");
}
Contract.EndContractBlock();
this = Guid.Empty;
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result)) {
this = result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static Guid Parse(String input)
{
if (input == null) {
throw new ArgumentNullException("input");
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result)) {
return result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static bool TryParse(String input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) {
result = parseResult.parsedGuid;
return true;
}
else {
result = Guid.Empty;
return false;
}
}
public static Guid ParseExact(String input, String format)
{
if (input == null)
throw new ArgumentNullException("input");
if (format == null)
throw new ArgumentNullException("format");
if( format.Length != 1) {
// all acceptable format strings are of length 1
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n') {
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b') {
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p') {
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x') {
style = GuidStyles.HexFormat;
}
else {
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result)) {
return result.parsedGuid;
}
else {
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(String input, String format, out Guid result)
{
if (format == null || format.Length != 1) {
result = Guid.Empty;
return false;
}
GuidStyles style;
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
style = GuidStyles.DigitFormat;
}
else if (formatCh == 'N' || formatCh == 'n') {
style = GuidStyles.NumberFormat;
}
else if (formatCh == 'B' || formatCh == 'b') {
style = GuidStyles.BraceFormat;
}
else if (formatCh == 'P' || formatCh == 'p') {
style = GuidStyles.ParenthesisFormat;
}
else if (formatCh == 'X' || formatCh == 'x') {
style = GuidStyles.HexFormat;
}
else {
// invalid guid format specification
result = Guid.Empty;
return false;
}
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult)) {
result = parseResult.parsedGuid;
return true;
}
else {
result = Guid.Empty;
return false;
}
}
private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
{
if (g == null) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
String guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
if (dashesExistInString) {
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) {
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireDashes) != 0) {
// dashes are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
if (bracesExistInString) {
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) {
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireBraces) != 0) {
// braces are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
if (parenthesisExistInString) {
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) {
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
else {
if ((flags & GuidStyles.RequireParenthesis) != 0) {
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
try {
// let's get on with the parsing
if (dashesExistInString) {
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
else if (bracesExistInString) {
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
else {
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
catch(IndexOutOfRangeException ex) {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
catch (ArgumentException ex) {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
}
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result) {
int numStart = 0;
int numLen = 0;
// Eat all of the whitespace
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
if(String.IsNullOrEmpty(guidString) || guidString[0] != '{') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Check for '0x'
if(!IsHexPrefix(guidString, 1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}");
return false;
}
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
// Read in the number
if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
// Check for '{'
if(guidString.Length <= numStart+numLen+1 || guidString[numStart+numLen+1] != '{') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
// Prepare for loop
numLen++;
byte[] bytes = new byte[8];
for(int i = 0; i < 8; i++)
{
// Check for '0x'
if(!IsHexPrefix(guidString, numStart+numLen+1)) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}");
return false;
}
// +3 to get by ',0x' or '{0x' for first case
numStart = numStart + numLen + 3;
// Calculate number length
if(i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
if(numLen <= 0) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber");
return false;
}
}
// Read in the number
uint number = (uint)Convert.ToInt32(guidString.Substring(numStart, numLen),16);
// check for overflow
if(number > 255) {
result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
return false;
}
bytes[i] = (byte)number;
}
result.parsedGuid._d = bytes[0];
result.parsedGuid._e = bytes[1];
result.parsedGuid._f = bytes[2];
result.parsedGuid._g = bytes[3];
result.parsedGuid._h = bytes[4];
result.parsedGuid._i = bytes[5];
result.parsedGuid._j = bytes[6];
result.parsedGuid._k = bytes[7];
// Check for last '}'
if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace");
return false;
}
// Check if we have extra characters at the end
if( numStart+numLen+1 != guidString.Length -1) {
result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd");
return false;
}
return true;
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) {
int startPos=0;
int temp;
long templ;
int currentPos = 0;
if(guidString.Length != 32) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
for(int i= 0; i< guidString.Length; i++) {
char ch = guidString[i];
if(ch >= '0' && ch <= '9') {
continue;
}
else {
char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture);
if(upperCaseCh >= 'A' && upperCaseCh <= 'F') {
continue;
}
}
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
return false;
startPos += 8;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
return false;
startPos += 4;
if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
return false;
startPos += 4;
if (!StringToInt(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out temp, ref result))
return false;
startPos += 4;
currentPos = startPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos!=12) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp>>8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp>>8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp>>24);
result.parsedGuid._i = (byte)(temp>>16);
result.parsedGuid._j = (byte)(temp>>8);
result.parsedGuid._k = (byte)(temp);
return true;
}
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) {
int startPos=0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
if (guidString[0]=='{') {
if (guidString.Length!=38 || guidString[37]!='}') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos=1;
}
else if (guidString[0]=='(') {
if (guidString.Length!=38 || guidString[37]!=')') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
startPos=1;
}
else if(guidString.Length != 36) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
if (guidString[8+startPos] != '-' ||
guidString[13+startPos] != '-' ||
guidString[18+startPos] != '-' ||
guidString[23+startPos] != '-') {
result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes");
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
result.parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
startPos=currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
if (currentPos - startPos != 12) {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
result.parsedGuid._d = (byte)(temp>>8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
result.parsedGuid._f = (byte)(temp>>8);
result.parsedGuid._g = (byte)(temp);
temp = (int)(templ);
result.parsedGuid._h = (byte)(temp>>24);
result.parsedGuid._i = (byte)(temp>>16);
result.parsedGuid._j = (byte)(temp>>8);
result.parsedGuid._k = (byte)(temp);
return true;
}
//
// StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
//<
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToShort(String str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToShort(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
[System.Security.SecurityCritical]
private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult) {
result = 0;
int x;
bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
}
}
[System.Security.SecurityCritical]
private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
result = 0;
int currStart = (parsePos == null) ? 0 : (*parsePos);
try {
result = ParseNumbers.StringToInt(str, 16, flags, parsePos);
}
catch (OverflowException ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.All) {
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
}
else {
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.None) {
parseResult.SetFailure(ex);
return false;
}
else {
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) {
parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
return false;
}
return true;
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int flags, out long result, ref GuidResult parseResult) {
return StringToLong(str, null, flags, out result, ref parseResult);
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult) {
fixed(int * ppos = &parsePos) {
return StringToLong(str, ppos, flags, out result, ref parseResult);
}
}
[System.Security.SecuritySafeCritical]
private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult) {
result = 0;
try {
result = ParseNumbers.StringToLong(str, 16, flags, parsePos);
}
catch (OverflowException ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.All) {
throw;
}
else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
}
else {
parseResult.SetFailure(ex);
return false;
}
}
catch (Exception ex) {
if (parseResult.throwStyle == GuidParseThrowStyle.None) {
parseResult.SetFailure(ex);
return false;
}
else {
throw;
}
}
return true;
}
private static String EatAllWhitespace(String str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
for(int i = 0; i < str.Length; i++)
{
curChar = str[i];
if(!Char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
return new String(chArr, 0, newLength);
}
private static bool IsHexPrefix(String str, int i)
{
if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x'))
return true;
else
return false;
}
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
byte[] g = new byte[16];
g[0] = (byte)(_a);
g[1] = (byte)(_a >> 8);
g[2] = (byte)(_a >> 16);
g[3] = (byte)(_a >> 24);
g[4] = (byte)(_b);
g[5] = (byte)(_b >> 8);
g[6] = (byte)(_c);
g[7] = (byte)(_c >> 8);
g[8] = _d;
g[9] = _e;
g[10] = _f;
g[11] = _g;
g[12] = _h;
g[13] = _i;
g[14] = _j;
g[15] = _k;
return g;
}
// Returns the guid in "registry" format.
public override String ToString()
{
return ToString("D",null);
}
public override int GetHashCode()
{
return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k);
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
public override bool Equals(Object o)
{
Guid g;
// Check that o is a Guid first
if(o == null || !(o is Guid))
return false;
else g = (Guid) o;
// Now compare each of the elements
if(g._a != _a)
return false;
if(g._b != _b)
return false;
if(g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
public bool Equals(Guid g)
{
// Now compare each of the elements
if(g._a != _a)
return false;
if(g._b != _b)
return false;
if(g._c != _c)
return false;
if (g._d != _d)
return false;
if (g._e != _e)
return false;
if (g._f != _f)
return false;
if (g._g != _g)
return false;
if (g._h != _h)
return false;
if (g._i != _i)
return false;
if (g._j != _j)
return false;
if (g._k != _k)
return false;
return true;
}
private int GetResult(uint me, uint them) {
if (me<them) {
return -1;
}
return 1;
}
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (!(value is Guid)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"));
}
Guid g = (Guid)value;
if (g._a!=this._a) {
return GetResult((uint)this._a, (uint)g._a);
}
if (g._b!=this._b) {
return GetResult((uint)this._b, (uint)g._b);
}
if (g._c!=this._c) {
return GetResult((uint)this._c, (uint)g._c);
}
if (g._d!=this._d) {
return GetResult((uint)this._d, (uint)g._d);
}
if (g._e!=this._e) {
return GetResult((uint)this._e, (uint)g._e);
}
if (g._f!=this._f) {
return GetResult((uint)this._f, (uint)g._f);
}
if (g._g!=this._g) {
return GetResult((uint)this._g, (uint)g._g);
}
if (g._h!=this._h) {
return GetResult((uint)this._h, (uint)g._h);
}
if (g._i!=this._i) {
return GetResult((uint)this._i, (uint)g._i);
}
if (g._j!=this._j) {
return GetResult((uint)this._j, (uint)g._j);
}
if (g._k!=this._k) {
return GetResult((uint)this._k, (uint)g._k);
}
return 0;
}
#if GENERICS_WORK
public int CompareTo(Guid value)
{
if (value._a!=this._a) {
return GetResult((uint)this._a, (uint)value._a);
}
if (value._b!=this._b) {
return GetResult((uint)this._b, (uint)value._b);
}
if (value._c!=this._c) {
return GetResult((uint)this._c, (uint)value._c);
}
if (value._d!=this._d) {
return GetResult((uint)this._d, (uint)value._d);
}
if (value._e!=this._e) {
return GetResult((uint)this._e, (uint)value._e);
}
if (value._f!=this._f) {
return GetResult((uint)this._f, (uint)value._f);
}
if (value._g!=this._g) {
return GetResult((uint)this._g, (uint)value._g);
}
if (value._h!=this._h) {
return GetResult((uint)this._h, (uint)value._h);
}
if (value._i!=this._i) {
return GetResult((uint)this._i, (uint)value._i);
}
if (value._j!=this._j) {
return GetResult((uint)this._j, (uint)value._j);
}
if (value._k!=this._k) {
return GetResult((uint)this._k, (uint)value._k);
}
return 0;
}
#endif // GENERICS_WORK
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
if(a._a != b._a)
return false;
if(a._b != b._b)
return false;
if(a._c != b._c)
return false;
if(a._d != b._d)
return false;
if(a._e != b._e)
return false;
if(a._f != b._f)
return false;
if(a._g != b._g)
return false;
if(a._h != b._h)
return false;
if(a._i != b._i)
return false;
if(a._j != b._j)
return false;
if(a._k != b._k)
return false;
return true;
}
public static bool operator !=(Guid a, Guid b)
{
return !(a == b);
}
#if !MONO
// This will create a new guid. Since we've now decided that constructors should 0-init,
// we need a method that allows users to create a guid.
[System.Security.SecuritySafeCritical] // auto-generated
public static Guid NewGuid() {
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
// uniqueness guarantees. It should also never return a known GUID, but it's unclear
// how extensively it checks for known values.
Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
Guid guid;
Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
return guid;
}
#endif
public String ToString(String format) {
return ToString(format, null);
}
private static char HexToChar(int a)
{
a = a & 0xf;
return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
[System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
{
return HexsToChars(guidChars, offset, a, b, false);
}
[System.Security.SecurityCritical]
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
{
if (hex) {
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(a>>4);
guidChars[offset++] = HexToChar(a);
if (hex) {
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
guidChars[offset++] = HexToChar(b>>4);
guidChars[offset++] = HexToChar(b);
return offset;
}
// IFormattable interface
// We currently ignore provider
[System.Security.SecuritySafeCritical]
public String ToString(String format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
string guidString;
int offset = 0;
bool dash = true;
bool hex = false;
if( format.Length != 1) {
// all acceptable format strings are of length 1
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
char formatCh = format[0];
if (formatCh == 'D' || formatCh == 'd') {
guidString = string.FastAllocateString(36);
}
else if (formatCh == 'N' || formatCh == 'n') {
guidString = string.FastAllocateString(32);
dash = false;
}
else if (formatCh == 'B' || formatCh == 'b') {
guidString = string.FastAllocateString(38);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '{';
guidChars[37] = '}';
}
}
}
else if (formatCh == 'P' || formatCh == 'p') {
guidString = string.FastAllocateString(38);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '(';
guidChars[37] = ')';
}
}
}
else if (formatCh == 'X' || formatCh == 'x') {
guidString = string.FastAllocateString(68);
unsafe {
fixed (char* guidChars = guidString) {
guidChars[offset++] = '{';
guidChars[67] = '}';
}
}
dash = false;
hex = true;
}
else {
throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
}
unsafe {
fixed (char* guidChars = guidString) {
if (hex) {
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
guidChars[offset++] = ',';
guidChars[offset++] = '{';
offset = HexsToChars(guidChars, offset, _d, _e, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _f, _g, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _h, _i, true);
guidChars[offset++] = ',';
offset = HexsToChars(guidChars, offset, _j, _k, true);
guidChars[offset++] = '}';
}
else {
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _b >> 8, _b);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _c >> 8, _c);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _d, _e);
if (dash) guidChars[offset++] = '-';
offset = HexsToChars(guidChars, offset, _f, _g);
offset = HexsToChars(guidChars, offset, _h, _i);
offset = HexsToChars(guidChars, offset, _j, _k);
}
}
}
return guidString;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: TextReader
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Abstract base class for all Text-only Readers.
** Subclasses will include StreamReader & StringReader.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
#if FEATURE_ASYNC_IO
using System.Threading;
using System.Threading.Tasks;
#endif
namespace System.IO {
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class TextReader : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class TextReader : IDisposable {
#endif // FEATURE_REMOTING
#if FEATURE_ASYNC_IO
[NonSerialized]
private static Func<object, string> _ReadLineDelegate = state => ((TextReader)state).ReadLine();
[NonSerialized]
private static Func<object, int> _ReadDelegate = state =>
{
Tuple<TextReader, char[], int, int> tuple = (Tuple<TextReader, char[], int, int>)state;
return tuple.Item1.Read(tuple.Item2, tuple.Item3, tuple.Item4);
};
#endif //FEATURE_ASYNC_IO
public static readonly TextReader Null = new NullTextReader();
protected TextReader() {}
// Closes this TextReader and releases any system resources associated with the
// TextReader. Following a call to Close, any operations on the TextReader
// may raise exceptions.
//
// This default method is empty, but descendant classes can override the
// method to provide the appropriate functionality.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
Contract.Ensures(Contract.Result<int>() >= -1);
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", 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 (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
int n = 0;
do {
int ch = Read();
if (ch == -1) break;
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual String ReadToEnd()
{
Contract.Ensures(Contract.Result<String>() != null);
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len=Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock([In, Out] char[] buffer, int index, int count)
{
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
int i, n = 0;
do {
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual String ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true) {
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n') Read();
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0) return sb.ToString();
return null;
}
#if FEATURE_ASYNC_IO
#region Task based Async APIs
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<String> ReadLineAsync()
{
return Task<String>.Factory.StartNew(_ReadLineDelegate, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public async virtual Task<String> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
Tuple<TextReader, char[], int, int> tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(_ReadDelegate, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return ReadBlockAsyncInternal(buffer, index, count);
}
[HostProtection(ExternalThreading=true)]
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Contract.Requires(buffer != null);
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
#endif //FEATURE_ASYNC_IO
[HostProtection(Synchronization=true)]
public static TextReader Synchronized(TextReader reader)
{
if (reader==null)
throw new ArgumentNullException("reader");
Contract.Ensures(Contract.Result<TextReader>() != null);
Contract.EndContractBlock();
if (reader is SyncTextReader)
return reader;
return new SyncTextReader(reader);
}
[Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader(){}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override String ReadLine()
{
return null;
}
}
[Serializable]
internal sealed class SyncTextReader : TextReader
{
internal TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override void Close()
{
// So that any overriden Close() gets run
_in.Close();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Peek()
{
return _in.Peek();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read()
{
return _in.Read();
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int Read([In, Out] char[] buffer, int index, int count)
{
return _in.Read(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
return _in.ReadBlock(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadLine()
{
return _in.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override String ReadToEnd()
{
return _in.ReadToEnd();
}
#if FEATURE_ASYNC_IO
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<String> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(ReadBlock(buffer, index, count));
}
[ComVisible(false)]
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
}
#endif //FEATURE_ASYNC_IO
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Text;
using System.Xaml;
namespace MS.Internal.Xaml.Parser
{
[DebuggerDisplay("{Text}")]
internal class XamlText
{
private const Char SPACE = ' ';
private const Char NEWLINE = '\n';
private const Char RETURN = '\r';
private const Char TAB = '\t';
private const Char OPENCURLIE = '{';
private const Char CLOSECURLIE = '}';
private const String ME_ESCAPE = "{}";
private const string RETURN_STRING = "\r";
private StringBuilder _sb;
private readonly bool _isSpacePreserve; // should space be preserved or collapsed?
private bool _isWhiteSpaceOnly; // is the whole thing whitespace.
public XamlText(bool spacePreserve)
{
// The majority of TEXT found in a XamlParse results in a single string call to Paste().
// A possible perf improvement might be to hold the first string and
// put off allocating the StringBuilder until a second string is Paste()ed.
_sb = new StringBuilder();
_isSpacePreserve = spacePreserve;
_isWhiteSpaceOnly = true;
}
public bool IsEmpty
{
get { return _sb.Length==0; }
}
public string Text
{
get
{
return _sb.ToString();
}
}
public string AttributeText
{
get
{
String text = Text;
if (text.StartsWith(ME_ESCAPE, false, TypeConverterHelper.InvariantEnglishUS))
{
return text.Remove(0, ME_ESCAPE.Length);
}
return text;
}
}
public bool IsSpacePreserved
{
get { return _isSpacePreserve; }
}
public bool IsWhiteSpaceOnly
{
get { return _isWhiteSpaceOnly; }
}
public void Paste(string text, bool trimLeadingWhitespace, bool convertCRLFtoLF=true)
{
bool newTextIsWhitespace = IsWhitespace(text);
if (_isSpacePreserve)
{
if (convertCRLFtoLF)
{
// (GetFixedDocumentSequence raises Exception "UnicodeString property does not contain
// enough characters to correspond to the contents of Indices property.")
//
// Convert CRLF into just LF. Including attribute text values.
// Attribute text is internal set to "preserve" to prevent (other) processing.
// We processing attribute values in this way because 3.x did it.
// Normally new lines are converted to SPACE by the XML reader.
//
// Note that the code actually just removes CR. Thus it affects
// attribute values that contain CR without LF, which can
// arise by explicit user declaration: <Element Prop="a b" />
// This is the root cause of the GetFixedDocumentSequence bug. I'm leaving it as-is, in
// case there are compat issues, but if the intent was to convert
// CRLF to LF, it should really say Replace("\r\n", "\n")
//
// To fix the GetFixedDocumentSequence bug, we don't do any substitutions if the
// property is Glyphs.UnicodeString, which should never be changed
// without changing the corresponding Glyphs.Indices property.
// See XamlScanner.EnqueueAnotherAttribute for the fixed call.
text = text.Replace(RETURN_STRING, "");
}
_sb.Append(text);
}
else if (newTextIsWhitespace)
{
if (IsEmpty && !trimLeadingWhitespace)
{
_sb.Append(SPACE);
}
}
else
{
bool textHadLeadingWhitespace = IsWhitespaceChar(text[0]);
bool textHadTrailingWhitespace = IsWhitespaceChar(text[text.Length - 1]);
bool existingTextHasTrailingWhitespace = false;
string trimmed = CollapseWhitespace(text);
// When Text is split by a Comment (or other non-Element/PropElement) we will paste
// two pieces of Text together.
// This ensures that the spacing between them is correct.
if (_sb.Length > 0)
{
// If the existing text is WS then just strike it!
if (_isWhiteSpaceOnly)
{
_sb = new StringBuilder();
}
else
{
// Notice if it ends in WS
if (IsWhitespaceChar(_sb[_sb.Length-1]))
{
existingTextHasTrailingWhitespace = true;
}
}
}
// If the new text item had leading whitespace
// AND we were not asked to trim it off
// AND there isn't existing text that ends in whitespace.
// THEN put a space before the trimmed Text.
if (textHadLeadingWhitespace && !trimLeadingWhitespace && !existingTextHasTrailingWhitespace)
{
_sb.Append(SPACE);
}
_sb.Append(trimmed);
// Always leave trailing WS, if it was present.
// Trimming trailing WS can only be figured out from higher level context.
//
if (textHadTrailingWhitespace)
{
_sb.Append(SPACE);
}
}
_isWhiteSpaceOnly = _isWhiteSpaceOnly && newTextIsWhitespace;
}
public bool LooksLikeAMarkupExtension
{
get
{
int length = _sb.Length;
if (length > 0 && _sb[0] == OPENCURLIE)
{
if (length > 1 && _sb[1] == CLOSECURLIE)
return false;
return true;
}
return false;
}
}
// ===========================================================
static bool IsWhitespace(string text)
{
for (int i=0; i<text.Length; i++)
{
if (!IsWhitespaceChar(text[i]))
return false;
}
return true;
}
static bool IsWhitespaceChar(Char ch)
{
return (ch == SPACE || ch == TAB || ch == NEWLINE || ch == RETURN);
}
// This removes all leading and trailing whitespace, and it
// collapses any internal runs of whitespace to a single space.
//
static string CollapseWhitespace(string text)
{
StringBuilder sb = new StringBuilder(text.Length);
int firstIdx=0;
while (firstIdx < text.Length)
{
// If it is not whitespace copy it to the destination.
char ch = text[firstIdx];
if (!IsWhitespaceChar(ch))
{
sb.Append(ch);
++firstIdx;
continue;
}
// Skip any runs of whitespace.
int advancingIdx = firstIdx;
while (++advancingIdx < text.Length)
{
if (!IsWhitespaceChar(text[advancingIdx]))
break;
}
// If the spacing is in the middle. (not at the ends)
if (firstIdx != 0 && advancingIdx != text.Length)
{
bool skipSpace = false;
// check some easy things before digging deep
// for Asian chars. (only process a single newline)
if (ch == NEWLINE)
{
if ((advancingIdx - firstIdx == 2) && text[firstIdx - 1] >= 0x1100)
{
if (HasSurroundingEastAsianChars(firstIdx, advancingIdx, text))
{
skipSpace = true;
}
}
}
if (!skipSpace)
{
sb.Append(SPACE);
}
}
firstIdx = advancingIdx;
}
return sb.ToString();
}
public static string TrimLeadingWhitespace(string source)
{
string result = source.TrimStart(SPACE, TAB, NEWLINE);
return result;
}
public static string TrimTrailingWhitespace(string source)
{
string result = source.TrimEnd(SPACE, TAB, NEWLINE);
return result;
}
// ---- Asian newline suppression code ------
// this code was modeled from the 3.5 XamlReaderHelper.cs
static bool HasSurroundingEastAsianChars(int start, int end, string text)
{
Debug.Assert(start > 0);
Debug.Assert(end < text.Length);
int beforeValue;
if (start - 2 < 0)
{
beforeValue = text[0];
}
else
{
beforeValue = ComputeUnicodeScalarValue(start - 1, start - 2, text);
}
if (IsEastAsianCodePoint(beforeValue))
{
int afterValue;
if (end + 1 >= text.Length)
{
afterValue = text[end];
}
else
{
afterValue = ComputeUnicodeScalarValue(end, end, text);
}
if (IsEastAsianCodePoint(afterValue))
{
return true;
}
}
return false;
}
static int ComputeUnicodeScalarValue(int takeOneIdx, int takeTwoIdx, string text)
{
int unicodeScalarValue=0;
bool isSurrogate = false;
Char highChar = text[takeTwoIdx];
if (Char.IsHighSurrogate(highChar))
{
Char lowChar = text[takeTwoIdx + 1];
if (Char.IsLowSurrogate(lowChar))
{
isSurrogate = true;
unicodeScalarValue = (((highChar & 0x03FF) << 10) | (lowChar & 0x3FF)) + 0x1000;
}
}
if (!isSurrogate)
{
unicodeScalarValue = text[takeOneIdx];
}
return unicodeScalarValue;
}
struct CodePointRange
{
public readonly int Min;
public readonly int Max;
public CodePointRange(int min, int max)
{
Min = min;
Max = max;
}
}
static CodePointRange[] EastAsianCodePointRanges = new CodePointRange[]
{
new CodePointRange ( 0x1100, 0x11FF ), // Hangul
new CodePointRange ( 0x2E80, 0x2FD5 ), // CJK and KangXi Radicals
new CodePointRange ( 0x2FF0, 0x2FFB ), // Ideographic Description
#if NICE_COMMENTED_RANGES
new CodePointRange ( 0x3040, 0x309F ), // Hiragana
new CodePointRange ( 0x30A0, 0x30FF ), // Katakana
new CodePointRange ( 0x3100, 0x312F ), // Bopomofo
new CodePointRange ( 0x3130, 0x318F ), // Hangul Compatibility Jamo
new CodePointRange ( 0x3190, 0x319F ), // Kanbun
new CodePointRange ( 0x31F0, 0x31FF ), // Katakana Phonetic Extensions
new CodePointRange ( 0x3400, 0x4DFF ), // CJK Unified Ideographs Extension A
new CodePointRange ( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
new CodePointRange ( 0xA000, 0xA4CF ), // Yi
#else
new CodePointRange ( 0x3040, 0x319F ),
new CodePointRange ( 0x31F0, 0xA4CF ),
#endif
new CodePointRange ( 0xAC00, 0xD7A3 ), // Hangul Syllables
new CodePointRange ( 0xF900, 0xFAFF ), // CJK Compatibility
new CodePointRange ( 0xFF00, 0xFFEF ), // Halfwidth and Fullwidth forms
// surrogates
new CodePointRange ( 0x20000, 0x2a6d6 ), // CJK Unified Ext. B
new CodePointRange ( 0x2F800, 0x2FA1D ), // CJK Compatibility Supplement
};
// taken directly from WPF 3.5
static bool IsEastAsianCodePoint(int unicodeScalarValue)
{
for (int i = 0; i < EastAsianCodePointRanges.Length; i++)
{
if (unicodeScalarValue >= EastAsianCodePointRanges[i].Min)
{
if (unicodeScalarValue <= EastAsianCodePointRanges[i].Max)
return true;
}
}
return false;
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copysecond (c) 2017 Atif Aziz. All seconds reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
static partial class MoreEnumerable
{
/// <summary>
/// Performs a left outer join on two homogeneous sequences.
/// Additional arguments specify key selection functions and result
/// projection functions.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements in the source sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector function.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence of the join operation.</param>
/// <param name="second">
/// The second sequence of the join operation.</param>
/// <param name="keySelector">
/// Function that projects the key given an element of one of the
/// sequences to join.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <returns>A sequence containing results projected from a left
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> LeftJoin<TSource, TKey, TResult>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
Func<TSource, TResult> firstSelector,
Func<TSource, TSource, TResult> bothSelector)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
return first.LeftJoin(second, keySelector,
firstSelector, bothSelector,
null);
}
/// <summary>
/// Performs a left outer join on two homogeneous sequences.
/// Additional arguments specify key selection functions, result
/// projection functions and a key comparer.
/// </summary>
/// <typeparam name="TSource">
/// The type of elements in the source sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector function.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence of the join operation.</param>
/// <param name="second">
/// The second sequence of the join operation.</param>
/// <param name="keySelector">
/// Function that projects the key given an element of one of the
/// sequences to join.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> instance used to compare
/// keys for equality.</param>
/// <returns>A sequence containing results projected from a left
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> LeftJoin<TSource, TKey, TResult>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
Func<TSource, TKey> keySelector,
Func<TSource, TResult> firstSelector,
Func<TSource, TSource, TResult> bothSelector,
IEqualityComparer<TKey>? comparer)
{
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
return first.LeftJoin(second,
keySelector, keySelector,
firstSelector, bothSelector,
comparer);
}
/// <summary>
/// Performs a left outer join on two heterogeneous sequences.
/// Additional arguments specify key selection functions and result
/// projection functions.
/// </summary>
/// <typeparam name="TFirst">
/// The type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">
/// The type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector functions.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence of the join operation.</param>
/// <param name="second">
/// The second sequence of the join operation.</param>
/// <param name="firstKeySelector">
/// Function that projects the key given an element from <paramref name="first"/>.</param>
/// <param name="secondKeySelector">
/// Function that projects the key given an element from <paramref name="second"/>.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <returns>A sequence containing results projected from a left
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> LeftJoin<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TFirst, TSecond, TResult> bothSelector) =>
first.LeftJoin(second,
firstKeySelector, secondKeySelector,
firstSelector, bothSelector,
null);
/// <summary>
/// Performs a left outer join on two heterogeneous sequences.
/// Additional arguments specify key selection functions, result
/// projection functions and a key comparer.
/// </summary>
/// <typeparam name="TFirst">
/// The type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">
/// The type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">
/// The type of the key returned by the key selector functions.</typeparam>
/// <typeparam name="TResult">
/// The type of the result elements.</typeparam>
/// <param name="first">
/// The first sequence of the join operation.</param>
/// <param name="second">
/// The second sequence of the join operation.</param>
/// <param name="firstKeySelector">
/// Function that projects the key given an element from <paramref name="first"/>.</param>
/// <param name="secondKeySelector">
/// Function that projects the key given an element from <paramref name="second"/>.</param>
/// <param name="firstSelector">
/// Function that projects the result given just an element from
/// <paramref name="first"/> where there is no corresponding element
/// in <paramref name="second"/>.</param>
/// <param name="bothSelector">
/// Function that projects the result given an element from
/// <paramref name="first"/> and an element from <paramref name="second"/>
/// that match on a common key.</param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> instance used to compare
/// keys for equality.</param>
/// <returns>A sequence containing results projected from a left
/// outer join of the two input sequences.</returns>
public static IEnumerable<TResult> LeftJoin<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TFirst, TSecond, TResult> bothSelector,
IEqualityComparer<TKey>? comparer)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector));
if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector));
if (firstSelector == null) throw new ArgumentNullException(nameof(firstSelector));
if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector));
return
from f in first.GroupJoin(second, firstKeySelector, secondKeySelector,
(f, ss) => (Value: f, Seconds: from s in ss select (HasValue: true, Value: s)),
comparer)
from s in f.Seconds.DefaultIfEmpty()
select s.HasValue ? bothSelector(f.Value, s.Value) : firstSelector(f.Value);
}
}
}
| |
//
// DefaultPreferenceWidgets.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.Library;
using Banshee.Preferences;
using Banshee.Collection;
using Banshee.ServiceStack;
using Banshee.Widgets;
using Banshee.Gui.Widgets;
namespace Banshee.Preferences.Gui
{
public static class DefaultPreferenceWidgets
{
public static void Load (PreferenceService service)
{
Page music = ServiceManager.SourceManager.MusicLibrary.PreferencesPage;
foreach (LibrarySource source in ServiceManager.SourceManager.FindSources<LibrarySource> ()) {
new LibraryLocationButton (source);
}
PreferenceBase folder_pattern = music["file-system"]["folder_pattern"];
folder_pattern.DisplayWidget = new PatternComboBox (folder_pattern, FileNamePattern.SuggestedFolders);
PreferenceBase file_pattern = music["file-system"]["file_pattern"];
file_pattern.DisplayWidget = new PatternComboBox (file_pattern, FileNamePattern.SuggestedFiles);
PreferenceBase pattern_display = music["file-system"].FindOrAdd (new VoidPreference ("file_folder_pattern"));
pattern_display.DisplayWidget = new PatternDisplay (folder_pattern.DisplayWidget, file_pattern.DisplayWidget);
// Set up the extensions tab UI
Banshee.Addins.Gui.AddinView view = new Banshee.Addins.Gui.AddinView ();
view.Show ();
Gtk.ScrolledWindow scroll = new Gtk.ScrolledWindow ();
scroll.HscrollbarPolicy = PolicyType.Never;
scroll.AddWithViewport (view);
scroll.Show ();
service["extensions"].DisplayWidget = scroll;
}
private class LibraryLocationButton : HBox
{
private LibrarySource source;
private SchemaPreference<string> preference;
private FileChooserButton chooser;
private Button reset;
private string created_directory;
public LibraryLocationButton (LibrarySource source)
{
this.source = source;
preference = source.PreferencesPage["library-location"]["library-location"] as SchemaPreference<string>;
preference.ShowLabel = false;
preference.DisplayWidget = this;
string dir = preference.Value ?? source.DefaultBaseDirectory;
Spacing = 5;
// FileChooserButton wigs out if the directory does not exist,
// so create it if it doesn't and store the fact that we did
// in case it ends up not being used, we can remove it
try {
if (!Banshee.IO.Directory.Exists (dir)) {
Banshee.IO.Directory.Create (dir);
created_directory = dir;
Log.DebugFormat ("Created library directory: {0}", created_directory);
}
} catch {
}
chooser = new FileChooserButton (Catalog.GetString ("Select library location"),
FileChooserAction.SelectFolder);
chooser.SetCurrentFolder (dir);
chooser.SelectionChanged += OnChooserChanged;
HBox box = new HBox ();
box.Spacing = 2;
box.PackStart (new Image (Stock.Undo, IconSize.Button), false, false, 0);
box.PackStart (new Label (Catalog.GetString ("Reset")), false, false, 0);
reset = new Button () {
Sensitive = dir != source.DefaultBaseDirectory,
TooltipText = String.Format (Catalog.GetString ("Reset location to default ({0})"), source.DefaultBaseDirectory)
};
reset.Clicked += OnReset;
reset.Add (box);
//Button open = new Button ();
//open.PackStart (new Image (Stock.Open, IconSize.Button), false, false, 0);
//open.Clicked += OnOpen;
PackStart (chooser, true, true, 0);
PackStart (reset, false, false, 0);
//PackStart (open, false, false, 0);
chooser.Show ();
reset.ShowAll ();
}
private void OnReset (object o, EventArgs args)
{
chooser.SetFilename (source.DefaultBaseDirectory);
}
//private void OnOpen (object o, EventArgs args)
//{
//open chooser.Filename
//}
private void OnChooserChanged (object o, EventArgs args)
{
preference.Value = chooser.Filename;
reset.Sensitive = chooser.Filename != source.DefaultBaseDirectory;
}
protected override void OnUnrealized ()
{
// If the directory we had to create to appease FileSystemChooser exists
// and ended up not being the one selected by the user we clean it up
if (created_directory != null && chooser.Filename != created_directory) {
try {
Banshee.IO.Directory.Delete (created_directory);
if (!Banshee.IO.Directory.Exists (created_directory)) {
Log.DebugFormat ("Deleted unused and empty previous library directory: {0}", created_directory);
created_directory = null;
}
} catch {
}
}
base.OnUnrealized ();
}
}
private class PatternComboBox : DictionaryComboBox<string>
{
private Preference<string> preference;
public PatternComboBox (PreferenceBase pref, string [] patterns)
{
preference = (Preference<string>)pref;
bool already_added = false;
string conf_pattern = preference.Value;
foreach (string pattern in patterns) {
if (!already_added && pattern.Equals (conf_pattern)) {
already_added = true;
}
Add (FileNamePattern.CreatePatternDescription (pattern), pattern);
}
if (!already_added) {
Add (FileNamePattern.CreatePatternDescription (conf_pattern), conf_pattern);
}
ActiveValue = conf_pattern;
}
protected override void OnChanged ()
{
preference.Value = ActiveValue;
base.OnChanged ();
}
}
private class PatternDisplay : WrapLabel
{
private PatternComboBox folder;
private PatternComboBox file;
private SampleTrackInfo track = new SampleTrackInfo ();
public PatternDisplay (object a, object b)
{
folder= (PatternComboBox)a;
file = (PatternComboBox)b;
folder.Changed += OnChanged;
file.Changed += OnChanged;
OnChanged (null, null);
}
private void OnChanged (object o, EventArgs args)
{
string display = FileNamePattern.CreateFromTrackInfo (FileNamePattern.CreateFolderFilePattern (
folder.ActiveValue, file.ActiveValue), track);
Markup = String.IsNullOrEmpty (display) ? String.Empty : String.Format ("<small>{0}.ogg</small>",
GLib.Markup.EscapeText (display));
}
}
}
}
| |
namespace Schema.NET.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class Values6Test
{
[Fact]
public void Constructor_Value1Passed_OnlyValue1HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(1);
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { 1 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value2Passed_OnlyValue2HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo");
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { "Foo" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value3Passed_OnlyValue3HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday);
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { DayOfWeek.Friday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value4Passed_OnlyValue4HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person());
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<Person>(item);
}
[Fact]
public void Constructor_Value5Passed_OnlyValue5HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue);
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.True(values.HasValue5);
Assert.Single(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<DateTime>(item);
}
[Fact]
public void Constructor_Value6Passed_OnlyValue6HasValue()
{
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(true);
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.True(values.HasValue6);
Assert.Single(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<bool>(item);
}
[Fact]
public void Constructor_Items_HasAllItems()
{
var person = new Person();
var values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(1, "Foo", DayOfWeek.Friday, person, DateTime.MinValue, true);
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
Assert.True(values.HasValue5);
Assert.Single(values.Value5);
Assert.True(values.HasValue6);
Assert.Single(values.Value6);
Assert.Equal(new List<object>() { 1, "Foo", DayOfWeek.Friday, person, DateTime.MinValue, true }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_NullList_ThrowsArgumentNullException() =>
Assert.Throws<ArgumentNullException>(() => new Values<int, string, DayOfWeek, Person, DateTime, bool>((List<object>)null!));
[Theory]
[InlineData(0)]
[InlineData(1, 1)]
[InlineData(2, 1, 2)]
[InlineData(1, "Foo")]
[InlineData(2, "Foo", "Bar")]
[InlineData(1, DayOfWeek.Friday)]
[InlineData(2, DayOfWeek.Friday, DayOfWeek.Monday)]
[InlineData(3, 1, "Foo", DayOfWeek.Friday)]
[InlineData(6, 1, 2, "Foo", "Bar", DayOfWeek.Friday, DayOfWeek.Monday)]
public void Count_Items_ReturnsExpectedCount(int expectedCount, params object[] items) =>
Assert.Equal(expectedCount, new Values<int, string, DayOfWeek, Person, DateTime, bool>(items).Count);
[Fact]
public void HasValue_DoesntHaveValue_ReturnsFalse() =>
Assert.False(default(Values<int, string, DayOfWeek, Person, DateTime, bool>).HasValue);
[Theory]
[InlineData(1)]
[InlineData("Foo")]
[InlineData(DayOfWeek.Friday)]
public void HasValue_HasValue_ReturnsTrue(params object[] parameters) =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(parameters).HasValue);
[Fact]
public void HasValue1_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue1);
[Fact]
public void HasValue1_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo").HasValue1);
[Fact]
public void HasValue2_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo").HasValue2);
[Fact]
public void HasValue2_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue2);
[Fact]
public void HasValue3_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday).HasValue3);
[Fact]
public void HasValue3_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue3);
[Fact]
public void HasValue4_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person()).HasValue4);
[Fact]
public void HasValue4_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue4);
[Fact]
public void HasValue5_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue).HasValue5);
[Fact]
public void HasValue5_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue5);
[Fact]
public void HasValue6_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true).HasValue6);
[Fact]
public void HasValue6_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).HasValue6);
[Fact]
public void ImplicitConversionOperator_Value1Passed_OnlyValue1HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = 1;
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { 1 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value2Passed_OnlyValue2HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = "Foo";
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { "Foo" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value3Passed_OnlyValue3HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = DayOfWeek.Friday;
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { DayOfWeek.Friday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value4Passed_OnlyValue4HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new Person();
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<Person>(item);
}
[Fact]
public void ImplicitConversionOperator_Value5Passed_OnlyValue5HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = DateTime.MinValue;
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.True(values.HasValue5);
Assert.Single(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<DateTime>(item);
}
[Fact]
public void ImplicitConversionOperator_Value6Passed_OnlyValue6HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = true;
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.True(values.HasValue6);
Assert.Single(values.Value6);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<bool>(item);
}
[Fact]
public void ImplicitConversionOperator_Value1CollectionPassed_OnlyValue1HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<int>() { 1, 2 };
Assert.True(values.HasValue1);
Assert.Equal(2, values.Value1.Count);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { 1, 2 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value2CollectionPassed_OnlyValue2HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<string>() { "Foo", "Bar" };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Equal(2, values.Value2.Count);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { "Foo", "Bar" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value3CollectionPassed_OnlyValue3HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<DayOfWeek>() { DayOfWeek.Friday, DayOfWeek.Monday };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Equal(2, values.Value3.Count);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(new List<object>() { DayOfWeek.Friday, DayOfWeek.Monday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value4CollectionPassed_OnlyValue4HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<Person>() { new Person(), new Person() };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Equal(2, values.Value4.Count);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(2, ((IValues)values).Cast<object>().ToList().Count);
}
[Fact]
public void ImplicitConversionOperator_Value5CollectionPassed_OnlyValue5HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<DateTime>() { DateTime.MinValue, DateTime.MinValue };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.True(values.HasValue5);
Assert.Equal(2, values.Value5.Count);
Assert.False(values.HasValue6);
Assert.Empty(values.Value6);
Assert.Equal(2, ((IValues)values).Cast<object>().ToList().Count);
}
[Fact]
public void ImplicitConversionOperator_Value6CollectionPassed_OnlyValue6HasValue()
{
Values<int, string, DayOfWeek, Person, DateTime, bool> values = new List<bool>() { true, true };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.False(values.HasValue4);
Assert.Empty(values.Value4);
Assert.False(values.HasValue5);
Assert.Empty(values.Value5);
Assert.True(values.HasValue6);
Assert.Equal(2, values.Value6.Count);
Assert.Equal(2, ((IValues)values).Cast<object>().ToList().Count);
}
[Fact]
public void ImplicitConversionToList_Value1Passed_ReturnsMatchingList()
{
List<int> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(1);
Assert.Equal(new List<int>() { 1 }, values);
}
[Fact]
public void ImplicitConversionToList_Value2Passed_ReturnsMatchingList()
{
List<string> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo");
Assert.Equal(new List<string>() { "Foo" }, values);
}
[Fact]
public void ImplicitConversionToList_Value3Passed_ReturnsMatchingList()
{
List<DayOfWeek> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday);
Assert.Equal(new List<DayOfWeek>() { DayOfWeek.Friday }, values);
}
[Fact]
public void ImplicitConversionToList_Value4Passed_ReturnsMatchingList()
{
var person = new Person();
List<Person> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(person);
Assert.Equal(new List<Person>() { person }, values);
}
[Fact]
public void ImplicitConversionToList_Value5Passed_ReturnsMatchingList()
{
List<DateTime> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue);
Assert.Equal(new List<DateTime>() { DateTime.MinValue }, values);
}
[Fact]
public void ImplicitConversionToList_Value6Passed_ReturnsMatchingList()
{
List<bool> values = new Values<int, string, DayOfWeek, Person, DateTime, bool>(true);
Assert.Equal(new List<bool>() { true }, values);
}
[Fact]
public void Deconstruct_Values_ReturnsAllEnumerables()
{
var person = new Person();
var (integers, strings, daysOfWeek, people, dates, bools) = new Values<int, string, DayOfWeek, Person, DateTime, bool>(1, "Foo", DayOfWeek.Friday, person, DateTime.MinValue, true);
Assert.Equal(new List<int>() { 1 }, integers);
Assert.Equal(new List<string>() { "Foo" }, strings);
Assert.Equal(new List<DayOfWeek>() { DayOfWeek.Friday }, daysOfWeek);
Assert.Equal(new List<Person>() { person }, people);
Assert.Equal(new List<DateTime>() { DateTime.MinValue }, dates);
Assert.Equal(new List<bool>() { true }, bools);
}
[Fact]
public void EqualsOperator_EqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(1));
[Fact]
public void EqualsOperator_NotEqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(2));
[Fact]
public void EqualsOperator_EqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo") == new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo"));
[Fact]
public void EqualsOperator_NotEqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo") == new Values<int, string, DayOfWeek, Person, DateTime, bool>("Bar"));
[Fact]
public void EqualsOperator_EqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday));
[Fact]
public void EqualsOperator_NotEqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Monday));
[Fact]
public void EqualsOperator_EqualValue4Passed_ReturnsTrue()
{
var person = new Person();
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(person) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(person));
}
[Fact]
public void EqualsOperator_NotEqualValue4Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "A" }) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "B" }));
[Fact]
public void EqualsOperator_EqualValue5Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue));
[Fact]
public void EqualsOperator_NotEqualValue5Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MaxValue));
[Fact]
public void EqualsOperator_EqualValue6Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(true));
[Fact]
public void EqualsOperator_NotEqualValue6Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true) == new Values<int, string, DayOfWeek, Person, DateTime, bool>(false));
[Fact]
public void NotEqualsOperator_EqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(1));
[Fact]
public void NotEqualsOperator_NotEqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(2));
[Fact]
public void NotEqualsOperator_EqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo") != new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo"));
[Fact]
public void NotEqualsOperator_NotEqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo") != new Values<int, string, DayOfWeek, Person, DateTime, bool>("Bar"));
[Fact]
public void NotEqualsOperator_EqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday));
[Fact]
public void NotEqualsOperator_NotEqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Monday));
[Fact]
public void NotEqualsOperator_EqualValue4Passed_ReturnsFalse()
{
var person = new Person();
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(person) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(person));
}
[Fact]
public void NotEqualsOperator_NotEqualValue4Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "A" }) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "B" }));
[Fact]
public void NotEqualsOperator_EqualValue5Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue));
[Fact]
public void NotEqualsOperator_NotEqualValue5Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MaxValue));
[Fact]
public void NotEqualsOperator_EqualValue6Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(true));
[Fact]
public void NotEqualsOperator_NotEqualValue6Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true) != new Values<int, string, DayOfWeek, Person, DateTime, bool>(false));
[Fact]
public void Equals_EqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1)));
[Fact]
public void Equals_NotEqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(2)));
[Fact]
public void Equals_EqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo").Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo")));
[Fact]
public void Equals_NotEqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo").Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>("Bar")));
[Fact]
public void Equals_EqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday)));
[Fact]
public void Equals_NotEqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Monday)));
[Fact]
public void Equals_EqualValue4Passed_ReturnsTrue()
{
var person = new Person();
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(person).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(person)));
}
[Fact]
public void Equals_NotEqualValue4Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "A" }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new Person { Name = "B" })));
[Fact]
public void Equals_EqualValue5Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue)));
[Fact]
public void Equals_NotEqualValue5Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MaxValue)));
[Fact]
public void Equals_EqualValue6Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true)));
[Fact]
public void Equals_NotEqualValue6Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(true).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(false)));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3EqualValue4EqualValue5EqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3EqualValue4EqualValue5EqualValue6NotEqual_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, false })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3EqualValue4EqualValue5NotEqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MaxValue })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3EqualValue4NotEqualValue5EqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person { Name = "Schema" }, DateTime.MinValue })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3NotEqualValue4EqualValue5EqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Wednesday, new Person(), DateTime.MinValue })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2NotEqualValue3EqualValue4EqualValue5EqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Bar", DayOfWeek.Tuesday, new Person(), DateTime.MinValue })));
[Fact]
public void Equals_MixedTypes_Value1NotEqualValue2EqualValue3EqualValue4EqualValue5EqualValue6Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 1, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue6_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue5_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue4_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue3_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue2_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue1_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue6_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue5_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), true })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue4_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue3_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue2_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue1_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true }).Equals(new Values<int, string, DayOfWeek, Person, DateTime, bool>(new object[] { "Foo", DayOfWeek.Tuesday, new Person(), DateTime.MinValue, true })));
[Fact]
public void GetHashCode_Value1Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(CombineHashCodes(CombineHashCodes(CombineHashCodes(CombineHashCodes(1.GetHashCode(), 0), 0), 0), 0), 0),
new Values<int, string, DayOfWeek, Person, DateTime, bool>(1).GetHashCode());
[Fact]
public void GetHashCode_Value2Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(CombineHashCodes(CombineHashCodes(CombineHashCodes("Foo".GetHashCode(StringComparison.Ordinal), 0), 0), 0), 0),
new Values<int, string, DayOfWeek, Person, DateTime, bool>("Foo").GetHashCode());
[Fact]
public void GetHashCode_Value3Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(CombineHashCodes(CombineHashCodes(DayOfWeek.Friday.GetHashCode(), 0), 0), 0),
new Values<int, string, DayOfWeek, Person, DateTime, bool>(DayOfWeek.Friday).GetHashCode());
[Fact]
public void GetHashCode_Value4Passed_ReturnsMatchingHashCode()
{
var person = new Person();
Assert.Equal(
CombineHashCodes(CombineHashCodes(person.GetHashCode(), 0), 0),
new Values<int, string, DayOfWeek, Person, DateTime, bool>(person).GetHashCode());
}
[Fact]
public void GetHashCode_Value5Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(DateTime.MinValue.GetHashCode(), 0),
new Values<int, string, DayOfWeek, Person, DateTime, bool>(DateTime.MinValue).GetHashCode());
[Fact]
public void GetHashCode_Value6Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
true.GetHashCode(),
new Values<int, string, DayOfWeek, Person, DateTime, bool>(true).GetHashCode());
private static int CombineHashCodes(int h1, int h2) => ((h1 << 5) + h1) ^ h2;
}
| |
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.Generic;
namespace Hydna.Net
{
internal class Connection : IDisposable
{
internal static bool hasTlsSupport = true;
private static Dictionary<string, List<Connection>> _connections;
static Connection ()
{
_connections = new Dictionary<string, List<Connection>>();
}
internal static Connection create (Channel channel, Uri uri)
{
Connection connection = null;
string connurl = null;
connurl = uri.Scheme + "://" + uri.Host + ":" + uri.Port;
if (_connections.ContainsKey(connurl)) {
List<Connection> all = _connections[connurl];
foreach (Connection conn in all) {
if (conn._channels.ContainsKey(uri.AbsolutePath) == false) {
connection = conn;
break;
}
}
}
if (connection == null) {
connection = new Connection(connurl, uri);
if (_connections.ContainsKey(connurl) == false) {
_connections.Add(connurl, new List<Connection>());
}
_connections[connurl].Add(connection);
}
connection.allocChannel(channel);
return connection;
}
private IConnectionAdapter _adapter;
private Dictionary<string, Channel> _channels;
private Dictionary<uint, Channel> _routes;
private Queue<Channel> _openQueue;
private string _id;
private bool _handshaked;
private int _refcount;
void IDisposable.Dispose()
{
try {
close();
}
catch (Exception) {
}
}
internal Connection (string id, Uri uri)
{
_id = id;
_refcount = 0;
_channels = new Dictionary<string, Channel>();
_routes = new Dictionary<uint, Channel>();
#if HYDNA_UNITY
_adapter = new ReflectClientAdapter();
#else
_adapter = new TcpClientAdapter();
#endif
_adapter.OnConnect = connectHandler;
_adapter.OnClose = closeHandler;
_adapter.OnFrame = frameHandler;
_adapter.Connect(uri);
_openQueue = new Queue<Channel>();
}
internal void Send(Frame frame)
{
if (_adapter == null)
return;
_adapter.Send(frame);
}
void allocChannel(Channel channel)
{
string path;
path = channel.AbsolutePath == null ? "/"
: channel.AbsolutePath;
if (_channels.ContainsKey(path)) {
throw new Exception("Channel already created");
}
_channels.Add(path, channel);
_refcount++;
if (_handshaked) {
byte[] pathbuff = Encoding.UTF8.GetBytes(channel.AbsolutePath);
Frame frame = Frame.Resolve(pathbuff);
_adapter.Send(frame);
}
else {
_openQueue.Enqueue(channel);
}
}
void deallocChannel(Channel channel)
{
deallocChannel(channel, null, null);
}
void deallocChannel(Channel channel, Frame frame, string reason)
{
if (channel.AbsolutePath == null)
return;
if (_channels.ContainsKey(channel.AbsolutePath))
_channels.Remove(channel.AbsolutePath);
if (channel.Ptr != 0)
_routes.Remove(channel.Ptr);
_refcount--;
if (_refcount == 0) {
close();
}
channel.handleClose(frame, reason);
}
void connectHandler()
{
Channel channel;
Frame frame;
byte[] path;
_handshaked = true;
while (_openQueue.Count > 0) {
channel = _openQueue.Dequeue();
path = Encoding.UTF8.GetBytes(channel.AbsolutePath);
frame = Frame.Resolve(path);
_adapter.Send(frame);
}
}
void frameHandler(Frame frame)
{
switch (frame.OpCode)
{
case OpCode.Open:
openHandler(frame);
break;
case OpCode.Data:
dataHandler(frame);
break;
case OpCode.Signal:
signalHandler(frame);
break;
case OpCode.Resolve:
resolveHandler(frame);
break;
}
}
void closeHandler(string reason)
{
close(reason);
}
void openHandler(Frame frame)
{
Channel channel;
if (_routes.ContainsKey(frame.Ptr) == false) {
close("Protocol error: Server sent invalid open packet");
return;
}
channel = _routes[frame.Ptr];
if (channel.State != ChannelState.Resolved) {
close("Protocol error: Server sent open to an open channel");
return;
}
if (frame.OpenFlag == OpenFlag.Success) {
channel.handleOpen(frame);
return;
}
deallocChannel(channel, frame, "Open was denied");
}
void dataHandler(Frame frame)
{
if (frame.Payload == null || frame.Payload.Length == 0) {
close("Protocol error: Zero data packet sent received");
return;
}
Channel channel;
if (frame.Ptr == 0) {
foreach (KeyValuePair<string, Channel> kvp in _channels) {
channel = kvp.Value;
if ((channel.Mode & ChannelMode.Read) == ChannelMode.Read) {
channel.handleData(frame.Clone());
}
}
return;
}
if (_routes.ContainsKey(frame.Ptr) == false)
return;
channel = _routes[frame.Ptr];
if ((channel.Mode & ChannelMode.Read) == ChannelMode.Read) {
channel.handleData(frame);
}
}
void signalHandler(Frame frame)
{
Channel channel;
if (frame.SignalFlag == SignalFlag.Emit) {
if (frame.Ptr == 0) {
foreach (KeyValuePair<string, Channel> kvp in _channels) {
channel = kvp.Value;
channel.handleSignal(frame.Clone());
}
}
else {
if (_routes.ContainsKey(frame.Ptr) == false)
return;
channel = _routes[frame.Ptr];
channel.handleSignal(frame);
}
}
else {
if (frame.Ptr == 0) {
foreach (KeyValuePair<string, Channel> kvp in _channels) {
channel = kvp.Value;
deallocChannel(channel, frame.Clone(), null);
}
}
else {
if (_routes.ContainsKey(frame.Ptr) == false)
return;
channel = _routes[frame.Ptr];
if (channel.State != ChannelState.Closing) {
// We havent closed our channel yet. We therefor need
// to send an ENDSIG in response to this packet.
Frame end = Frame.Create(frame.Ptr,
SignalFlag.End,
ContentType.Utf,
null);
_adapter.Send(end);
}
deallocChannel(channel, frame, null);
}
}
}
void resolveHandler(Frame frame)
{
string path;
try {
path = Encoding.UTF8.GetString(frame.Payload);
}
catch (EncoderFallbackException) {
// Ignore unresolved paths;
return;
}
Channel channel;
if (_channels.ContainsKey(path) == false) {
return;
}
channel = _channels[path];
if (channel.State == ChannelState.Closing) {
deallocChannel(channel);
return;
}
if (frame.ResolveFlag != ResolveFlag.Success) {
deallocChannel(channel, frame, "Unable to resolve path");
return;
}
_routes.Add(frame.Ptr, channel);
channel.handleResolved(frame.Ptr);
Frame open = Frame.Create(frame.Ptr,
channel.Mode,
channel.ctoken,
channel.token);
_adapter.Send(open);
}
void close(string reason)
{
Dictionary<string, Channel> channels;
channels = new Dictionary<string, Channel>(_channels);
foreach (KeyValuePair<string, Channel> kvp in channels) {
Channel channel = kvp.Value;
deallocChannel(channel, null, reason);
}
close();
}
void close()
{
if (_adapter != null) {
_adapter.OnConnect = null;
_adapter.OnClose = null;
_adapter.OnFrame = null;
_adapter.Close();
_adapter = null;
}
_channels = null;
_routes = null;
_handshaked = false;
if (_id != null) {
if (_connections.ContainsKey(_id)) {
List<Connection> list = _connections[_id];
list.Remove(this);
if (list.Count == 0)
_connections.Remove(_id);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using MySql.Data.MySqlClient;
using NetGore.IO;
namespace NetGore.Db.Schema
{
/// <summary>
/// Reads the schema for a database.
/// </summary>
[Serializable]
public class SchemaReader
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string _columnsAlias = "c";
const string _queryStr =
"SELECT {0}" + " FROM COLUMNS AS {2}" + " LEFT JOIN TABLES AS t" +
" ON {2}.TABLE_NAME = t.TABLE_NAME AND c.TABLE_SCHEMA = t.TABLE_SCHEMA" + " WHERE t.TABLE_SCHEMA = '{1}'";
const string _rootNodeName = "DbSchema";
const string _tablesNodeName = "Tables";
readonly IEnumerable<TableSchema> _tableSchemas;
/// <summary>
/// Initializes the <see cref="SchemaReader"/> class.
/// </summary>
static SchemaReader()
{
EncodingFormat = GenericValueIOFormat.Binary;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchemaReader"/> class.
/// </summary>
/// <param name="dbSettings">The <see cref="DbConnectionSettings"/> for connecting to the database to read
/// the schema of.</param>
public SchemaReader(DbConnectionSettings dbSettings)
{
var conn = OpenConnection(dbSettings);
_tableSchemas = ExecuteQuery(conn, dbSettings);
CloseConnection(conn);
}
/// <summary>
/// Initializes a new instance of the <see cref="SchemaReader"/> class.
/// </summary>
/// <param name="reader">The <see cref="IValueReader"/> to read the values from.</param>
public SchemaReader(IValueReader reader)
{
_tableSchemas = reader.ReadManyNodes(_tablesNodeName, r => new TableSchema(r)).ToCompact();
}
/// <summary>
/// Gets or sets the <see cref="GenericValueIOFormat"/> to use for when an instance of this class
/// writes itself out to a new <see cref="GenericValueWriter"/>. If null, the format to use
/// will be inherited from <see cref="GenericValueWriter.DefaultFormat"/>.
/// Default value is <see cref="GenericValueIOFormat.Binary"/>.
/// </summary>
public static GenericValueIOFormat? EncodingFormat { get; set; }
/// <summary>
/// Gets the schema for the database tables.
/// </summary>
public IEnumerable<TableSchema> TableSchemas
{
get { return _tableSchemas; }
}
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="conn">The <see cref="IDbConnection"/>.</param>
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
static void CloseConnection(IDbConnection conn)
{
if (conn == null)
{
Debug.Fail("conn is null.");
return;
}
try
{
conn.Close();
conn.Dispose();
}
catch (ObjectDisposedException)
{
const string errmsg = "Connection `{0}` already disposed.";
if (log.IsDebugEnabled)
log.DebugFormat(errmsg, conn);
}
catch (Exception ex)
{
const string errmsg = "Failed to dispose `{0}`. Exception: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, conn, ex);
Debug.Fail(string.Format(errmsg, conn, ex));
}
}
static IEnumerable<TableSchema> ExecuteQuery(MySqlConnection conn, DbConnectionSettings dbSettings)
{
var tableColumns = new Dictionary<string, List<ColumnSchema>>();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = GetQueryString(dbSettings);
using (var r = cmd.ExecuteReader())
{
while (r.Read())
{
var column = new ColumnSchema(r);
List<ColumnSchema> columnList;
if (!tableColumns.TryGetValue(column.TableName, out columnList))
{
columnList = new List<ColumnSchema>();
tableColumns.Add(column.TableName, columnList);
}
columnList.Add(column);
}
}
}
var ret = tableColumns.Select(x => new TableSchema(x.Key, x.Value));
// ToArray() required to serialize, otherwise it is a LINQ statement
return ret.ToArray();
}
static string GetColumnsString()
{
var sb = new StringBuilder();
foreach (var c in ColumnSchema.ValueNames)
{
sb.Append(_columnsAlias);
sb.Append(".");
sb.Append(c);
sb.Append(", ");
}
sb.Length -= 2;
return sb.ToString();
}
static string GetQueryString(DbConnectionSettings dbSettings)
{
return string.Format(_queryStr, GetColumnsString(), dbSettings.Database, _columnsAlias);
}
/// <summary>
/// Loads a <see cref="SchemaReader"/> from the specified file path.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <returns>The loaded <see cref="SchemaReader"/></returns>
public static SchemaReader Load(string filePath)
{
var reader = GenericValueReader.CreateFromFile(filePath, _rootNodeName);
return new SchemaReader(reader);
}
/// <summary>
/// Opens the connection.
/// </summary>
/// <param name="dbSettings">The db settings.</param>
/// <returns>The <see cref="MySqlConnection"/>.</returns>
static MySqlConnection OpenConnection(DbConnectionSettings dbSettings)
{
var s = new MySqlConnectionStringBuilder
{ UserID = dbSettings.User, Password = dbSettings.Pass, Server = dbSettings.Host, Database = "information_schema" };
var connStr = s.ToString();
var conn = new MySqlConnection(connStr);
conn.Open();
return conn;
}
/// <summary>
/// Saves the values to the specified file path.
/// </summary>
/// <param name="filePath">The file path.</param>
public void Save(string filePath)
{
var tables = _tableSchemas.ToArray();
using (var writer = GenericValueWriter.Create(filePath, _rootNodeName, EncodingFormat))
{
writer.WriteManyNodes(_tablesNodeName, tables, (w, table) => table.Write(w));
}
}
}
}
| |
//
// CryptographyContext.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace MimeKit.Cryptography {
/// <summary>
/// An abstract cryptography context.
/// </summary>
/// <remarks>
/// Generally speaking, applications should not use a <see cref="CryptographyContext"/>
/// directly, but rather via higher level APIs such as <see cref="MultipartSigned"/>,
/// <see cref="MultipartEncrypted"/> and <see cref="ApplicationPkcs7Mime"/>.
/// </remarks>
public abstract class CryptographyContext : IDisposable
{
const string SubclassAndRegisterFormat = "You need to subclass {0} and then register it with MimeKit.Cryptography.CryptographyContext.Register().";
static ConstructorInfo SecureMimeContextConstructor;
static ConstructorInfo OpenPgpContextConstructor;
static readonly object mutex = new object ();
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CryptographyContext"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="CryptographyContext"/>.
/// </remarks>
protected CryptographyContext ()
{
}
/// <summary>
/// Gets the signature protocol.
/// </summary>
/// <remarks>
/// <para>The signature protocol is used by <see cref="MultipartSigned"/>
/// in order to determine what the protocol parameter of the Content-Type
/// header should be.</para>
/// </remarks>
/// <value>The signature protocol.</value>
public abstract string SignatureProtocol { get; }
/// <summary>
/// Gets the encryption protocol.
/// </summary>
/// <remarks>
/// <para>The encryption protocol is used by <see cref="MultipartEncrypted"/>
/// in order to determine what the protocol parameter of the Content-Type
/// header should be.</para>
/// </remarks>
/// <value>The encryption protocol.</value>
public abstract string EncryptionProtocol { get; }
/// <summary>
/// Gets the key exchange protocol.
/// </summary>
/// <remarks>
/// <para>The key exchange protocol is really only used for PGP.</para>
/// </remarks>
/// <value>The key exchange protocol.</value>
public abstract string KeyExchangeProtocol { get; }
#if NOT_YET
/// <summary>
/// Gets or sets a value indicating whether this <see cref="MimeKit.Cryptography.CryptographyContext"/> allows online
/// certificate retrieval.
/// </summary>
/// <value><c>true</c> if online certificate retrieval should be allowed; otherwise, <c>false</c>.</value>
public bool AllowOnlineCertificateRetrieval { get; set; }
/// <summary>
/// Gets or sets the online certificate retrieval timeout.
/// </summary>
/// <value>The online certificate retrieval timeout.</value>
public TimeSpan OnlineCertificateRetrievalTimeout { get; set; }
#endif
/// <summary>
/// Checks whether or not the specified protocol is supported by the <see cref="CryptographyContext"/>.
/// </summary>
/// <remarks>
/// Used in order to make sure that the protocol parameter value specified in either a multipart/signed
/// or multipart/encrypted part is supported by the supplied cryptography context.
/// </remarks>
/// <returns><c>true</c> if the protocol is supported; otherwise <c>false</c></returns>
/// <param name="protocol">The protocol.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="protocol"/> is <c>null</c>.
/// </exception>
public abstract bool Supports (string protocol);
/// <summary>
/// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part.
/// </summary>
/// <remarks>
/// Maps the <see cref="DigestAlgorithm"/> to the appropriate string identifier
/// as used by the micalg parameter value of a multipart/signed Content-Type
/// header.
/// </remarks>
/// <returns>The micalg value.</returns>
/// <param name="micalg">The digest algorithm.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="micalg"/> is out of range.
/// </exception>
public abstract string GetDigestAlgorithmName (DigestAlgorithm micalg);
/// <summary>
/// Gets the digest algorithm from the micalg parameter value in a multipart/signed part.
/// </summary>
/// <remarks>
/// Maps the micalg parameter value string back to the appropriate <see cref="DigestAlgorithm"/>.
/// </remarks>
/// <returns>The digest algorithm.</returns>
/// <param name="micalg">The micalg parameter value.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="micalg"/> is <c>null</c>.
/// </exception>
public abstract DigestAlgorithm GetDigestAlgorithm (string micalg);
/// <summary>
/// Cryptographically signs the content.
/// </summary>
/// <remarks>
/// Cryptographically signs the content using the specified signer and digest algorithm.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the detached signature data.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="digestAlgo"/> is out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A signing certificate could not be found for <paramref name="signer"/>.
/// </exception>
public abstract MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content);
/// <summary>
/// Verifies the specified content using the detached signatureData.
/// </summary>
/// <remarks>
/// Verifies the specified content using the detached signatureData.
/// </remarks>
/// <returns>A list of digital signatures.</returns>
/// <param name="content">The content.</param>
/// <param name="signatureData">The signature data.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signatureData"/> is <c>null</c>.</para>
/// </exception>
public abstract DigitalSignatureCollection Verify (Stream content, Stream signatureData);
/// <summary>
/// Encrypts the specified content for the specified recipients.
/// </summary>
/// <remarks>
/// Encrypts the specified content for the specified recipients.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the encrypted data.</returns>
/// <param name="recipients">The recipients.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="CertificateNotFoundException">
/// A certificate could not be found for one or more of the <paramref name="recipients"/>.
/// </exception>
public abstract MimePart Encrypt (IEnumerable<MailboxAddress> recipients, Stream content);
/// <summary>
/// Decrypts the specified encryptedData.
/// </summary>
/// <remarks>
/// Decrypts the specified encryptedData.
/// </remarks>
/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
/// <param name="encryptedData">The encrypted data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encryptedData"/> is <c>null</c>.
/// </exception>
public abstract MimeEntity Decrypt (Stream encryptedData);
/// <summary>
/// Imports the public certificates or keys from the specified stream.
/// </summary>
/// <remarks>
/// Imports the public certificates or keys from the specified stream.
/// </remarks>
/// <param name="stream">The raw certificate or key data.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="stream"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Importing keys is not supported by this cryptography context.
/// </exception>
public abstract void Import (Stream stream);
/// <summary>
/// Exports the keys for the specified mailboxes.
/// </summary>
/// <remarks>
/// Exports the keys for the specified mailboxes.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported keys.</returns>
/// <param name="mailboxes">The mailboxes.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="mailboxes"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="mailboxes"/> was empty.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// Exporting keys is not supported by this cryptography context.
/// </exception>
public abstract MimePart Export (IEnumerable<MailboxAddress> mailboxes);
/// <summary>
/// Releases the unmanaged resources used by the <see cref="CryptographyContext"/> and
/// optionally releases the managed resources.
/// </summary>
/// <remarks>
/// Releases the unmanaged resources used by the <see cref="CryptographyContext"/> and
/// optionally releases the managed resources.
/// </remarks>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only the unmanaged resources.</param>
protected virtual void Dispose (bool disposing)
{
}
/// <summary>
/// Releases all resources used by the <see cref="MimeKit.Cryptography.CryptographyContext"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="MimeKit.Cryptography.CryptographyContext"/>. The
/// <see cref="Dispose()"/> method leaves the <see cref="MimeKit.Cryptography.CryptographyContext"/> in an unusable state. After
/// calling <see cref="Dispose()"/>, you must release all references to the <see cref="MimeKit.Cryptography.CryptographyContext"/> so
/// the garbage collector can reclaim the memory that the <see cref="MimeKit.Cryptography.CryptographyContext"/> was occupying.</remarks>
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
/// <summary>
/// Creates a new <see cref="CryptographyContext"/> for the specified protocol.
/// </summary>
/// <remarks>
/// <para>Creates a new <see cref="CryptographyContext"/> for the specified protocol.</para>
/// <para>The default <see cref="CryptographyContext"/> types can over overridden by calling
/// the <see cref="Register"/> method with the preferred type.</para>
/// </remarks>
/// <returns>The <see cref="CryptographyContext"/> for the protocol.</returns>
/// <param name="protocol">The protocol.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="protocol"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// There are no supported <see cref="CryptographyContext"/>s that support
/// the specified <paramref name="protocol"/>.
/// </exception>
public static CryptographyContext Create (string protocol)
{
if (protocol == null)
throw new ArgumentNullException ("protocol");
protocol = protocol.ToLowerInvariant ();
lock (mutex) {
switch (protocol) {
case "application/x-pkcs7-signature":
case "application/pkcs7-signature":
case "application/x-pkcs7-mime":
case "application/pkcs7-mime":
case "application/x-pkcs7-keys":
case "application/pkcs7-keys":
if (SecureMimeContextConstructor != null)
return (CryptographyContext) SecureMimeContextConstructor.Invoke (new object[0]);
#if !PORTABLE
if (!SqliteCertificateDatabase.IsAvailable) {
const string format = "SQLite is not available. Either install the {0} nuget or subclass MimeKit.Cryptography.SecureMimeContext and register it with MimeKit.Cryptography.CryptographyContext.Register().";
#if COREFX
throw new NotSupportedException (string.Format (format, "Microsoft.Data.Sqlite"));
#else
throw new NotSupportedException (string.Format (format, "System.Data.SQLite"));
#endif
}
return new DefaultSecureMimeContext ();
#else
throw new NotSupportedException (string.Format (SubclassAndRegisterFormat, "MimeKit.Cryptography.SecureMimeContext"));
#endif
case "application/x-pgp-signature":
case "application/pgp-signature":
case "application/x-pgp-encrypted":
case "application/pgp-encrypted":
case "application/x-pgp-keys":
case "application/pgp-keys":
if (OpenPgpContextConstructor != null)
return (CryptographyContext) OpenPgpContextConstructor.Invoke (new object[0]);
throw new NotSupportedException (string.Format (SubclassAndRegisterFormat, "MimeKit.Cryptography.OpenPgpContext or MimeKit.Cryptography.GnuPGContext"));
default:
throw new NotSupportedException ();
}
}
}
#if PORTABLE
static ConstructorInfo GetConstructor (TypeInfo type)
{
foreach (var ctor in type.DeclaredConstructors) {
var args = ctor.GetParameters ();
if (args.Length != 0)
continue;
return ctor;
}
return null;
}
#endif
/// <summary>
/// Registers a default <see cref="SecureMimeContext"/> or <see cref="OpenPgpContext"/>.
/// </summary>
/// <remarks>
/// Registers the specified type as the default <see cref="SecureMimeContext"/> or
/// <see cref="OpenPgpContext"/>.
/// </remarks>
/// <param name="type">A custom subclass of <see cref="SecureMimeContext"/> or
/// <see cref="OpenPgpContext"/>.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="type"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="type"/> is not a subclass of
/// <see cref="SecureMimeContext"/> or <see cref="OpenPgpContext"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="type"/> does not have a parameterless constructor.</para>
/// </exception>
public static void Register (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
#if PORTABLE || COREFX
var info = type.GetTypeInfo ();
#else
var info = type;
#endif
#if PORTABLE
var ctor = GetConstructor (info);
#else
var ctor = type.GetConstructor (new Type[0]);
#endif
if (ctor == null)
throw new ArgumentException ("The specified type must have a parameterless constructor.", "type");
if (info.IsSubclassOf (typeof (SecureMimeContext))) {
lock (mutex) {
SecureMimeContextConstructor = ctor;
}
} else if (info.IsSubclassOf (typeof (OpenPgpContext))) {
lock (mutex) {
OpenPgpContextConstructor = ctor;
}
} else {
throw new ArgumentException ("The specified type must be a subclass of SecureMimeContext or OpenPgpContext.", "type");
}
}
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Windows.Data.Xml.Dom;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using Shield.Core;
using System.Diagnostics;
namespace Shield
{
public class Parser
{
public string Content { get; set; }
public string Instructions { get; set; }
public Dictionary<string, string> Dictionary => this.dictionary;
public bool IsDictionary { get; set; }
private XmlDocument doc;
private XmlNodeList nodes;
private Dictionary<string, string> dictionary = new Dictionary<string, string>();
private string keypart, valuepart;
public bool Parse()
{
var temp = this.Content;
var results = new List<string>();
var potentialResults = new Stack<string>();
var prefix = string.Empty;
var parses = Instructions.Split('|');
foreach (var parse in parses)
{
var colon = parse.IndexOf(':');
if (colon > -1)
{
var cmd = parse.Substring(0, colon);
var part = parse.Substring(colon + 1);
var save = cmd.Contains("?");
var nextToken = cmd.Contains("&");
var prefixed = cmd.Contains("+");
var restore = cmd.Contains("^");
if (nextToken)
{
results.Add(temp);
temp = "";
}
if (prefixed)
{
prefix += temp;
temp = string.Empty;
}
if (restore)
{
temp = potentialResults.Count > 0 ? potentialResults.Pop() : this.Content;
}
if (save)
{
potentialResults.Push(prefix + temp);
prefix = string.Empty;
}
var contains = temp.Contains(part);
if (cmd.Contains("i"))
{
if (!CheckDoc(temp))
{
return false;
}
nodes = doc.SelectNodes(part);
IsDictionary = true;
}
else if (cmd.Contains("k"))
{
keypart = part;
}
else if (cmd.Contains("v"))
{
valuepart = part;
}
else if (cmd.Contains("table") && nodes != null)
{
if (part.Contains("name="))
{
Tablename = part.Substring(part.IndexOf("name=") + 5);
var j = Tablename.IndexOf(";");
if (j > -1)
{
Tablename = Tablename.Substring(0, j);
}
}
foreach (var node in nodes)
{
IXmlNode key = null;
XmlNodeList valueset = null;
try
{
key = node.SelectSingleNode(keypart);
valueset = node.SelectNodes(valuepart);
}
catch (Exception)
{
//skip if not matching
continue;
}
if (!string.IsNullOrWhiteSpace(key?.InnerText))
{
if (!string.IsNullOrWhiteSpace(key.InnerText) && !dictionary.ContainsKey(key.InnerText))
{
var values = new StringBuilder();
var count = valueset.Count();
foreach (var value in valueset)
{
values.Append(value.InnerText);
if (--count > 0)
{
values.Append("~");
}
}
dictionary.Add(key.InnerText, values.ToString());
}
}
}
Debug.WriteLine(string.Format("Table {0} saved count = {1}", Tablename, dictionary.Count));
}
else if (cmd.Contains("R"))
{
temp = temp.RightOf(part);
}
else if (cmd.Contains("L"))
{
temp = temp.LeftOf(part);
}
else if (cmd.Contains("B"))
{
temp = temp.Between(part);
}
else if (cmd.Contains("!"))
{
temp = part;
}
else if (cmd.Contains("J") || cmd.Contains("j"))
{
var jParsed = JToken.Parse(temp);
if (jParsed != null)
{
var jToken = jParsed.SelectToken(part);
if (jToken != null)
{
if (cmd.Contains("j"))
{
temp = ((JProperty)jToken).Name;
if (cmd.Contains("J"))
{
temp += ":'" + jToken.Value<string>() + "'";
}
}
else
{
temp = jToken.Value<string>();
}
}
else
{
temp = string.Empty;
}
}
else
{
temp = string.Empty;
}
}
else if (cmd.Contains("X"))
{
var expr = new Regex(part);
var matches = expr.Match(part);
var matchResults = new StringBuilder();
while (matches.Success)
{
contains = true;
matchResults.Append(matches.Value);
matchResults.Append("~");
matches = matches.NextMatch();
}
temp = matchResults.ToString();
if (!string.IsNullOrWhiteSpace(temp))
{
temp = temp.Substring(0, temp.Length - 1);
}
}
else if (cmd.Contains("F"))
{
results.Add(prefix + temp);
prefix = string.Empty;
temp = string.Format(part, results.ToArray());
results.Clear();
}
if (save && !contains)
{
temp = potentialResults.Pop();
}
}
if (string.IsNullOrWhiteSpace(temp))
{
break;
}
}
if (!string.IsNullOrWhiteSpace(temp))
{
results.Add(prefix + temp);
prefix = string.Empty;
}
var builder = new StringBuilder();
for (var i = 0; i < results.Count; i++)
{
builder.Append(results[i]);
if (i < results.Count - 1)
{
builder.Append("|");
}
}
Result = builder.Length == 0 ? string.Empty : builder.ToString();
return true;
}
public string Tablename { get; set; }
public string Result { get; set; }
public bool CheckDoc(string temp)
{
if (doc != null) return true;
try
{
doc = new XmlDocument();
doc.LoadXml(temp);
}
catch (Exception) //backup leverage html agility pack
{
try
{
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(temp);
hdoc.OptionOutputAsXml = true;
hdoc.OptionAutoCloseOnEnd = true;
MemoryStream stream = new MemoryStream();
XmlWriter xtw = XmlWriter.Create(stream, new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment });
hdoc.Save(xtw);
stream.Position = 0;
doc.LoadXml((new System.IO.StreamReader(stream)).ReadToEnd());
}
catch (Exception)
{
return false;
}
}
return true;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// The Service Bus Management API is a REST API for managing Service Bus
/// queues, topics, rules and subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780776.aspx for
/// more information)
/// </summary>
public static partial class TopicOperationsExtensions
{
/// <summary>
/// Creates a new topic. Once created, this topic resource manifest is
/// immutable. This operation is not idempotent. Repeating the create
/// call, after a topic with same name has been created successfully,
/// will result in a 409 Conflict error message. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780728.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topic'>
/// Required. The Service Bus topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static ServiceBusTopicResponse Create(this ITopicOperations operations, string namespaceName, ServiceBusTopic topic)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).CreateAsync(namespaceName, topic);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new topic. Once created, this topic resource manifest is
/// immutable. This operation is not idempotent. Repeating the create
/// call, after a topic with same name has been created successfully,
/// will result in a 409 Conflict error message. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780728.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topic'>
/// Required. The Service Bus topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static Task<ServiceBusTopicResponse> CreateAsync(this ITopicOperations operations, string namespaceName, ServiceBusTopic topic)
{
return operations.CreateAsync(namespaceName, topic, CancellationToken.None);
}
/// <summary>
/// Deletes an existing topic. This operation will also remove all
/// associated state including associated subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/hh780721.aspx for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this ITopicOperations operations, string namespaceName, string topicName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).DeleteAsync(namespaceName, topicName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing topic. This operation will also remove all
/// associated state including associated subscriptions. (see
/// http://msdn.microsoft.com/en-us/library/hh780721.aspx for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this ITopicOperations operations, string namespaceName, string topicName)
{
return operations.DeleteAsync(namespaceName, topicName, CancellationToken.None);
}
/// <summary>
/// The topic description is an XML AtomPub document that defines the
/// desired semantics for a topic. The topic description contains the
/// following properties. For more information, see the
/// TopicDescription Properties topic. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static ServiceBusTopicResponse Get(this ITopicOperations operations, string namespaceName, string topicName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).GetAsync(namespaceName, topicName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The topic description is an XML AtomPub document that defines the
/// desired semantics for a topic. The topic description contains the
/// following properties. For more information, see the
/// TopicDescription Properties topic. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static Task<ServiceBusTopicResponse> GetAsync(this ITopicOperations operations, string namespaceName, string topicName)
{
return operations.GetAsync(namespaceName, topicName, CancellationToken.None);
}
/// <summary>
/// Gets the set of connection strings for a topic.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// The set of connection details for a service bus entity.
/// </returns>
public static ServiceBusConnectionDetailsResponse GetConnectionDetails(this ITopicOperations operations, string namespaceName, string topicName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).GetConnectionDetailsAsync(namespaceName, topicName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the set of connection strings for a topic.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topicName'>
/// Required. The topic.
/// </param>
/// <returns>
/// The set of connection details for a service bus entity.
/// </returns>
public static Task<ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(this ITopicOperations operations, string namespaceName, string topicName)
{
return operations.GetConnectionDetailsAsync(namespaceName, topicName, CancellationToken.None);
}
/// <summary>
/// Enumerates the topics in the service namespace. An empty feed is
/// returned if no topic exists in the service namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780744.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of topics.
/// </returns>
public static ServiceBusTopicsResponse List(this ITopicOperations operations, string namespaceName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).ListAsync(namespaceName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enumerates the topics in the service namespace. An empty feed is
/// returned if no topic exists in the service namespace. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/hh780744.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <returns>
/// A response to a request for a list of topics.
/// </returns>
public static Task<ServiceBusTopicsResponse> ListAsync(this ITopicOperations operations, string namespaceName)
{
return operations.ListAsync(namespaceName, CancellationToken.None);
}
/// <summary>
/// Updates a topic. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topic'>
/// Required. The Service Bus topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static ServiceBusTopicResponse Update(this ITopicOperations operations, string namespaceName, ServiceBusTopic topic)
{
return Task.Factory.StartNew((object s) =>
{
return ((ITopicOperations)s).UpdateAsync(namespaceName, topic);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a topic. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ITopicOperations.
/// </param>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='topic'>
/// Required. The Service Bus topic.
/// </param>
/// <returns>
/// A response to a request for a particular topic.
/// </returns>
public static Task<ServiceBusTopicResponse> UpdateAsync(this ITopicOperations operations, string namespaceName, ServiceBusTopic topic)
{
return operations.UpdateAsync(namespaceName, topic, CancellationToken.None);
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using OpenSource.UPnP;
using System.Threading;
using OpenSource.UPnP.AV;
using System.Collections;
using OpenSource.Utilities;
using System.Globalization;
using System.Text.RegularExpressions;
namespace OpenSource.UPnP.AV.CdsMetadata
{
/// <summary>
/// This class is a helper class for sorting ContentDirectory entries for an XML response.
/// Its function is to compare the values of a media entry's xml element or attribute.
/// By default, the class only compares the first value within a set of acceptable properties.
/// If the values match, then does the next value get compared. If all values of a property set
/// match then the result comparison is 0.
/// </summary>
public class MetadataValueComparer : IComparer
{
/// <summary>
/// Instantiates a MetadataValueComparer with a metadata property name
/// (easily retrieved from using <see cref="Tags"/>'s indexer with the
/// <see cref="CommonPropertyNames"/>,
/// <see cref="_DC"/>,
/// <see cref="_UPNP"/>, or
/// <see cref="_ATTRIB"/>
/// enumerators)
/// and an indication if the results should compare in ascending or descending order.
/// </summary>
/// <param name="property">metadata property name</param>
/// <param name="ascending">true, if Compare results are ascending order</param>
public MetadataValueComparer (string property, bool ascending)
{
this.m_Ascending = ascending;
this.m_TE = new TagExtractor(property);
}
/// <summary>
/// This compares two <see cref="IUPnPMedia"/> objects
/// and compares them based on the values of a single property name
/// (supplied at construction time).
/// </summary>
/// <param name="m1"><see cref="IUPnPMedia"/></param>
/// <param name="m2"><see cref="IUPnPMedia"/></param>
/// <returns>comparison result with ascending or descending flag taken into account: 0, 1, -1 </returns>
public int Compare (object m1, object m2)
{
IUPnPMedia e1 = (IUPnPMedia) m1;
IUPnPMedia e2 = (IUPnPMedia) m2;
IList vals1 = this.m_TE.Extract(e1);
IList vals2 = this.m_TE.Extract(e2);
try
{
int i = 0;
int max = Math.Min(vals1.Count, vals2.Count);
while (i < max)
{
object obj1 = vals1[i];
object obj2 = vals2[i];
int cmp;
try
{
cmp = CompareObject(obj1, obj2, false);
}
catch (Exception e)
{
throw new Exception("MetadataValueComparer.Compare() error", e);
}
if (cmp != 0)
{
if (this.m_Ascending == false)
{
cmp = cmp * -1;
}
return cmp;
}
i++;
}
}
catch (Exception e)
{
throw new Exception("MetadataValueComparer.Compare() error", e);
}
// If we get here, then all values matched...
// so use the difference of the number of
// values to determine comparison result.
int diff = vals1.Count - vals2.Count;
if (this.m_Ascending == false)
{
diff = diff * -1;
}
return diff;
}
/// <summary>
/// This method is useful if metadata values are already obtained and a
/// comparison is needed. The method compares val1 against val2.
/// If the types don't match, then the type of val1 is
/// used to determine the semantics of val2, and an attempt
/// to cast val2 into the same type of val1 is made. This is useful
/// when val1 is a uri/number and val2 is a string.
/// </summary>
/// <param name="val1">a value of some type</param>
/// <param name="val2">another value of the same type, or a string that can be cast into the type of val1</param>
/// <param name="ignoreCase">indicates if we should ignore the case for text-related comparisons</param>
/// <returns>a comparison result: 0, 1, -1</returns>
public static int CompareTagValues(object val1, object val2, bool ignoreCase)
{
string type1 = val1.GetType().ToString();
string type2 = val2.GetType().ToString();
object v1 = val1;
object v2 = val2;
if (type1 != type2)
{
// If the data types for the two objects don't match
// I do my best to convert the second object
// into a data type of the first object.
string strval2 = val2.ToString();
switch (type1)
{
case "System.Char":
v2 = strval2[0];
break;
case "System.String":
v2 = strval2;
break;
case "System.Boolean":
if ((strval2 == "0") || (strval2 == "no"))
{
v2 = false;
}
else if ((strval2 == "1") || (strval2 == "yes"))
{
v2 = true;
}
else
{
try
{
v2 = bool.Parse(strval2);
}
catch
{
v2 = strval2;
}
}
break;
case "System.Uri":
//Uri is an exception - we'll always compare as a string.
v2 = strval2;
break;
case "System.Byte":
v2 = byte.Parse(strval2);
break;
case "System.UInt16":
v2 = UInt16.Parse(strval2);
break;
case "System.UInt32":
v2 = UInt32.Parse(strval2);
break;
case "System.Int32":
v2 = Int32.Parse(strval2);
break;
case "System.Int16":
v2 = Int16.Parse(strval2);
break;
case "System.SByte":
v2 = sbyte.Parse(strval2);
break;
case "System.Single":
v2 = Single.Parse(strval2);
break;
case "System.Double":
v2 = Double.Parse(strval2);
break;
case "System.DateTime":
DateTimeFormatInfo formatInfo = PropertyDateTime.GetFormatInfo();
v2 = DateTime.Parse(strval2, formatInfo);
break;
default:
throw new Exception("Cannot recast object of " + type2 + " into object of " + type1);
}
}
return CompareObject(v1, v2, ignoreCase);
}
/// <summary>
/// Implements the core logic for comparing two objects of the same primitive type.
/// If the objects are not of a primitive type, then the ToString() operation
/// is used and then the comparison is made.
/// </summary>
/// <param name="obj1">object with value</param>
/// <param name="obj2">object with value</param>
/// <param name="ignoreCase">indicates if we should ignore the case for text-related comparisons</param>
/// <returns>comparison result: 0, 1, -1</returns>
private static int CompareObject(object obj1, object obj2, bool ignoreCase)
{
if ((obj1 == null) && (obj2 == null))
{
return 0;
}
else if ((obj1 != null) && (obj2 == null))
{
return 1;
}
else if ((obj1 == null) && (obj2 != null))
{
return -1;
}
Type t1 = obj1.GetType();
Type t2 = obj1.GetType();
string type1 = t1.ToString();
string type2 = t2.ToString();
if (type1 != type2)
{
throw new Exception("Cannot compare 2 values with a different data type.");
}
switch (type1)
{
case "System.Char":
char v1 = (char) obj1;
char v2 = (char) obj2;
if (v1 == v2) return 0;
if (v1 > v2) return 1;
if (v1 < v2) return -1;
break;
case "System.String":
string s1 = obj1.ToString();
string s2 = obj2.ToString();
int cmps = string.Compare(s1, s2, ignoreCase);
return cmps;
case "System.Boolean":
bool b1 = (bool) obj1;
bool b2 = (bool) obj2;
if (b1 == b2) return 0;
if (b1) return 1;
if (b2) return -1;
break;
case "System.Uri":
string u1 = obj1.ToString();
string u2 = obj2.ToString();
int cmp = string.Compare(u1, u2, ignoreCase);
return cmp;
case "System.Byte":
byte byte1 = (byte) obj1;
byte byte2 = (byte) obj2;
if (byte1 == byte2) return 0;
if (byte1 > byte2) return 1;
if (byte1 < byte2) return -1;
break;
case "System.UInt16":
UInt16 ui16_1 = (UInt16) obj1;
UInt16 ui16_2 = (UInt16) obj2;
if (ui16_1 == ui16_2) return 0;
if (ui16_1 > ui16_2) return 1;
if (ui16_1 < ui16_2) return -1;
break;
case "System.UInt32":
UInt32 ui32_1 = (UInt32) obj1;
UInt32 ui32_2 = (UInt32) obj2;
if (ui32_1 == ui32_2) return 0;
if (ui32_1 > ui32_2) return 1;
if (ui32_1 < ui32_2) return -1;
break;
case "System.Int32":
Int32 i32_v1 = (Int32) obj1;
Int32 i32_v2 = (Int32) obj2;
if (i32_v1 == i32_v2) return 0;
if (i32_v1 > i32_v2) return 1;
if (i32_v1 < i32_v2) return -1;
break;
case "System.Int16":
Int16 i16_v1 = (Int16) obj1;
Int16 i16_v2 = (Int16) obj2;
if (i16_v1 == i16_v2) return 0;
if (i16_v1 > i16_v2) return 1;
if (i16_v1 < i16_v2) return -1;
break;
case "System.SByte":
sbyte sb_v1 = (sbyte) obj1;
sbyte sb_v2 = (sbyte) obj2;
if (sb_v1 == sb_v2) return 0;
if (sb_v1 > sb_v2) return 1;
if (sb_v1 < sb_v2) return -1;
break;
case "System.Single":
Single s_v1 = (Single) obj1;
Single s_v2 = (Single) obj2;
if (s_v1 == s_v2) return 0;
if (s_v1 > s_v2) return 1;
if (s_v1 < s_v2) return -1;
break;
case "System.Double":
Double d_v1 = (Double) obj1;
Double d_v2 = (Double) obj2;
if (d_v1 == d_v2) return 0;
if (d_v1 > d_v2) return 1;
if (d_v1 < d_v2) return -1;
break;
case "System.DateTime":
DateTime dt1 = (DateTime) obj1;
DateTime dt2 = (DateTime) obj2;
if (dt1.Ticks == dt2.Ticks) return 0;
if (dt1.Ticks > dt2.Ticks) return 1;
if (dt1.Ticks < dt2.Ticks) return -1;
break;
default:
//throw new Exception("Cannot compare objects of type " + type1);
IComparable comparable1 = obj1 as IComparable;
IComparable comparable2 = obj2 as IComparable;
if (comparable1 != null)
{
if (comparable2 != null)
{
return comparable1.CompareTo(comparable2);
}
}
string default1 = obj1.ToString();
string default2 = obj2.ToString();
int def_cmps = string.Compare(default1, default2, ignoreCase);
return def_cmps;
}
return 0;
}
/// <summary>
/// Indicates if the results should be ascending or descending.
/// </summary>
public readonly bool m_Ascending = false;
/// <summary>
/// Extracts the metadata values for a given property name or attribute.
/// </summary>
private TagExtractor m_TE;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Permissions bitflags
/// </summary>
/*
[Flags]
public enum PermissionMask : uint
{
None = 0,
Transfer = 1 << 13,
Modify = 1 << 14,
Copy = 1 << 15,
Move = 1 << 19,
Damage = 1 << 20,
All = 0x7FFFFFFF
}
*/
/// <summary>
/// Connects avatar inventories to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianInventoryServiceConnector")]
public class SimianInventoryServiceConnector : IInventoryService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// private object m_gestureSyncRoot = new object();
private bool m_Enabled = false;
private string m_serverUrl = String.Empty;
private string m_userServerUrl = String.Empty;
#region ISharedRegionModule
public SimianInventoryServiceConnector()
{
}
public string Name { get { return "SimianInventoryServiceConnector"; } }
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
if (m_Enabled) { scene.RegisterModuleInterface<IInventoryService>(this); }
}
public void Close()
{
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled) { scene.UnregisterModuleInterface<IInventoryService>(this); }
}
#endregion ISharedRegionModule
public SimianInventoryServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public SimianInventoryServiceConnector(string url)
{
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + '/';
m_serverUrl = url;
}
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddInventoryFolder" },
{ "FolderID", folder.ID.ToString() },
{ "ParentID", folder.ParentID.ToString() },
{ "OwnerID", folder.Owner.ToString() },
{ "Name", folder.Name },
{ "ContentType", SLUtil.SLAssetTypeToContentType(folder.Type) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error creating folder " + folder.Name + " for " + folder.Owner + ": " +
response["Message"].AsString());
}
return success;
}
/// <summary>
/// Add a new item to the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully added</returns>
public bool AddItem(InventoryItemBase item)
{
// A folder of UUID.Zero means we need to find the most appropriate home for this item
if (item.Folder == UUID.Zero)
{
InventoryFolderBase folder = GetFolderForType(item.Owner, (AssetType)item.AssetType);
if (folder != null && folder.ID != UUID.Zero)
item.Folder = folder.ID;
else
item.Folder = item.Owner; // Root folder
}
if ((AssetType)item.AssetType == AssetType.Gesture)
UpdateGesture(item.Owner, item.ID, item.Flags == 1);
if (item.BasePermissions == 0)
m_log.WarnFormat("[SIMIAN INVENTORY CONNECTOR]: Adding inventory item {0} ({1}) with no base permissions", item.Name, item.ID);
OSDMap permissions = new OSDMap
{
{ "BaseMask", OSD.FromInteger(item.BasePermissions) },
{ "EveryoneMask", OSD.FromInteger(item.EveryOnePermissions) },
{ "GroupMask", OSD.FromInteger(item.GroupPermissions) },
{ "NextOwnerMask", OSD.FromInteger(item.NextPermissions) },
{ "OwnerMask", OSD.FromInteger(item.CurrentPermissions) }
};
OSDMap extraData = new OSDMap()
{
{ "Flags", OSD.FromInteger(item.Flags) },
{ "GroupID", OSD.FromUUID(item.GroupID) },
{ "GroupOwned", OSD.FromBoolean(item.GroupOwned) },
{ "SalePrice", OSD.FromInteger(item.SalePrice) },
{ "SaleType", OSD.FromInteger(item.SaleType) },
{ "Permissions", permissions }
};
// Add different asset type only if it differs from inventory type
// (needed for links)
string invContentType = SLUtil.SLInvTypeToContentType(item.InvType);
string assetContentType = SLUtil.SLAssetTypeToContentType(item.AssetType);
if (invContentType != assetContentType)
extraData["LinkedItemType"] = OSD.FromString(assetContentType);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddInventoryItem" },
{ "ItemID", item.ID.ToString() },
{ "AssetID", item.AssetID.ToString() },
{ "ParentID", item.Folder.ToString() },
{ "OwnerID", item.Owner.ToString() },
{ "Name", item.Name },
{ "Description", item.Description },
{ "CreatorID", item.CreatorId },
{ "CreatorData", item.CreatorData },
{ "ContentType", invContentType },
{ "ExtraData", OSDParser.SerializeJsonString(extraData) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error creating item " + item.Name + " for " + item.Owner + ": " +
response["Message"].AsString());
}
return success;
}
/// <summary>
/// Create the entire inventory for a given user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public bool CreateUserInventory(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddInventory" },
{ "OwnerID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Inventory creation for " + userID + " failed: " + response["Message"].AsString());
return success;
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
//bool DeleteItem(InventoryItemBase item);
public bool DeleteFolders(UUID userID, List<UUID> folderIDs)
{
return DeleteItems(userID, folderIDs);
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public bool DeleteItems(UUID userID, List<UUID> itemIDs)
{
// TODO: RemoveInventoryNode should be replaced with RemoveInventoryNodes
bool allSuccess = true;
for (int i = 0; i < itemIDs.Count; i++)
{
UUID itemID = itemIDs[i];
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveInventoryNode" },
{ "OwnerID", userID.ToString() },
{ "ItemID", itemID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error removing item " + itemID + " for " + userID + ": " +
response["Message"].AsString());
allSuccess = false;
}
}
return allSuccess;
}
/// <summary>
/// Get the active gestures of the agent.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public List<InventoryItemBase> GetActiveGestures(UUID userID)
{
OSDArray items = FetchGestures(userID);
string[] itemIDs = new string[items.Count];
for (int i = 0; i < items.Count; i++)
itemIDs[i] = items[i].AsUUID().ToString();
// NameValueCollection requestArgs = new NameValueCollection
// {
// { "RequestMethod", "GetInventoryNodes" },
// { "OwnerID", userID.ToString() },
// { "Items", String.Join(",", itemIDs) }
// };
// FIXME: Implement this in SimianGrid
return new List<InventoryItemBase>(0);
}
/// <summary>
/// Get a folder, given by its UUID
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", folder.ID.ToString() },
{ "OwnerID", folder.Owner.ToString() },
{ "IncludeFolders", "1" },
{ "IncludeItems", "0" },
{ "ChildrenOnly", "1" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
OSDArray items = (OSDArray)response["Items"];
List<InventoryFolderBase> folders = GetFoldersFromResponse(items, folder.ID, true);
if (folders.Count > 0)
return folders[0];
}
return null;
}
/// <summary>
/// Gets everything (folders and items) inside a folder
/// </summary>
/// <param name="userID"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.UserID = userID;
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", folderID.ToString() },
{ "OwnerID", userID.ToString() },
{ "IncludeFolders", "1" },
{ "IncludeItems", "1" },
{ "ChildrenOnly", "1" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
OSDArray items = (OSDArray)response["Items"];
inventory.Folders = GetFoldersFromResponse(items, folderID, false);
inventory.Items = GetItemsFromResponse(items);
}
else
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error fetching folder " + folderID + " content for " + userID + ": " +
response["Message"].AsString());
inventory.Folders = new List<InventoryFolderBase>(0);
inventory.Items = new List<InventoryItemBase>(0);
}
return inventory;
}
/// <summary>
/// Gets the user folder for the given folder-type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
string contentType = SLUtil.SLAssetTypeToContentType((int)type);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetFolderForType" },
{ "ContentType", contentType },
{ "OwnerID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Folder"] is OSDMap)
{
OSDMap folder = (OSDMap)response["Folder"];
return new InventoryFolderBase(
folder["ID"].AsUUID(),
folder["Name"].AsString(),
folder["OwnerID"].AsUUID(),
(short)SLUtil.ContentTypeToSLAssetType(folder["ContentType"].AsString()),
folder["ParentID"].AsUUID(),
(ushort)folder["Version"].AsInteger()
);
}
else
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Default folder not found for content type " + contentType + ": " + response["Message"].AsString());
return GetRootFolder(userID);
}
}
/// <summary>
/// Gets the items inside a folder
/// </summary>
/// <param name="userID"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
InventoryCollection inventory = new InventoryCollection();
inventory.UserID = userID;
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", folderID.ToString() },
{ "OwnerID", userID.ToString() },
{ "IncludeFolders", "0" },
{ "IncludeItems", "1" },
{ "ChildrenOnly", "1" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
OSDArray items = (OSDArray)response["Items"];
return GetItemsFromResponse(items);
}
else
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error fetching folder " + folderID + " for " + userID + ": " +
response["Message"].AsString());
return new List<InventoryItemBase>(0);
}
}
/// <summary>
/// Gets the skeleton of the inventory -- folders only
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public List<InventoryFolderBase> GetInventorySkeleton(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", userID.ToString() },
{ "OwnerID", userID.ToString() },
{ "IncludeFolders", "1" },
{ "IncludeItems", "0" },
{ "ChildrenOnly", "0" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
OSDArray items = (OSDArray)response["Items"];
return GetFoldersFromResponse(items, userID, true);
}
else
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Failed to retrieve inventory skeleton for " + userID + ": " +
response["Message"].AsString());
return new List<InventoryFolderBase>(0);
}
}
/// <summary>
/// Get an item, given by its UUID
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public InventoryItemBase GetItem(InventoryItemBase item)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", item.ID.ToString() },
{ "OwnerID", item.Owner.ToString() },
{ "IncludeFolders", "1" },
{ "IncludeItems", "1" },
{ "ChildrenOnly", "1" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
List<InventoryItemBase> items = GetItemsFromResponse((OSDArray)response["Items"]);
if (items.Count > 0)
{
// The requested item should be the first in this list, but loop through
// and sanity check just in case
for (int i = 0; i < items.Count; i++)
{
if (items[i].ID == item.ID)
return items[i];
}
}
}
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Item " + item.ID + " owned by " + item.Owner + " not found");
return null;
}
/// <summary>
/// Retrieve the root inventory folder for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
public InventoryFolderBase GetRootFolder(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetInventoryNode" },
{ "ItemID", userID.ToString() },
{ "OwnerID", userID.ToString() },
{ "IncludeFolders", "1" },
{ "IncludeItems", "0" },
{ "ChildrenOnly", "1" }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["Items"] is OSDArray)
{
OSDArray items = (OSDArray)response["Items"];
List<InventoryFolderBase> folders = GetFoldersFromResponse(items, userID, true);
if (folders.Count > 0)
return folders[0];
}
return null;
}
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID)
{
return GetRootFolder(userID) != null;
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
CommonInit(source);
}
}
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder)
{
return AddFolder(folder);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
bool success = true;
while (items.Count > 0)
{
List<InventoryItemBase> currentItems = new List<InventoryItemBase>();
UUID destFolderID = items[0].Folder;
// Find all of the items being moved to the current destination folder
for (int i = 0; i < items.Count; i++)
{
InventoryItemBase item = items[i];
if (item.Folder == destFolderID)
currentItems.Add(item);
}
// Do the inventory move for the current items
success &= MoveItems(ownerID, items, destFolderID);
// Remove the processed items from the list
for (int i = 0; i < currentItems.Count; i++)
items.Remove(currentItems[i]);
}
return success;
}
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "PurgeInventoryFolder" },
{ "OwnerID", folder.Owner.ToString() },
{ "FolderID", folder.ID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Error purging folder " + folder.ID + " for " + folder.Owner + ": " +
response["Message"].AsString());
}
return success;
}
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder)
{
return AddFolder(folder);
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item)
{
if (item.AssetID != UUID.Zero)
{
return AddItem(item);
}
else
{
// This is actually a folder update
InventoryFolderBase folder = new InventoryFolderBase(item.ID, item.Name, item.Owner, (short)item.AssetType, item.Folder, 0);
return UpdateFolder(folder);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["InventoryService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("InventoryServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
gridConfig = source.Configs["UserAccountService"];
if (gridConfig != null)
{
serviceUrl = gridConfig.GetString("UserAccountServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
m_userServerUrl = serviceUrl;
m_Enabled = true;
}
}
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN INVENTORY CONNECTOR]: No InventoryServerURI specified, disabling connector");
else if (String.IsNullOrEmpty(m_userServerUrl))
m_log.Info("[SIMIAN INVENTORY CONNECTOR]: No UserAccountServerURI specified, disabling connector");
}
private OSDArray FetchGestures(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_userServerUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap user = response["User"] as OSDMap;
if (user != null && response.ContainsKey("Gestures"))
{
OSD gestures = OSDParser.DeserializeJson(response["Gestures"].AsString());
if (gestures != null && gestures is OSDArray)
return (OSDArray)gestures;
else
m_log.Error("[SIMIAN INVENTORY CONNECTOR]: Unrecognized active gestures data for " + userID);
}
}
else
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Failed to fetch active gestures for " + userID + ": " +
response["Message"].AsString());
}
return new OSDArray();
}
private List<InventoryFolderBase> GetFoldersFromResponse(OSDArray items, UUID baseFolder, bool includeBaseFolder)
{
List<InventoryFolderBase> invFolders = new List<InventoryFolderBase>(items.Count);
for (int i = 0; i < items.Count; i++)
{
OSDMap item = items[i] as OSDMap;
if (item != null && item["Type"].AsString() == "Folder")
{
UUID folderID = item["ID"].AsUUID();
if (folderID == baseFolder && !includeBaseFolder)
continue;
invFolders.Add(new InventoryFolderBase(
folderID,
item["Name"].AsString(),
item["OwnerID"].AsUUID(),
(short)SLUtil.ContentTypeToSLAssetType(item["ContentType"].AsString()),
item["ParentID"].AsUUID(),
(ushort)item["Version"].AsInteger()
));
}
}
// m_log.Debug("[SIMIAN INVENTORY CONNECTOR]: Parsed " + invFolders.Count + " folders from SimianGrid response");
return invFolders;
}
private List<InventoryItemBase> GetItemsFromResponse(OSDArray items)
{
List<InventoryItemBase> invItems = new List<InventoryItemBase>(items.Count);
for (int i = 0; i < items.Count; i++)
{
OSDMap item = items[i] as OSDMap;
if (item != null && item["Type"].AsString() == "Item")
{
InventoryItemBase invItem = new InventoryItemBase();
invItem.AssetID = item["AssetID"].AsUUID();
invItem.AssetType = SLUtil.ContentTypeToSLAssetType(item["ContentType"].AsString());
invItem.CreationDate = item["CreationDate"].AsInteger();
invItem.CreatorId = item["CreatorID"].AsString();
invItem.CreatorData = item["CreatorData"].AsString();
invItem.Description = item["Description"].AsString();
invItem.Folder = item["ParentID"].AsUUID();
invItem.ID = item["ID"].AsUUID();
invItem.InvType = SLUtil.ContentTypeToSLInvType(item["ContentType"].AsString());
invItem.Name = item["Name"].AsString();
invItem.Owner = item["OwnerID"].AsUUID();
OSDMap extraData = item["ExtraData"] as OSDMap;
if (extraData != null && extraData.Count > 0)
{
invItem.Flags = extraData["Flags"].AsUInteger();
invItem.GroupID = extraData["GroupID"].AsUUID();
invItem.GroupOwned = extraData["GroupOwned"].AsBoolean();
invItem.SalePrice = extraData["SalePrice"].AsInteger();
invItem.SaleType = (byte)extraData["SaleType"].AsInteger();
OSDMap perms = extraData["Permissions"] as OSDMap;
if (perms != null)
{
invItem.BasePermissions = perms["BaseMask"].AsUInteger();
invItem.CurrentPermissions = perms["OwnerMask"].AsUInteger();
invItem.EveryOnePermissions = perms["EveryoneMask"].AsUInteger();
invItem.GroupPermissions = perms["GroupMask"].AsUInteger();
invItem.NextPermissions = perms["NextOwnerMask"].AsUInteger();
}
if (extraData.ContainsKey("LinkedItemType"))
invItem.AssetType = SLUtil.ContentTypeToSLAssetType(extraData["LinkedItemType"].AsString());
}
if (invItem.BasePermissions == 0)
{
m_log.InfoFormat("[SIMIAN INVENTORY CONNECTOR]: Forcing item permissions to full for item {0} ({1})",
invItem.Name, invItem.ID);
invItem.BasePermissions = (uint)PermissionMask.All;
invItem.CurrentPermissions = (uint)PermissionMask.All;
invItem.EveryOnePermissions = (uint)PermissionMask.All;
invItem.GroupPermissions = (uint)PermissionMask.All;
invItem.NextPermissions = (uint)PermissionMask.All;
}
invItems.Add(invItem);
}
}
// m_log.Debug("[SIMIAN INVENTORY CONNECTOR]: Parsed " + invItems.Count + " items from SimianGrid response");
return invItems;
}
private bool MoveItems(UUID ownerID, List<InventoryItemBase> items, UUID destFolderID)
{
string[] itemIDs = new string[items.Count];
for (int i = 0; i < items.Count; i++)
itemIDs[i] = items[i].ID.ToString();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "MoveInventoryNodes" },
{ "OwnerID", ownerID.ToString() },
{ "FolderID", destFolderID.ToString() },
{ "Items", String.Join(",", itemIDs) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Failed to move " + items.Count + " items to " +
destFolderID + ": " + response["Message"].AsString());
}
return success;
}
private void SaveGestures(UUID userID, OSDArray gestures)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "Gestures", OSDParser.SerializeJsonString(gestures) }
};
OSDMap response = SimianGrid.PostToService(m_userServerUrl, requestArgs);
if (!response["Success"].AsBoolean())
{
m_log.Warn("[SIMIAN INVENTORY CONNECTOR]: Failed to save active gestures for " + userID + ": " +
response["Message"].AsString());
}
}
private void UpdateGesture(UUID userID, UUID itemID, bool enabled)
{
OSDArray gestures = FetchGestures(userID);
OSDArray newGestures = new OSDArray();
for (int i = 0; i < gestures.Count; i++)
{
UUID gesture = gestures[i].AsUUID();
if (gesture != itemID)
newGestures.Add(OSD.FromUUID(gesture));
}
if (enabled)
newGestures.Add(OSD.FromUUID(itemID));
SaveGestures(userID, newGestures);
}
}
}
| |
// created on 1/6/2002 at 22:27
// Npgsql.PGUtil.cs
//
// Author:
// Francisco Jr. (fxjrlists@yahoo.com.br)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Text;
namespace Revenj.DatabasePersistence.Postgres.Npgsql
{
///<summary>
/// This class provides many util methods to handle
/// reading and writing of PostgreSQL protocol messages.
/// </summary>
internal static class PGUtil
{
// Logging related values
//TODO: What should this value be?
//There is an obvious balancing act in setting this value. The larger the value, the fewer times
//we need to use it and the more efficient we are in that regard. The smaller the value, the
//less space is used, and the more efficient we are in that regard.
//Multiples of memory page size are often good, which tends to be 4096 (4kB) and hence 4096 is
//often used for cases like this (e.g. the default size of the buffer in System.IO.BufferedStream).
//This is hard to guess, and even harder to guess if any overhead will be involved making a value
//of 4096 * x - overhead the real ideal with this approach.
//If this buffer were per-instance in a non-static class then 4096 would probably be the one to go for,
//but since this buffer is shared we can perhaps afford to go a bit larger.
//
//Another potentially useful value, since we will be using a network stream which in turn is using
//a TCP/IP stream, is the size of the TCP/IP window. This is even harder to predict than
//memory page size, but is likely to be 1460 * 44 = 64240. It could be lower or higher but experimentation
//shows that on at least the experimentation machine (.NET on WindowsXP, connecting to postgres server on
//localhost) if more than 64240 was available only 64240 would be used in each pass), so for at least
//that machine anything higher than 64240 is a waste.
//64240 being a bit much, settling for 4096 for now.
private const int THRASH_CAN_SIZE = 4096;
//This buffer array is used for reading and ignoring bytes we want to discard.
//It is thread-safe solely because it is never read from!
//Any attempt to read from this array deserves to fail.
//Note that in the cases where we are reading bytes to actually process them, we either
//have a buffer supplied from elsewhere (the calling method) or we create a small buffer
//as needed. This is since the buffer being used means that there that the possible performance
//gain of not creating a new buffer will be cancelled out by whatever buffering will have to be
//done to actually use the data. This is not the case here - we are pre-assigning a buffer for
//this case purely because we don't care what gets put into it.
private static readonly byte[] THRASH_CAN = new byte[THRASH_CAN_SIZE];
private static readonly Encoding ENCODING_UTF8 = Encoding.UTF8;
private static readonly string NULL_TERMINATOR_STRING = '\x00'.ToString();
/// <summary>
/// This method takes a version string as returned by SELECT VERSION() and returns
/// a valid version string ("7.2.2" for example).
/// This is only needed when running protocol version 2.
/// This does not do any validity checks.
/// </summary>
public static string ExtractServerVersion(string VersionString)
{
Int32 Start = 0, End = 0;
// find the first digit and assume this is the start of the version number
for (; Start < VersionString.Length && !char.IsDigit(VersionString[Start]); Start++)
{
;
}
End = Start;
// read until hitting whitespace, which should terminate the version number
for (; End < VersionString.Length && !char.IsWhiteSpace(VersionString[End]); End++)
{
;
}
// Deal with this here so that if there are
// changes in a future backend version, we can handle it here in the
// protocol handler and leave everybody else put of it.
VersionString = VersionString.Substring(Start, End - Start + 1);
for (int idx = 0; idx != VersionString.Length; ++idx)
{
char c = VersionString[idx];
if (!char.IsDigit(c) && c != '.')
{
VersionString = VersionString.Substring(0, idx);
break;
}
}
return VersionString;
}
///<summary>
/// This method gets a C NULL terminated string from the network stream.
/// It keeps reading a byte in each time until a NULL byte is returned.
/// It returns the resultant string of bytes read.
/// This string is sent from backend.
/// </summary>
public static String ReadString(Stream network_stream, ByteBuffer buffer)
{
buffer.Reset();
int bRead;
for (bRead = network_stream.ReadByte(); bRead > 0; bRead = network_stream.ReadByte())
{
buffer.Add((byte)bRead);
}
if (bRead == -1)
{
throw new IOException();
}
return buffer.GetUtf8String();
}
public static char ReadChar(Stream stream, byte[] buffer)
{
for (int i = 0; i != 4; ++i)
{
int byteRead = stream.ReadByte();
if (byteRead == -1)
{
throw new EndOfStreamException();
}
buffer[i] = (byte)byteRead;
if (ValidUTF8Ending(buffer, 0, i + 1)) //catch multi-byte encodings where we have not yet enough bytes.
{
return ENCODING_UTF8.GetChars(buffer)[0];
}
}
throw new InvalidDataException();
}
public static int ReadChars(Stream stream, char[] output, int maxChars, ref int maxRead, int outputIdx)
{
if (maxChars == 0 || maxRead == 0)
{
return 0;
}
byte[] buffer = new byte[Math.Min(maxRead, maxChars * 4)];
int bytesSoFar = 0;
int charsSoFar = 0;
//A string of x chars length will take at least x bytes and at most
//4x. We set our buffer to 4x in size, but start with only reading x bytes.
//If we don't have the full string at this point, then we now have a new number
//of characters to read, and so we try to read one byte per character remaining to read.
//This hence involves the fewest possible number of passes through CheckedStreamRead
//without the risk of accidentally reading too far into the stream.
do
{
int toRead = Math.Min(maxRead, maxChars - charsSoFar);
CheckedStreamRead(stream, buffer, bytesSoFar, toRead);
maxRead -= toRead;
bytesSoFar += toRead;
}
while (maxRead > 0 && (charsSoFar = PessimisticGetCharCount(buffer, 0, bytesSoFar)) < maxChars);
return ENCODING_UTF8.GetDecoder().GetChars(buffer, 0, bytesSoFar, output, outputIdx, false);
}
public static int SkipChars(Stream stream, int maxChars, ref int maxRead)
{
//This is the same as ReadChars, but it just discards the characters read.
if (maxChars == 0 || maxRead == 0)
{
return 0;
}
byte[] buffer = new byte[Math.Min(maxRead, ENCODING_UTF8.GetMaxByteCount(maxChars))];
int bytesSoFar = 0;
int charsSoFar = 0;
do
{
int toRead = Math.Min(maxRead, maxChars - charsSoFar);
CheckedStreamRead(stream, buffer, bytesSoFar, toRead);
maxRead -= toRead;
bytesSoFar += toRead;
}
while (maxRead > 0 && (charsSoFar = PessimisticGetCharCount(buffer, 0, bytesSoFar)) < maxChars);
return charsSoFar;
}
// Encoding.GetCharCount will count an incomplete character as a character.
// This makes sense if the user wants to assign a char[] buffer, since the incomplete character
// might be represented as U+FFFD or a similar approach may be taken.
// It's not much use though if we know the stream has >= x characters in it and we
// want to read x complete characters - we need to know that the last character is complete.
// Therefore we need to check on this.
// SECURITY CONSIDERATIONS:
// This function assumes we recieve valid UTF-8 data and as such security considerations
// must be noticed.
// In the case of deliberate mal-formed UTF-8 data, this function will not be used
// in it's interpretation. In the worse case it will result in the stream being mis-read
// and the operation malfunctioning, but anyone who is acting as a man-in-the-middle
// on the stream can already do that to us in a variety of interesting ways, so this
// function does not introduce a security issue in this regard.
// Therefore the optimisation of assuming valid UTF-8 data is reasonable and not insecure.
public static bool ValidUTF8Ending(byte[] buffer, int index, int count)
{
if (count <= 0)
{
return false;
}
byte examine = buffer[index + count - 1];
//simplest case and also the most common with most data- a single-octet character. Handle directly.
if ((examine & 0x80) == 0)
{
return true;
}
//if the last byte isn't a trailing byte we're clearly not at the end.
if ((examine & 0xC0) != 0x80)
{
return false;
}
byte[] masks = new byte[] { 0xE0, 0xF0, 0xF8 };
byte[] matches = new byte[] { 0xC0, 0xE0, 0xF0 };
for (int i = 0; i + 2 <= count; ++i)
{
examine = buffer[index + count - 2 - i];
if ((examine & masks[i]) == matches[i])
{
return true;
}
if ((examine & 0xC0) != 0x80)
{
return false;
}
}
return false;
}
/// <summary>
/// Reads requested number of bytes from stream with retries until Stream.Read returns 0 or count is reached.
/// </summary>
/// <param name="stream">Stream to read</param>
/// <param name="buffer">byte buffer to fill</param>
/// <param name="offset">starting position to fill the buffer</param>
/// <param name="count">number of bytes to read</param>
/// <returns>The number of bytes read. May be less than count if no more bytes are available.</returns>
public static int ReadBytes(Stream stream, byte[] buffer, int offset, int count)
{
int end = offset + count;
int got = 0;
int need = count;
do
{
got = stream.Read(buffer, offset, need);
offset += got;
need -= got;
}
while (offset < end && got != 0);
// return bytes read
return count - (end - offset);
}
//This is like Encoding.UTF8.GetCharCount() but it ignores a trailing incomplete
//character. See comments on ValidUTF8Ending()
public static int PessimisticGetCharCount(byte[] buffer, int index, int count)
{
return ENCODING_UTF8.GetCharCount(buffer, index, count) - (ValidUTF8Ending(buffer, index, count) ? 0 : 1);
}
///<summary>
/// This method writes a C NULL terminated string to the network stream.
/// It appends a NULL terminator to the end of the String.
/// </summary>
///<summary>
/// This method writes a C NULL terminated string to the network stream.
/// It appends a NULL terminator to the end of the String.
/// </summary>
public static void WriteString(String the_string, Stream network_stream)
{
byte[] bytes = ENCODING_UTF8.GetBytes(the_string + NULL_TERMINATOR_STRING);
network_stream.Write(bytes, 0, bytes.Length);
}
/// <summary>
/// This method writes a set of bytes to the stream. It also enables logging of them.
/// </summary>
public static void WriteBytes(byte[] the_bytes, Stream network_stream)
{
network_stream.Write(the_bytes, 0, the_bytes.Length);
network_stream.Write(new byte[1], 0, 1);
}
///<summary>
/// This method writes a C NULL terminated string limited in length to the
/// backend server.
/// It pads the string with null bytes to the size specified.
/// </summary>
public static void WriteLimString(String the_string, Int32 n, Stream network_stream)
{
//Note: We do not know the size in bytes until after we have converted the string.
byte[] bytes = ENCODING_UTF8.GetBytes(the_string);
if (bytes.Length > n)
{
throw new ArgumentOutOfRangeException("the_string", the_string,
string.Format("String too large", the_string, n));
}
network_stream.Write(bytes, 0, bytes.Length);
//pad with zeros.
if (bytes.Length < n)
{
bytes = new byte[n - bytes.Length];
network_stream.Write(bytes, 0, bytes.Length);
}
}
public static void CheckedStreamReadShort(Stream stream, byte[] buffer, int offset, int size)
{
while (size != 0)
{
var read = stream.Read(buffer, offset, size);
offset += read;
size -= read;
}
}
public static void CheckedStreamRead(Stream stream, byte[] buffer, int offset, int size)
{
int bytes_from_stream = 0;
int total_bytes_read = 0;
// need to read in chunks so the socket doesn't run out of memory in recv
// the network stream doesn't prevent this and downloading a large bytea
// will throw an IOException with an error code of 10055 (WSAENOBUFS)
while (size > 0)
{
// chunked read of maxReadChunkSize
int readSize = size > 8192 ? 8192 : size;
bytes_from_stream = stream.Read(buffer, offset + total_bytes_read, readSize);
total_bytes_read += bytes_from_stream;
size -= bytes_from_stream;
}
}
public static void EatShortStreamBytes(Stream stream, int size)
{
while (size > 0)
{
size -= stream.Read(THRASH_CAN, 0, size);
}
}
public static void EatStreamBytes(Stream stream, int size)
{
//See comment on THRASH_CAN and THRASH_CAN_SIZE.
while (size > 0)
{
size -= stream.Read(THRASH_CAN, 0, size < THRASH_CAN_SIZE ? size : THRASH_CAN_SIZE);
}
}
public static int ReadEscapedBytes(Stream stream, byte[] buffer, byte[] output, int maxBytes, ref int maxRead, int outputIdx)
{
maxBytes = maxBytes > output.Length - outputIdx ? output.Length - outputIdx : maxBytes;
int i;
for (i = 0; i != maxBytes && maxRead > 0; ++i)
{
char c = ReadChar(stream, buffer);
--maxRead;
if (c == '\\')
{
--maxRead;
switch (c = ReadChar(stream, buffer))
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
maxRead -= 2;
output[outputIdx++] =
(byte)
((int.Parse(c.ToString()) << 6) | (int.Parse(ReadChar(stream, buffer).ToString()) << 3) |
int.Parse(ReadChar(stream, buffer).ToString()));
break;
default:
output[outputIdx++] = (byte)c;
break;
}
}
else
{
output[outputIdx++] = (byte)c;
}
}
return i;
}
public static int SkipEscapedBytes(Stream stream, byte[] buffer, int maxBytes, ref int maxRead)
{
int i;
for (i = 0; i != maxBytes && maxRead > 0; ++i)
{
--maxRead;
if (ReadChar(stream, buffer) == '\\')
{
--maxRead;
switch (ReadChar(stream, buffer))
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
maxRead -= 2;
EatStreamBytes(stream, 2); //note assumes all representations of '0' through '9' are single-byte.
break;
}
}
}
return i;
}
/// <summary>
/// Write a 32-bit integer to the given stream in the correct byte order.
/// </summary>
public static void WriteInt32(Stream stream, Int32 value)
{
var number = IPAddress.HostToNetworkOrder(value);
stream.WriteByte((byte)number);
stream.WriteByte((byte)(number >> 8));
stream.WriteByte((byte)(number >> 16));
stream.WriteByte((byte)(number >> 24));
}
/// <summary>
/// Read a 32-bit integer from the given stream in the correct byte order.
/// </summary>
public static int ReadInt32(Stream stream, byte[] buffer)
{
CheckedStreamReadShort(stream, buffer, 0, 4);
var value = buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
return IPAddress.NetworkToHostOrder(value);
}
/// <summary>
/// Write a 16-bit integer to the given stream in the correct byte order.
/// </summary>
public static void WriteInt16(Stream stream, Int16 value)
{
var number = IPAddress.HostToNetworkOrder(value);
stream.WriteByte((byte)number);
stream.WriteByte((byte)(number >> 8));
}
/// <summary>
/// Read a 16-bit integer from the given stream in the correct byte order.
/// </summary>
public static short ReadInt16(Stream stream, byte[] buffer)
{
CheckedStreamReadShort(stream, buffer, 2, 2);
var value = buffer[2] + (buffer[3] << 8);
return IPAddress.NetworkToHostOrder((short)value);
}
public static int RotateShift(int val, int shift)
{
return (val << shift) | (val >> (sizeof(int) - shift));
}
}
internal enum FormatCode : short
{
Text = 0,
Binary = 1
}
internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _inner;
public ReadOnlyDictionary(Dictionary<TKey, TValue> inner)
{
_inner = inner;
}
private static void StopWrite()
{
throw new NotSupportedException("The collection is read-only");
}
public TValue this[TKey key]
{
get { return _inner[key]; }
set { StopWrite(); }
}
public ICollection<TKey> Keys
{
get { return _inner.Keys; }
}
public ICollection<TValue> Values
{
get { return _inner.Values; }
}
public int Count
{
get { return _inner.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool ContainsKey(TKey key)
{
return _inner.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
StopWrite();
}
public bool Remove(TKey key)
{
StopWrite();
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
return _inner.TryGetValue(key, out value);
}
public void Add(KeyValuePair<TKey, TValue> item)
{
StopWrite();
}
public void Clear()
{
StopWrite();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return ((IDictionary<TKey, TValue>)_inner).Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((IDictionary<TKey, TValue>)_inner).CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
StopWrite();
return false;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
foreach (KeyValuePair<TKey, TValue> kvp in _inner)
{
yield return new KeyValuePair<TKey, TValue>(kvp.Key, kvp.Value); //return copy so changes don't affect our copy.
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return _inner.GetEnumerator();
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class ActionBlockTests
{
[Fact]
public void TestToString()
{
// Test ToString() with the only custom configuration being NameFormat
DataflowTestHelpers.TestToString(
nameFormat => nameFormat != null ?
new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) :
new ActionBlock<int>(i => { }));
// Test ToString() with other configuration
DataflowTestHelpers.TestToString(
nameFormat => nameFormat != null ?
new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat, SingleProducerConstrained = true }) :
new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions() { SingleProducerConstrained = true }));
}
[Fact]
public async Task TestOfferMessage()
{
var generators = new Func<ActionBlock<int>>[]
{
() => new ActionBlock<int>(i => { }),
() => new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 }),
() => new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1, MaxDegreeOfParallelism = 4 })
};
foreach (var generator in generators)
{
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
var target = generator();
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
target = generator();
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
}
}
[Fact]
public void TestPost()
{
foreach (bool bounded in DataflowTestHelpers.BooleanValues)
{
ActionBlock<int> ab = new ActionBlock<int>(i => { },
new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }); // test greedy and then non-greedy
Assert.True(ab.Post(0), "Expected non-completed ActionBlock to accept Post'd message");
ab.Complete();
Assert.False(ab.Post(0), "Expected Complete'd ActionBlock to decline messages");
}
}
[Fact]
public async Task TestCompletionTask()
{
await DataflowTestHelpers.TestCompletionTask(() => new ActionBlock<int>(i => { }));
}
[Fact]
public void TestCtor()
{
// Invalid arguments
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>((Func<int, Task>)null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>((Func<int, Task>)null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>(i => { }, null));
Assert.Throws<ArgumentNullException>(() => new ActionBlock<int>(i => default(Task), null));
// Valid arguments; make sure they don't throw, and validate some properties afterwards
var blocks = new[]
{
new ActionBlock<int>(i => { }),
new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }),
new ActionBlock<int>(i => { }, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true) }),
new ActionBlock<int>(i => default(Task)),
new ActionBlock<int>(i => default(Task), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 }),
new ActionBlock<int>(i => default(Task), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }),
new ActionBlock<int>(i => default(Task), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true) })
};
foreach (var block in blocks)
{
Assert.Equal(0, block.InputCount);
Assert.NotNull(block.Completion);
}
}
[Fact]
public async Task TestBasicMessageProcessing()
{
var options = new[]
{
// Actual values used here aren't important; just want to make sure the block works
// with these properties set to non-default values
new ExecutionDataflowBlockOptions { },
new ExecutionDataflowBlockOptions { BoundedCapacity = 1 },
new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 2 },
new ExecutionDataflowBlockOptions { SingleProducerConstrained = true },
new ExecutionDataflowBlockOptions { TaskScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler },
new ExecutionDataflowBlockOptions
{
BoundedCapacity = 2,
MaxMessagesPerTask = 4,
SingleProducerConstrained = true,
TaskScheduler = new ConcurrentExclusiveSchedulerPair().ConcurrentScheduler,
CancellationToken = new CancellationTokenSource().Token,
NameFormat = ""
}
};
// Make sure all data makes it through the block
for (int propMechanism = 0; propMechanism < 2; propMechanism++)
{
foreach (var option in options)
{
string result = null;
foreach (var target in new[]
{
new ActionBlock<char>(c => result += c, option), // sync
new ActionBlock<char>(c => Task.Run(() => result += c), option) // async
})
{
result = "";
switch (propMechanism)
{
case 0:
for (int i = 0; i < 26; i++)
{
char c = (char)('a' + i);
if (option.BoundedCapacity == DataflowBlockOptions.Unbounded)
target.Post(c);
else
await target.SendAsync(c); // will work even if Unbounded, but we can test Post if it's Unbounded
}
target.Complete();
break;
case 1:
var source = new BufferBlock<char>();
source.PostAll(Enumerable.Range(0, 26).Select(i => (char)('a' + i)));
source.Complete();
source.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
break;
}
await target.Completion;
Assert.Equal(expected: "abcdefghijklmnopqrstuvwxyz", actual: result);
}
}
}
}
[Fact]
public async Task TestSchedulerUsage()
{
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
var scheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
var actionBlockSync = new ActionBlock<int>(_ => Assert.Equal(scheduler.Id, TaskScheduler.Current.Id),
new ExecutionDataflowBlockOptions
{
TaskScheduler = scheduler,
SingleProducerConstrained = singleProducerConstrained
});
actionBlockSync.PostRange(0, 10);
actionBlockSync.Complete();
await actionBlockSync.Completion;
var actionBlockAsync = new ActionBlock<int>(_ => {
Assert.Equal(scheduler.Id, TaskScheduler.Current.Id);
return Task.FromResult(0);
}, new ExecutionDataflowBlockOptions
{
TaskScheduler = scheduler,
SingleProducerConstrained = singleProducerConstrained
});
actionBlockAsync.PostRange(0, 10);
actionBlockAsync.Complete();
await actionBlockAsync.Completion;
}
}
[Fact]
public async Task TestInputCount()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2);
var options = new ExecutionDataflowBlockOptions { SingleProducerConstrained = singleProducerConstrained };
Action<int> body = _ => {
barrier1.SignalAndWait();
// will test InputCount here
barrier2.SignalAndWait();
};
ActionBlock<int> ab = sync ?
new ActionBlock<int>(body, options) :
new ActionBlock<int>(i => Task.Run(() => body(i)), options);
for (int iter = 0; iter < 2; iter++)
{
ab.PostItems(1, 2);
for (int i = 1; i >= 0; i--)
{
barrier1.SignalAndWait();
Assert.Equal(expected: i, actual: ab.InputCount);
barrier2.SignalAndWait();
}
}
ab.Complete();
await ab.Completion;
}
}
[Fact]
public async Task TestOrderMaintained()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
var options = new ExecutionDataflowBlockOptions { SingleProducerConstrained = singleProducerConstrained };
int prev = -1;
Action<int> body = i =>
{
Assert.Equal(expected: prev + 1, actual: i);
prev = i;
};
ActionBlock<int> ab = sync ?
new ActionBlock<int>(body, options) :
new ActionBlock<int>(i => Task.Run(() => body(i)), options);
ab.PostRange(0, 100);
ab.Complete();
await ab.Completion;
}
}
[Fact]
public async Task TestNonGreedy()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
var barrier1 = new Barrier(2);
Action<int> body = _ => barrier1.SignalAndWait();
var options = new ExecutionDataflowBlockOptions { BoundedCapacity = 1 };
ActionBlock<int> ab = sync ?
new ActionBlock<int>(body, options) :
new ActionBlock<int>(i => Task.Run(() => body(i)), options);
Task<bool>[] sends = Enumerable.Range(0, 10).Select(i => ab.SendAsync(i)).ToArray();
for (int i = 0; i < sends.Length; i++)
{
Assert.True(sends[i].Result); // Next send should have completed and with the value successfully accepted
for (int j = i + 1; j < sends.Length; j++) // No further sends should have completed yet
{
Assert.False(sends[j].IsCompleted);
}
barrier1.SignalAndWait();
}
ab.Complete();
await ab.Completion;
}
}
[Fact]
public async Task TestConsumeToAccept()
{
foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1 })
foreach (bool singleProducer in DataflowTestHelpers.BooleanValues)
{
int sum = 0;
var bb = new BroadcastBlock<int>(i => i * 2, new DataflowBlockOptions { MaxMessagesPerTask = maxMessagesPerTask });
var ab = new ActionBlock<int>(i => sum += i, new ExecutionDataflowBlockOptions { SingleProducerConstrained = singleProducer });
bb.LinkTo(ab, new DataflowLinkOptions { PropagateCompletion = true });
const int Messages = 100;
bb.PostRange(1, Messages + 1);
bb.Complete();
await ab.Completion;
Assert.Equal(expected: 100 * 101, actual: sum);
}
}
[Fact]
public async Task TestOperationCanceledExceptionsIgnored()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
var options = new ExecutionDataflowBlockOptions { SingleProducerConstrained = singleProducerConstrained };
int sumOfOdds = 0;
Action<int> body = i => {
if ((i % 2) == 0) throw new OperationCanceledException();
sumOfOdds += i;
};
ActionBlock<int> ab = sync ?
new ActionBlock<int>(body, options) :
new ActionBlock<int>(async i => { await Task.Yield(); body(i); }, options);
const int MaxValue = 10;
ab.PostRange(0, MaxValue);
ab.Complete();
await ab.Completion;
Assert.Equal(
expected: Enumerable.Range(0, MaxValue).Where(i => i % 2 != 0).Sum(),
actual: sumOfOdds);
}
}
[Fact]
public async Task TestPrecanceledToken()
{
var options = new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) };
var blocks = new []
{
new ActionBlock<int>(i => { }, options),
new ActionBlock<int>(i => Task.FromResult(0), options)
};
foreach (ActionBlock<int> ab in blocks)
{
Assert.False(ab.Post(42));
Assert.Equal(expected: 0, actual: ab.InputCount);
Assert.NotNull(ab.Completion);
ab.Complete();
((IDataflowBlock)ab).Fault(new Exception());
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ab.Completion);
}
}
[Fact]
public async Task TestFault()
{
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
var ab = new ActionBlock<int>(i => { },
new ExecutionDataflowBlockOptions { SingleProducerConstrained = true });
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)ab).Fault(null));
((IDataflowBlock)ab).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => ab.Completion);
}
}
[Fact]
public async Task TestFaulting()
{
for (int trial = 0; trial < 3; trial++)
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
var options = new ExecutionDataflowBlockOptions { SingleProducerConstrained = singleProducerConstrained };
Action thrower = () => { throw new InvalidOperationException(); };
ActionBlock<int> ab = null;
switch (trial)
{
case 0: ab = new ActionBlock<int>(i => thrower(), options); break;
case 1: ab = new ActionBlock<int>(i => { thrower(); return Task.FromResult(0); }, options); break;
case 2: ab = new ActionBlock<int>(i => Task.Run(thrower), options); break;
}
for (int i = 0; i < 4; i++)
{
ab.Post(i); // Post may return false, depending on race with ActionBlock faulting
}
await Assert.ThrowsAsync<InvalidOperationException>(async () => await ab.Completion);
if (!singleProducerConstrained)
{
Assert.Equal(expected: 0, actual: ab.InputCount); // not 100% guaranteed in the SPSC case
}
Assert.False(ab.Post(5));
}
}
[Fact]
public async Task TestNullReturnedTasks()
{
int sumOfOdds = 0;
var ab = new ActionBlock<int>(i => {
if ((i % 2) == 0) return null;
return Task.Run(() => { sumOfOdds += i; });
});
const int MaxValue = 10;
ab.PostRange(0, MaxValue);
ab.Complete();
await ab.Completion;
Assert.Equal(
expected: Enumerable.Range(0, MaxValue).Where(i => i % 2 != 0).Sum(),
actual: sumOfOdds);
}
[Fact]
public async Task TestParallelExecution()
{
int dop = 2;
foreach (bool sync in DataflowTestHelpers.BooleanValues)
foreach (bool singleProducerConstrained in DataflowTestHelpers.BooleanValues)
{
Barrier barrier = new Barrier(dop);
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, SingleProducerConstrained = singleProducerConstrained };
ActionBlock<int> ab = sync ?
new ActionBlock<int>(_ => barrier.SignalAndWait(), options) :
new ActionBlock<int>(_ => Task.Run(() => barrier.SignalAndWait()), options);
int iters = dop * 4;
ab.PostRange(0, iters);
ab.Complete();
await ab.Completion;
}
}
[Fact]
public async Task TestReleasingOfPostponedMessages()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2);
Action<int> body = i => { barrier1.SignalAndWait(); barrier2.SignalAndWait(); };
var options = new ExecutionDataflowBlockOptions { BoundedCapacity = 1 };
ActionBlock<int> ab = sync ?
new ActionBlock<int>(body, options) :
new ActionBlock<int>(i => Task.Run(() => body(i)), options);
ab.Post(0);
barrier1.SignalAndWait();
Task<bool>[] sends = Enumerable.Range(0, 10).Select(i => ab.SendAsync(i)).ToArray();
Assert.All(sends, s => Assert.False(s.IsCompleted));
ab.Complete();
barrier2.SignalAndWait();
await ab.Completion;
Assert.All(sends, s => Assert.False(s.Result));
}
}
[Fact]
public async Task TestExceptionDataStorage()
{
const string DataKey = "DataflowMessageValue"; // must match key used in dataflow source
// Validate that a message which causes the ActionBlock to fault
// ends up being stored (ToString) in the resulting exception's Data
var ab1 = new ActionBlock<int>((Action<int>)(i => { throw new FormatException(); }));
ab1.Post(42);
await Assert.ThrowsAsync<FormatException>(() => ab1.Completion);
AggregateException e = ab1.Completion.Exception;
Assert.Equal(expected: 1, actual: e.InnerExceptions.Count);
Assert.Equal(expected: "42", actual: (string)e.InnerException.Data[DataKey]);
// Test case where message's ToString throws
var ab2 = new ActionBlock<ObjectWithFaultyToString>((Action<ObjectWithFaultyToString>)(i => { throw new FormatException(); }));
ab2.Post(new ObjectWithFaultyToString());
Exception ex = await Assert.ThrowsAsync<FormatException>(() => ab2.Completion);
Assert.False(ex.Data.Contains(DataKey));
}
private class ObjectWithFaultyToString
{
public override string ToString() { throw new InvalidTimeZoneException(); }
}
[Fact]
public async Task TestFaultyScheduler()
{
var ab = new ActionBlock<int>(i => { },
new ExecutionDataflowBlockOptions
{
TaskScheduler = new DelegateTaskScheduler
{
QueueTaskDelegate = delegate { throw new FormatException(); }
}
});
ab.Post(42);
await Assert.ThrowsAsync<TaskSchedulerException>(() => ab.Completion);
}
}
}
| |
using System;
using System.Numerics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
namespace GUI.Types.Renderer
{
internal class Camera
{
private const float CAMERASPEED = 300f; // Per second
private const float FOV = OpenTK.MathHelper.PiOver4;
public Vector3 Location { get; private set; }
public float Pitch { get; private set; }
public float Yaw { get; private set; }
public float Scale { get; private set; } = 1.0f;
private Matrix4x4 ProjectionMatrix;
public Matrix4x4 CameraViewMatrix { get; private set; }
public Matrix4x4 ViewProjectionMatrix { get; private set; }
public Frustum ViewFrustum { get; } = new Frustum();
// Set from outside this class by forms code
public bool MouseOverRenderArea { get; set; }
private Vector2 WindowSize;
private float AspectRatio;
private bool MouseDragging;
private Vector2 MouseDelta;
private Vector2 MousePreviousPosition;
private KeyboardState KeyboardState;
public Camera()
{
Location = new Vector3(1);
LookAt(new Vector3(0));
}
private void RecalculateMatrices()
{
CameraViewMatrix = Matrix4x4.CreateScale(Scale) * Matrix4x4.CreateLookAt(Location, Location + GetForwardVector(), Vector3.UnitZ);
ViewProjectionMatrix = CameraViewMatrix * ProjectionMatrix;
ViewFrustum.Update(ViewProjectionMatrix);
}
// Calculate forward vector from pitch and yaw
private Vector3 GetForwardVector()
{
return new Vector3((float)(Math.Cos(Yaw) * Math.Cos(Pitch)), (float)(Math.Sin(Yaw) * Math.Cos(Pitch)), (float)Math.Sin(Pitch));
}
private Vector3 GetRightVector()
{
return new Vector3((float)Math.Cos(Yaw - OpenTK.MathHelper.PiOver2), (float)Math.Sin(Yaw - OpenTK.MathHelper.PiOver2), 0);
}
public void SetViewportSize(int viewportWidth, int viewportHeight)
{
// Store window size and aspect ratio
AspectRatio = viewportWidth / (float)viewportHeight;
WindowSize = new Vector2(viewportWidth, viewportHeight);
// Calculate projection matrix
ProjectionMatrix = Matrix4x4.CreatePerspectiveFieldOfView(FOV, AspectRatio, 1.0f, 40000.0f);
RecalculateMatrices();
// setup viewport
GL.Viewport(0, 0, viewportWidth, viewportHeight);
}
public void CopyFrom(Camera fromOther)
{
AspectRatio = fromOther.AspectRatio;
WindowSize = fromOther.WindowSize;
Location = fromOther.Location;
Pitch = fromOther.Pitch;
Yaw = fromOther.Yaw;
ProjectionMatrix = fromOther.ProjectionMatrix;
CameraViewMatrix = fromOther.CameraViewMatrix;
ViewProjectionMatrix = fromOther.ViewProjectionMatrix;
ViewFrustum.Update(ViewProjectionMatrix);
}
public void SetLocation(Vector3 location)
{
Location = location;
RecalculateMatrices();
}
public void SetLocationPitchYaw(Vector3 location, float pitch, float yaw)
{
Location = location;
Pitch = pitch;
Yaw = yaw;
RecalculateMatrices();
}
public void LookAt(Vector3 target)
{
var dir = Vector3.Normalize(target - Location);
Yaw = (float)Math.Atan2(dir.Y, dir.X);
Pitch = (float)Math.Asin(dir.Z);
ClampRotation();
RecalculateMatrices();
}
public void SetFromTransformMatrix(Matrix4x4 matrix)
{
Location = matrix.Translation;
// Extract view direction from view matrix and use it to calculate pitch and yaw
var dir = new Vector3(matrix.M11, matrix.M12, matrix.M13);
Yaw = (float)Math.Atan2(dir.Y, dir.X);
Pitch = (float)Math.Asin(dir.Z);
RecalculateMatrices();
}
public void SetScale(float scale)
{
Scale = scale;
RecalculateMatrices();
}
public void Tick(float deltaTime)
{
if (!MouseOverRenderArea)
{
return;
}
// Use the keyboard state to update position
HandleKeyboardInput(deltaTime);
// Full width of the screen is a 1 PI (180deg)
Yaw -= (float)Math.PI * MouseDelta.X / WindowSize.X;
Pitch -= ((float)Math.PI / AspectRatio) * MouseDelta.Y / WindowSize.Y;
ClampRotation();
RecalculateMatrices();
}
public void HandleInput(MouseState mouseState, KeyboardState keyboardState)
{
KeyboardState = keyboardState;
if (MouseOverRenderArea && mouseState.LeftButton == ButtonState.Pressed)
{
if (!MouseDragging)
{
MouseDragging = true;
MousePreviousPosition = new Vector2(mouseState.X, mouseState.Y);
}
var mouseNewCoords = new Vector2(mouseState.X, mouseState.Y);
MouseDelta.X = mouseNewCoords.X - MousePreviousPosition.X;
MouseDelta.Y = mouseNewCoords.Y - MousePreviousPosition.Y;
MousePreviousPosition = mouseNewCoords;
}
if (!MouseOverRenderArea || mouseState.LeftButton == ButtonState.Released)
{
MouseDragging = false;
MouseDelta = default;
}
}
private void HandleKeyboardInput(float deltaTime)
{
var speed = CAMERASPEED * deltaTime;
// Double speed if shift is pressed
if (KeyboardState.IsKeyDown(Key.ShiftLeft))
{
speed *= 2;
}
else if (KeyboardState.IsKeyDown(Key.F))
{
speed *= 10;
}
if (KeyboardState.IsKeyDown(Key.W))
{
Location += GetForwardVector() * speed;
}
if (KeyboardState.IsKeyDown(Key.S))
{
Location -= GetForwardVector() * speed;
}
if (KeyboardState.IsKeyDown(Key.D))
{
Location += GetRightVector() * speed;
}
if (KeyboardState.IsKeyDown(Key.A))
{
Location -= GetRightVector() * speed;
}
if (KeyboardState.IsKeyDown(Key.Z))
{
Location += new Vector3(0, 0, -speed);
}
if (KeyboardState.IsKeyDown(Key.Q))
{
Location += new Vector3(0, 0, speed);
}
}
// Prevent camera from going upside-down
private void ClampRotation()
{
if (Pitch >= OpenTK.MathHelper.PiOver2)
{
Pitch = OpenTK.MathHelper.PiOver2 - 0.001f;
}
else if (Pitch <= -OpenTK.MathHelper.PiOver2)
{
Pitch = -OpenTK.MathHelper.PiOver2 + 0.001f;
}
}
}
}
| |
using System.Collections;
using Game;
using Game.Enums;
using JetBrains.Annotations;
using Mod;
using Mod.Keybinds;
using Mod.Managers;
using Mod.Modules;
using Photon;
using Photon.Enums;
using RC;
using UnityEngine;
using Random = UnityEngine.Random;
// ReSharper disable once CheckNamespace
public class TITAN_EREN : Photon.MonoBehaviour
{
private string attackAnimation;
private Transform attackBox;
private bool attackChkOnce;
public GameObject bottomObject;
public bool canJump = true;
private ArrayList checkPoints = new ArrayList();
public Camera currentCamera;
public Vector3 dashDirection;
private float dieTime;
private float facingDirection;
private float gravity = 500f;
private bool grounded;
public bool hasDied;
private bool hasDieSteam;
public bool hasSpawn;
private string hitAnimation;
private float hitPause;
private ArrayList hitTargets;
private bool isAttack;
public bool isHit;
private bool isHitWhileCarryingRock;
private bool isNextAttack;
private bool isPlayRoar;
private bool isROCKMOVE;
public float jumpHeight = 2f;
private bool justGrounded;
public float lifeTime = 9999f;
private float lifeTimeMax = 9999f;
public float maxVelocityChange = 100f;
public GameObject myNetWorkName;
public float myR;
private bool needFreshCorePosition;
private bool needRoar;
private Vector3 oldCorePosition;
public GameObject realBody;
public GameObject rock;
private bool rockHitGround;
public bool rockLift;
private int rockPhase;
public float speed = 80f;
private int stepSoundPhase = 2;
private Vector3 targetCheckPt;
private float waitCounter;
public void born()
{
foreach (GameObject obj2 in GameObject.FindGameObjectsWithTag("titan"))
{
if (obj2.GetComponent<FEMALE_TITAN>() != null)
{
obj2.GetComponent<FEMALE_TITAN>().erenIsHere(gameObject);
}
}
if (!this.bottomObject.GetComponent<CheckHitGround>().isGrounded)
{
this.playAnimation("jump_air");
this.needRoar = true;
}
else
{
this.needRoar = false;
this.playAnimation("born");
this.isPlayRoar = false;
}
this.playSound("snd_eren_shift");
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
{
Instantiate(Resources.Load("FX/Thunder"), transform.position + Vector3.up * 23f, Quaternion.Euler(270f, 0f, 0f));
}
else if (photonView.isMine)
{
PhotonNetwork.Instantiate("FX/Thunder", transform.position + Vector3.up * 23f, Quaternion.Euler(270f, 0f, 0f), 0);
}
float num2 = 30f;
this.lifeTime = 30f;
this.lifeTimeMax = num2;
}
private void crossFade(string aniName, float time)
{
animation.CrossFade(aniName, time);
if (PhotonNetwork.connected && photonView.isMine)
{
photonView.RPC(Rpc.CrossFade, PhotonTargets.Others, aniName, time);
}
}
[RPC]
[UsedImplicitly]
private void EndMovingRock()
{
this.isROCKMOVE = false;
}
private void falseAttack()
{
this.isAttack = false;
this.isNextAttack = false;
this.hitTargets = new ArrayList();
this.attackChkOnce = false;
}
private void FixedUpdate()
{
if (!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer)
{
if (this.rockLift)
{
this.RockUpdate();
}
else if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)
{
if (this.hitPause > 0f)
{
rigidbody.velocity = Vector3.zero;
}
else if (this.hasDied)
{
rigidbody.velocity = Vector3.zero + Vector3.up * rigidbody.velocity.y;
rigidbody.AddForce(new Vector3(0f, -this.gravity * rigidbody.mass, 0f));
}
else if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)
{
if (rigidbody.velocity.magnitude > 50f)
{
this.currentCamera.GetComponent<Camera>().fieldOfView = Mathf.Lerp(this.currentCamera.GetComponent<Camera>().fieldOfView, Mathf.Min(100f, rigidbody.velocity.magnitude), 0.1f);
}
else
{
this.currentCamera.GetComponent<Camera>().fieldOfView = Mathf.Lerp(this.currentCamera.GetComponent<Camera>().fieldOfView, 50f, 0.1f);
}
if (this.bottomObject.GetComponent<CheckHitGround>().isGrounded)
{
if (!this.grounded)
{
this.justGrounded = true;
}
this.grounded = true;
this.bottomObject.GetComponent<CheckHitGround>().isGrounded = false;
}
else
{
this.grounded = false;
}
float x = 0f;
float z = 0f;
if (!IN_GAME_MAIN_CAMERA.isTyping)
{
if (Shelter.InputManager.IsKeyPressed(InputAction.Forward))
{
z = 1f;
}
else if (Shelter.InputManager.IsKeyPressed(InputAction.Back))
{
z = -1f;
}
else
{
z = 0f;
}
if (Shelter.InputManager.IsKeyPressed(InputAction.Left))
{
x = -1f;
}
else if (Shelter.InputManager.IsKeyPressed(InputAction.Right))
{
x = 1f;
}
else
{
x = 0f;
}
}
if (this.needFreshCorePosition)
{
this.oldCorePosition = transform.position - transform.Find("Amarture/Core").position;
this.needFreshCorePosition = false;
}
if (!this.isAttack && !this.isHit)
{
if (this.grounded)
{
Vector3 zero = Vector3.zero;
if (this.justGrounded)
{
this.justGrounded = false;
zero = rigidbody.velocity;
if (animation.IsPlaying("jump_air"))
{
GameObject obj2 = (GameObject) Instantiate(Resources.Load("FX/boom2_eren"), transform.position, Quaternion.Euler(270f, 0f, 0f));
obj2.transform.localScale = Vector3.one * 1.5f;
if (this.needRoar)
{
this.playAnimation("born");
this.needRoar = false;
this.isPlayRoar = false;
}
else
{
this.playAnimation("jump_land");
}
}
}
if (!animation.IsPlaying("jump_land") && !this.isAttack && !this.isHit && !animation.IsPlaying("born"))
{
Vector3 vector7 = new Vector3(x, 0f, z);
float y = this.currentCamera.transform.rotation.eulerAngles.y;
float num4 = Mathf.Atan2(z, x) * 57.29578f;
num4 = -num4 + 90f;
float num5 = y + num4;
float num6 = -num5 + 90f;
float num7 = Mathf.Cos(num6 * 0.01745329f);
float num8 = Mathf.Sin(num6 * 0.01745329f);
zero = new Vector3(num7, 0f, num8);
float num9 = vector7.magnitude <= 0.95f ? (vector7.magnitude >= 0.25f ? vector7.magnitude : 0f) : 1f;
zero = zero * num9;
zero = zero * this.speed;
if (x == 0f && z == 0f)
{
if (!animation.IsPlaying("idle") && !animation.IsPlaying("dash_land") && !animation.IsPlaying("dodge") && !animation.IsPlaying("jump_start") && !animation.IsPlaying("jump_air") && !animation.IsPlaying("jump_land"))
{
this.crossFade("idle", 0.1f);
zero = zero * 0f;
}
num5 = -874f;
}
else if (!animation.IsPlaying("run") && !animation.IsPlaying("jump_start") && !animation.IsPlaying("jump_air"))
{
this.crossFade("run", 0.1f);
}
if (num5 != -874f)
{
this.facingDirection = num5;
}
}
Vector3 velocity = rigidbody.velocity;
Vector3 force = zero - velocity;
force.x = Mathf.Clamp(force.x, -this.maxVelocityChange, this.maxVelocityChange);
force.z = Mathf.Clamp(force.z, -this.maxVelocityChange, this.maxVelocityChange);
force.y = 0f;
if (animation.IsPlaying("jump_start") && animation["jump_start"].normalizedTime >= 1f)
{
this.playAnimation("jump_air");
force.y += 240f;
}
else if (animation.IsPlaying("jump_start"))
{
force = -rigidbody.velocity;
}
rigidbody.AddForce(force, ForceMode.VelocityChange);
rigidbody.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, this.facingDirection, 0f), Time.deltaTime * 10f);
}
else
{
if (animation.IsPlaying("jump_start") && animation["jump_start"].normalizedTime >= 1f)
{
this.playAnimation("jump_air");
rigidbody.AddForce(Vector3.up * 240f, ForceMode.VelocityChange);
}
if (!animation.IsPlaying("jump") && !this.isHit)
{
Vector3 vector11 = new Vector3(x, 0f, z);
float num10 = this.currentCamera.transform.rotation.eulerAngles.y;
float num11 = Mathf.Atan2(z, x) * 57.29578f;
num11 = -num11 + 90f;
float num12 = num10 + num11;
float num13 = -num12 + 90f;
float num14 = Mathf.Cos(num13 * 0.01745329f);
float num15 = Mathf.Sin(num13 * 0.01745329f);
Vector3 vector13 = new Vector3(num14, 0f, num15);
float num16 = vector11.magnitude <= 0.95f ? (vector11.magnitude >= 0.25f ? vector11.magnitude : 0f) : 1f;
vector13 = vector13 * num16;
vector13 = vector13 * (this.speed * 2f);
if (x == 0f && z == 0f)
{
num12 = -874f;
}
else
{
rigidbody.AddForce(vector13, ForceMode.Impulse);
}
if (num12 != -874f)
{
this.facingDirection = num12;
}
if (!animation.IsPlaying(string.Empty) && !animation.IsPlaying("attack3_2") && !animation.IsPlaying("attack5"))
{
rigidbody.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, this.facingDirection, 0f), Time.deltaTime * 6f);
}
}
}
}
else
{
Vector3 vector4 = transform.position - transform.Find("Amarture/Core").position - this.oldCorePosition;
this.oldCorePosition = transform.position - transform.Find("Amarture/Core").position;
rigidbody.velocity = vector4 / Time.deltaTime + Vector3.up * rigidbody.velocity.y;
rigidbody.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, this.facingDirection, 0f), Time.deltaTime * 10f);
if (this.justGrounded)
{
this.justGrounded = false;
}
}
rigidbody.AddForce(new Vector3(0f, -this.gravity * rigidbody.mass, 0f));
}
}
}
}
public void hitByFT(int phase)
{
if (!this.hasDied)
{
this.isHit = true;
this.hitAnimation = "hit_annie_" + phase;
this.falseAttack();
this.playAnimation(this.hitAnimation);
this.needFreshCorePosition = true;
if (phase == 3)
{
GameObject obj2;
this.hasDied = true;
Transform tr = this.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck");
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient)
{
obj2 = PhotonNetwork.Instantiate("bloodExplore", tr.position + Vector3.up * 1f * 4f, Quaternion.Euler(270f, 0f, 0f), 0);
}
else
{
obj2 = (GameObject) Instantiate(Resources.Load("bloodExplore"), tr.position + Vector3.up * 1f * 4f, Quaternion.Euler(270f, 0f, 0f));
}
obj2.transform.localScale = this.transform.localScale;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient)
{
obj2 = PhotonNetwork.Instantiate("bloodsplatter", tr.position, Quaternion.Euler(90f + tr.rotation.eulerAngles.x, tr.rotation.eulerAngles.y, tr.rotation.eulerAngles.z), 0);
}
else
{
obj2 = (GameObject) Instantiate(Resources.Load("bloodsplatter"), tr.position, Quaternion.Euler(90f + tr.rotation.eulerAngles.x, tr.rotation.eulerAngles.y, tr.rotation.eulerAngles.z));
}
obj2.transform.localScale = this.transform.localScale;
obj2.transform.parent = tr;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient)
{
obj2 = PhotonNetwork.Instantiate("FX/justSmoke", tr.position, Quaternion.Euler(270f, 0f, 0f), 0);
}
else
{
obj2 = (GameObject) Instantiate(Resources.Load("FX/justSmoke"), tr.position, Quaternion.Euler(270f, 0f, 0f));
}
obj2.transform.parent = tr;
}
}
}
public void hitByFTByServer(int phase)
{
photonView.RPC(Rpc.HitByFemaleTitan, PhotonTargets.All, phase);
}
[RPC]
[UsedImplicitly]
private void HitByFTRPC(int phase)
{
if (photonView.isMine)
{
this.hitByFT(phase);
}
}
public void hitByTitan()
{
if (!this.isHit && !this.hasDied && !animation.IsPlaying("born"))
{
if (this.rockLift)
{
this.crossFade("die", 0.1f);
this.isHitWhileCarryingRock = true;
GameManager.instance.GameLose();
photonView.RPC(Rpc.PlayRockAnimation, PhotonTargets.All, "set");
}
else
{
this.isHit = true;
this.hitAnimation = "hit_titan";
this.falseAttack();
this.playAnimation(this.hitAnimation);
this.needFreshCorePosition = true;
}
}
}
[RPC]
[UsedImplicitly]
private void HitByTitanRPC()
{
if (photonView.isMine)
{
this.hitByTitan();
}
}
public void DoLateUpdate()
{
if ((!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer) && !this.rockLift && (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine))
{
Quaternion to = Quaternion.Euler(GameObject.Find("MainCamera").transform.rotation.eulerAngles.x, GameObject.Find("MainCamera").transform.rotation.eulerAngles.y, 0f);
GameObject.Find("MainCamera").transform.rotation = Quaternion.Lerp(GameObject.Find("MainCamera").transform.rotation, to, Time.deltaTime * 2f);
}
}
public void loadskin()
{
string url = GameManager.settings.TitanSkin.Eren;
if (!Utility.IsValidImageUrl(url))
return;
if (ModuleManager.Enabled(nameof(ModuleEnableSkins)))
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
StartCoroutine(this.loadskinE(url));
else if (photonView.isMine)
photonView.RPC(Rpc.LoadSkin, PhotonTargets.AllBuffered, url);
}
}
public IEnumerator loadskinE(string url)
{
while (!this.hasSpawn)
{
yield return null;
}
bool mipmap = GameManager.settings.UseMipmap;
bool iteratorVariable1 = false;
foreach (Renderer iteratorVariable4 in this.GetComponentsInChildren<Renderer>())
{
if (!GameManager.linkHash[2].ContainsKey(url))
{
WWW link = new WWW(url);
yield return link;
Texture2D iteratorVariable6 = RCextensions.LoadImageRC(link, mipmap, 1000000);
link.Dispose();
if (!GameManager.linkHash[2].ContainsKey(url))
{
iteratorVariable1 = true;
iteratorVariable4.material.mainTexture = iteratorVariable6;
GameManager.linkHash[2].Add(url, iteratorVariable4.material);
iteratorVariable4.material = (Material)GameManager.linkHash[2][url];
}
else
{
iteratorVariable4.material = (Material)GameManager.linkHash[2][url];
}
}
else
{
iteratorVariable4.material = (Material)GameManager.linkHash[2][url];
}
}
if (iteratorVariable1)
{
GameManager.instance.UnloadAssets();
}
}
[RPC]
[UsedImplicitly]
public void LoadskinRPC(string url)
{
Shelter.LogBoth("LOADING {0} SKIN", nameof(TITAN_EREN));
Shelter.LogBoth("{0}: {1}", nameof(url), url);
if (ModuleManager.Enabled(nameof(ModuleEnableSkins)) && Utility.IsValidImageUrl(url))
{
StartCoroutine(this.loadskinE(url));
}
}
[RPC]
[UsedImplicitly]
private void NetCrossFade(string aniName, float time)
{
animation.CrossFade(aniName, time);
}
[RPC]
[UsedImplicitly]
private void NetPlayAnimation(string aniName)
{
animation.Play(aniName);
}
[RPC]
[UsedImplicitly]
private void NetPlayAnimationAt(string aniName, float normalizedTime)
{
animation.Play(aniName);
animation[aniName].normalizedTime = normalizedTime;
}
[RPC]
[UsedImplicitly]
private void NetTauntAttack(float tauntTime, float distance = 100f)
{
foreach (GameObject obj2 in GameObject.FindGameObjectsWithTag("titan"))
{
if (Vector3.Distance(obj2.transform.position, transform.position) < distance && obj2.GetComponent<TITAN>() != null)
{
obj2.GetComponent<TITAN>().GetTaunted(gameObject, tauntTime);
}
if (obj2.GetComponent<FEMALE_TITAN>() != null)
{
obj2.GetComponent<FEMALE_TITAN>().erenIsHere(gameObject);
}
}
}
private void OnDestroy()
{
if (GameObject.Find("MultiplayerManager") != null)
{
GameManager.instance.ErenTitans.Remove(this);
}
}
public void playAnimation(string aniName)
{
animation.Play(aniName);
if (PhotonNetwork.connected && photonView.isMine)
{
photonView.RPC(Rpc.PlayAnimation, PhotonTargets.Others, aniName);
}
}
private void playAnimationAt(string aniName, float normalizedTime)
{
animation.Play(aniName);
animation[aniName].normalizedTime = normalizedTime;
if (PhotonNetwork.connected && photonView.isMine)
{
photonView.RPC(Rpc.PlayAnimationAt, PhotonTargets.Others, aniName, normalizedTime);
}
}
private void playSound(string sndname)
{
this.PlaysoundRPC(sndname);
if (IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer)
{
photonView.RPC(Rpc.PlaySound, PhotonTargets.Others, sndname);
}
}
[RPC]
[UsedImplicitly]
private void PlaysoundRPC(string sndname)
{
transform.Find(sndname).GetComponent<AudioSource>().Play();
}
[RPC]
[UsedImplicitly]
private void RemoveMe()
{
PhotonNetwork.RemoveRPCs(photonView);
Destroy(gameObject);
}
[RPC]
[UsedImplicitly]
private void RockPlayAnimation(string anim)
{
this.rock.animation.Play(anim);
this.rock.animation[anim].speed = 1f;
}
private void RockUpdate()
{
if (!this.isHitWhileCarryingRock)
{
if (this.isROCKMOVE)
{
this.rock.transform.position = transform.position;
this.rock.transform.rotation = transform.rotation;
}
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)
{
if (this.rockPhase == 0)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -10f * rigidbody.mass, 0f));
this.waitCounter += Time.deltaTime;
if (this.waitCounter > 20f)
{
this.rockPhase++;
this.crossFade("idle", 1f);
this.waitCounter = 0f;
this.setRoute();
}
}
else if (this.rockPhase == 1)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -this.gravity * rigidbody.mass, 0f));
this.waitCounter += Time.deltaTime;
if (this.waitCounter > 2f)
{
this.rockPhase++;
this.crossFade("run", 0.2f);
this.waitCounter = 0f;
}
}
else if (this.rockPhase == 2)
{
Vector3 vector = transform.forward * 30f;
Vector3 velocity = rigidbody.velocity;
Vector3 force = vector - velocity;
force.x = Mathf.Clamp(force.x, -this.maxVelocityChange, this.maxVelocityChange);
force.z = Mathf.Clamp(force.z, -this.maxVelocityChange, this.maxVelocityChange);
force.y = 0f;
rigidbody.AddForce(force, ForceMode.VelocityChange);
if (transform.position.z < -238f)
{
transform.position = new Vector3(transform.position.x, 0f, -238f);
this.rockPhase++;
this.crossFade("idle", 0.2f);
this.waitCounter = 0f;
}
}
else if (this.rockPhase == 3)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -10f * rigidbody.mass, 0f));
this.waitCounter += Time.deltaTime;
if (this.waitCounter > 1f)
{
this.rockPhase++;
this.crossFade("rock_lift", 0.1f);
photonView.RPC(Rpc.PlayRockAnimation, PhotonTargets.All, "lift");
this.waitCounter = 0f;
this.targetCheckPt = (Vector3) this.checkPoints[0];
}
}
else if (this.rockPhase == 4)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -this.gravity * rigidbody.mass, 0f));
this.waitCounter += Time.deltaTime;
if (this.waitCounter > 4.2f)
{
this.rockPhase++;
this.crossFade("rock_walk", 0.1f);
object[] objArray3 = new object[] { "move" };
photonView.RPC(Rpc.PlayRockAnimation, PhotonTargets.All, objArray3);
this.rock.animation["move"].normalizedTime = animation["rock_walk"].normalizedTime;
this.waitCounter = 0f;
photonView.RPC(Rpc.StartRockAnimation, PhotonTargets.All);
}
}
else if (this.rockPhase == 5)
{
if (Vector3.Distance(transform.position, this.targetCheckPt) < 10f)
{
if (this.checkPoints.Count > 0)
{
if (this.checkPoints.Count == 1)
{
this.rockPhase++;
}
else
{
Vector3 vector6 = (Vector3) this.checkPoints[0];
this.targetCheckPt = vector6;
this.checkPoints.RemoveAt(0);
GameObject[] objArray = GameObject.FindGameObjectsWithTag("titanRespawn2");
GameObject obj2 = GameObject.Find("titanRespawnTrost" + (7 - this.checkPoints.Count));
if (obj2 != null)
{
foreach (GameObject obj3 in objArray)
{
if (obj3.transform.parent.gameObject == obj2)
{
GameObject obj4 = GameManager.instance.SpawnTitan(70, obj3.transform.position, obj3.transform.rotation);
obj4.GetComponent<TITAN>().isAlarm = true;
obj4.GetComponent<TITAN>().chaseDistance = 999999f;
}
}
}
}
}
else
{
this.rockPhase++;
}
}
if (this.checkPoints.Count > 0 && Random.Range(0, 3000) < 10 - this.checkPoints.Count)
{
Quaternion quaternion;
RaycastHit hit;
if (Random.Range(0, 10) > 5)
{
quaternion = transform.rotation * Quaternion.Euler(0f, Random.Range(150f, 210f), 0f);
}
else
{
quaternion = transform.rotation * Quaternion.Euler(0f, Random.Range(-30f, 30f), 0f);
}
Vector3 vector7 = quaternion * new Vector3(Random.Range(100f, 200f), 0f, 0f);
Vector3 position = transform.position + vector7;
LayerMask mask2 = 1 << LayerMask.NameToLayer("Ground");
float y = 0f;
if (Physics.Raycast(position + Vector3.up * 500f, -Vector3.up, out hit, 1000f, mask2.value))
{
y = hit.point.y;
}
position += Vector3.up * y;
GameObject obj5 = GameManager.instance.SpawnTitan(70, position, transform.rotation);
obj5.GetComponent<TITAN>().isAlarm = true;
obj5.GetComponent<TITAN>().chaseDistance = 999999f;
}
Vector3 vector10 = transform.forward * 6f;
Vector3 vector11 = rigidbody.velocity;
Vector3 vector12 = vector10 - vector11;
vector12.x = Mathf.Clamp(vector12.x, -this.maxVelocityChange, this.maxVelocityChange);
vector12.z = Mathf.Clamp(vector12.z, -this.maxVelocityChange, this.maxVelocityChange);
vector12.y = 0f;
rigidbody.AddForce(vector12, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -this.gravity * rigidbody.mass, 0f));
Vector3 vector13 = this.targetCheckPt - transform.position;
float current = -Mathf.Atan2(vector13.z, vector13.x) * 57.29578f;
float num4 = -Mathf.DeltaAngle(current, gameObject.transform.rotation.eulerAngles.y - 90f);
gameObject.transform.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, gameObject.transform.rotation.eulerAngles.y + num4, 0f), 0.8f * Time.deltaTime);
}
else if (this.rockPhase == 6)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -10f * rigidbody.mass, 0f));
transform.rotation = Quaternion.Euler(0f, 0f, 0f);
this.rockPhase++;
this.crossFade("rock_fix_hole", 0.1f);
object[] objArray4 = new object[] { "set" };
photonView.RPC(Rpc.PlayRockAnimation, PhotonTargets.All, objArray4);
photonView.RPC(Rpc.StopRockAnimation, PhotonTargets.All);
}
else if (this.rockPhase == 7)
{
rigidbody.AddForce(-rigidbody.velocity, ForceMode.VelocityChange);
rigidbody.AddForce(new Vector3(0f, -10f * rigidbody.mass, 0f));
if (animation["rock_fix_hole"].normalizedTime >= 1.2f)
{
this.crossFade("die", 0.1f);
this.rockPhase++;
GameManager.instance.GameWin();
}
if (animation["rock_fix_hole"].normalizedTime >= 0.62f && !this.rockHitGround)
{
this.rockHitGround = true;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient)
{
PhotonNetwork.Instantiate("FX/boom1_CT_KICK", new Vector3(0f, 30f, 684f), Quaternion.Euler(270f, 0f, 0f), 0);
}
else
{
Instantiate(Resources.Load("FX/boom1_CT_KICK"), new Vector3(0f, 30f, 684f), Quaternion.Euler(270f, 0f, 0f));
}
}
}
}
}
}
public void setRoute()
{
GameObject obj2 = GameObject.Find("routeTrost");
this.checkPoints = new ArrayList();
for (int i = 1; i <= 7; i++)
{
this.checkPoints.Add(obj2.transform.Find("r" + i).position);
}
this.checkPoints.Add("end");
}
private void showAimUI()
{
GameObject obj2 = GameObject.Find("cross1");
GameObject obj3 = GameObject.Find("cross2");
GameObject obj4 = GameObject.Find("crossL1");
GameObject obj5 = GameObject.Find("crossL2");
GameObject obj6 = GameObject.Find("crossR1");
GameObject obj7 = GameObject.Find("crossR2");
GameObject obj8 = GameObject.Find("LabelDistance");
Vector3 vector = Vector3.up * 10000f;
obj7.transform.localPosition = vector;
obj6.transform.localPosition = vector;
obj5.transform.localPosition = vector;
obj4.transform.localPosition = vector;
obj8.transform.localPosition = vector;
obj3.transform.localPosition = vector;
obj2.transform.localPosition = vector;
}
private void showSkillCD()
{
GameObject.Find("skill_cd_eren").GetComponent<UISprite>().fillAmount = this.lifeTime / this.lifeTimeMax;
}
private void Start()
{
this.loadskin();
GameManager.instance.ErenTitans.Add(this);
if (this.rockLift)
{
this.rock = GameObject.Find("rock");
this.rock.animation["lift"].speed = 0f;
}
else
{
this.currentCamera = GameObject.Find("MainCamera").GetComponent<Camera>();
this.oldCorePosition = transform.position - transform.Find("Amarture/Core").position;
this.myR = Mathf.Sqrt(2) * 6f;
animation["hit_annie_1"].speed = 0.8f;
animation["hit_annie_2"].speed = 0.7f;
animation["hit_annie_3"].speed = 0.7f;
}
this.hasSpawn = true;
}
[RPC]
[UsedImplicitly]
private void StartMovingRock()
{
this.isROCKMOVE = true;
}
public void DoUpdate()
{
if ((!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer) && !this.rockLift)
{
if (animation.IsPlaying("run"))
{
if (animation["run"].normalizedTime % 1f > 0.3f && animation["run"].normalizedTime % 1f < 0.75f && this.stepSoundPhase == 2)
{
this.stepSoundPhase = 1;
Transform tr = this.transform.Find("snd_eren_foot");
tr.GetComponent<AudioSource>().Stop();
tr.GetComponent<AudioSource>().Play();
}
if (animation["run"].normalizedTime % 1f > 0.75f && this.stepSoundPhase == 1)
{
this.stepSoundPhase = 2;
Transform transform2 = transform.Find("snd_eren_foot");
transform2.GetComponent<AudioSource>().Stop();
transform2.GetComponent<AudioSource>().Play();
}
}
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)
{
if (this.hasDied)
{
if (animation["die"].normalizedTime >= 1f || this.hitAnimation == "hit_annie_3")
{
if (this.realBody != null)
{
this.realBody.GetComponent<HERO>().backToHuman();
this.realBody.transform.position = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck").position + Vector3.up * 2f;
this.realBody = null;
}
this.dieTime += Time.deltaTime;
if (this.dieTime > 2f && !this.hasDieSteam)
{
this.hasDieSteam = true;
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
{
GameObject obj2 = (GameObject)Instantiate(Resources.Load("FX/FXtitanDie1"));
obj2.transform.position = transform.Find("Amarture/Core/Controller_Body/hip").position;
obj2.transform.localScale = transform.localScale;
}
else if (photonView.isMine)
{
PhotonNetwork.Instantiate("FX/FXtitanDie1", transform.Find("Amarture/Core/Controller_Body/hip").position, Quaternion.Euler(-90f, 0f, 0f), 0).transform.localScale = transform.localScale;
}
}
if (this.dieTime > 5f)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
{
GameObject obj4 = (GameObject)Instantiate(Resources.Load("FX/FXtitanDie"));
obj4.transform.position = transform.Find("Amarture/Core/Controller_Body/hip").position;
obj4.transform.localScale = transform.localScale;
Destroy(gameObject);
}
else if (photonView.isMine)
{
PhotonNetwork.Instantiate("FX/FXtitanDie", transform.Find("Amarture/Core/Controller_Body/hip").position, Quaternion.Euler(-90f, 0f, 0f), 0).transform.localScale = transform.localScale;
PhotonNetwork.Destroy(photonView);
}
}
}
}
else if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)
{
if (this.isHit)
{
if (animation[this.hitAnimation].normalizedTime >= 1f)
{
this.isHit = false;
this.falseAttack();
this.playAnimation("idle");
}
}
else
{
if (this.lifeTime > 0f)
{
this.lifeTime -= Time.deltaTime;
if (this.lifeTime <= 0f)
{
this.hasDied = true;
this.playAnimation("die");
return;
}
}
if (this.grounded && !this.isAttack && !animation.IsPlaying("jump_land") && !this.isAttack && !animation.IsPlaying("born"))
{
if (Shelter.InputManager.IsDown(InputAction.Attack) || Shelter.InputManager.IsDown(InputAction.Special))
{
bool flag = false;
if (IN_GAME_MAIN_CAMERA.cameraMode == CameraType.Stop && Shelter.InputManager.IsKeyPressed(InputAction.Back) || Shelter.InputManager.IsDown(InputAction.Special))
{
if (IN_GAME_MAIN_CAMERA.cameraMode == CameraType.Stop && Shelter.InputManager.IsDown(InputAction.Special))
{
flag = true;
}
if (!flag)
{
this.attackAnimation = "attack_kick";
}
}
else
{
this.attackAnimation = "attack_combo_001";
}
if (!flag)
{
this.playAnimation(this.attackAnimation);
animation[this.attackAnimation].time = 0f;
this.isAttack = true;
this.needFreshCorePosition = true;
if (this.attackAnimation == "attack_combo_001" || this.attackAnimation == "attack_combo_001")
{
this.attackBox = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R");
}
else if (this.attackAnimation == "attack_combo_002")
{
this.attackBox = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L");
}
else if (this.attackAnimation == "attack_kick")
{
this.attackBox = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R/shin_R/foot_R");
}
this.hitTargets = new ArrayList();
}
}
if (Shelter.InputManager.IsDown(InputAction.Salute))
{
this.crossFade("born", 0.1f);
animation["born"].normalizedTime = 0.28f;
this.isPlayRoar = false;
}
}
if (!this.isAttack)
{
if ((this.grounded || animation.IsPlaying("idle")) && (!animation.IsPlaying("jump_start") && !animation.IsPlaying("jump_air")) && !animation.IsPlaying("jump_land") && Shelter.InputManager.IsDown(InputAction.BothHooks))
{
this.crossFade("jump_start", 0.1f);
}
}
else
{
if (animation[this.attackAnimation].time >= 0.1f && Shelter.InputManager.IsDown(InputAction.Attack))
{
this.isNextAttack = true;
}
float num = 0f;
float num2 = 0f;
float num3 = 0f;
string str = string.Empty;
switch (this.attackAnimation)
{
case "attack_combo_001":
num = 0.4f;
num2 = 0.5f;
num3 = 0.66f;
str = "attack_combo_002";
break;
case "attack_combo_002":
num = 0.15f;
num2 = 0.25f;
num3 = 0.43f;
str = "attack_combo_003";
break;
case "attack_combo_003":
num3 = 0f;
num = 0.31f;
num2 = 0.37f;
break;
case "attack_kick":
num3 = 0f;
num = 0.32f;
num2 = 0.38f;
break;
default:
num = 0.5f;
num2 = 0.85f;
break;
}
if (this.hitPause > 0f)
{
this.hitPause -= Time.deltaTime;
if (this.hitPause <= 0f)
{
animation[this.attackAnimation].speed = 1f;
this.hitPause = 0f;
}
}
if (num3 > 0f && this.isNextAttack && animation[this.attackAnimation].normalizedTime >= num3)
{
if (this.hitTargets.Count > 0)
{
Transform transform3 = (Transform)this.hitTargets[0];
if (transform3 != null)
{
transform.rotation = Quaternion.Euler(0f, Quaternion.LookRotation(transform3.position - transform.position).eulerAngles.y, 0f);
this.facingDirection = transform.rotation.eulerAngles.y;
}
}
this.falseAttack();
this.attackAnimation = str;
this.crossFade(this.attackAnimation, 0.1f);
animation[this.attackAnimation].time = 0f;
animation[this.attackAnimation].speed = 1f;
this.isAttack = true;
this.needFreshCorePosition = true;
if (this.attackAnimation == "attack_combo_002")
{
this.attackBox = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L");
}
else if (this.attackAnimation == "attack_combo_003")
{
this.attackBox = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R");
}
this.hitTargets = new ArrayList();
}
if (animation[this.attackAnimation].normalizedTime >= num && animation[this.attackAnimation].normalizedTime <= num2 || !this.attackChkOnce && animation[this.attackAnimation].normalizedTime >= num)
{
if (!this.attackChkOnce)
{
if (this.attackAnimation == "attack_combo_002")
{
this.playSound("snd_eren_swing2");
}
else if (this.attackAnimation == "attack_combo_001")
{
this.playSound("snd_eren_swing1");
}
else if (this.attackAnimation == "attack_combo_003")
{
this.playSound("snd_eren_swing3");
}
this.attackChkOnce = true;
}
Collider[] colliderArray = Physics.OverlapSphere(this.attackBox.transform.position, 8f);
for (int i = 0; i < colliderArray.Length; i++)
{
if (colliderArray[i].gameObject.transform.root.GetComponent<TITAN>() == null)
{
continue;
}
bool flag2 = false;
for (int j = 0; j < this.hitTargets.Count; j++)
{
if (colliderArray[i].gameObject.transform.root == (Transform)this.hitTargets[j])
{
flag2 = true;
break;
}
}
if (!flag2 && !colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().hasDie)
{
animation[this.attackAnimation].speed = 0f;
if (this.attackAnimation == "attack_combo_002")
{
this.hitPause = 0.05f;
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().HitLeft(transform.position, this.hitPause);
this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(1f, 0.03f);
}
else if (this.attackAnimation == "attack_combo_001")
{
this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(1.2f, 0.04f);
this.hitPause = 0.08f;
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().HitRight(transform.position, this.hitPause);
}
else if (this.attackAnimation == "attack_combo_003")
{
this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(3f, 0.1f);
this.hitPause = 0.3f;
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().dieHeadBlow(transform.position, this.hitPause);
}
else if (this.attackAnimation == "attack_kick")
{
this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(3f, 0.1f);
this.hitPause = 0.2f;
if (colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().abnormalType == AbnormalType.Crawler)
{
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().dieBlow(transform.position, this.hitPause);
}
else if (colliderArray[i].gameObject.transform.root.transform.localScale.x < 2f)
{
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().dieBlow(transform.position, this.hitPause);
}
else
{
colliderArray[i].gameObject.transform.root.GetComponent<TITAN>().HitRight(transform.position, this.hitPause);
}
}
this.hitTargets.Add(colliderArray[i].gameObject.transform.root);
if (IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer)
{
PhotonNetwork.Instantiate("hitMeatBIG", (colliderArray[i].transform.position + this.attackBox.position) * 0.5f, Quaternion.Euler(270f, 0f, 0f), 0);
}
else
{
Instantiate(Resources.Load("hitMeatBIG"), (colliderArray[i].transform.position + this.attackBox.position) * 0.5f, Quaternion.Euler(270f, 0f, 0f));
}
}
}
}
if (animation[this.attackAnimation].normalizedTime >= 1f)
{
this.falseAttack();
this.playAnimation("idle");
}
}
if (animation.IsPlaying("jump_land") && animation["jump_land"].normalizedTime >= 1f)
{
this.crossFade("idle", 0.1f);
}
if (animation.IsPlaying("born"))
{
if (animation["born"].normalizedTime >= 0.28f && !this.isPlayRoar)
{
this.isPlayRoar = true;
this.playSound("snd_eren_roar");
}
if (animation["born"].normalizedTime >= 0.5f && animation["born"].normalizedTime <= 0.7f)
{
this.currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(0.5f, 1f);
}
if (animation["born"].normalizedTime >= 1f)
{
this.crossFade("idle", 0.1f);
if (IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer)
{
if (PhotonNetwork.isMasterClient)
{
photonView.RPC(Rpc.TauntAttack, PhotonTargets.MasterClient, 10f, 500f);
}
else
{
this.NetTauntAttack(10f, 500f);
}
}
else
{
this.NetTauntAttack(10f, 500f);
}
}
}
this.showAimUI();
this.showSkillCD();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Content.Server.Audio;
using Content.Server.Damage.Systems;
using Content.Server.Power.Components;
using Content.Server.Shuttles.Components;
using Content.Shared.Damage;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Maps;
using Content.Shared.Physics;
using Content.Shared.Temperature;
using Content.Shared.Shuttles.Components;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Collision.Shapes;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Utility;
namespace Content.Server.Shuttles.EntitySystems
{
public sealed class ThrusterSystem : EntitySystem
{
[Robust.Shared.IoC.Dependency] private readonly IMapManager _mapManager = default!;
[Robust.Shared.IoC.Dependency] private readonly AmbientSoundSystem _ambient = default!;
[Robust.Shared.IoC.Dependency] private readonly FixtureSystem _fixtureSystem = default!;
[Robust.Shared.IoC.Dependency] private readonly DamageableSystem _damageable = default!;
// Essentially whenever thruster enables we update the shuttle's available impulses which are used for movement.
// This is done for each direction available.
public const string BurnFixture = "thruster-burn";
private readonly HashSet<ThrusterComponent> _activeThrusters = new();
// Used for accumulating burn if someone touches a firing thruster.
private float _accumulator;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ThrusterComponent, ActivateInWorldEvent>(OnActivateThruster);
SubscribeLocalEvent<ThrusterComponent, ComponentInit>(OnThrusterInit);
SubscribeLocalEvent<ThrusterComponent, ComponentShutdown>(OnThrusterShutdown);
SubscribeLocalEvent<ThrusterComponent, PowerChangedEvent>(OnPowerChange);
SubscribeLocalEvent<ThrusterComponent, AnchorStateChangedEvent>(OnAnchorChange);
SubscribeLocalEvent<ThrusterComponent, RotateEvent>(OnRotate);
SubscribeLocalEvent<ThrusterComponent, IsHotEvent>(OnIsHotEvent);
SubscribeLocalEvent<ThrusterComponent, StartCollideEvent>(OnStartCollide);
SubscribeLocalEvent<ThrusterComponent, EndCollideEvent>(OnEndCollide);
SubscribeLocalEvent<ThrusterComponent, ExaminedEvent>(OnThrusterExamine);
_mapManager.TileChanged += OnTileChange;
}
private void OnThrusterExamine(EntityUid uid, ThrusterComponent component, ExaminedEvent args)
{
// Powered is already handled by other power components
var enabled = Loc.GetString("thruster-comp-enabled",
("enabledColor", component.Enabled ? "green": "red"),
("enabled", component.Enabled ? "on": "off"));
args.PushMarkup(enabled);
if (component.Type == ThrusterType.Linear &&
EntityManager.TryGetComponent(uid, out TransformComponent? xform) &&
xform.Anchored)
{
var nozzleDir = Loc.GetString("thruster-comp-nozzle-direction",
("direction", xform.LocalRotation.Opposite().ToWorldVec().GetDir().ToString().ToLowerInvariant()));
args.PushMarkup(nozzleDir);
var exposed = NozzleExposed(xform);
var nozzleText = Loc.GetString("thruster-comp-nozzle-exposed",
("exposedColor", exposed ? "green" : "red"),
("exposed", exposed ? "is": "is not"));
args.PushMarkup(nozzleText);
}
}
public override void Shutdown()
{
base.Shutdown();
_mapManager.TileChanged -= OnTileChange;
}
private void OnIsHotEvent(EntityUid uid, ThrusterComponent component, IsHotEvent args)
{
args.IsHot = component.Type != ThrusterType.Angular && component.IsOn;
}
private void OnTileChange(object? sender, TileChangedEventArgs e)
{
// If the old tile was space but the new one isn't then disable all adjacent thrusters
if (e.NewTile.IsSpace() || !e.OldTile.IsSpace()) return;
var tilePos = e.NewTile.GridIndices;
for (var x = -1; x <= 1; x++)
{
for (var y = -1; y <= 1; y++)
{
if (x != 0 && y != 0) continue;
var checkPos = tilePos + new Vector2i(x, y);
foreach (var ent in _mapManager.GetGrid(e.NewTile.GridIndex).GetAnchoredEntities(checkPos))
{
if (!EntityManager.TryGetComponent(ent, out ThrusterComponent? thruster) || !thruster.RequireSpace) continue;
// Work out if the thruster is facing this direction
var direction = EntityManager.GetComponent<TransformComponent>(ent).LocalRotation.ToWorldVec();
if (new Vector2i((int) direction.X, (int) direction.Y) != new Vector2i(x, y)) continue;
DisableThruster(ent, thruster);
}
}
}
}
private void OnActivateThruster(EntityUid uid, ThrusterComponent component, ActivateInWorldEvent args)
{
component.Enabled ^= true;
}
/// <summary>
/// If the thruster rotates change the direction where the linear thrust is applied
/// </summary>
private void OnRotate(EntityUid uid, ThrusterComponent component, ref RotateEvent args)
{
// TODO: Disable visualizer for old direction
if (!component.Enabled ||
component.Type != ThrusterType.Linear ||
!EntityManager.TryGetComponent(uid, out TransformComponent? xform) ||
!_mapManager.TryGetGrid(xform.GridID, out var grid) ||
!EntityManager.TryGetComponent(grid.GridEntityId, out ShuttleComponent? shuttleComponent))
{
return;
}
var canEnable = CanEnable(uid, component);
// If it's not on then don't enable it inadvertantly (given we don't have an old rotation)
if (!canEnable && !component.IsOn) return;
// Enable it if it was turned off but new tile is valid
if (!component.IsOn && canEnable)
{
EnableThruster(uid, component);
return;
}
// Disable if new tile invalid
if (component.IsOn && !canEnable)
{
DisableThruster(uid, component, xform, args.OldRotation);
return;
}
var oldDirection = (int) args.OldRotation.GetCardinalDir() / 2;
var direction = (int) args.NewRotation.GetCardinalDir() / 2;
shuttleComponent.LinearThrust[oldDirection] -= component.Thrust;
DebugTools.Assert(shuttleComponent.LinearThrusters[oldDirection].Contains(component));
shuttleComponent.LinearThrusters[oldDirection].Remove(component);
shuttleComponent.LinearThrust[direction] += component.Thrust;
DebugTools.Assert(!shuttleComponent.LinearThrusters[direction].Contains(component));
shuttleComponent.LinearThrusters[direction].Add(component);
}
private void OnAnchorChange(EntityUid uid, ThrusterComponent component, ref AnchorStateChangedEvent args)
{
if (args.Anchored && CanEnable(uid, component))
{
EnableThruster(uid, component);
}
else
{
DisableThruster(uid, component);
}
}
private void OnThrusterInit(EntityUid uid, ThrusterComponent component, ComponentInit args)
{
_ambient.SetAmbience(uid, false);
if (!component.Enabled)
{
return;
}
if (CanEnable(uid, component))
{
EnableThruster(uid, component);
}
}
private void OnThrusterShutdown(EntityUid uid, ThrusterComponent component, ComponentShutdown args)
{
DisableThruster(uid, component);
}
private void OnPowerChange(EntityUid uid, ThrusterComponent component, PowerChangedEvent args)
{
if (args.Powered && CanEnable(uid, component))
{
EnableThruster(uid, component);
}
else
{
DisableThruster(uid, component);
}
}
/// <summary>
/// Tries to enable the thruster and turn it on. If it's already enabled it does nothing.
/// </summary>
public void EnableThruster(EntityUid uid, ThrusterComponent component, TransformComponent? xform = null)
{
if (component.IsOn ||
!Resolve(uid, ref xform) ||
!_mapManager.TryGetGrid(xform.GridID, out var grid)) return;
component.IsOn = true;
if (!EntityManager.TryGetComponent(grid.GridEntityId, out ShuttleComponent? shuttleComponent)) return;
// Logger.DebugS("thruster", $"Enabled thruster {uid}");
switch (component.Type)
{
case ThrusterType.Linear:
var direction = (int) xform.LocalRotation.GetCardinalDir() / 2;
shuttleComponent.LinearThrust[direction] += component.Thrust;
DebugTools.Assert(!shuttleComponent.LinearThrusters[direction].Contains(component));
shuttleComponent.LinearThrusters[direction].Add(component);
// Don't just add / remove the fixture whenever the thruster fires because perf
if (EntityManager.TryGetComponent(uid, out PhysicsComponent? physicsComponent) &&
component.BurnPoly.Count > 0)
{
var shape = new PolygonShape();
shape.SetVertices(component.BurnPoly);
var fixture = new Fixture(physicsComponent, shape)
{
ID = BurnFixture,
Hard = false,
CollisionLayer = (int) CollisionGroup.MobImpassable
};
_fixtureSystem.CreateFixture(physicsComponent, fixture);
}
break;
case ThrusterType.Angular:
shuttleComponent.AngularThrust += component.Thrust;
DebugTools.Assert(!shuttleComponent.AngularThrusters.Contains(component));
shuttleComponent.AngularThrusters.Add(component);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (EntityManager.TryGetComponent(uid, out AppearanceComponent? appearanceComponent))
{
appearanceComponent.SetData(ThrusterVisualState.State, true);
}
if (EntityManager.TryGetComponent(uid, out PointLightComponent? pointLightComponent))
{
pointLightComponent.Enabled = true;
}
_ambient.SetAmbience(uid, true);
}
/// <summary>
/// Tries to disable the thruster.
/// </summary>
public void DisableThruster(EntityUid uid, ThrusterComponent component, TransformComponent? xform = null, Angle? angle = null)
{
if (!component.IsOn ||
!Resolve(uid, ref xform) ||
!_mapManager.TryGetGrid(xform.GridID, out var grid)) return;
component.IsOn = false;
if (!EntityManager.TryGetComponent(grid.GridEntityId, out ShuttleComponent? shuttleComponent)) return;
// Logger.DebugS("thruster", $"Disabled thruster {uid}");
switch (component.Type)
{
case ThrusterType.Linear:
angle ??= xform.LocalRotation;
var direction = (int) angle.Value.GetCardinalDir() / 2;
shuttleComponent.LinearThrust[direction] -= component.Thrust;
DebugTools.Assert(shuttleComponent.LinearThrusters[direction].Contains(component));
shuttleComponent.LinearThrusters[direction].Remove(component);
break;
case ThrusterType.Angular:
shuttleComponent.AngularThrust -= component.Thrust;
DebugTools.Assert(shuttleComponent.AngularThrusters.Contains(component));
shuttleComponent.AngularThrusters.Remove(component);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (EntityManager.TryGetComponent(uid, out AppearanceComponent? appearanceComponent))
{
appearanceComponent.SetData(ThrusterVisualState.State, false);
}
if (EntityManager.TryGetComponent(uid, out PointLightComponent? pointLightComponent))
{
pointLightComponent.Enabled = false;
}
_ambient.SetAmbience(uid, false);
if (EntityManager.TryGetComponent(uid, out PhysicsComponent? physicsComponent))
{
_fixtureSystem.DestroyFixture(physicsComponent, BurnFixture);
}
_activeThrusters.Remove(component);
component.Colliding.Clear();
}
public bool CanEnable(EntityUid uid, ThrusterComponent component)
{
if (!component.Enabled) return false;
var xform = EntityManager.GetComponent<TransformComponent>(uid);
if (!xform.Anchored ||
EntityManager.TryGetComponent(uid, out ApcPowerReceiverComponent? receiver) && !receiver.Powered)
{
return false;
}
if (!component.RequireSpace)
return true;
return NozzleExposed(xform);
}
private bool NozzleExposed(TransformComponent xform)
{
var (x, y) = xform.LocalPosition + xform.LocalRotation.Opposite().ToWorldVec();
var tile = _mapManager.GetGrid(xform.GridID).GetTileRef(new Vector2i((int) Math.Floor(x), (int) Math.Floor(y)));
return tile.Tile.IsSpace();
}
#region Burning
public override void Update(float frameTime)
{
base.Update(frameTime);
_accumulator += frameTime;
if (_accumulator < 1) return;
_accumulator -= 1;
foreach (var comp in _activeThrusters.ToArray())
{
MetaDataComponent? metaData = null;
if (!comp.Firing || comp.Damage == null || Paused(comp.Owner, metaData) || Deleted(comp.Owner, metaData)) continue;
DebugTools.Assert(comp.Colliding.Count > 0);
foreach (var uid in comp.Colliding.ToArray())
{
_damageable.TryChangeDamage(uid, comp.Damage);
}
}
}
private void OnStartCollide(EntityUid uid, ThrusterComponent component, StartCollideEvent args)
{
if (args.OurFixture.ID != BurnFixture) return;
_activeThrusters.Add(component);
component.Colliding.Add((args.OtherFixture.Body).Owner);
}
private void OnEndCollide(EntityUid uid, ThrusterComponent component, EndCollideEvent args)
{
if (args.OurFixture.ID != BurnFixture) return;
component.Colliding.Remove((args.OtherFixture.Body).Owner);
if (component.Colliding.Count == 0)
{
_activeThrusters.Remove(component);
}
}
/// <summary>
/// Considers a thrust direction as being active.
/// </summary>
public void EnableLinearThrustDirection(ShuttleComponent component, DirectionFlag direction)
{
if ((component.ThrustDirections & direction) != 0x0) return;
component.ThrustDirections |= direction;
var index = GetFlagIndex(direction);
foreach (var comp in component.LinearThrusters[index])
{
if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent))
continue;
comp.Firing = true;
appearanceComponent.SetData(ThrusterVisualState.Thrusting, true);
}
}
/// <summary>
/// Disables a thrust direction.
/// </summary>
public void DisableLinearThrustDirection(ShuttleComponent component, DirectionFlag direction)
{
if ((component.ThrustDirections & direction) == 0x0) return;
component.ThrustDirections &= ~direction;
var index = GetFlagIndex(direction);
foreach (var comp in component.LinearThrusters[index])
{
if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent))
continue;
comp.Firing = false;
appearanceComponent.SetData(ThrusterVisualState.Thrusting, false);
}
}
public void DisableLinearThrusters(ShuttleComponent component)
{
foreach (DirectionFlag dir in Enum.GetValues(typeof(DirectionFlag)))
{
DisableLinearThrustDirection(component, dir);
}
DebugTools.Assert(component.ThrustDirections == DirectionFlag.None);
}
public void SetAngularThrust(ShuttleComponent component, bool on)
{
if (on)
{
foreach (var comp in component.AngularThrusters)
{
if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent))
continue;
comp.Firing = true;
appearanceComponent.SetData(ThrusterVisualState.Thrusting, true);
}
}
else
{
foreach (var comp in component.AngularThrusters)
{
if (!EntityManager.TryGetComponent((comp).Owner, out AppearanceComponent? appearanceComponent))
continue;
comp.Firing = false;
appearanceComponent.SetData(ThrusterVisualState.Thrusting, false);
}
}
}
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetFlagIndex(DirectionFlag flag)
{
return (int) Math.Log2((int) flag);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.HSSF.Model;
using System.Globalization;
/// <summary>
/// @author Glen Stampoultzis
/// </summary>
public class ColumnInfoRecordsAggregate : RecordAggregate
{
private class CIRComparator : IComparer
{
public static IComparer instance = new CIRComparator();
private CIRComparator()
{
// enforce singleton
}
public int Compare(Object a, Object b)
{
return CompareColInfos((ColumnInfoRecord)a, (ColumnInfoRecord)b);
}
public static int CompareColInfos(ColumnInfoRecord a, ColumnInfoRecord b)
{
return a.FirstColumn - b.FirstColumn;
}
}
// int size = 0;
ArrayList records = null;
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfoRecordsAggregate"/> class.
/// </summary>
public ColumnInfoRecordsAggregate()
{
records = new ArrayList();
}
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfoRecordsAggregate"/> class.
/// </summary>
/// <param name="rs">The rs.</param>
public ColumnInfoRecordsAggregate(RecordStream rs): this()
{
bool isInOrder = true;
ColumnInfoRecord cirPrev = null;
while (rs.PeekNextClass() == typeof(ColumnInfoRecord))
{
ColumnInfoRecord cir = (ColumnInfoRecord)rs.GetNext();
records.Add(cir);
if (cirPrev != null && CIRComparator.CompareColInfos(cirPrev, cir) > 0)
{
isInOrder = false;
}
cirPrev = cir;
}
if (records.Count < 1)
{
throw new InvalidOperationException("No column info records found");
}
if (!isInOrder)
{
records.Sort(CIRComparator.instance);
}
}
/** It's an aggregate... just made something up */
public override short Sid
{
get { return -1012; }
}
/// <summary>
/// Gets the num columns.
/// </summary>
/// <value>The num columns.</value>
public int NumColumns
{
get
{
return records.Count;
}
}
/// <summary>
/// Gets the size of the record.
/// </summary>
/// <value>The size of the record.</value>
public override int RecordSize
{
get
{
int size = 0;
for (IEnumerator iterator = records.GetEnumerator(); iterator.MoveNext(); )
size += ((ColumnInfoRecord)iterator.Current).RecordSize;
return size;
}
}
public IEnumerator GetEnumerator()
{
return records.GetEnumerator();
}
/**
* Performs a deep Clone of the record
*/
public Object Clone()
{
ColumnInfoRecordsAggregate rec = new ColumnInfoRecordsAggregate();
for (int k = 0; k < records.Count; k++)
{
ColumnInfoRecord ci = (ColumnInfoRecord)records[k];
ci = (ColumnInfoRecord)ci.Clone();
rec.records.Add(ci);
}
return rec;
}
/// <summary>
/// Inserts a column into the aggregate (at the end of the list).
/// </summary>
/// <param name="col">The column.</param>
public void InsertColumn(ColumnInfoRecord col)
{
records.Add(col);
records.Sort(CIRComparator.instance);
}
/// <summary>
/// Inserts a column into the aggregate (at the position specified
/// by index
/// </summary>
/// <param name="idx">The index.</param>
/// <param name="col">The columninfo.</param>
public void InsertColumn(int idx, ColumnInfoRecord col)
{
records.Insert(idx, col);
}
/// <summary>
/// called by the class that is responsible for writing this sucker.
/// Subclasses should implement this so that their data is passed back in a
/// byte array.
/// </summary>
/// <param name="offset">offset to begin writing at</param>
/// <param name="data">byte array containing instance data</param>
/// <returns>number of bytes written</returns>
public override int Serialize(int offset, byte[] data)
{
IEnumerator itr = records.GetEnumerator();
int pos = offset;
while (itr.MoveNext())
{
pos += ((Record)itr.Current).Serialize(pos, data);
}
return pos - offset;
}
/// <summary>
/// Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order
/// that they should be written to file. Implementors may or may not return the actual
/// Records being used to manage POI's internal implementation. Callers should not
/// assume either way, and therefore only attempt to modify those Records after cloning
/// </summary>
/// <param name="rv"></param>
public override void VisitContainedRecords(RecordVisitor rv)
{
int nItems = records.Count;
if (nItems < 1)
{
return;
}
ColumnInfoRecord cirPrev = null;
for (int i = 0; i < nItems; i++)
{
ColumnInfoRecord cir = (ColumnInfoRecord)records[i];
rv.VisitRecord(cir);
if (cirPrev != null && CIRComparator.CompareColInfos(cirPrev, cir) > 0)
{
// Excel probably wouldn't mind, but there is much logic in this class
// that assumes the column info records are kept in order
throw new InvalidOperationException("Column info records are out of order");
}
cirPrev = cir;
}
}
/// <summary>
/// Finds the start of column outline group.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public int FindStartOfColumnOutlineGroup(int idx)
{
// Find the start of the Group.
ColumnInfoRecord columnInfo = (ColumnInfoRecord)records[idx];
int level = columnInfo.OutlineLevel;
while (idx != 0)
{
ColumnInfoRecord prevColumnInfo = (ColumnInfoRecord)records[idx - 1];
if (columnInfo.FirstColumn - 1 == prevColumnInfo.LastColumn)
{
if (prevColumnInfo.OutlineLevel < level)
{
break;
}
idx--;
columnInfo = prevColumnInfo;
}
else
{
break;
}
}
return idx;
}
/// <summary>
/// Finds the end of column outline group.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public int FindEndOfColumnOutlineGroup(int idx)
{
// Find the end of the Group.
ColumnInfoRecord columnInfo = (ColumnInfoRecord)records[idx];
int level = columnInfo.OutlineLevel;
while (idx < records.Count - 1)
{
ColumnInfoRecord nextColumnInfo = (ColumnInfoRecord)records[idx + 1];
if (columnInfo.LastColumn + 1 == nextColumnInfo.FirstColumn)
{
if (nextColumnInfo.OutlineLevel < level)
{
break;
}
idx++;
columnInfo = nextColumnInfo;
}
else
{
break;
}
}
return idx;
}
/// <summary>
/// Gets the col info.
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns></returns>
public ColumnInfoRecord GetColInfo(int idx)
{
return (ColumnInfoRecord)records[idx];
}
/// <summary>
/// Determines whether [is column group collapsed] [the specified idx].
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns>
/// <c>true</c> if [is column group collapsed] [the specified idx]; otherwise, <c>false</c>.
/// </returns>
public bool IsColumnGroupCollapsed(int idx)
{
int endOfOutlineGroupIdx = FindEndOfColumnOutlineGroup(idx);
int nextColInfoIx = endOfOutlineGroupIdx + 1;
if (nextColInfoIx >= records.Count)
{
return false;
}
ColumnInfoRecord nextColInfo = GetColInfo(nextColInfoIx);
if (!GetColInfo(endOfOutlineGroupIdx).IsAdjacentBefore(nextColInfo))
{
return false;
}
return nextColInfo.IsCollapsed;
}
/// <summary>
/// Determines whether [is column group hidden by parent] [the specified idx].
/// </summary>
/// <param name="idx">The idx.</param>
/// <returns>
/// <c>true</c> if [is column group hidden by parent] [the specified idx]; otherwise, <c>false</c>.
/// </returns>
public bool IsColumnGroupHiddenByParent(int idx)
{
// Look out outline details of end
int endLevel = 0;
bool endHidden = false;
int endOfOutlineGroupIdx = FindEndOfColumnOutlineGroup(idx);
if (endOfOutlineGroupIdx < records.Count)
{
ColumnInfoRecord nextInfo = GetColInfo(endOfOutlineGroupIdx + 1);
if (GetColInfo(endOfOutlineGroupIdx).IsAdjacentBefore(nextInfo))
{
endLevel = nextInfo.OutlineLevel;
endHidden = nextInfo.IsHidden;
}
}
// Look out outline details of start
int startLevel = 0;
bool startHidden = false;
int startOfOutlineGroupIdx = FindStartOfColumnOutlineGroup(idx);
if (startOfOutlineGroupIdx > 0)
{
ColumnInfoRecord prevInfo = GetColInfo(startOfOutlineGroupIdx - 1);
if (prevInfo.IsAdjacentBefore(GetColInfo(startOfOutlineGroupIdx)))
{
startLevel = prevInfo.OutlineLevel;
startHidden = prevInfo.IsHidden;
}
}
if (endLevel > startLevel)
{
return endHidden;
}
return startHidden;
}
/// <summary>
/// Collapses the column.
/// </summary>
/// <param name="columnNumber">The column number.</param>
public void CollapseColumn(int columnNumber)
{
int idx = FindColInfoIdx(columnNumber, 0);
if (idx == -1)
return;
// Find the start of the group.
int groupStartColInfoIx = FindStartOfColumnOutlineGroup(idx);
ColumnInfoRecord columnInfo = GetColInfo(groupStartColInfoIx);
// Hide all the columns until the end of the group
int lastColIx = SetGroupHidden(groupStartColInfoIx, columnInfo.OutlineLevel, true);
// Write collapse field
SetColumn(lastColIx + 1, null, null, null, null, true);
}
/// <summary>
/// Expands the column.
/// </summary>
/// <param name="columnNumber">The column number.</param>
public void ExpandColumn(int columnNumber)
{
int idx = FindColInfoIdx(columnNumber, 0);
if (idx == -1)
return;
// If it is already exapanded do nothing.
if (!IsColumnGroupCollapsed(idx))
return;
// Find the start of the Group.
int startIdx = FindStartOfColumnOutlineGroup(idx);
ColumnInfoRecord columnInfo = GetColInfo(startIdx);
// Find the end of the Group.
int endIdx = FindEndOfColumnOutlineGroup(idx);
ColumnInfoRecord endColumnInfo = GetColInfo(endIdx);
// expand:
// colapsed bit must be UnSet
// hidden bit Gets UnSet _if_ surrounding Groups are expanded you can determine
// this by looking at the hidden bit of the enclosing Group. You will have
// to look at the start and the end of the current Group to determine which
// is the enclosing Group
// hidden bit only is altered for this outline level. ie. don't Uncollapse contained Groups
if (!IsColumnGroupHiddenByParent(idx))
{
for (int i = startIdx; i <= endIdx; i++)
{
if (columnInfo.OutlineLevel == GetColInfo(i).OutlineLevel)
GetColInfo(i).IsHidden = false;
}
}
// Write collapse field
SetColumn(columnInfo.LastColumn + 1, null, null, null, null, false);
}
/**
* Sets all non null fields into the <c>ci</c> parameter.
*/
private static void SetColumnInfoFields(ColumnInfoRecord ci, short? xfStyle, int? width,
int? level, Boolean? hidden, Boolean? collapsed)
{
if (xfStyle != null)
{
ci.XFIndex = Convert.ToInt16(xfStyle, CultureInfo.InvariantCulture);
}
if (width != null)
{
ci.ColumnWidth = Convert.ToInt32(width, CultureInfo.InvariantCulture);
}
if (level != null)
{
ci.OutlineLevel = (short)level;
}
if (hidden != null)
{
ci.IsHidden = Convert.ToBoolean(hidden, CultureInfo.InvariantCulture);
}
if (collapsed != null)
{
ci.IsCollapsed = Convert.ToBoolean(collapsed, CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Attempts to merge the col info record at the specified index
/// with either or both of its neighbours
/// </summary>
/// <param name="colInfoIx">The col info ix.</param>
private void AttemptMergeColInfoRecords(int colInfoIx)
{
int nRecords = records.Count;
if (colInfoIx < 0 || colInfoIx >= nRecords)
{
throw new ArgumentException("colInfoIx " + colInfoIx
+ " is out of range (0.." + (nRecords - 1) + ")");
}
ColumnInfoRecord currentCol = GetColInfo(colInfoIx);
int nextIx = colInfoIx + 1;
if (nextIx < nRecords)
{
if (MergeColInfoRecords(currentCol, GetColInfo(nextIx)))
{
records.RemoveAt(nextIx);
}
}
if (colInfoIx > 0)
{
if (MergeColInfoRecords(GetColInfo(colInfoIx - 1), currentCol))
{
records.RemoveAt(colInfoIx);
}
}
}
/**
* merges two column info records (if they are adjacent and have the same formatting, etc)
* @return <c>false</c> if the two column records could not be merged
*/
private static bool MergeColInfoRecords(ColumnInfoRecord ciA, ColumnInfoRecord ciB)
{
if (ciA.IsAdjacentBefore(ciB) && ciA.FormatMatches(ciB))
{
ciA.LastColumn = ciB.LastColumn;
return true;
}
return false;
}
/// <summary>
/// Sets all adjacent columns of the same outline level to the specified hidden status.
/// </summary>
/// <param name="pIdx">the col info index of the start of the outline group.</param>
/// <param name="level">The level.</param>
/// <param name="hidden">The hidden.</param>
/// <returns>the column index of the last column in the outline group</returns>
private int SetGroupHidden(int pIdx, int level, bool hidden)
{
int idx = pIdx;
ColumnInfoRecord columnInfo = GetColInfo(idx);
while (idx < records.Count)
{
columnInfo.IsHidden = (hidden);
if (idx + 1 < records.Count)
{
ColumnInfoRecord nextColumnInfo = GetColInfo(idx + 1);
if (!columnInfo.IsAdjacentBefore(nextColumnInfo))
{
break;
}
if (nextColumnInfo.OutlineLevel < level)
{
break;
}
columnInfo = nextColumnInfo;
}
idx++;
}
return columnInfo.LastColumn;
}
/// <summary>
/// Sets the column.
/// </summary>
/// <param name="targetColumnIx">The target column ix.</param>
/// <param name="xfIndex">Index of the xf.</param>
/// <param name="width">The width.</param>
/// <param name="level">The level.</param>
/// <param name="hidden">The hidden.</param>
/// <param name="collapsed">The collapsed.</param>
public void SetColumn(int targetColumnIx, short? xfIndex, int? width, int? level, bool? hidden, bool? collapsed)
{
ColumnInfoRecord ci = null;
int k = 0;
for (k = 0; k < records.Count; k++)
{
ColumnInfoRecord tci = (ColumnInfoRecord)records[k];
if (tci.ContainsColumn(targetColumnIx))
{
ci = tci;
break;
}
if (tci.FirstColumn > targetColumnIx)
{
// call targetColumnIx infos after k are for later targetColumnIxs
break; // exit now so k will be the correct insert pos
}
}
if (ci == null)
{
// okay so there IsN'T a targetColumnIx info record that cover's this targetColumnIx so lets Create one!
ColumnInfoRecord nci = new ColumnInfoRecord();
nci.FirstColumn = targetColumnIx;
nci.LastColumn = targetColumnIx;
SetColumnInfoFields(nci, xfIndex, width, level, hidden, collapsed);
InsertColumn(k, nci);
AttemptMergeColInfoRecords(k);
return;
}
bool styleChanged = ci.XFIndex != xfIndex;
bool widthChanged = ci.ColumnWidth != width;
bool levelChanged = ci.OutlineLevel != level;
bool hiddenChanged = ci.IsHidden != hidden;
bool collapsedChanged = ci.IsCollapsed != collapsed;
bool targetColumnIxChanged = styleChanged || widthChanged || levelChanged || hiddenChanged || collapsedChanged;
if (!targetColumnIxChanged)
{
// do nothing...nothing Changed.
return;
}
if ((ci.FirstColumn == targetColumnIx)
&& (ci.LastColumn == targetColumnIx))
{ // if its only for this cell then
// ColumnInfo ci for a single column, the target column
SetColumnInfoFields(ci, xfIndex, width, level, hidden, collapsed);
AttemptMergeColInfoRecords(k);
return;
}
if ((ci.FirstColumn == targetColumnIx)
|| (ci.LastColumn == targetColumnIx))
{
// The target column is at either end of the multi-column ColumnInfo ci
// we'll just divide the info and create a new one
if (ci.FirstColumn == targetColumnIx)
{
ci.FirstColumn = targetColumnIx + 1;
}
else
{
ci.LastColumn = targetColumnIx - 1;
k++; // adjust insert pos to insert after
}
ColumnInfoRecord nci = CopyColInfo(ci);
nci.FirstColumn = targetColumnIx;
nci.LastColumn = targetColumnIx;
SetColumnInfoFields(nci, xfIndex, width, level, hidden, collapsed);
InsertColumn(k, nci);
AttemptMergeColInfoRecords(k);
}
else
{
//split to 3 records
ColumnInfoRecord ciStart = ci;
ColumnInfoRecord ciMid = CopyColInfo(ci);
ColumnInfoRecord ciEnd = CopyColInfo(ci);
int lastcolumn = ci.LastColumn;
ciStart.LastColumn = (targetColumnIx - 1);
ciMid.FirstColumn=(targetColumnIx);
ciMid.LastColumn=(targetColumnIx);
SetColumnInfoFields(ciMid, xfIndex, width, level, hidden, collapsed);
InsertColumn(++k, ciMid);
ciEnd.FirstColumn = (targetColumnIx + 1);
ciEnd.LastColumn = (lastcolumn);
InsertColumn(++k, ciEnd);
// no need to attemptMergeColInfoRecords because we
// know both on each side are different
}
}
private ColumnInfoRecord CopyColInfo(ColumnInfoRecord ci)
{
return (ColumnInfoRecord)ci.Clone();
}
/**
* Sets all non null fields into the <c>ci</c> parameter.
*/
private void SetColumnInfoFields(ColumnInfoRecord ci, short xfStyle, short width, int level, bool hidden, bool collapsed)
{
ci.XFIndex = (xfStyle);
ci.ColumnWidth = (width);
ci.OutlineLevel = (short)level;
ci.IsHidden = (hidden);
ci.IsCollapsed = (collapsed);
}
/// <summary>
/// Collapses the col info records.
/// </summary>
/// <param name="columnIdx">The column index.</param>
public void CollapseColInfoRecords(int columnIdx)
{
if (columnIdx == 0)
return;
ColumnInfoRecord previousCol = (ColumnInfoRecord)records[columnIdx - 1];
ColumnInfoRecord currentCol = (ColumnInfoRecord)records[columnIdx];
bool adjacentColumns = previousCol.LastColumn == currentCol.FirstColumn - 1;
if (!adjacentColumns)
return;
bool columnsMatch =
previousCol.XFIndex == currentCol.XFIndex &&
previousCol.Options == currentCol.Options &&
previousCol.ColumnWidth == currentCol.ColumnWidth;
if (columnsMatch)
{
previousCol.LastColumn = currentCol.LastColumn;
records.Remove(columnIdx);
}
}
/// <summary>
/// Creates an outline Group for the specified columns.
/// </summary>
/// <param name="fromColumnIx">Group from this column (inclusive)</param>
/// <param name="toColumnIx">Group to this column (inclusive)</param>
/// <param name="indent">if true the Group will be indented by one level;if false indenting will be Removed by one level.</param>
public void GroupColumnRange(int fromColumnIx, int toColumnIx, bool indent)
{
int colInfoSearchStartIdx = 0; // optimization to speed up the search for col infos
for (int i = fromColumnIx; i <= toColumnIx; i++)
{
int level = 1;
int colInfoIdx = FindColInfoIdx(i, colInfoSearchStartIdx);
if (colInfoIdx != -1)
{
level = GetColInfo(colInfoIdx).OutlineLevel;
if (indent)
{
level++;
}
else
{
level--;
}
level = Math.Max(0, level);
level = Math.Min(7, level);
colInfoSearchStartIdx = Math.Max(0, colInfoIdx - 1); // -1 just in case this column is collapsed later.
}
SetColumn(i, null, null, level, null, null);
}
}
/// <summary>
/// Finds the ColumnInfoRecord
/// which contains the specified columnIndex
/// </summary>
/// <param name="columnIndex">index of the column (not the index of the ColumnInfoRecord)</param>
/// <returns> /// <c>null</c>
/// if no column info found for the specified column
/// </returns>
public ColumnInfoRecord FindColumnInfo(int columnIndex)
{
int nInfos = records.Count;
for (int i = 0; i < nInfos; i++)
{
ColumnInfoRecord ci = GetColInfo(i);
if (ci.ContainsColumn(columnIndex))
{
return ci;
}
}
return null;
}
private int FindColInfoIdx(int columnIx, int fromColInfoIdx)
{
if (columnIx < 0)
{
throw new ArgumentException("column parameter out of range: " + columnIx);
}
if (fromColInfoIdx < 0)
{
throw new ArgumentException("fromIdx parameter out of range: " + fromColInfoIdx);
}
for (int k = fromColInfoIdx; k < records.Count; k++)
{
ColumnInfoRecord ci = GetColInfo(k);
if (ci.ContainsColumn(columnIx))
{
return k;
}
if (ci.FirstColumn > columnIx)
{
break;
}
}
return -1;
}
/// <summary>
/// Gets the max outline level.
/// </summary>
/// <value>The max outline level.</value>
public int MaxOutlineLevel
{
get
{
int result = 0;
int count = records.Count;
for (int i = 0; i < count; i++)
{
ColumnInfoRecord columnInfoRecord = GetColInfo(i);
result = Math.Max(columnInfoRecord.OutlineLevel, result);
}
return result;
}
}
}
}
| |
namespace GridImageUpload
{
partial class frmGridImageUpload
{
/// <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()
{
this.grpLogin = new System.Windows.Forms.GroupBox();
this.cmdConnect = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.txtPassword = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtLastName = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.txtFirstName = new System.Windows.Forms.TextBox();
this.grpUpload = new System.Windows.Forms.GroupBox();
this.txtAssetID = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.lblSize = new System.Windows.Forms.Label();
this.prgUpload = new System.Windows.Forms.ProgressBar();
this.picPreview = new System.Windows.Forms.PictureBox();
this.cmdLoad = new System.Windows.Forms.Button();
this.txtSendtoName = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.chkLossless = new System.Windows.Forms.CheckBox();
this.cmdUpload = new System.Windows.Forms.Button();
this.grpLogin.SuspendLayout();
this.grpUpload.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picPreview)).BeginInit();
this.SuspendLayout();
//
// grpLogin
//
this.grpLogin.Controls.Add(this.cmdConnect);
this.grpLogin.Controls.Add(this.label3);
this.grpLogin.Controls.Add(this.txtPassword);
this.grpLogin.Controls.Add(this.label2);
this.grpLogin.Controls.Add(this.txtLastName);
this.grpLogin.Controls.Add(this.label1);
this.grpLogin.Controls.Add(this.txtFirstName);
this.grpLogin.Location = new System.Drawing.Point(11, 260);
this.grpLogin.Name = "grpLogin";
this.grpLogin.Size = new System.Drawing.Size(379, 101);
this.grpLogin.TabIndex = 67;
this.grpLogin.TabStop = false;
//
// cmdConnect
//
this.cmdConnect.Location = new System.Drawing.Point(251, 62);
this.cmdConnect.Name = "cmdConnect";
this.cmdConnect.Size = new System.Drawing.Size(120, 24);
this.cmdConnect.TabIndex = 3;
this.cmdConnect.Text = "Connect";
this.cmdConnect.Click += new System.EventHandler(this.cmdConnect_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(251, 20);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(120, 16);
this.label3.TabIndex = 72;
this.label3.Text = "Password";
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(251, 36);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(120, 20);
this.txtPassword.TabIndex = 2;
//
// label2
//
this.label2.Location = new System.Drawing.Point(132, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 16);
this.label2.TabIndex = 70;
this.label2.Text = "Last Name";
//
// txtLastName
//
this.txtLastName.Location = new System.Drawing.Point(132, 36);
this.txtLastName.Name = "txtLastName";
this.txtLastName.Size = new System.Drawing.Size(112, 20);
this.txtLastName.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(6, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(120, 16);
this.label1.TabIndex = 68;
this.label1.Text = "First Name";
//
// txtFirstName
//
this.txtFirstName.Location = new System.Drawing.Point(6, 36);
this.txtFirstName.Name = "txtFirstName";
this.txtFirstName.Size = new System.Drawing.Size(120, 20);
this.txtFirstName.TabIndex = 0;
//
// grpUpload
//
this.grpUpload.Controls.Add(this.txtAssetID);
this.grpUpload.Controls.Add(this.label4);
this.grpUpload.Controls.Add(this.lblSize);
this.grpUpload.Controls.Add(this.prgUpload);
this.grpUpload.Controls.Add(this.picPreview);
this.grpUpload.Controls.Add(this.cmdLoad);
this.grpUpload.Controls.Add(this.txtSendtoName);
this.grpUpload.Controls.Add(this.label6);
this.grpUpload.Controls.Add(this.chkLossless);
this.grpUpload.Controls.Add(this.cmdUpload);
this.grpUpload.Location = new System.Drawing.Point(12, 12);
this.grpUpload.Name = "grpUpload";
this.grpUpload.Size = new System.Drawing.Size(379, 242);
this.grpUpload.TabIndex = 68;
this.grpUpload.TabStop = false;
//
// txtAssetID
//
this.txtAssetID.Location = new System.Drawing.Point(90, 204);
this.txtAssetID.Name = "txtAssetID";
this.txtAssetID.ReadOnly = true;
this.txtAssetID.Size = new System.Drawing.Size(280, 20);
this.txtAssetID.TabIndex = 8;
this.txtAssetID.TabStop = false;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 207);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(66, 13);
this.label4.TabIndex = 79;
this.label4.Text = "Asset UUID:";
//
// lblSize
//
this.lblSize.AutoSize = true;
this.lblSize.Location = new System.Drawing.Point(79, 96);
this.lblSize.Name = "lblSize";
this.lblSize.Size = new System.Drawing.Size(0, 13);
this.lblSize.TabIndex = 77;
//
// prgUpload
//
this.prgUpload.Location = new System.Drawing.Point(9, 175);
this.prgUpload.Name = "prgUpload";
this.prgUpload.Size = new System.Drawing.Size(362, 23);
this.prgUpload.TabIndex = 76;
//
// picPreview
//
this.picPreview.Location = new System.Drawing.Point(9, 96);
this.picPreview.Name = "picPreview";
this.picPreview.Size = new System.Drawing.Size(64, 64);
this.picPreview.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picPreview.TabIndex = 75;
this.picPreview.TabStop = false;
//
// cmdLoad
//
this.cmdLoad.Location = new System.Drawing.Point(160, 136);
this.cmdLoad.Name = "cmdLoad";
this.cmdLoad.Size = new System.Drawing.Size(102, 24);
this.cmdLoad.TabIndex = 6;
this.cmdLoad.Text = "Load Texture";
this.cmdLoad.UseVisualStyleBackColor = true;
this.cmdLoad.Click += new System.EventHandler(this.cmdLoad_Click);
//
// txtSendtoName
//
this.txtSendtoName.Location = new System.Drawing.Point(131, 64);
this.txtSendtoName.Name = "txtSendtoName";
this.txtSendtoName.Size = new System.Drawing.Size(239, 20);
this.txtSendtoName.TabIndex = 5;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(6, 67);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(112, 13);
this.label6.TabIndex = 71;
this.label6.Text = "Send Copy To Avatar:";
//
// chkLossless
//
this.chkLossless.Location = new System.Drawing.Point(9, 19);
this.chkLossless.Name = "chkLossless";
this.chkLossless.Size = new System.Drawing.Size(362, 37);
this.chkLossless.TabIndex = 4;
this.chkLossless.Text = "Single Layer Lossless (only useful for pixel perfect reproductions of small image" +
"s, such as sculpt maps)";
this.chkLossless.UseVisualStyleBackColor = true;
this.chkLossless.CheckedChanged += new System.EventHandler(this.chkLossless_CheckedChanged);
//
// cmdUpload
//
this.cmdUpload.Enabled = false;
this.cmdUpload.Location = new System.Drawing.Point(268, 136);
this.cmdUpload.Name = "cmdUpload";
this.cmdUpload.Size = new System.Drawing.Size(103, 24);
this.cmdUpload.TabIndex = 7;
this.cmdUpload.Text = "Upload Texture";
this.cmdUpload.UseVisualStyleBackColor = true;
this.cmdUpload.Click += new System.EventHandler(this.cmdUpload_Click);
//
// frmGridImageUpload
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(402, 373);
this.Controls.Add(this.grpUpload);
this.Controls.Add(this.grpLogin);
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(410, 400);
this.MinimumSize = new System.Drawing.Size(410, 400);
this.Name = "frmGridImageUpload";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "SL Image Upload";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmGridImageUpload_FormClosed);
this.grpLogin.ResumeLayout(false);
this.grpLogin.PerformLayout();
this.grpUpload.ResumeLayout(false);
this.grpUpload.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picPreview)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox grpLogin;
private System.Windows.Forms.Button cmdConnect;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtLastName;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtFirstName;
private System.Windows.Forms.GroupBox grpUpload;
private System.Windows.Forms.Button cmdUpload;
private System.Windows.Forms.CheckBox chkLossless;
private System.Windows.Forms.TextBox txtSendtoName;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.PictureBox picPreview;
private System.Windows.Forms.Button cmdLoad;
private System.Windows.Forms.ProgressBar prgUpload;
private System.Windows.Forms.Label lblSize;
private System.Windows.Forms.TextBox txtAssetID;
private System.Windows.Forms.Label label4;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public struct Span<T>
{
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
_length = array.Length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
int arrayLength = array.Length;
if ((uint)start > (uint)arrayLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = arrayLength - start;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = Unsafe.As<Pinnable<T>>(array);
_byteOffset = SpanHelpers.PerTypeValues<T>.ArrayAdjustment.Add<T>(start);
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_length = length;
_pinnable = null;
_byteOffset = new IntPtr(pointer);
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because
/// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when the specified object is null.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
if (obj == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
IntPtr byteOffset = Unsafe.ByteOffset<T>(ref pinnable.Data, ref objectData);
return new Span<T>(pinnable, byteOffset, length);
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(Pinnable<T> pinnable, IntPtr byteOffset, int length)
{
Debug.Assert(length >= 0);
_length = length;
_pinnable = pinnable;
_byteOffset = byteOffset;
}
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
// TODO: https://github.com/dotnet/corefx/issues/13681
// Until we get over the hurdle of C# 7 tooling, this indexer will return "T" and have a setter rather than a "ref T". (The doc comments
// continue to reflect the original intent of returning "ref T")
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if ((uint) index >= ((uint) _length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index) = value; }
else
Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index) = value;
}
}
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
// TODO: https://github.com/dotnet/corefx/issues/13681
// Until we get over the hurdle of C# 7 tooling, this temporary method will simulate the intended "ref T" indexer for those
// who need bypass the workaround for performance.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T GetItem(int index)
{
if ((uint)index >= ((uint)_length))
ThrowHelper.ThrowIndexOutOfRangeException();
if (_pinnable == null)
unsafe { return ref Unsafe.Add<T>(ref Unsafe.AsRef<T>(_byteOffset.ToPointer()), index); }
else
return ref Unsafe.Add<T>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset), index);
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
public unsafe void Clear()
{
int length = _length;
if (length == 0)
return;
var byteLength = (UIntPtr)((uint)length * Unsafe.SizeOf<T>());
if ((Unsafe.SizeOf<T>() & (sizeof(IntPtr) - 1)) != 0)
{
if (_pinnable == null)
{
var ptr = (byte*)_byteOffset.ToPointer();
SpanHelpers.ClearLessThanPointerSized(ptr, byteLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
SpanHelpers.ClearLessThanPointerSized(ref b, byteLength);
}
}
else
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
{
UIntPtr pointerSizedLength = (UIntPtr)((length * Unsafe.SizeOf<T>()) / sizeof(IntPtr));
ref IntPtr ip = ref Unsafe.As<T, IntPtr>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithReferences(ref ip, pointerSizedLength);
}
else
{
ref byte b = ref Unsafe.As<T, byte>(ref DangerousGetPinnableReference());
SpanHelpers.ClearPointerSizedWithoutReferences(ref b, byteLength);
}
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public unsafe void Fill(T value)
{
int length = _length;
if (length == 0)
return;
if (Unsafe.SizeOf<T>() == 1)
{
byte fill = Unsafe.As<T, byte>(ref value);
if (_pinnable == null)
{
Unsafe.InitBlockUnaligned(_byteOffset.ToPointer(), fill, (uint)length);
}
else
{
ref byte r = ref Unsafe.As<T, byte>(ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset));
Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
}
}
else
{
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
// Simple loop unrolling
int i = 0;
for (; i < (length & ~7); i += 8)
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
Unsafe.Add<T>(ref r, i + 4) = value;
Unsafe.Add<T>(ref r, i + 5) = value;
Unsafe.Add<T>(ref r, i + 6) = value;
Unsafe.Add<T>(ref r, i + 7) = value;
}
if (i < (length & ~3))
{
Unsafe.Add<T>(ref r, i + 0) = value;
Unsafe.Add<T>(ref r, i + 1) = value;
Unsafe.Add<T>(ref r, i + 2) = value;
Unsafe.Add<T>(ref r, i + 3) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.Add<T>(ref r, i) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination._length)
return false;
// TODO: This is a tide-over implementation as we plan to add a overlap-safe cpblk-based api to Unsafe. (https://github.com/dotnet/corefx/issues/13427)
unsafe
{
ref T src = ref DangerousGetPinnableReference();
ref T dst = ref destination.DangerousGetPinnableReference();
IntPtr srcMinusDst = Unsafe.ByteOffset<T>(ref dst, ref src);
int length = _length;
bool srcGreaterThanDst = (sizeof(IntPtr) == sizeof(int)) ? srcMinusDst.ToInt32() >= 0 : srcMinusDst.ToInt64() >= 0;
if (srcGreaterThanDst)
{
// Source address greater than or equal to destination address. Can do normal copy.
for (int i = 0; i < length; i++)
{
Unsafe.Add<T>(ref dst, i) = Unsafe.Add<T>(ref src, i);
}
}
else
{
// Source address less than destination address. Must do backward copy.
int i = length;
while (i-- != 0)
{
Unsafe.Add<T>(ref dst, i) = Unsafe.Add<T>(ref src, i);
}
}
return true;
}
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left.DangerousGetPinnableReference(), ref right.DangerousGetPinnableReference());
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => new Span<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(span._pinnable, span._byteOffset, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
int length = _length - start;
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
IntPtr newOffset = _byteOffset.Add<T>(start);
return new Span<T>(_pinnable, newOffset, length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return SpanHelpers.PerTypeValues<T>.EmptyArray;
T[] result = new T[_length];
CopyTo(result);
return result;
}
/// <summary>
/// Returns a 0-length span whose base is the null pointer.
/// </summary>
public static Span<T> Empty => default(Span<T>);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
unsafe { return ref Unsafe.AsRef<T>(_byteOffset.ToPointer()); }
else
return ref Unsafe.AddByteOffset<T>(ref _pinnable.Data, _byteOffset);
}
// These expose the internal representation for Span-related apis use only.
internal Pinnable<T> Pinnable => _pinnable;
internal IntPtr ByteOffset => _byteOffset;
//
// If the Span was constructed from an object,
//
// _pinnable = that object (unsafe-casted to a Pinnable<T>)
// _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref span[0]"
//
// If the Span was constructed from a native pointer,
//
// _pinnable = null
// _byteOffset = the pointer
//
private readonly Pinnable<T> _pinnable;
private readonly IntPtr _byteOffset;
private readonly int _length;
}
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public static class Span
{
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="T"/> to Span of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<byte> AsBytes<T>(this Span<T> source)
where T : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
int newLength = checked(source.Length * Unsafe.SizeOf<T>());
return new Span<byte>(Unsafe.As<Pinnable<byte>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="T"/> to ReadOnlySpan of bytes.
/// That type may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <param name="source">The source slice, of type <typeparamref name="T"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source)
where T : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(T));
int newLength = checked(source.Length * Unsafe.SizeOf<T>());
return new ReadOnlySpan<byte>(Unsafe.As<Pinnable<byte>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom));
if (SpanHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo));
int newLength = checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()));
return new Span<TTo>(Unsafe.As<Pinnable<TTo>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Casts a ReadOnlySpan of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
/// These types may not contain pointers or references. This is checked at runtime in order to preserve type safety.
/// </summary>
/// <remarks>
/// Supported only for platforms that support misaligned memory access.
/// </remarks>
/// <param name="source">The source slice, of type <typeparamref name="TFrom"/>.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
/// <exception cref="System.OverflowException">
/// Thrown if the Length property of the new Span would exceed Int32.MaxValue.
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source)
where TFrom : struct
where TTo : struct
{
if (SpanHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TFrom));
if (SpanHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowArgumentException_InvalidTypeWithPointersNotSupported(typeof(TTo));
int newLength = checked((int)((long)source.Length * Unsafe.SizeOf<TFrom>() / Unsafe.SizeOf<TTo>()));
return new ReadOnlySpan<TTo>(Unsafe.As<Pinnable<TTo>>(source.Pinnable), source.ByteOffset, newLength);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string.
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), StringAdjustment, text.Length);
}
/// <summary>
/// Creates a new readonly span over the portion of the target string, beginning at 'start'.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text, int start)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
int textLength = text.Length;
if ((uint)start > (uint)textLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
unsafe
{
byte* byteOffset = ((byte*)StringAdjustment) + (uint)(start * sizeof(char));
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), (IntPtr)byteOffset, textLength - start);
}
}
/// <summary>
/// Creates a new readonly span over the portion of the target string, beginning at <paramref name="start"/>, of given <paramref name="length"/>.
/// </summary>
/// <param name="text">The target string.</param>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<char> Slice(this string text, int start, int length)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
int textLength = text.Length;
if ((uint)start > (uint)textLength || (uint)length > (uint)(textLength - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
unsafe
{
byte* byteOffset = ((byte*)StringAdjustment) + (uint)(start * sizeof(char));
return new ReadOnlySpan<char>(Unsafe.As<Pinnable<char>>(text), (IntPtr)byteOffset, length);
}
}
private static readonly IntPtr StringAdjustment = MeasureStringAdjustment();
private static IntPtr MeasureStringAdjustment()
{
string sampleString = "a";
unsafe
{
fixed (char* pSampleString = sampleString)
{
return Unsafe.ByteOffset<char>(ref Unsafe.As<Pinnable<char>>(sampleString).Data, ref Unsafe.AsRef<char>(pSampleString));
}
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The core assembly for the DotSpatial 6.0 distribution.
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/30/2009 8:55:03 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Windows.Forms;
using DotSpatial.Data;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// CollectionPropertyGrid
/// </summary>
public class CollectionPropertyGrid : Form
{
#region Events
/// <summary>
/// Occurs whenever the apply changes button is clicked, or else when the ok button is clicked.
/// </summary>
public event EventHandler ChangesApplied;
/// <summary>
/// Occurs whenever the add item is clicked. This is because the Collection Property Grid
/// doesn't necessarilly know how to create a default item. (An alternative would be
/// to send in a factory, but I think this will work just as well.)
/// </summary>
public event EventHandler AddItemClicked;
#endregion
private CollectionControl ccItems;
private DialogButtons dialogButtons1;
private Panel panel1;
private PropertyGrid propertyGrid1;
private SplitContainer splitContainer1;
#region Private Variables
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CollectionPropertyGrid));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.ccItems = new DotSpatial.Symbology.Forms.CollectionControl();
this.propertyGrid1 = new System.Windows.Forms.PropertyGrid();
this.panel1 = new System.Windows.Forms.Panel();
this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1");
this.splitContainer1.Panel1.Controls.Add(this.ccItems);
//
// splitContainer1.Panel2
//
resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2");
this.splitContainer1.Panel2.Controls.Add(this.propertyGrid1);
//
// ccItems
//
resources.ApplyResources(this.ccItems, "ccItems");
this.ccItems.Name = "ccItems";
this.ccItems.SelectedName = null;
this.ccItems.SelectedObject = null;
//
// propertyGrid1
//
resources.ApplyResources(this.propertyGrid1, "propertyGrid1");
this.propertyGrid1.Name = "propertyGrid1";
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.dialogButtons1);
this.panel1.Name = "panel1";
//
// dialogButtons1
//
resources.ApplyResources(this.dialogButtons1, "dialogButtons1");
this.dialogButtons1.Name = "dialogButtons1";
//
// CollectionPropertyGrid
//
resources.ApplyResources(this, "$this");
this.AllowDrop = true;
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.Name = "CollectionPropertyGrid";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of CollectionPropertyGrid
/// </summary>
public CollectionPropertyGrid()
{
InitializeComponent();
Configure();
}
/// <summary>
/// Creates a new instance of CollectionPropertyGrid
/// </summary>
/// <param name="list">The INamedList to display</param>
public CollectionPropertyGrid(INamedList list)
{
InitializeComponent();
NamedList = list;
ccItems.AddClicked += ccItems_AddClicked;
ccItems.SelectedItemChanged += ccItems_SelectedItemChanged;
ccItems_SelectedItemChanged(ccItems, EventArgs.Empty);
ccItems.RemoveClicked += ccItems_RemoveClicked;
Configure();
}
private void Configure()
{
dialogButtons1.OkClicked += btnOk_Click;
dialogButtons1.CancelClicked += btnCancel_Click;
dialogButtons1.ApplyClicked += btnApply_Click;
}
private void ccItems_RemoveClicked(object sender, EventArgs e)
{
propertyGrid1.SelectedObject = ccItems.SelectedObject;
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the tool that connects each item with a string name.
/// </summary>
public INamedList NamedList
{
get
{
if (ccItems != null) return ccItems.ItemNames;
return null;
}
set
{
ccItems.ItemNames = value;
}
}
#endregion
#region Events
#endregion
#region Event Handlers
private void ccItems_AddClicked(object sender, EventArgs e)
{
OnAddClicked();
}
private void ccItems_SelectedItemChanged(object sender, EventArgs e)
{
propertyGrid1.SelectedObject = ccItems.SelectedObject;
}
private void btnApply_Click(object sender, EventArgs e)
{
OnApplyChanges();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
OnApplyChanges();
Close();
}
#endregion
#region Protected Methods
/// <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);
}
/// <summary>
/// Occurs when the add button is clicked
/// </summary>
protected virtual void OnAddClicked()
{
if (AddItemClicked != null) AddItemClicked(this, EventArgs.Empty);
}
/// <summary>
/// Fires the ChangesApplied event
/// </summary>
protected virtual void OnApplyChanges()
{
if (ChangesApplied != null) ChangesApplied(this, EventArgs.Empty);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using GuruComponents.Netrix.ComInterop;
namespace GuruComponents.Netrix.WebEditing.UndoRedo
{
/// <summary>
/// This class realises a simple batched undo manager.
/// </summary>
/// <remarks>
/// Its purpose is to pack multiple action in one stack operation to simplify undo for the user.
/// </remarks>
public class BatchedUndoUnit : Interop.IOleUndoUnit, IUndoStack
{
private string _description;
private int _startIndex;
private int _numUndos;
private Interop.IOleUndoUnit[] _undoUnits;
private BatchedUndoType _type;
private IHtmlEditor _editor;
internal BatchedUndoUnit(string description, IHtmlEditor editor, BatchedUndoType type)
{
_description = description;
_type = type;
_editor = editor;
}
private Interop.IOleUndoManager undoManager
{
get { return ((HtmlEditor)_editor).UndoManager; }
}
/// <summary>
/// Return the type of this unit, either Undo or Redo.
/// </summary>
public BatchedUndoType Type
{
get
{
return _type;
}
}
/// <summary>
/// Returns the collection of Undo/Redo objects available.
/// </summary>
/// <remarks>
/// The current type of unit object decided whether this method returns the Undo or Redo history.
/// The collections consists of <see cref="UndoObject"/> objects, which implement <see cref="IUndoObject"/>.
/// These objects may have information about subobjects, which the undo manager creates if the user
/// requests packed undo sequences.
/// </remarks>
/// <seealso cref="NumChildUndos"/>
/// <seealso cref="HasChildUndos"/>
/// <seealso cref="UndoObject"/>
/// <seealso cref="Type"/>
/// <returns>Returns a collection of objects of type <see cref="IUndoObject"/>.</returns>
public System.Collections.Generic.List<IUndoObject> GetUndoHistory()
{
int i = 0;
//IntPtr k = IntPtr.Zero;
Interop.IOleUndoUnit unit;
Interop.IEnumOleUndoUnits undoUnits = null;
if (_type == BatchedUndoType.Undo)
{
undoUnits = ((HtmlEditor)_editor).UndoManager.EnumUndoable();
}
else
{
undoUnits = ((HtmlEditor)_editor).UndoManager.EnumRedoable();
}
System.Collections.Generic.List<IUndoObject> undos = new System.Collections.Generic.List<IUndoObject>();
if (undoUnits != null)
{
undoUnits.Reset();
try
{
while (i == 0)
{
undoUnits.Next(1, out unit, out i);
if (undoUnits == null || i == 0)
{
break;
} //Interop.IOleUndoUnit unit = (Interop.IOleUndoUnit) Marshal.GetObjectForIUnknown(k);
string s;
unit.GetDescription(out s);
UndoUnit managedUndo = null;
if (unit is UndoUnit)
{
managedUndo = (UndoUnit)unit;
}
else
{
managedUndo = new UndoUnit(unit, ((HtmlEditor)_editor).UndoManager);
}
UndoObject wrappedObject = new UndoObject(s, managedUndo, ((HtmlEditor)_editor).UndoManager);
undos.Add(wrappedObject);
i = 0;
}
}
catch
{
}
}
return undos;
}
/// <summary>
/// Returns <c>true</c> if there are child undo objects available.
/// </summary>
/// <seealso cref="NumChildUndos"/>
/// <seealso cref="Type"/>
public bool HasChildUndos
{
get
{
return (NumChildUndos > 0);
}
}
/// <summary>
/// Returns the number of child undos available.
/// </summary>
/// <seealso cref="HasChildUndos"/>
/// <seealso cref="Type"/>
public int NumChildUndos
{
get
{
if (_undoUnits != null)
return _undoUnits.Length;
else
return 0;
}
}
/// <summary>
/// Returns the array of child undo objects, if this is privatly packed stack.
/// </summary>
/// <seealso cref="IUndoObject"/>
/// <seealso cref="Type"/>
public UndoObject[] ChildUndos
{
get
{
UndoObject[] childUndos = new UndoObject[0];
if (_undoUnits != null && _undoUnits.Length > 0)
{
childUndos = new UndoObject[_undoUnits.Length];
for (int i = 0; i < _undoUnits.Length; i++)
{
Interop.IOleUndoUnit childUnit = _undoUnits[i];
string s;
childUnit.GetDescription(out s);
UndoUnit managedUnit = new UndoUnit(childUnit, ((HtmlEditor)_editor).UndoManager);
childUndos[i] = new UndoObject(s, managedUnit, ((HtmlEditor)_editor).UndoManager);
}
}
return childUndos;
}
}
/// <summary>
/// Closes the current stack.
/// </summary>
/// <remarks>
/// Using this method will pack all previously collected operations into one undo steps. Next time the
/// Undo command is send the control will undo all packed steps.
/// </remarks>
public void Close()
{
Interop.IEnumOleUndoUnits undoUnits, redoUnits;
try
{
int i = 0;
if (_type == BatchedUndoType.Undo)
{
undoUnits = undoManager.EnumUndoable();
i = CountUndos(undoUnits);
_numUndos = Math.Max(0, i - _startIndex);
Pack(undoManager.EnumUndoable());
}
else
{
redoUnits = undoManager.EnumRedoable();
i = CountUndos(redoUnits);
_numUndos = Math.Max(0, i - _startIndex);
Pack(undoManager.EnumRedoable());
}
}
catch
{
}
}
/// <summary>
/// Clears the complete collection of undo/redo stacks.
/// </summary>
/// <remarks>
/// After issuing this method the control will lose all undo stacks and reset the Undo command
/// to unavailable state. The next operation will become the first undoable one.
/// </remarks>
public void Reset()
{
try
{
this.undoManager.Enable(false);
this.undoManager.Enable(true);
Close();
}
catch
{
}
}
/// <summary>
/// Enables or Disables the undo manager.
/// </summary>
/// <remarks>
/// If the undo manager is disabled, any following operation will not become part of the undo stack and
/// cannot be "undone" by any action, whether it is sent by user or code.
/// </remarks>
/// <param name="enabled">Specifies <c>True</c> for enable and <c>False</c> for disable.</param>
public void Enable(bool enabled)
{
this.undoManager.Enable(enabled);
}
/// <summary>
/// Gets the number of undo/redo steps currently in the stack.
/// </summary>
/// <remarks>
/// This property returns the number of undo/redo steps that can be issued by the undo command, NOT the
/// number of packed steps, each undo manager instance covers. When one did five operations, then
/// packed six operations into one stack and sent then two single operations, this property will
/// returns eight (five, one for the packed stack and two).
/// </remarks>
/// <seealso cref="Type"/>
public int UndoSteps
{
get
{
Interop.IEnumOleUndoUnits undoUnits;
if (_type == BatchedUndoType.Undo)
{
undoUnits = undoManager.EnumUndoable();
}
else
{
undoUnits = undoManager.EnumRedoable();
}
int i = CountUndos(undoUnits);
return i;
}
}
/// <summary>
/// Counts number of undo operations.
/// </summary>
/// <param name="enumerator"></param>
/// <returns>Number of undo operations.</returns>
private int CountUndos(Interop.IEnumOleUndoUnits enumerator)
{
int j = 0;
int i = 0;
//IntPtr k = IntPtr.Zero;
Interop.IOleUndoUnit unit;
if (enumerator == null) return 0;
try
{
enumerator.Reset();
}
catch
{
return 0;
}
try
{
while (i == 0)
{
enumerator.Next(1, out unit, out i);
if (unit != null)
{
if (unit is BatchedUndoUnit)
{
// packed steps
}
else
{
Marshal.ReleaseComObject(unit);
}
}
if (enumerator == null || i == 0)
{
break;
}
i = 0;
j++;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message, "UNDO->COUNTUNDOS->ERROR");
}
finally
{
enumerator.Reset();
}
return j;
}
/// <summary>
/// Instructs the undo unit to carry out its action. Note that if it
/// contains child undo units, it must call their Do methods as well.
/// </summary>
/// <param name="undoManager">Specifies pointer to the undo manager.</param>
/// <returns>Returns non zero interger value if the undo unit
/// successfully carried out its action</returns>
public virtual int Do(Interop.IOleUndoManager undoManager)
{
try
{
for (int i = _numUndos - 1 ; i >= 0; i--)
{
_undoUnits[i].Do(undoManager);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message, "UNDO->DO->ERROR");
}
return Interop.S_OK;
}
/// <summary>
/// Gets the name of the undo manager.
/// </summary>
public string Name
{
get
{
string s;
GetDescription(out s);
return s;
}
}
/// <summary>
/// Gets the description of the last operation collected by the undo/redo manager.
/// </summary>
/// <returns>Returns description of last operation.</returns>
public string GetLastDescription()
{
try
{
if (_type == BatchedUndoType.Undo)
{
if (this._numUndos > 0)
return this.undoManager.GetLastUndoDescription();
else
return String.Empty;
}
else
{
return this.undoManager.GetLastRedoDescription();
}
}
catch
{
return String.Empty;
}
}
/// <summary>
/// Returns a string that describes the undo unit and can be used in the undo
/// or redo user interface.
/// </summary>
/// <param name="s">Specifies the string describing this undo unit.</param>
/// <returns>Returns non zero value if the string was successfully returned. </returns>
public virtual int GetDescription(out string s)
{
s = _description;
return Interop.S_OK;
}
/// <summary>
/// Returns the CLSID and a type identifier for the undo unit
/// </summary>
/// <param name="clsid">Specifies CLSID for the undo unit.</param>
/// <param name="plID">Specifies the type identifier for the undo unit. </param>
/// <returns></returns>
public virtual int GetUnitType(out int clsid, out int plID)
{
clsid = 0;
plID = (int) _type;
return Interop.S_OK;
}
public void Open()
{
try
{
Interop.IEnumOleUndoUnits units = null;
if (_type == BatchedUndoType.Undo)
{
undoManager.Enable(true);
units = undoManager.EnumUndoable();
if (units != null)
{
_startIndex = CountUndos(units);
}
}
else
{
undoManager.Enable(true);
units = undoManager.EnumRedoable();
if (units != null)
{
_startIndex = CountUndos(units);
}
}
}
catch
{
_startIndex = 0; // restart in case of error
}
}
/// <summary>
/// Notifies that a new unit has been added.
/// </summary>
public event EventHandler NextOperationAdded;
/// <summary>
/// Notifies the last undo unit in the collection that a new unit has been added.
/// </summary>
/// <remarks>
/// An object can create an undo unit for an action and add it to the undo manager
/// but can continue inserting data into it through private interfaces. When the undo
/// unit receives a call to this method, it communicates back to the creating object
/// that the context has changed. Then, the creating object stops inserting data into
/// the undo unit.
/// The parent undo unit calls this method on its most recently added child undo unit
/// to notify the child unit that the context has changed and a new undo unit has been
/// added.
/// For example, this method is used for supporting fuzzy actions, like typing, which
/// do not have a clear point of termination but instead are terminated only when
/// something else happens.
/// </remarks>
/// <returns>Returns always non zero value. This return type is provided only for remotability.</returns>
public virtual int OnNextAdd()
{
if (NextOperationAdded != null)
{
NextOperationAdded(this as IUndoStack, new EventArgs());
}
return Interop.S_OK;
}
private void Pack(Interop.IEnumOleUndoUnits enumerator)
{
enumerator.Reset();
Interop.IOleUndoUnit[] units = new Interop.IOleUndoUnit[(uint)_startIndex];
_undoUnits = new Interop.IOleUndoUnit[(uint)_numUndos];
//IntPtr j1 = IntPtr.Zero;
Interop.IOleUndoUnit unit;
int i1 = 0;
for (int k = 0; k < _startIndex; k++)
{
enumerator.Next(1, out unit, out i1);
units[k] = unit; // (Interop.IOleUndoUnit)Marshal.GetObjectForIUnknown(unit);
//Marshal.Release(unit);
}
for (int i2 = 0; i2 < _numUndos; i2++)
{
enumerator.Next(1, out unit, out i1);
_undoUnits[i2] = unit; // (Interop.IOleUndoUnit)Marshal.GetObjectForIUnknown(unit);
//Marshal.Release(unit);
}
undoManager.DiscardFrom(null);
for (int j2 = 0; j2 < _startIndex; j2++)
{
if (units[j2] == null) continue;
undoManager.Add(units[j2]);
}
undoManager.Add(this);
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nancy.Cookies;
/// <summary>
/// Provides strongly-typed access to HTTP request headers.
/// </summary>
public class RequestHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
private readonly IDictionary<string, IEnumerable<string>> headers;
/// <summary>
/// Initializes a new instance of the <see cref="RequestHeaders"/> class.
/// </summary>
/// <param name="headers">The headers.</param>
public RequestHeaders(IDictionary<string, IEnumerable<string>> headers)
{
this.headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Content-types that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> Accept
{
get { return GetWeightedValues("Accept").ToList(); }
set { this.SetHeaderValues("Accept", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Character sets that are acceptable.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptCharset
{
get { return this.GetWeightedValues("Accept-Charset"); }
set { this.SetHeaderValues("Accept-Charset", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Acceptable encodings.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> AcceptEncoding
{
get { return this.GetSplitValues("Accept-Encoding"); }
set { this.SetHeaderValues("Accept-Encoding", value, x => x); }
}
/// <summary>
/// Acceptable languages for response.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<Tuple<string, decimal>> AcceptLanguage
{
get { return this.GetWeightedValues("Accept-Language"); }
set { this.SetHeaderValues("Accept-Language", value, GetWeightedValuesAsStrings); }
}
/// <summary>
/// Acceptable languages for response.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Authorization
{
get { return this.GetValue("Authorization", x => x.First()); }
set { this.SetHeaderValues("Authorization", value, x => new[] { x }); }
}
/// <summary>
/// Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> CacheControl
{
get { return this.GetValue("Cache-Control"); }
set { this.SetHeaderValues("Cache-Control", value, x => x); }
}
/// <summary>
/// Contains name/value pairs of information stored for that URL.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains <see cref="INancyCookie"/> instances if they are available; otherwise it will be empty.</value>
public IEnumerable<INancyCookie> Cookie
{
get { return this.GetValue("Cookie", GetNancyCookies); }
}
/// <summary>
/// What type of connection the user-agent would prefer.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Connection
{
get { return this.GetValue("Connection", x => x.First()); }
set { this.SetHeaderValues("Connection", value, x => new[] { x }); }
}
/// <summary>
/// The length of the request body in octets (8-bit bytes).
/// </summary>
/// <value>The lenght of the contents if it is available; otherwise 0.</value>
public long ContentLength
{
get { return this.GetValue("Content-Length", x => Convert.ToInt64(x.First())); }
set { this.SetHeaderValues("Content-Length", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// The mime type of the body of the request (used with POST and PUT requests).
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string ContentType
{
get { return this.GetValue("Content-Type", x => x.First()); }
set { this.SetHeaderValues("Content-Type", value, x => new[] { x }); }
}
/// <summary>
/// The date and time that the message was sent.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the message was sent. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? Date
{
get { return this.GetValue("Date", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("Date", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// The domain name of the server (for virtual hosting), mandatory since HTTP/1.1
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Host
{
get { return this.GetValue("Host", x => x.First()); }
set { this.SetHeaderValues("Host", value, x => new[] { x }); }
}
/// <summary>
/// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfMatch
{
get { return this.GetValue("If-Match"); }
set { this.SetHeaderValues("If-Match", value, x => x); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource must have been changed since. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? IfModifiedSince
{
get { return this.GetValue("If-Modified-Since", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("If-Modified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Allows a 304 Not Modified to be returned if content is unchanged
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value>
public IEnumerable<string> IfNoneMatch
{
get { return this.GetValue("If-None-Match"); }
set { this.SetHeaderValues("If-None-Match", value, x => x); }
}
/// <summary>
/// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string IfRange
{
get { return this.GetValue("If-Range", x => x.First()); }
set { this.SetHeaderValues("If-Range", value, x => new[] { x }); }
}
/// <summary>
/// Only send the response if the entity has not been modified since a specific time.
/// </summary>
/// <value>A <see cref="DateTime"/> instance that specifies when the requested resource may not have been changed since. If not available then <see cref="DateTime.MinValue"/> will be returned.</value>
public DateTime? IfUnmodifiedSince
{
get { return this.GetValue("If-Unmodified-Since", x => ParseDateTime(x.First())); }
set { this.SetHeaderValues("If-Unmodified-Since", value, x => new[] { GetDateAsString(value) }); }
}
/// <summary>
/// Gets the names of the available request headers.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> containing the names of the headers.</value>
public IEnumerable<string> Keys
{
get { return this.headers.Keys; }
}
/// <summary>
/// Limit the number of times the message can be forwarded through proxies or gateways.
/// </summary>
/// <value>The number of the maximum allowed number of forwards if it is available; otherwise 0.</value>
public int MaxForwards
{
get { return this.GetValue("Max-Forwards", x => Convert.ToInt32(x.First())); }
set { this.SetHeaderValues("Max-Forwards", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }
}
/// <summary>
/// This is the address of the previous web page from which a link to the currently requested page was followed.
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string Referrer
{
get { return this.GetValue("Referer", x => x.First()); }
set { this.SetHeaderValues("Referer", value, x => new[] { x }); }
}
/// <summary>
/// The user agent string of the user agent
/// </summary>
/// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value>
public string UserAgent
{
get { return this.GetValue("User-Agent", x => x.First()); }
set { this.SetHeaderValues("User-Agent", value, x => new[] { x }); }
}
/// <summary>
/// Gets all the header values.
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> that contains all the header values.</value>
public IEnumerable<IEnumerable<string>> Values
{
get { return this.headers.Values; }
}
/// <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 IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
{
return this.headers.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Gets the values for the header identified by the <paramref name="name"/> parameter.
/// </summary>
/// <param name="name">The name of the header to return the values for.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains the values for the header. If the header is not defined then <see cref="Enumerable.Empty{TResult}"/> is returned.</returns>
public IEnumerable<string> this[string name]
{
get
{
return (this.headers.ContainsKey(name)) ?
this.headers[name] :
Enumerable.Empty<string>();
}
}
private static string GetDateAsString(DateTime? value)
{
return !value.HasValue ? null : value.Value.ToString("R", CultureInfo.InvariantCulture);
}
private IEnumerable<string> GetSplitValues(string header)
{
var values = this.GetValue(header);
return values
.SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Trim())
.ToList();
}
private IEnumerable<Tuple<string, decimal>> GetWeightedValues(string headerName)
{
var values = this.GetSplitValues(headerName);
var parsed = values.Select(x =>
{
var sections = x.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
var mediaRange = sections[0].Trim();
var quality = 1m;
for (var index = 1; index < sections.Length; index++)
{
var trimmedValue = sections[index].Trim();
if (trimmedValue.StartsWith("q=", StringComparison.OrdinalIgnoreCase))
{
decimal temp;
var stringValue = trimmedValue.Substring(2);
if (decimal.TryParse(stringValue, NumberStyles.Number, CultureInfo.InvariantCulture, out temp))
{
quality = temp;
}
}
else
{
mediaRange += ";" + trimmedValue;
}
}
return new Tuple<string, decimal>(mediaRange, quality);
});
return parsed
.OrderByDescending(x => x.Item2);
}
private static object GetDefaultValue(Type T)
{
if (IsGenericEnumerable(T))
{
var enumerableType = T.GetGenericArguments().First();
var x = typeof(List<>).MakeGenericType(new[] { enumerableType });
return Activator.CreateInstance(x);
}
if (T == typeof(DateTime))
{
return null;
}
return T == typeof(string) ?
string.Empty :
null;
}
private static IEnumerable<INancyCookie> GetNancyCookies(IEnumerable<string> cookies)
{
if (cookies == null)
{
yield break;
}
foreach (var cookie in cookies)
{
var cookieStrings = cookie.Split(';');
foreach (var cookieString in cookieStrings)
{
var equalPos = cookieString.IndexOf('=');
if (equalPos >= 0)
{
yield return new NancyCookie(cookieString.Substring(0, equalPos).TrimStart(), cookieString.Substring(equalPos+1).TrimEnd());
}
}
}
}
private IEnumerable<string> GetValue(string name)
{
return this.GetValue(name, x => x);
}
private T GetValue<T>(string name, Func<IEnumerable<string>, T> converter)
{
if (!this.headers.ContainsKey(name))
{
return (T)(GetDefaultValue(typeof(T)) ?? default(T));
}
return converter.Invoke(this.headers[name]);
}
private static IEnumerable<string> GetWeightedValuesAsStrings(IEnumerable<Tuple<string, decimal>> values)
{
return values.Select(x => string.Concat(x.Item1, ";q=", x.Item2.ToString(CultureInfo.InvariantCulture)));
}
private static bool IsGenericEnumerable(Type T)
{
return !(T == typeof(string)) && T.IsGenericType && T.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
private static DateTime? ParseDateTime(string value)
{
DateTime result;
// note CultureInfo.InvariantCulture is ignored
if (DateTime.TryParseExact(value, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
return result;
}
return null;
}
private void SetHeaderValues<T>(string header, T value, Func<T, IEnumerable<string>> valueTransformer)
{
if (EqualityComparer<T>.Default.Equals(value, default(T)))
{
if (this.headers.ContainsKey(header))
{
this.headers.Remove(header);
}
}
else
{
this.headers[header] = valueTransformer.Invoke(value);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NuGet
{
public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup
{
private readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>();
private readonly bool _enableCaching;
public LocalPackageRepository(string physicalPath)
: this(physicalPath, enableCaching: true)
{
}
public LocalPackageRepository(string physicalPath, bool enableCaching)
: this(new DefaultPackagePathResolver(physicalPath),
new PhysicalFileSystem(physicalPath),
enableCaching)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
: this(pathResolver, fileSystem, enableCaching: true)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching)
{
if (pathResolver == null) {
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null) {
throw new ArgumentNullException("fileSystem");
}
FileSystem = fileSystem;
PathResolver = pathResolver;
_enableCaching = enableCaching;
}
public override string Source
{
get
{
return FileSystem.Root;
}
}
public override bool SupportsPrereleasePackages
{
get { return true; }
}
protected IFileSystem FileSystem
{
get;
private set;
}
public IPackagePathResolver PathResolver
{
get;
set;
}
public override IQueryable<IPackage> GetPackages()
{
return GetPackages(OpenPackage).AsSafeQueryable();
}
public override void AddPackage(IPackage package)
{
string packageFilePath = GetPackageFilePath(package);
FileSystem.AddFileWithCheck(packageFilePath, package.GetStream);
}
public override void RemovePackage(IPackage package)
{
// Delete the package file
string packageFilePath = GetPackageFilePath(package);
FileSystem.DeleteFileSafe(packageFilePath);
// Delete the package directory if any
FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false);
// If this is the last package delete the package directory
if (!FileSystem.GetFilesSafe(String.Empty).Any() &&
!FileSystem.GetDirectoriesSafe(String.Empty).Any()) {
FileSystem.DeleteDirectorySafe(String.Empty, recursive: false);
}
}
public IPackage FindPackage(string packageId, SemanticVersion version)
{
return FindPackage(OpenPackage, packageId, version);
}
internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version)
{
return (from path in GetAllPackagePaths(packageId, version)
where FileSystem.FileExists(path)
let package = GetPackage(openPackage, path)
where package.Version == version
select package).FirstOrDefault();
}
private IEnumerable<string> GetAllPackagePaths(string packageId, SemanticVersion version)
{
// Since we look at the file system to determine if a package is installed,
// we need to enumerate the list of possible versions and check the path for
// each one
return (from v in VersionUtility.GetPossibleVersions(version)
from path in GetPackagePaths(packageId, v)
select path).Distinct();
}
private IEnumerable<string> GetPackagePaths(string packageId, SemanticVersion version)
{
var packageName = new PackageName(packageId, version);
string packagePath;
if (_packagePathLookup.TryGetValue(packageName, out packagePath)) {
yield return packagePath;
}
yield return GetPackageFilePath(packageId, version);
yield return PathResolver.GetPackageFileName(packageId, version);
}
internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage)
{
foreach (var path in GetPackageFiles()) {
IPackage package = GetPackage(openPackage, path);
yield return package;
}
}
private IPackage GetPackage(Func<string, IPackage> openPackage, string path)
{
PackageCacheEntry cacheEntry;
DateTimeOffset lastModified = FileSystem.GetLastModified(path);
// If we never cached this file or we did and it's current last modified time is newer
// create a new entry
if (!_packageCache.TryGetValue(path, out cacheEntry) ||
(cacheEntry != null && lastModified > cacheEntry.LastModifiedTime)) {
// We need to do this so we capture the correct loop variable
string packagePath = path;
// Create the package
IPackage package = openPackage(packagePath);
// create a cache entry with the last modified time
cacheEntry = new PackageCacheEntry(package, lastModified);
if (_enableCaching) {
// Store the entry
_packageCache[packagePath] = cacheEntry;
_packagePathLookup[new PackageName(package.Id, package.Version)] = path;
}
}
return cacheEntry.Package;
}
internal IEnumerable<string> GetPackageFiles()
{
// Check for package files one level deep. We use this at package install time
// to determine the set of installed packages. Installed packages are copied to
// {id}.{version}\{packagefile}.{extension}.
foreach (var dir in FileSystem.GetDirectories(String.Empty)) {
foreach (var path in FileSystem.GetFiles(dir, "*" + Constants.PackageExtension)) {
yield return path;
}
}
// Check top level directory
foreach (var path in FileSystem.GetFiles(String.Empty, "*" + Constants.PackageExtension)) {
yield return path;
}
}
protected virtual IPackage OpenPackage(string path)
{
var package = new ZipPackage(() => FileSystem.OpenFile(path), _enableCaching);
// Set the last modified date on the package
package.Published = FileSystem.GetLastModified(path);
// Clear the cache whenever we open a new package file
ZipPackage.ClearCache(package);
return package;
}
protected virtual string GetPackageFilePath(IPackage package)
{
return Path.Combine(PathResolver.GetPackageDirectory(package),
PathResolver.GetPackageFileName(package));
}
protected virtual string GetPackageFilePath(string id, SemanticVersion version)
{
return Path.Combine(PathResolver.GetPackageDirectory(id, version),
PathResolver.GetPackageFileName(id, version));
}
private class PackageCacheEntry
{
public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime)
{
Package = package;
LastModifiedTime = lastModifiedTime;
}
public IPackage Package { get; private set; }
public DateTimeOffset LastModifiedTime { get; private set; }
}
private class PackageName : IEquatable<PackageName>
{
public PackageName(string packageId, SemanticVersion version)
{
PackageId = packageId;
Version = version;
}
public string PackageId { get; private set; }
public SemanticVersion Version { get; private set; }
public bool Equals(PackageName other)
{
return PackageId.Equals(other.PackageId, StringComparison.OrdinalIgnoreCase) &&
Version.Equals(other.Version);
}
public override int GetHashCode()
{
var combiner = new HashCodeCombiner();
combiner.AddObject(PackageId);
combiner.AddObject(Version);
return combiner.CombinedHash;
}
public override string ToString()
{
return PackageId + " " + Version;
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmGRVTemplate
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmGRVTemplate() : base()
{
Load += frmGRVTemplate_Load;
KeyPress += frmGRVTemplate_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdDown;
public System.Windows.Forms.Button cmdDown {
get { return withEventsField_cmdDown; }
set {
if (withEventsField_cmdDown != null) {
withEventsField_cmdDown.Click -= cmdDown_Click;
}
withEventsField_cmdDown = value;
if (withEventsField_cmdDown != null) {
withEventsField_cmdDown.Click += cmdDown_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdUp;
public System.Windows.Forms.Button cmdUp {
get { return withEventsField_cmdUp; }
set {
if (withEventsField_cmdUp != null) {
withEventsField_cmdUp.Click -= cmdUp_Click;
}
withEventsField_cmdUp = value;
if (withEventsField_cmdUp != null) {
withEventsField_cmdUp.Click += cmdUp_Click;
}
}
}
private System.Windows.Forms.ListBox withEventsField_lstItem;
public System.Windows.Forms.ListBox lstItem {
get { return withEventsField_lstItem; }
set {
if (withEventsField_lstItem != null) {
withEventsField_lstItem.DoubleClick -= lstItem_DoubleClick;
}
withEventsField_lstItem = value;
if (withEventsField_lstItem != null) {
withEventsField_lstItem.DoubleClick += lstItem_DoubleClick;
}
}
}
private System.Windows.Forms.ComboBox withEventsField_cmbTemplate;
public System.Windows.Forms.ComboBox cmbTemplate {
get { return withEventsField_cmbTemplate; }
set {
if (withEventsField_cmbTemplate != null) {
withEventsField_cmbTemplate.SelectedIndexChanged -= cmbTemplate_SelectedIndexChanged;
}
withEventsField_cmbTemplate = value;
if (withEventsField_cmbTemplate != null) {
withEventsField_cmbTemplate.SelectedIndexChanged += cmbTemplate_SelectedIndexChanged;
}
}
}
private System.Windows.Forms.ListBox withEventsField_lstTemplate;
public System.Windows.Forms.ListBox lstTemplate {
get { return withEventsField_lstTemplate; }
set {
if (withEventsField_lstTemplate != null) {
withEventsField_lstTemplate.DoubleClick -= lstTemplate_DoubleClick;
}
withEventsField_lstTemplate = value;
if (withEventsField_lstTemplate != null) {
withEventsField_lstTemplate.DoubleClick += lstTemplate_DoubleClick;
}
}
}
public System.Windows.Forms.Button cmdNew;
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_0;
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmGRVTemplate));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdDown = new System.Windows.Forms.Button();
this.cmdUp = new System.Windows.Forms.Button();
this.lstItem = new System.Windows.Forms.ListBox();
this.cmbTemplate = new System.Windows.Forms.ComboBox();
this.lstTemplate = new System.Windows.Forms.ListBox();
this.cmdNew = new System.Windows.Forms.Button();
this._lbl_2 = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "GRV Template Editor";
this.ClientSize = new System.Drawing.Size(419, 382);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmGRVTemplate";
this.cmdDown.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdDown.Text = "Down";
this.cmdDown.Size = new System.Drawing.Size(46, 70);
this.cmdDown.Location = new System.Drawing.Point(363, 294);
this.cmdDown.TabIndex = 5;
this.cmdDown.BackColor = System.Drawing.SystemColors.Control;
this.cmdDown.CausesValidation = true;
this.cmdDown.Enabled = true;
this.cmdDown.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdDown.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdDown.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdDown.TabStop = true;
this.cmdDown.Name = "cmdDown";
this.cmdUp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdUp.Text = "Up";
this.cmdUp.Size = new System.Drawing.Size(46, 70);
this.cmdUp.Location = new System.Drawing.Point(363, 45);
this.cmdUp.TabIndex = 4;
this.cmdUp.BackColor = System.Drawing.SystemColors.Control;
this.cmdUp.CausesValidation = true;
this.cmdUp.Enabled = true;
this.cmdUp.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdUp.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdUp.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdUp.TabStop = true;
this.cmdUp.Name = "cmdUp";
this.lstItem.Size = new System.Drawing.Size(172, 319);
this.lstItem.Location = new System.Drawing.Point(186, 45);
this.lstItem.TabIndex = 3;
this.lstItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstItem.BackColor = System.Drawing.SystemColors.Window;
this.lstItem.CausesValidation = true;
this.lstItem.Enabled = true;
this.lstItem.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstItem.IntegralHeight = true;
this.lstItem.Cursor = System.Windows.Forms.Cursors.Default;
this.lstItem.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstItem.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstItem.Sorted = false;
this.lstItem.TabStop = true;
this.lstItem.Visible = true;
this.lstItem.MultiColumn = false;
this.lstItem.Name = "lstItem";
this.cmbTemplate.Size = new System.Drawing.Size(268, 21);
this.cmbTemplate.Location = new System.Drawing.Point(87, 3);
this.cmbTemplate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbTemplate.TabIndex = 2;
this.cmbTemplate.BackColor = System.Drawing.SystemColors.Window;
this.cmbTemplate.CausesValidation = true;
this.cmbTemplate.Enabled = true;
this.cmbTemplate.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbTemplate.IntegralHeight = true;
this.cmbTemplate.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbTemplate.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbTemplate.Sorted = false;
this.cmbTemplate.TabStop = true;
this.cmbTemplate.Visible = true;
this.cmbTemplate.Name = "cmbTemplate";
this.lstTemplate.Size = new System.Drawing.Size(172, 319);
this.lstTemplate.Location = new System.Drawing.Point(6, 45);
this.lstTemplate.TabIndex = 1;
this.lstTemplate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstTemplate.BackColor = System.Drawing.SystemColors.Window;
this.lstTemplate.CausesValidation = true;
this.lstTemplate.Enabled = true;
this.lstTemplate.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstTemplate.IntegralHeight = true;
this.lstTemplate.Cursor = System.Windows.Forms.Cursors.Default;
this.lstTemplate.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstTemplate.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstTemplate.Sorted = false;
this.lstTemplate.TabStop = true;
this.lstTemplate.Visible = true;
this.lstTemplate.MultiColumn = false;
this.lstTemplate.Name = "lstTemplate";
this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNew.Text = "New ...";
this.cmdNew.Size = new System.Drawing.Size(49, 22);
this.cmdNew.Location = new System.Drawing.Point(360, 3);
this.cmdNew.TabIndex = 0;
this.cmdNew.Visible = false;
this.cmdNew.BackColor = System.Drawing.SystemColors.Control;
this.cmdNew.CausesValidation = true;
this.cmdNew.Enabled = true;
this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNew.TabStop = true;
this.cmdNew.Name = "cmdNew";
this._lbl_2.Text = "GRV Columns :";
this._lbl_2.Size = new System.Drawing.Size(72, 13);
this._lbl_2.Location = new System.Drawing.Point(189, 30);
this._lbl_2.TabIndex = 8;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_1.Text = "Available Columns :";
this._lbl_1.Size = new System.Drawing.Size(92, 13);
this._lbl_1.Location = new System.Drawing.Point(9, 30);
this._lbl_1.TabIndex = 7;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = true;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_0.Text = "GRV Tempate :";
this._lbl_0.Size = new System.Drawing.Size(74, 13);
this._lbl_0.Location = new System.Drawing.Point(8, 6);
this._lbl_0.TabIndex = 6;
this._lbl_0.BackColor = System.Drawing.Color.Transparent;
this._lbl_0.Enabled = true;
this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = true;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_0.Name = "_lbl_0";
this.Controls.Add(cmdDown);
this.Controls.Add(cmdUp);
this.Controls.Add(lstItem);
this.Controls.Add(cmbTemplate);
this.Controls.Add(lstTemplate);
this.Controls.Add(cmdNew);
this.Controls.Add(_lbl_2);
this.Controls.Add(_lbl_1);
this.Controls.Add(_lbl_0);
//Me.lbl.SetIndex(_lbl_2, CType(2, Short))
//Me.lbl.SetIndex(_lbl_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_0, CType(0, Short))
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// UserSettings.cs
//
using System.Runtime.CompilerServices;
namespace Xrm.Sdk
{
public class UserSettingsAttributes
{
public static string UserSettingsId = "usersettingsid";
public static string BusinessUnitId = "businessunitid";
public static string CalendarType = "calendartype";
public static string CurrencyDecimalPrecision = "currencydecimalprecision";
public static string CurrencyFormatCode = "currencyformatcode";
public static string CurrencySymbol = "currencysymbol";
public static string DateFormatCode = "dateformatcode";
public static string DateFormatString = "dateformatstring";
public static string DateSeparator = "dateseparator";
public static string DecimalSymbol = "decimalsymbol";
public static string DefaultCalendarView = "defaultcalendarview";
public static string DefaultDashboardId = "defaultdashboardid";
public static string LocaleId = "localeid";
public static string LongDateFormatCode = "longdateformatcode";
public static string NegativeCurrencyFormatCode = "negativecurrencyformatcode";
public static string NegativeFormatCode = "negativeformatcode";
public static string NumberGroupFormat = "numbergroupformat";
public static string NumberSeparator = "numberseparator";
public static string OfflineSyncInterval = "offlinesyncinterval";
public static string PricingDecimalPrecision = "pricingdecimalprecision";
public static string ShowWeekNumber = "showweeknumber";
public static string SystemUserId = "systemuserid";
public static string TimeFormatCodestring = "timeformatcodestring";
public static string TimeFormatString = "timeformatstring";
public static string TimeSeparator = "timeseparator";
public static string TimeZoneBias = "timezonebias";
public static string TimeZoneCode = "timezonecode";
public static string TimeZoneDaylightBias = "timezonedaylightbias";
public static string TimeZoneDaylightDay = "timezonedaylightday";
public static string TimeZoneDaylightDayOfWeek = "timezonedaylightdayofweek";
public static string TimeZoneDaylightHour = "timezonedaylighthour";
public static string TimeZoneDaylightMinute = "timezonedaylightminute";
public static string TimeZoneDaylightMonth = "timezonedaylightmonth";
public static string TimeZoneDaylightSecond = "timezonedaylightsecond";
public static string TimeZoneDaylightYear = "timezonedaylightyear";
public static string TimeZoneStandardBias = "timezonestandardbias";
public static string TimeZoneStandardDay = "timezonestandardday";
public static string TimeZoneStandardDayOfWeek = "timezonestandarddayofweek";
public static string TimeZoneStandardHour = "timezonestandardhour";
public static string TimeZoneStandardMinute = "timezonestandardminute";
public static string TimeZoneStandardMonth = "timezonestandardmonth";
public static string TimeZoneStandardSecond = "timezonestandardsecond";
public static string TimeZoneStandardYear = "timezonestandardyear";
public static string TransactionCurrencyId = "transactioncurrencyid";
public static string UILanguageId = "uilanguageid";
public static string WorkdayStartTime = "workdaystarttime";
public static string WorkdayStopTime = "workdaystoptime";
}
public partial class UserSettings : Entity
{
public static string EntityLogicalName = "usersettings";
public UserSettings()
: base(EntityLogicalName)
{
}
[ScriptName("usersettingsid")]
public Guid UserSettingsId;
[ScriptName("businessunitid")]
public Guid BusinessUnitId;
[ScriptName("calendartype")]
public int? CalendarType;
[ScriptName("currencydecimalprecision")]
public int? CurrencyDecimalPrecision;
[ScriptName("currencyformatcode")]
public int? CurrencyFormatCode;
[ScriptName("currencysymbol")]
public string CurrencySymbol;
[ScriptName("dateformatcode")]
public int? DateFormatCode;
[ScriptName("dateformatstring")]
public string DateFormatString;
[ScriptName("dateseparator")]
public string DateSeparator;
[ScriptName("decimalsymbol")]
public string DecimalSymbol;
[ScriptName("defaultcalendarview")]
public int? DefaultCalendarView;
[ScriptName("defaultdashboardid")]
public Guid DefaultDashboardId;
[ScriptName("localeid")]
public int? LocaleId;
[ScriptName("longdateformatcode")]
public int? LongDateFormatCode;
[ScriptName("negativecurrencyformatcode")]
public int? NegativeCurrencyFormatCode;
[ScriptName("negativeformatcode")]
public int? NegativeFormatCode;
[ScriptName("numbergroupformat")]
public string NumberGroupFormat;
[ScriptName("numberseparator")]
public string NumberSeparator;
[ScriptName("offlinesyncinterval")]
public int? OfflineSyncInterval;
[ScriptName("pricingdecimalprecision")]
public int? PricingDecimalPrecision;
[ScriptName("showweeknumber")]
public bool? ShowWeekNumber;
[ScriptName("systemuserid")]
public Guid SystemUserId;
[ScriptName("timeformatcodestring")]
public int? TimeFormatCodestring;
[ScriptName("timeformatstring")]
public string TimeFormatString;
[ScriptName("timeseparator")]
public string TimeSeparator;
[ScriptName("timezonebias")]
public int? TimeZoneBias;
[ScriptName("timezonecode")]
public int? TimeZoneCode;
[ScriptName("timezonedaylightbias")]
public int? TimeZoneDaylightBias;
[ScriptName("timezonedaylightday")]
public int? TimeZoneDaylightDay;
[ScriptName("timezonedaylightdayofweek")]
public int? TimeZoneDaylightDayOfWeek;
[ScriptName("timezonedaylighthour")]
public int? TimeZoneDaylightHour;
[ScriptName("timezonedaylightminute")]
public int? TimeZoneDaylightMinute;
[ScriptName("timezonedaylightmonth")]
public int? TimeZoneDaylightMonth;
[ScriptName("timezonedaylightsecond")]
public int? TimeZoneDaylightSecond;
[ScriptName("timezonedaylightyear")]
public int? TimeZoneDaylightYear;
[ScriptName("timezonestandardbias")]
public int? TimeZoneStandardBias;
[ScriptName("timezonestandardday")]
public int? TimeZoneStandardDay;
[ScriptName("timezonestandarddayofweek")]
public int? TimeZoneStandardDayOfWeek;
[ScriptName("timezonestandardhour")]
public int? TimeZoneStandardHour;
[ScriptName("timezonestandardminute")]
public int? TimeZoneStandardMinute;
[ScriptName("timezonestandardmonth")]
public int? TimeZoneStandardMonth;
[ScriptName("timezonestandardsecond")]
public int? TimeZoneStandardSecond;
[ScriptName("timezonestandardyear")]
public int? TimeZoneStandardYear;
[ScriptName("transactioncurrencyid")]
public EntityReference TransactionCurrencyId;
[ScriptName("uilanguageid")]
public int? UILanguageId;
[ScriptName("workdaystarttime")]
public string WorkdayStartTime;
[ScriptName("workdaystoptime")]
public string WorkdayStopTime;
public string GetNumberFormatString(int decimalPlaces)
{
return "###,###,###.000";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
namespace Umbraco.Core.ObjectResolution
{
/// <summary>
/// The base class for all lazy many-objects resolvers.
/// </summary>
/// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam>
/// <typeparam name="TResolved">The type of the resolved objects.</typeparam>
/// <remarks>
/// <para>This is a special case resolver for when types get lazily resolved in order to resolve the actual types. This is useful
/// for when there is some processing overhead (i.e. Type finding in assemblies) to return the Types used to instantiate the instances.
/// In some these cases we don't want to have to type-find during application startup, only when we need to resolve the instances.</para>
/// <para>Important notes about this resolver: it does not support Insert or Remove and therefore does not support any ordering unless
/// the types are marked with the WeightedPluginAttribute.</para>
/// </remarks>
public abstract class LazyManyObjectsResolverBase<TResolver, TResolved> : ManyObjectsResolverBase<TResolver, TResolved>
where TResolved : class
where TResolver : ResolverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: base(scope)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects,
/// with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext)
: base(httpContext)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(IEnumerable<Lazy<Type>> lazyTypeList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(scope)
{
AddTypes(lazyTypeList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list
/// of functions producing types, and an optional lifetime scope.
/// </summary>
/// <param name="typeListProducerList">The list of functions producing types.</param>
/// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param>
/// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks>
/// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception>
protected LazyManyObjectsResolverBase(Func<IEnumerable<Type>> typeListProducerList, ObjectLifetimeScope scope = ObjectLifetimeScope.Application)
: this(scope)
{
_typeListProducerList.Add(typeListProducerList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of
/// lazy object types, with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <param name="lazyTypeList">The list of lazy object types.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Lazy<Type>> lazyTypeList)
: this(httpContext)
{
AddTypes(lazyTypeList);
}
/// <summary>
/// Initializes a new instance of the <see cref="LazyManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of
/// functions producing types, with creation of objects based on an HttpRequest lifetime scope.
/// </summary>
/// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param>
/// <param name="typeListProducerList">The list of functions producing types.</param>
/// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception>
protected LazyManyObjectsResolverBase(HttpContextBase httpContext, Func<IEnumerable<Type>> typeListProducerList)
: this(httpContext)
{
_typeListProducerList.Add(typeListProducerList);
}
#endregion
private readonly List<Lazy<Type>> _lazyTypeList = new List<Lazy<Type>>();
private readonly List<Func<IEnumerable<Type>>> _typeListProducerList = new List<Func<IEnumerable<Type>>>();
private readonly List<Type> _excludedTypesList = new List<Type>();
private List<Type> _resolvedTypes = null;
private readonly ReaderWriterLockSlim _resolvedTypesLock = new ReaderWriterLockSlim();
/// <summary>
/// Gets a value indicating whether the resolver has resolved types to create instances from.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal bool HasResolvedTypes
{
get
{
using (new ReadLock(_resolvedTypesLock))
{
return _resolvedTypes != null;
}
}
}
/// <summary>
/// Gets the list of types to create instances from.
/// </summary>
/// <remarks>When called, will get the types from the lazy list.</remarks>
protected override IEnumerable<Type> InstanceTypes
{
get
{
using (var lck = new UpgradeableReadLock(_resolvedTypesLock))
{
if (_resolvedTypes == null)
{
lck.UpgradeToWriteLock();
_resolvedTypes = new List<Type>();
// get the types by evaluating the lazy & producers
var types = new List<Type>();
types.AddRange(_lazyTypeList.Select(x => x.Value));
types.AddRange(_typeListProducerList.SelectMany(x => x()));
// we need to validate each resolved type now since we could
// not do it before evaluating the lazy & producers
foreach (var type in types.Where(x => !_excludedTypesList.Contains(x)))
{
AddValidAndNoDuplicate(_resolvedTypes, type);
}
}
return _resolvedTypes;
}
}
}
/// <summary>
/// Ensures that type is valid and not a duplicate
/// then appends the type to the end of the list
/// </summary>
/// <param name="list"></param>
/// <param name="type"></param>
private void AddValidAndNoDuplicate(List<Type> list, Type type)
{
EnsureCorrectType(type);
if (list.Contains(type))
{
throw new InvalidOperationException(string.Format(
"Type {0} is already in the collection of types.", type.FullName));
}
list.Add(type);
}
#region Types collection manipulation
/// <summary>
/// Removes types from the list of types, once it has been lazily evaluated, and before actual objects are instanciated.
/// </summary>
/// <param name="value">The type to remove.</param>
public override void RemoveType(Type value)
{
EnsureSupportsRemove();
_excludedTypesList.Add(value);
}
/// <summary>
/// Lazily adds types from lazy types.
/// </summary>
/// <param name="types">The lazy types, to add.</param>
protected void AddTypes(IEnumerable<Lazy<Type>> types)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
foreach (var t in types)
{
_lazyTypeList.Add(t);
}
}
}
/// <summary>
/// Lazily adds types from a function producing types.
/// </summary>
/// <param name="typeListProducer">The functions producing types, to add.</param>
public void AddTypeListDelegate(Func<IEnumerable<Type>> typeListProducer)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_typeListProducerList.Add(typeListProducer);
}
}
/// <summary>
/// Lazily adds a type from a lazy type.
/// </summary>
/// <param name="value">The lazy type, to add.</param>
public void AddType(Lazy<Type> value)
{
EnsureSupportsAdd();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Add(value);
}
}
/// <summary>
/// Lazily adds a type from an actual type.
/// </summary>
/// <param name="value">The actual type, to add.</param>
/// <remarks>The type is converted to a lazy type.</remarks>
public override void AddType(Type value)
{
AddType(new Lazy<Type>(() => value));
}
/// <summary>
/// Clears all lazy types
/// </summary>
public override void Clear()
{
EnsureSupportsClear();
using (Resolution.Configuration)
using (GetWriteLock())
{
_lazyTypeList.Clear();
}
}
#endregion
#region Types collection manipulation support
/// <summary>
/// Gets a <c>false</c> value indicating that the resolver does NOT support inserting types.
/// </summary>
protected override bool SupportsInsert
{
get { return false; }
}
#endregion
}
}
| |
using Breeze.Sharp;
using Breeze.Sharp.Core;
using Foo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Breeze.Sharp.Tests {
[TestClass]
public class QueryTests {
private String _serviceName;
[TestInitialize]
public void TestInitializeMethod() {
Configuration.Instance.ProbeAssemblies(typeof(Customer).Assembly);
_serviceName = TestFns.serviceName;
}
[TestCleanup]
public void TearDown() {
}
[TestMethod]
public async Task WhereTypeWithTimeSpan() {
var em = await TestFns.NewEm(_serviceName);
var q1 = EntityQuery.From<TimeLimit>();
var tls = await em.ExecuteQuery(q1);
Assert.IsTrue(tls.Any());
Assert.IsTrue(tls.All(tl => tl.MaxTime.Ticks >= 0)) ;
}
[TestMethod]
public async Task WhereTypeRequiringCast() {
var em = await TestFns.NewEm(_serviceName);
var q1 = EntityQuery.From<OrderDetail>().Where(od => od.Quantity > 10);
var r1 = await em.ExecuteQuery(q1);
Assert.IsTrue(r1.Any());
Assert.IsTrue(r1.All(r => r.Quantity > 10));
}
[TestMethod]
public async Task WhereTypeWithEnum() {
var em = await TestFns.NewEm(_serviceName);
var q1 = EntityQuery.From<Role>();
var r1 = await em.ExecuteQuery(q1);
Assert.IsTrue(r1.Any());
Assert.IsTrue(r1.Any(r => r.RoleType != null));
}
[TestMethod]
public async Task WhereEnumEquals() {
//Assert.Inconclusive("Waiting on OData server impl that supports 'cast' - maybe in WebApi 2.2?");
// OData server impl does not yet understand 'cast'
var em = await TestFns.NewEm(_serviceName);
var q0 = EntityQuery.From<Role>().Where(r => r.RoleType == RoleType.Guest);
var rp0 = q0.GetResourcePath(em.MetadataStore);
var q1 = EntityQuery.From<Role>().Where(r => r.Description.StartsWith("G") && r.RoleType == RoleType.Guest);
var rp1 = q1.GetResourcePath(em.MetadataStore);
var q2 =
EntityQuery.From<Role>()
.Where(r => r.RoleType == RoleType.Guest && r.Description.StartsWith("G"))
.Select(r => new {r.Description});
var rp2 = q2.GetResourcePath(em.MetadataStore);
var r0 = await em.ExecuteQuery(q0);
Assert.IsTrue(r0.Any());
Assert.IsTrue(r0.All(r => r.RoleType == RoleType.Guest));
var q3 = EntityQuery.From<Role>()
.Where(r => r.RoleType == RoleType.Guest)
.Select(r => new { r.Description });
var r3 = await em.ExecuteQuery(q3);
Assert.IsTrue(r3.Any());
}
[TestMethod]
public async Task WherePropertyPath() {
var em = await TestFns.NewEm(_serviceName);
// Products in a Category whose name starts with "S"
var query1 = EntityQuery.From<Product>()
.Where(product => product.Category.CategoryName.StartsWith("S"));
var r1 = await em.ExecuteQuery(query1);
Assert.IsTrue(r1.Any());
// Orders sold to a Customer located in California
var query2 = new EntityQuery<Order>()
.Where(order => order.Customer.Region == "CA");
var r2 = await em.ExecuteQuery(query2);
Assert.IsTrue(r2.Any());
}
[TestMethod]
public async Task RequerySameEntity() {
var entityManager = await TestFns.NewEm(_serviceName);
// Orders with freight cost over 100.
var query = new EntityQuery<Order>().Where(o => o.Freight > 100);
var orders100 = await entityManager.ExecuteQuery(query);
Assert.IsTrue(orders100.Any(), "There should be orders with freight cost > 100");
var query2 = new EntityQuery<Order>().Where(o => o.Freight > 50);
var orders50 = await entityManager.ExecuteQuery(query2);
Assert.IsTrue(orders50.Any(), "There should be orders with freight cost > 50");
Assert.IsTrue(orders50.Count() >= orders100.Count(), "There should be more orders with freight > 50 than 100");
}
[TestMethod]
public async Task NoWhere() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Customer>();
var results = await em1.ExecuteQuery(q);
Assert.IsTrue(results.Cast<Object>().Count() > 0);
var r1 = await em1.ExecuteQuery(q.Take(2));
Assert.IsTrue(r1.Count() == 2);
}
[TestMethod]
public async Task WhereContains() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Customer>()
.Where(c => c.CompanyName.Contains("market"));
var results = await em1.ExecuteQuery(q);
Assert.IsTrue(results.Any());
}
[TestMethod]
public async Task SelectScalarNpNoAnon() {
Assert.Inconclusive("Known issue with OData - use an anon projection instead");
var em1 = await TestFns.NewEm(_serviceName);
var q1 = new EntityQuery<Order>().Where(o => true).Select(o => o.Customer).Take(5);
var r1 = await q1.Execute(em1);
Assert.IsTrue(r1.Count() == 5);
var ok = r1.All(r => r.GetType() == typeof(Customer));
Assert.IsTrue(ok);
}
[TestMethod]
public async Task SelectSimpleAnonEntity() {
var em1 = await TestFns.NewEm(_serviceName);
var q1 = new EntityQuery<Order>().Select(o => new { o.Customer }).Take(5);
var r1 = await q1.Execute(em1);
Assert.IsTrue(r1.Count() == 5);
var ok = r1.All(r => r.Customer.GetType() == typeof(Customer));
Assert.IsTrue(ok);
}
[TestMethod]
public async Task SelectSimpleAnonEntityCollection() {
var em1 = await TestFns.NewEm(_serviceName);
var q1 = new EntityQuery<Customer>().Where(c => c.CompanyName.StartsWith("C")).Select(c => new { c.Orders });
var r1 = await q1.Execute(em1);
Assert.IsTrue(r1.Count() > 0);
var ok = r1.All(r => r.Orders.Count() > 0);
Assert.IsTrue(ok);
}
[TestMethod]
public async Task NonGenericQuery() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C")).Take(3);
var q3 = (EntityQuery)q2;
var results = await em1.ExecuteQuery(q3);
Assert.IsTrue(results.Cast<Object>().Count() == 3);
}
[TestMethod]
public async Task InlineCount() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C")) ;
var q3 = q2.InlineCount();
var results = await q3.Execute(em1);
var count = ((IHasInlineCount) results).InlineCount;
Assert.IsTrue(results.Count() > 0);
Assert.IsTrue(results.Count() == count, "counts should be the same");
Assert.IsTrue(results.All(r1 => r1.GetType() == typeof(Foo.Customer)), "should all get customers");
}
[TestMethod]
public async Task InlineCount2() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C")).Take(2);
var q3 = q2.InlineCount();
var results = await q3.Execute(em1);
var count = ((IHasInlineCount)results).InlineCount;
Assert.IsTrue(results.Count() == 2);
Assert.IsTrue(results.Count() < count, "counts should be the same");
Assert.IsTrue(results.All(r1 => r1.GetType() == typeof(Foo.Customer)), "should all get customers");
}
[TestMethod]
public async Task WhereOrderByMulti() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Customer>()
.OrderBy(c => c.Country).ThenBy(c => c.CompanyName);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Any());
}
[TestMethod]
public async Task WhereOrderByPropertyPath() {
var em1 = await TestFns.NewEm(_serviceName);
// Products sorted by their Category names (in descending order)
var query1 = EntityQuery.From<Product>()
.OrderByDescending(p => p.Category.CategoryName);
var r1 = await query1.Execute(em1);
Assert.IsTrue(r1.Any());
// Products sorted by their Category names, then by Product name (in descending order)
var query2 = EntityQuery.From<Product>()
.OrderBy(p => p.Category.CategoryName)
.ThenByDescending(p => p.ProductName);
var r2 = await query2.Execute(em1);
Assert.IsTrue(r2.Any());
}
[TestMethod]
public async Task WhereAny() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Employee>()
.Where(emp => emp.Orders.Any(order => order.Freight > 10));
var results = await q.Execute(em1);
Assert.IsTrue(results.Any());
}
[TestMethod]
public async Task WhereAnyNested() {
var em1 = await TestFns.NewEm(_serviceName);
var query1 = new EntityQuery<Customer>()
.Where(c => c.Orders.Any(o => o.OrderDetails.All(od => od.UnitPrice > 200)));
var results = await query1.Execute(em1);
Assert.IsTrue(results.Any());
}
[TestMethod]
public async Task WhereAnyOrderBy() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>();
var q2 = q.Where(c => c.CompanyName.StartsWith("C") && c.Orders.Any(o => o.Freight > 10));
var q3 = q2.OrderBy(c => c.CompanyName).Skip(2);
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
Assert.IsTrue(results.All(r1 => r1.GetType() == typeof(Foo.Customer)), "should all get customers");
var cust = results.First();
var companyName = cust.CompanyName;
var custId = cust.CustomerID;
var orders = cust.Orders;
}
[TestMethod]
public async Task WithOverwriteChanges() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C")) ;
var q3 = q2.OrderBy(c => c.CompanyName).Take(2);
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() == 2);
results.ForEach(r => {
r.City = "xxx";
r.CompanyName = "xxx";
});
var results2 = await q3.With(MergeStrategy.OverwriteChanges).Execute(em1);
// contents of results2 should be exactly the same as results
Assert.IsTrue(results.Count() == 2);
}
[TestMethod]
public async Task WithEntityManager() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.OrderBy(c => c.CompanyName).Take(2);
var results = await q3.With(em1).Execute();
Assert.IsTrue(results.Count() == 2);
}
[TestMethod]
public async Task WhereOrderByTake() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.OrderBy(c => c.CompanyName).Take(2);
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() == 2);
Assert.IsTrue(results.All(r1 => r1.GetType() == typeof(Foo.Customer)), "should all get customers");
}
[TestMethod]
public async Task SelectAnonSingleDp() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Customer>("Customers")
.Where(c => c.CompanyName.StartsWith("C"))
.Select(c => new { c.CompanyName });
var results = await q.Execute(em1);
Assert.IsTrue(results.Any());
}
[TestMethod]
public async Task SelectAnonWithOrderBy() {
Assert.Inconclusive("doesn't yet work properly because of MS OData bug");
// The current code runs but returns a collection of anon objects
// each with an empty "CompanyName"
var em1 = await TestFns.NewEm(_serviceName);
var query = new EntityQuery<Order>()
.Where(o => o.Customer.CompanyName.StartsWith("C"))
.OrderBy(o => o.Customer.CompanyName)
.Select(o => new { o.Customer.CompanyName});
var results = await query.Execute(em1);
Assert.IsTrue(results.Any());
}
[TestMethod]
public async Task SelectAnonWithEntityCollection() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.Select(c => new { Orders = c.Orders });
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
var ok = results.All(r1 => ( r1.Orders.Count() > 0 ) && r1.Orders.All(o => o.GetType() == typeof(Foo.Order)));
Assert.IsTrue(ok, "every item of anon should contain a collection of Orders");
}
[TestMethod]
public async Task SelectAnonWithScalarAndEntityCollection() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.Select(c => new { c.CompanyName, c.Orders});
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
var ok = results.All(r1 => (r1.Orders.Count() > 0) && r1.Orders.All(o => o.GetType() == typeof(Foo.Order)));
Assert.IsTrue(ok, "every item of anon should contain a collection of Orders");
ok = results.All(r1 => r1.CompanyName.Length > 0);
Assert.IsTrue(ok, "anon type should have a populated company name");
}
[TestMethod]
public async Task SelectAnonWithScalarEntity() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Order>("Orders");
var q2 = q.Where(c => c.Freight > 500);
var q3 = q2.Select(c => new { c.Customer, c.Freight });
var results = await q3.Execute(em1);
// get rid of orders with null customers
results = results.Where(r => r.Customer != null);
Assert.IsTrue(results.Any());
var ok = results.All(r1 => r1.Freight > 500);
Assert.IsTrue(ok, "anon type should the right freight");
ok = results.All(r1 => r1.Customer.GetType() == typeof(Foo.Customer));
Assert.IsTrue(ok, "anon type should have a populated 'Customer'");
}
[TestMethod]
public async Task SelectAnonWithScalarSelf() {
Assert.Inconclusive("OData doesn't support this kind of query (I think)");
return;
/*
// Pretty sure this is an issue with OData not supporting this syntax.
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.Select(c => new { c.CompanyName, c });
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
var ok = results.All(r1 => r1.CompanyName.Length > 0);
Assert.IsTrue(ok, "anon type should have a populated company name");
ok = results.All(r1 => r1.c.GetType() == typeof(Foo.Customer));
Assert.IsTrue(ok, "anon type should have a populated 'Customer'");
*/
}
[TestMethod]
public async Task ExpandNonScalar() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.Expand(c => c.Orders);
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
var ok = results.All(r1 =>
r1.GetType() == typeof(Foo.Customer) &&
r1.Orders.Count() > 0 &&
r1.Orders.All(o => o.GetType() == typeof(Foo.Order)) &&
r1.Orders.All(o => o.Customer == r1));
Assert.IsTrue(ok, "every Customer should contain a collection of Orders");
ok = results.All(r1 => r1.CompanyName.Length > 0);
Assert.IsTrue(ok, "and should have a populated company name");
}
[TestMethod]
public async Task ExpandScalar() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Order>("Orders");
var q2 = q.Where(o => o.Freight > 500);
var q3 = q2.Expand(o => o.Customer);
var results = await q3.Execute(em1);
// get rid of orders with null customers
results = results.Where(r => r.Customer != null);
Assert.IsTrue(results.Any());
var ok = results.All(r1 =>
r1.GetType() == typeof(Foo.Order) &&
r1.Customer.GetType() == typeof(Foo.Customer));
Assert.IsTrue(ok, "every Order should have a customer");
ok = results.All(r1 => r1.Freight > 500);
Assert.IsTrue(ok, "and should have the right freight");
}
[TestMethod]
public async Task SelectIntoCustom() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Foo.Customer>("Customers");
var q2 = q.Where(c => c.CompanyName.StartsWith("C"));
var q3 = q2.Select(c => new Dummy() { CompanyName = c.CompanyName, Orders = c.Orders} );
var results = await q3.Execute(em1);
Assert.IsTrue(results.Count() > 0);
var ok = results.All(r1 =>
r1.GetType() == typeof(Dummy) &&
r1.Orders.Count() > 0 &&
r1.Orders.All(o => o.GetType() == typeof(Foo.Order)));
Assert.IsTrue(ok, "every Dummy should contain a collection of Orders");
ok = results.All(r1 => r1.CompanyName.Length > 0);
Assert.IsTrue(ok, "and should have a populated company name");
}
public class Dummy {
public String CompanyName;
public IEnumerable<Foo.Order> Orders;
}
[TestMethod]
public async Task WhereGuid() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Customer>().Where(c => c.CustomerID.Equals(Guid.NewGuid())); // && true);
var rp = q.GetResourcePath(em1.MetadataStore);
var r = await em1.ExecuteQuery(q);
Assert.IsTrue(r.Count() == 0, "should be no results");
}
[TestMethod]
public async Task WhereGuid2() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Order>().Where(o => o.CustomerID == Guid.NewGuid()); // && true);
var rp = q.GetResourcePath(em1.MetadataStore);
var r = await em1.ExecuteQuery(q);
Assert.IsTrue(r.Count() == 0, "should be no results");
}
[TestMethod]
public async Task WhereEntityKey() {
var em1 = await TestFns.NewEm(_serviceName);
var q = new EntityQuery<Customer>().Take(1);
var r = await em1.ExecuteQuery(q);
var customer = r.First();
var q1 = new EntityQuery<Customer>().Where(c => c.CustomerID == customer.CustomerID);
var r1 = await em1.ExecuteQuery(q1);
Assert.IsTrue(r1.First() == customer);
var ek = customer.EntityAspect.EntityKey;
var q2 = ek.ToQuery();
var r2 = await em1.ExecuteQuery(q2);
Assert.IsTrue(r2.Cast<Customer>().First() == customer);
}
[TestMethod]
public async Task WhereSameFieldTwice() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = EntityQuery.From<Order>().Where(o => o.Freight > 100 && o.Freight < 200);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0);
Assert.IsTrue(r0.All(r => r.Freight > 100 && r.Freight < 200), "should match query criteria");
}
[TestMethod]
public async Task ExpandWhereOneToOne() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Order>().Where(o => o.InternationalOrder != null).Take(3).Expand("InternationalOrder");
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() == 3);
Assert.IsTrue(r0.All(r => r.InternationalOrder != null));
}
[TestMethod]
public async Task WhereFnStringFns() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Customer>().Where(c => c.CompanyName.ToLower().StartsWith("c"));
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Any());
Assert.IsTrue(r0.All(c => c.CompanyName.ToLower().StartsWith("c")));
var q1 = EntityQuery.From<Customer>().Where(c => c.CompanyName.Substring(1,2).ToUpper() == "OM");
var r1 = await q1.Execute(em1);
Assert.IsTrue(r1.Any());
Assert.IsTrue(r1.All(c => c.CompanyName.Substring(1,2).ToUpper() == "OM"));
}
[TestMethod]
public async Task WhereFnYear() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Employee>().Where(e => e.HireDate.Value.Year > 1993);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0);
Assert.IsTrue(r0.All(r => r.HireDate.Value.Year > 1993));
var r1 = q0.ExecuteLocally(em1);
Assert.IsTrue(r1.Count() == r0.Count());
}
[TestMethod]
public async Task WhereFnMonth() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Employee>().Where(e => e.HireDate.Value.Month > 6 && e.HireDate.Value.Month < 11);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0);
Assert.IsTrue(r0.All(e => e.HireDate.Value.Month > 6 && e.HireDate.Value.Month < 11));
var r1 = q0.ExecuteLocally(em1);
Assert.IsTrue(r1.Count() == r0.Count());
}
[TestMethod]
public async Task WhereFnAdd() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Employee>().Where(e => e.EmployeeID + e.ReportsToEmployeeID.Value > 3);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0);
Assert.IsTrue(r0.All(e => e.EmployeeID + e.ReportsToEmployeeID > 3));
var r1 = q0.ExecuteLocally(em1);
Assert.IsTrue(r1.Count() == r0.Count());
}
[TestMethod]
public async Task QueryWithBadResourceName() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Customer>("Error").Where(c => c.CompanyName.StartsWith("P"));
try {
var r0 = await q0.Execute(em1);
Assert.Fail("shouldn't get here");
} catch (Exception e) {
Assert.IsTrue(e.Message.ToLower().Contains("not found"), "should be the right message");
}
}
[TestMethod]
public async Task Take0() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Customer>().Take(0);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() == 0);
}
[TestMethod]
public async Task Take0WithInlineCount() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Customer>().Take(0).InlineCount();
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() == 0);
var count = ((IHasInlineCount) r0).InlineCount;
Assert.IsTrue(count > 0);
}
[TestMethod]
public async Task ExpandNested() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<OrderDetail>().Take(5).Expand(od => od.Order.Customer);
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0, "should have returned some orderDetails");
Assert.IsTrue(r0.All(od => od.Order != null && od.Order.Customer != null));
}
[TestMethod]
public async Task ExpandNested3Levels() {
var em1 = await TestFns.NewEm(_serviceName);
var q0 = new EntityQuery<Order>().Take(5).Expand("OrderDetails.Product.Category");
var r0 = await q0.Execute(em1);
Assert.IsTrue(r0.Count() > 0, "should have returned some orders");
Assert.IsTrue(r0.All(o => o.OrderDetails.Any(od => od.Product.Category != null)));
}
//test("query with take, orderby and expand", function () {
// if (testFns.DEBUG_MONGO) {
// ok(true, "NA for Mongo - expand not yet supported");
// return;
// }
// var em = newEm();
// var q1 = EntityQuery.from("Products")
// .expand("category")
// .orderBy("category.categoryName desc, productName");
// stop();
// var topTen;
// em.executeQuery(q1).then(function (data) {
// topTen = data.results.slice(0, 10);
// var q2 = q1.take(10);
// return em.executeQuery(q2);
// }).then(function (data2) {
// var topTenAgain = data2.results;
// for(var i=0; i<10; i++) {
// ok(topTen[i] === topTenAgain[i]);
// }
// }).fail(testFns.handleFail).fin(start);
//});
//test("query with take, skip, orderby and expand", function () {
// if (testFns.DEBUG_MONGO) {
// ok(true, "NA for Mongo - expand not yet supported");
// return;
// }
// var em = newEm();
// var q1 = EntityQuery.from("Products")
// .expand("category")
// .orderBy("category.categoryName, productName");
// stop();
// var nextTen;
// em.executeQuery(q1).then(function (data) {
// nextTen = data.results.slice(10, 20);
// var q2 = q1.skip(10).take(10);
// return em.executeQuery(q2);
// }).then(function (data2) {
// var nextTenAgain = data2.results;
// for (var i = 0; i < 10; i++) {
// ok(nextTen[i] === nextTenAgain[i], extractDescr(nextTen[i]) + " -- " + extractDescr(nextTenAgain[i]));
// }
// }).fail(testFns.handleFail).fin(start);
//});
//function extractDescr(product) {
// var cat = product.getProperty("category");
// return cat && cat.getProperty("categoryName") + ":" + product.getProperty("productName");
//}
//test("query with quotes", function () {
// var em = newEm();
// var q = EntityQuery.from("Customers")
// .where("companyName", 'contains', "'")
// .using(em);
// stop();
// q.execute().then(function (data) {
// ok(data.results.length > 0);
// var r = em.executeQueryLocally(q);
// ok(r.length === data.results.length, "local query should return same subset");
// }).fail(testFns.handleFail).fin(start);
//});
//test("bad query test", function () {
// var em = newEm();
// var q = EntityQuery.from("EntityThatDoesnotExist")
// .using(em);
// stop();
// q.execute().then(function (data) {
// ok(false, "should not get here");
// }).fail(function (e) {
// ok(e.message && e.message.toLowerCase().indexOf("entitythatdoesnotexist") >= 0, e.message);
// }).fin(function(x) {
// start();
// });
//});
//test("OData predicate - add combined with regular predicate", function () {
// if (testFns.DEBUG_MONGO) {
// ok(true, "Mongo does not yet support the 'add' OData predicate");
// return;
// }
// var manager = newEm();
// var predicate = Predicate.create("EmployeeID add ReportsToEmployeeID gt 3").and("employeeID", "<", 9999);
// var query = new breeze.EntityQuery()
// .from("Employees")
// .where(predicate);
// stop();
// manager.executeQuery(query).then(function (data) {
// ok(data.results.length > 0, "there should be records returned");
// try {
// manager.executeQueryLocally(query);
// ok(false, "shouldn't get here");
// } catch (e) {
// ok(e, "should throw an exception");
// }
// }).fail(testFns.handleFail).fin(start);
//});
//test("select with inlinecount", function () {
// var manager = newEm();
// var query = new breeze.EntityQuery()
// .from("Customers")
// .select("companyName, region, city")
// .inlineCount();
// stop();
// manager.executeQuery(query).then(function (data) {
// ok(data.results.length == data.inlineCount, "inlineCount should match return count");
// }).fail(testFns.handleFail).fin(start);
//});
//test("select with inlinecount and take", function () {
// var manager = newEm();
// var query = new breeze.EntityQuery()
// .from("Customers")
// .select("companyName, region, city")
// .take(5)
// .inlineCount();
// stop();
// manager.executeQuery(query).then(function (data) {
// ok(data.results.length == 5, "should be 5 records returned");
// ok(data.inlineCount > 5, "should have an inlinecount > 5");
// }).fail(testFns.handleFail).fin(start);
//});
//test("select with inlinecount and take and orderBy", function () {
// var manager = newEm();
// var query = new breeze.EntityQuery()
// .from("Customers")
// .select("companyName, region, city")
// .orderBy("city, region")
// .take(5)
// .inlineCount();
// stop();
// manager.executeQuery(query).then(function (data) {
// ok(data.results.length == 5, "should be 5 records returned");
// ok(data.inlineCount > 5, "should have an inlinecount > 5");
// }).fail(testFns.handleFail).fin(start);
//});
//test("expand not working with paging or inlinecount", function () {
// var manager = newEm();
// var predicate = Predicate.create(testFns.orderKeyName, "<", 10500);
// stop();
// var query = new breeze.EntityQuery()
// .from("Orders")
// .expand("orderDetails, orderDetails.product")
// .where(predicate)
// .inlineCount()
// .orderBy("orderDate")
// .take(2)
// .skip(1)
// .using(manager)
// .execute()
// .then(function (data) {
// ok(data.inlineCount > 0, "should have an inlinecount");
// var localQuery = breeze.EntityQuery
// .from('OrderDetails');
// // For ODATA this is a known bug: https://aspnetwebstack.codeplex.com/workitem/1037
// // having to do with mixing expand and inlineCount
// // it sounds like it might already be fixed in the next major release but not yet avail.
// var orderDetails = manager.executeQueryLocally(localQuery);
// ok(orderDetails.length > 0, "should not be empty");
// var localQuery2 = breeze.EntityQuery
// .from('Products');
// var products = manager.executeQueryLocally(localQuery2);
// ok(products.length > 0, "should not be empty");
// }).fail(testFns.handleFail).fin(start);
//});
//test("test date in projection", function () {
// var manager = newEm();
// var query = new breeze.EntityQuery()
// .from("Orders")
// .where("orderDate", "!=", null)
// .orderBy("orderDate")
// .take(3);
// var orderDate;
// var orderDate2;
// stop();
// manager.executeQuery(query).then(function (data) {
// var result = data.results[0];
// orderDate = result.getProperty("orderDate");
// ok(core.isDate(orderDate), "orderDate should be of 'Date type'");
// var manager2 = newEm();
// var query = new breeze.EntityQuery()
// .from("Orders")
// .where("orderDate", "!=", null)
// .orderBy("orderDate")
// .take(3)
// .select("orderDate");
// return manager2.executeQuery(query);
// }).then(function (data2) {
// orderDate2 = data2.results[0].orderDate;
// if (testFns.DEBUG_ODATA) {
// ok(core.isDate(orderDate2), "orderDate2 is not a date - ugh'");
// var orderDate2a = orderDate2;
// } else {
// ok(!core.isDate(orderDate2), "orderDate pojection should not be a date except with ODATA'");
// var orderDate2a = breeze.DataType.parseDateFromServer(orderDate2);
// }
// ok(orderDate.getTime() === orderDate2a.getTime(), "should be the same date");
// }).fail(testFns.handleFail).fin(start);
//});
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.Controls
{
/// <summary>
/// Summary description for MiniForm.
/// </summary>
public class MiniForm : BaseForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private IWin32Window _parentFrame ;
private IMiniFormOwner _owner ;
private bool _floatAboveMainFrame = false ;
private bool _dismissOnDeactivate = false ;
public MiniForm()
: this(Win32WindowImpl.ForegroundWin32Window)
{
}
public MiniForm(IWin32Window parentFrame)
{
_parentFrame = parentFrame ;
//
// Required for Windows Form Designer support
//
InitializeComponent();
// double-buffered painting
User32.SetWindowLong(Handle, GWL.STYLE, User32.GetWindowLong(Handle, GWL.STYLE) & ~WS.CLIPCHILDREN);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
}
public bool DismissOnDeactivate
{
get
{
return _dismissOnDeactivate ;
}
set
{
_dismissOnDeactivate = value ;
}
}
public void FloatAboveOwner( IMiniFormOwner owner )
{
_floatAboveMainFrame = true ;
_owner = owner ;
_owner.AddOwnedForm(this);
}
protected IWin32Window ParentFrame
{
get
{
return _parentFrame ;
}
}
protected override CreateParams CreateParams
{
get
{
// copy base create params
CreateParams createParams = base.CreateParams;
// add system standard drop shadow
if ( ShowDropShadow )
{
const int CS_DROPSHADOW = 0x20000 ;
createParams.ClassStyle |= CS_DROPSHADOW ;
}
// prevent appearance in alt-tab window
createParams.ClassStyle |= 0x00000080 ; // WS_EX_TOOLWINDOW
return createParams ;
}
}
protected virtual bool ShowDropShadow
{
get
{
return true ;
}
}
/// <summary>
/// Override out Activated event to allow parent form to retains its 'activated'
/// look (caption bar color, etc.) even when we are active
/// </summary>
/// <param name="e"></param>
protected override void OnActivated(EventArgs e)
{
// call base
base.OnActivated (e);
// send the parent form a WM_NCACTIVATE message to cause it to to retain it's
// activated title bar appearance
User32.SendMessage( ParentFrame.Handle, WM.NCACTIVATE, new UIntPtr(1), IntPtr.Zero ) ;
}
/// <summary>
/// Automatically close when the form is deactivated
/// </summary>
/// <param name="e">event args</param>
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate (e);
if ( DismissOnDeactivate )
{
// set a timer that will result in the closing of the form
// (we do this because if actually call Close right here it
// will prevent the mouse event that resulted in the deactivation
// of the form from actually triggering in the new target
// window -- this allows the mouse event to trigger and the
// form to go away almost instantly
Timer closeDelayTimer = new Timer() ;
closeDelayTimer.Tick +=new EventHandler(closeDelayTimer_Tick);
closeDelayTimer.Interval = 10 ;
closeDelayTimer.Start() ;
}
}
/// <summary>
/// Actually close the form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void closeDelayTimer_Tick(object sender, EventArgs e)
{
// stop and dispose the timer
Timer closeDelayTimer = (Timer)sender ;
closeDelayTimer.Stop() ;
closeDelayTimer.Dispose() ;
// cancel the form
Close() ;
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing (e);
if ( _floatAboveMainFrame )
_owner.RemoveOwnedForm(this);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// MiniForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(292, 266);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "MiniForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "MiniForm";
}
#endregion
}
public interface IMiniFormOwner
{
void AddOwnedForm(Form f);
void RemoveOwnedForm(Form f);
}
}
| |
using System;
using Craft.Net.Common;
using Craft.Net.Anvil;
using System.Collections.Generic;
using System.Reflection;
using Craft.Net.Physics;
namespace Craft.Net.Logic
{
public abstract class Block : Item
{
public override short ItemId { get { return BlockId; } }
public delegate BoundingBox? BoundingBoxHandler(BlockInfo info);
public delegate bool IsSolidOnFaceHandler(BlockInfo info, BlockFace face);
public delegate void BlockMinedHandler(World world, Coordinates3D coordinates, BlockInfo info);
public delegate bool BlockRightClickedHandler(World world, Coordinates3D coordinates, BlockInfo info, BlockFace face, Coordinates3D cursor, ItemInfo? item);
private static Dictionary<short, string> BlockNames { get; set; }
private static Dictionary<short, double> BlockHardness { get; set; }
public static IBlockPhysicsProvider PhysicsProvider { get; private set; }
private static Dictionary<short, string> BlockPlacementSoundEffects { get; set; }
private static Dictionary<short, BoundingBoxHandler> BoundingBoxHandlers { get; set; }
private static Dictionary<short, IsSolidOnFaceHandler> IsSolidOnFaceHandlers { get; set; }
private static Dictionary<short, BlockMinedHandler> BlockMinedHandlers { get; set; }
private static Dictionary<short, BlockRightClickedHandler> BlockRightClickedHandlers { get; set; }
static Block()
{
PhysicsProvider = new BlockPhysicsProvider();
BoundingBoxHandlers = new Dictionary<short, BoundingBoxHandler>();
IsSolidOnFaceHandlers = new Dictionary<short, IsSolidOnFaceHandler>();
BlockMinedHandlers = new Dictionary<short, BlockMinedHandler>();
BlockRightClickedHandlers = new Dictionary<short, BlockRightClickedHandler>();
BlockHardness = new Dictionary<short, double>();
BlockNames = new Dictionary<short, string>();
BlockPlacementSoundEffects = new Dictionary<short, string>();
ReflectBlocks(typeof(Block).Assembly);
}
public static void ReflectBlocks(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (typeof(Block).IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
{
LoadBlock((Block)Activator.CreateInstance(type));
}
}
}
public static void LoadBlock<T>() where T : Block
{
LoadBlock(default(T));
}
private static void LoadBlock(Block block)
{
BlockNames.Add(block.BlockId, block.Name);
Item.LoadItem(block);
if (!Item.ItemUsedOnBlockHandlers.ContainsKey(block.BlockId))
Item.ItemUsedOnBlockHandlers[block.BlockId] = DefaultUsedOnBlockHandler;
}
public static string GetPlacementSoundEffect(short blockId)
{
if (BlockPlacementSoundEffects.ContainsKey(blockId))
return BlockPlacementSoundEffects[blockId];
return SoundEffect.DigStone;
}
protected void SetPlacementSoundEffect(string soundEffect)
{
BlockPlacementSoundEffects[BlockId] = soundEffect;
}
protected void SetBoundingBoxHandler(BoundingBoxHandler handler)
{
BoundingBoxHandlers[BlockId] = handler;
}
protected void SetIsSolidOnFaceHandler(IsSolidOnFaceHandler handler)
{
IsSolidOnFaceHandlers[BlockId] = handler;
}
protected void SetBlockMinedHandler(BlockMinedHandler handler)
{
BlockMinedHandlers[BlockId] = handler;
}
protected void SetBlockRightClickedHandler(BlockRightClickedHandler handler)
{
BlockRightClickedHandlers[BlockId] = handler;
}
protected void SetDropHandler(Func<World, Coordinates3D, BlockInfo, ItemStack[]> dropHandler, bool overrideSilkTouch = false)
{
SetBlockMinedHandler((world, coordinates, info) =>
{
world.SetBlockId(coordinates, 0);
world.SetMetadata(coordinates, 0);
foreach (var drop in dropHandler(world, coordinates, info))
world.OnSpawnEntityRequested(new ItemEntity((Vector3)coordinates + new Vector3(0.5), drop));
});
}
private class BlockPhysicsProvider : IBlockPhysicsProvider
{
public BoundingBox? GetBoundingBox(World world, Coordinates3D coordinates)
{
// TODO: Consider passing block info to a handler to get a fancier bounding box
var info = world.GetBlockInfo(coordinates);
return Block.GetBoundingBox(info);
}
}
public static BoundingBox? GetBoundingBox(BlockInfo info)
{
if (BoundingBoxHandlers.ContainsKey(info.BlockId))
return BoundingBoxHandlers[info.BlockId](info);
else
return DefaultBoundingBoxHandler(info);
}
public static bool GetIsSolidOnFace(BlockInfo info, BlockFace face)
{
if (IsSolidOnFaceHandlers.ContainsKey(info.BlockId))
return IsSolidOnFaceHandlers[info.BlockId](info, face);
else
return DefaultIsSolidOnFaceHandler(info, face);
}
internal static void OnBlockMined(World world, Coordinates3D coordinates)
{
var info = world.GetBlockInfo(coordinates);
if (BlockMinedHandlers.ContainsKey(info.BlockId))
BlockMinedHandlers[info.BlockId](world, coordinates, info);
else
DefaultBlockMinedHandler(world, coordinates, info);
}
internal static bool OnBlockRightClicked(World world, Coordinates3D coordinates, BlockFace face, Coordinates3D cursor, ItemInfo? item)
{
var info = world.GetBlockInfo(coordinates);
if (BlockRightClickedHandlers.ContainsKey(info.BlockId))
return BlockRightClickedHandlers[info.BlockId](world, coordinates, info, face, cursor, item);
else
return DefaultBlockRightClickedHandler(world, coordinates, info, face, item);
}
public static int GetHarvestTime(short blockId, short itemId, World world, PlayerEntity entity, out short damage)
{
int time = GetHarvestTime(blockId, itemId, out damage);
var type = Item.GetToolType(itemId);
if (type != null)
{
if (!Item.IsEfficient(itemId, blockId))
{
//if (entity.IsUnderwater(world) && !entity.IsOnGround(world))
// time *= 25;
//else if (entity.IsUnderwater(world) || !entity.IsOnGround(world))
// time *= 5;
// TODO
}
}
return time;
}
public static double GetBlockHardness(short blockId)
{
if (BlockHardness.ContainsKey(blockId))
return BlockHardness[blockId];
return 0;
}
/// <summary>
/// Gets the amount of time (in milliseconds) it takes to harvest this
/// block with the given tool.
/// </summary>
public static int GetHarvestTime(short blockId, short itemId, out short damage)
{
// time is in seconds until returned
double hardness = GetBlockHardness(blockId);
if (hardness == -1)
{
damage = 0;
return -1;
}
double time = hardness * 1.5;
var tool = Item.GetToolType(itemId);
var material = Item.GetItemMaterial(itemId);
damage = 0;
// Adjust for tool in use
if (tool != null)
{
//if (!CanHarvest(tool))
// time *= 3.33;
if (Item.IsEfficient(itemId, blockId) && material != null)
{
switch (material.Value)
{
case ItemMaterial.Wood:
time /= 2;
break;
case ItemMaterial.Stone:
time /= 4;
break;
case ItemMaterial.Iron:
time /= 6;
break;
case ItemMaterial.Diamond:
time /= 8;
break;
case ItemMaterial.Gold:
time /= 12;
break;
}
}
// Do tool damage
damage = 1;
if (tool.Value == Craft.Net.Logic.ToolType.Pickaxe
|| tool.Value == Craft.Net.Logic.ToolType.Axe
|| tool.Value == Craft.Net.Logic.ToolType.Shovel)
{
damage = (short)(hardness != 0 ? 1 : 0);
}
else if (tool.Value == Craft.Net.Logic.ToolType.Sword)
{
damage = (short)(hardness != 0 ? 2 : 0);
time /= 1.5;
//if (this is CobwebBlock) // TODO
// time /= 15;
}
else if (tool.Value == Craft.Net.Logic.ToolType.Hoe)
damage = 0;
// else if (tool is ShearsItem) // TODO
// {
// if (this is WoolBlock)
// time /= 5;
// if (this is LeavesBlock || this is CobwebBlock)
// time /= 15;
// if (this is CobwebBlock || this is LeavesBlock || this is TallGrassBlock ||
// this is TripwireBlock || this is VineBlock)
// damage = 1;
// else
// damage = 0;
// }
else
damage = 0;
}
return (int)(time * 1000);
}
private static void DefaultBlockMinedHandler(World world, Coordinates3D coordinates, BlockInfo info)
{
world.SetBlockId(coordinates, 0);
world.SetMetadata(coordinates, 0);
world.OnSpawnEntityRequested(new ItemEntity((Vector3)coordinates + new Vector3(0.5),
new ItemStack(info.BlockId, 1, info.Metadata)));
}
/*private */internal static void DefaultUsedOnBlockHandler(World world, Coordinates3D coordinates, BlockFace face, Coordinates3D cursor, ItemInfo item)
{
coordinates += MathHelper.BlockFaceToCoordinates(face);
world.SetBlockId(coordinates, item.ItemId);
world.SetMetadata(coordinates, (byte)item.Metadata);
}
private static bool DefaultBlockRightClickedHandler(World world, Coordinates3D coordinates, BlockInfo block, BlockFace face, ItemInfo? item)
{
return true;
}
private static BoundingBox? DefaultBoundingBoxHandler(BlockInfo info)
{
return new BoundingBox(Vector3.Zero, Vector3.One);
}
private static bool DefaultIsSolidOnFaceHandler(BlockInfo info, BlockFace face)
{
return true;
}
public abstract short BlockId { get; }
protected Block(string name, ItemMaterial? material = null, ToolType? toolType = null, double? hardness = null)
: base(name, material, toolType)
{
if (hardness != null)
BlockHardness[BlockId] = hardness.Value;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Serialization;
namespace Chronos
{
/// <summary>
/// Determines what type of clock a timeline observes.
/// </summary>
public enum TimelineMode
{
/// <summary>
/// The timeline observes a LocalClock attached to the same GameObject.
/// </summary>
Local,
/// <summary>
/// The timeline observes a GlobalClock referenced by globalClockKey.
/// </summary>
Global
}
/// <summary>
/// A component that combines timing measurements from an observed LocalClock or GlobalClock and any AreaClock within which it is. This component should be attached to any GameObject that should be affected by Chronos.
/// </summary>
[AddComponentMenu("Time/Timeline")]
[DisallowMultipleComponent]
[HelpURL("http://ludiq.io/chronos/documentation#Timeline")]
public class Timeline : TimelineEffector
{
protected internal const float DefaultRecordingDuration = 30;
public Timeline()
{
children = new HashSet<TimelineChild>();
areaClocks = new HashSet<IAreaClock>();
occurrences = new HashSet<Occurrence>();
handledOccurrences = new HashSet<Occurrence>();
previousDeltaTimes = new Queue<float>();
timeScale = lastTimeScale = 1;
}
protected override void Start()
{
timeScale = lastTimeScale = clock.timeScale;
base.Start();
}
protected override void Update()
{
TriggerEvents();
lastTimeScale = timeScale;
timeScale = clock.timeScale; // Start with the time scale from local / global clock
foreach (IAreaClock areaClock in areaClocks) // Blend it with the time scale of each area clock
{
if (areaClock != null)
{
float areaClockTimeScale = areaClock.TimeScale(this);
if (areaClock.innerBlend == ClockBlend.Multiplicative)
{
timeScale *= areaClockTimeScale;
}
else // if (areaClock.innerBlend == ClockBlend.Additive)
{
timeScale += areaClockTimeScale;
}
}
}
if (!rewindable) // Cap to 0 for non-rewindable timelines
{
timeScale = Mathf.Max(0, timeScale);
}
if (timeScale != lastTimeScale)
{
foreach (var component in components)
{
component.AdjustProperties();
}
foreach (var child in children)
{
foreach (var component in child.components)
{
component.AdjustProperties();
}
}
}
float unscaledDeltaTime = Timekeeper.unscaledDeltaTime;
deltaTime = unscaledDeltaTime * timeScale;
fixedDeltaTime = Time.fixedDeltaTime * timeScale;
time += deltaTime;
unscaledTime += unscaledDeltaTime;
RecordSmoothing();
base.Update();
if (timeScale > 0)
{
TriggerForwardOccurrences();
}
else if (timeScale < 0)
{
TriggerBackwardOccurrences();
}
}
#region Fields
protected internal float lastTimeScale;
protected Queue<float> previousDeltaTimes;
protected HashSet<Occurrence> occurrences;
protected HashSet<Occurrence> handledOccurrences;
protected Occurrence nextForwardOccurrence;
protected Occurrence nextBackwardOccurrence;
protected internal HashSet<IAreaClock> areaClocks;
protected internal HashSet<TimelineChild> children;
#endregion
#region Properties
protected override Timeline timeline
{
get { return this; }
}
[SerializeField]
private TimelineMode _mode;
/// <summary>
/// Determines what type of clock the timeline observes.
/// </summary>
public TimelineMode mode
{
get { return _mode; }
set
{
_mode = value;
_clock = null;
}
}
[SerializeField, GlobalClock]
private string _globalClockKey;
/// <summary>
/// The key of the GlobalClock that is observed by the timeline. This value is only used for the Global mode.
/// </summary>
public string globalClockKey
{
get { return _globalClockKey; }
set
{
_globalClockKey = value;
_clock = null;
}
}
private Clock _clock;
/// <summary>
/// The clock observed by the timeline.
/// </summary>
public Clock clock
{
get
{
if (_clock == null)
{
_clock = FindClock();
}
return _clock;
}
}
/// <summary>
/// The time scale of the timeline, computed from all observed clocks. For more information, see Clock.timeScale.
/// </summary>
public float timeScale { get; protected set; }
/// <summary>
/// The delta time of the timeline, computed from all observed clocks. For more information, see Clock.deltaTime.
/// </summary>
public float deltaTime { get; protected set; }
/// <summary>
/// The fixed delta time of the timeline, computed from all observed clocks. For more information, see Clock.fixedDeltaTime.
/// </summary>
public float fixedDeltaTime { get; protected set; }
/// <summary>
/// A smoothed out delta time. Use this value if you need to avoid spikes and fluctuations in delta times. The amount of frames over which this value is smoothed can be adjusted via smoothingDeltas.
/// </summary>
public float smoothDeltaTime
{
get { return (deltaTime + previousDeltaTimes.Sum()) / (previousDeltaTimes.Count + 1); }
}
/// <summary>
/// The amount of frames over which smoothDeltaTime is smoothed.
/// </summary>
public static int smoothingDeltas = 5;
/// <summary>
/// The time in seconds since the creation of this timeline, computed from all observed clocks. For more information, see Clock.time.
/// </summary>
public float time { get; protected internal set; }
/// <summary>
/// The unscaled time in seconds since the creation of this timeline. For more information, see Clock.unscaledTime.
/// </summary>
public float unscaledTime { get; protected set; }
/// <summary>
/// Indicates the state of the timeline.
/// </summary>
public TimeState state
{
get { return Timekeeper.GetTimeState(timeScale); }
}
#endregion
#region Timing
protected virtual Clock FindClock()
{
if (mode == TimelineMode.Local)
{
LocalClock localClock = GetComponent<LocalClock>();
if (localClock == null)
{
throw new ChronosException(string.Format("Missing local clock for timeline."));
}
return localClock;
}
else if (mode == TimelineMode.Global)
{
GlobalClock oldGlobalClock = _clock as GlobalClock;
if (oldGlobalClock != null)
{
oldGlobalClock.Unregister(this);
}
if (!Timekeeper.instance.HasClock(globalClockKey))
{
throw new ChronosException(string.Format("Missing global clock for timeline: '{0}'.", globalClockKey));
}
GlobalClock globalClock = Timekeeper.instance.Clock(globalClockKey);
globalClock.Register(this);
return globalClock;
}
else
{
throw new ChronosException(string.Format("Unknown timeline mode: '{0}'.", mode));
}
}
/// <summary>
/// Releases the timeline from the specified area clock's effects.
/// </summary>
public virtual void ReleaseFrom(IAreaClock areaClock)
{
areaClock.Release(this);
}
/// <summary>
/// Releases the timeline from the effects of all the area clocks within which it is.
/// </summary>
public virtual void ReleaseFromAll()
{
foreach (IAreaClock areaClock in areaClocks.Where(ac => ac != null).ToArray())
{
areaClock.Release(this);
}
areaClocks.Clear();
}
protected virtual void TriggerEvents()
{
if (lastTimeScale != 0 && timeScale == 0)
{
SendMessage("OnStartPause", SendMessageOptions.DontRequireReceiver);
}
if (lastTimeScale == 0 && timeScale != 0)
{
SendMessage("OnStopPause", SendMessageOptions.DontRequireReceiver);
}
if (lastTimeScale >= 0 && timeScale < 0)
{
SendMessage("OnStartRewind", SendMessageOptions.DontRequireReceiver);
}
if (lastTimeScale < 0 && timeScale >= 0)
{
SendMessage("OnStopRewind", SendMessageOptions.DontRequireReceiver);
}
if ((lastTimeScale <= 0 || lastTimeScale >= 1) && (timeScale > 0 && timeScale < 1))
{
SendMessage("OnStartSlowDown", SendMessageOptions.DontRequireReceiver);
}
if ((lastTimeScale > 0 && lastTimeScale < 1) && (timeScale <= 0 || timeScale >= 1))
{
SendMessage("OnStopSlowDown", SendMessageOptions.DontRequireReceiver);
}
if (lastTimeScale <= 1 && timeScale > 1)
{
SendMessage("OnStartFastForward", SendMessageOptions.DontRequireReceiver);
}
if (lastTimeScale > 1 && timeScale <= 1)
{
SendMessage("OnStopFastForward", SendMessageOptions.DontRequireReceiver);
}
}
protected virtual void RecordSmoothing()
{
if (deltaTime != 0)
{
previousDeltaTimes.Enqueue(deltaTime);
}
if (previousDeltaTimes.Count > smoothingDeltas)
{
previousDeltaTimes.Dequeue();
}
}
#endregion
#region Occurrences
protected void TriggerForwardOccurrences()
{
handledOccurrences.Clear();
while (nextForwardOccurrence != null && nextForwardOccurrence.time <= time)
{
nextForwardOccurrence.Forward();
handledOccurrences.Add(nextForwardOccurrence);
nextBackwardOccurrence = nextForwardOccurrence;
nextForwardOccurrence = OccurrenceAfter(nextForwardOccurrence.time, handledOccurrences);
}
}
protected void TriggerBackwardOccurrences()
{
handledOccurrences.Clear();
while (nextBackwardOccurrence != null && nextBackwardOccurrence.time >= time)
{
nextBackwardOccurrence.Backward();
if (nextBackwardOccurrence.repeatable)
{
handledOccurrences.Add(nextBackwardOccurrence);
nextForwardOccurrence = nextBackwardOccurrence;
}
else
{
occurrences.Remove(nextBackwardOccurrence);
}
nextBackwardOccurrence = OccurrenceBefore(nextBackwardOccurrence.time, handledOccurrences);
}
}
protected Occurrence OccurrenceAfter(float time, params Occurrence[] ignored)
{
return OccurrenceAfter(time, (IEnumerable<Occurrence>) ignored);
}
protected Occurrence OccurrenceAfter(float time, IEnumerable<Occurrence> ignored)
{
Occurrence after = null;
foreach (Occurrence occurrence in occurrences)
{
if (occurrence.time >= time &&
!ignored.Contains(occurrence) &&
(after == null || occurrence.time < after.time))
{
after = occurrence;
}
}
return after;
}
protected Occurrence OccurrenceBefore(float time, params Occurrence[] ignored)
{
return OccurrenceBefore(time, (IEnumerable<Occurrence>) ignored);
}
protected Occurrence OccurrenceBefore(float time, IEnumerable<Occurrence> ignored)
{
Occurrence before = null;
foreach (Occurrence occurrence in occurrences)
{
if (occurrence.time <= time &&
!ignored.Contains(occurrence) &&
(before == null || occurrence.time > before.time))
{
before = occurrence;
}
}
return before;
}
protected virtual void PlaceOccurence(Occurrence occurrence, float time)
{
if (time == this.time)
{
if (timeScale >= 0)
{
occurrence.Forward();
nextBackwardOccurrence = occurrence;
}
else
{
occurrence.Backward();
nextForwardOccurrence = occurrence;
}
}
else if (time > this.time)
{
if (nextForwardOccurrence == null ||
nextForwardOccurrence.time > time)
{
nextForwardOccurrence = occurrence;
}
}
else if (time < this.time)
{
if (nextBackwardOccurrence == null ||
nextBackwardOccurrence.time < time)
{
nextBackwardOccurrence = occurrence;
}
}
}
/// <summary>
/// Schedules an occurrence at a specified absolute time in seconds on the timeline.
/// </param>
public virtual Occurrence Schedule(float time, bool repeatable, Occurrence occurrence)
{
occurrence.time = time;
occurrence.repeatable = repeatable;
occurrences.Add(occurrence);
PlaceOccurence(occurrence, time);
return occurrence;
}
/// <summary>
/// Executes an occurrence now and places it on the schedule for rewinding.
/// </summary>
public Occurrence Do(bool repeatable, Occurrence occurrence)
{
return Schedule(time, repeatable, occurrence);
}
/// <summary>
/// Plans an occurrence to be executed in the specified delay in seconds.
/// </summary>
public Occurrence Plan(float delay, bool repeatable, Occurrence occurrence)
{
if (delay <= 0)
{
throw new ChronosException("Planned occurrences must be in the future.");
}
return Schedule(time + delay, repeatable, occurrence);
}
/// <summary>
/// Creates a "memory" of an occurrence at a specified "past-delay" in seconds. This means that the occurrence will only be executed if time is rewound, and that it will be executed backward first.
/// </summary>
public Occurrence Memory(float delay, bool repeatable, Occurrence occurrence)
{
if (delay >= 0)
{
throw new ChronosException("Memory occurrences must be in the past.");
}
return Schedule(time - delay, repeatable, occurrence);
}
#region Func<T>
public Occurrence Schedule<T>(float time, bool repeatable, ForwardFunc<T> forward, BackwardFunc<T> backward)
{
return Schedule(time, repeatable, new FuncOccurence<T>(forward, backward));
}
public Occurrence Do<T>(bool repeatable, ForwardFunc<T> forward, BackwardFunc<T> backward)
{
return Do(repeatable, new FuncOccurence<T>(forward, backward));
}
public Occurrence Plan<T>(float delay, bool repeatable, ForwardFunc<T> forward, BackwardFunc<T> backward)
{
return Plan(delay, repeatable, new FuncOccurence<T>(forward, backward));
}
public Occurrence Memory<T>(float delay, bool repeatable, ForwardFunc<T> forward, BackwardFunc<T> backward)
{
return Memory(delay, repeatable, new FuncOccurence<T>(forward, backward));
}
#endregion
#region Action
public Occurrence Schedule(float time, bool repeatable, ForwardAction forward, BackwardAction backward)
{
return Schedule(time, repeatable, new ActionOccurence(forward, backward));
}
public Occurrence Do(bool repeatable, ForwardAction forward, BackwardAction backward)
{
return Do(repeatable, new ActionOccurence(forward, backward));
}
public Occurrence Plan(float delay, bool repeatable, ForwardAction forward, BackwardAction backward)
{
return Plan(delay, repeatable, new ActionOccurence(forward, backward));
}
public Occurrence Memory(float delay, bool repeatable, ForwardAction forward, BackwardAction backward)
{
return Memory(delay, repeatable, new ActionOccurence(forward, backward));
}
#endregion
#region Forward Action
public Occurrence Schedule(float time, ForwardAction forward)
{
return Schedule(time, false, new ForwardActionOccurence(forward));
}
public Occurrence Plan(float delay, ForwardAction forward)
{
return Plan(delay, false, new ForwardActionOccurence(forward));
}
public Occurrence Memory(float delay, ForwardAction forward)
{
return Memory(delay, false, new ForwardActionOccurence(forward));
}
#endregion
/// <summary>
/// Removes the specified occurrence from the timeline.
/// </summary>
public void Cancel(Occurrence occurrence)
{
if (!occurrences.Contains(occurrence))
{
throw new ChronosException("Occurrence to cancel not found on timeline.");
}
else
{
if (occurrence == nextForwardOccurrence)
{
nextForwardOccurrence = OccurrenceAfter(occurrence.time, occurrence);
}
if (occurrence == nextBackwardOccurrence)
{
nextBackwardOccurrence = OccurrenceBefore(occurrence.time, occurrence);
}
occurrences.Remove(occurrence);
}
}
/// <summary>
/// Removes the specified occurrence from the timeline and returns true if it is found. Otherwise, returns false.
/// </summary>
public bool TryCancel(Occurrence occurrence)
{
if (!occurrences.Contains(occurrence))
{
return false;
}
else
{
Cancel(occurrence);
return true;
}
}
/// <summary>
/// Change the absolute time in seconds of the specified occurrence on the timeline.
/// </summary>
public void Reschedule(Occurrence occurrence, float time)
{
occurrence.time = time;
PlaceOccurence(occurrence, time);
}
/// <summary>
/// Moves the specified occurrence forward on the timeline by the specified delay in seconds.
/// </summary>
public void Postpone(Occurrence occurrence, float delay)
{
Reschedule(occurrence, time + delay);
}
/// <summary>
/// Moves the specified occurrence backward on the timeline by the specified delay in seconds.
/// </summary>
public void Prepone(Occurrence occurrence, float delay)
{
Reschedule(occurrence, time - delay);
}
#endregion
#region Coroutines
/// <summary>
/// Suspends the coroutine execution for the given amount of seconds. This method should only be used with a yield statement in coroutines.
/// </summary>
public Coroutine WaitForSeconds(float seconds)
{
return StartCoroutine(WaitingForSeconds(seconds));
}
protected IEnumerator WaitingForSeconds(float seconds)
{
float start = time;
while (time < start + seconds)
{
yield return null;
}
}
#endregion
#region Rewinding / Recording
[SerializeField, FormerlySerializedAs("_recordTransform")]
private bool _rewindable = true;
/// <summary>
/// Determines whether the timeline should record support rewind.
/// </summary>
public bool rewindable
{
get { return _rewindable; }
set
{
_rewindable = value;
if (particleSystem != null)
{
CacheComponents();
}
}
}
[SerializeField]
private float _recordingDuration = DefaultRecordingDuration;
/// <summary>
/// The maximum duration in seconds during which snapshots will be recorded. Higher values offer more rewind time but require more memory.
/// </summary>
public float recordingDuration
{
get { return _recordingDuration; }
set
{
_recordingDuration = value;
if (recorder != null)
{
recorder.Reset();
}
}
}
#endregion
}
}
| |
// 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.Speech.V1P1Beta1.Snippets
{
using Google.Api.Gax.Grpc;
using Google.LongRunning;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedSpeechClientSnippets
{
/// <summary>Snippet for Recognize</summary>
public void RecognizeRequestObject()
{
// Snippet: Recognize(RecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = speechClient.Recognize(request);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeRequestObjectAsync()
{
// Snippet: RecognizeAsync(RecognizeRequest, CallSettings)
// Additional: RecognizeAsync(RecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognizeRequest request = new RecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
};
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(request);
// End snippet
}
/// <summary>Snippet for Recognize</summary>
public void Recognize()
{
// Snippet: Recognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = speechClient.Recognize(config, audio);
// End snippet
}
/// <summary>Snippet for RecognizeAsync</summary>
public async Task RecognizeAsync()
{
// Snippet: RecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: RecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
RecognizeResponse response = await speechClient.RecognizeAsync(config, audio);
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognizeRequestObject()
{
// Snippet: LongRunningRecognize(LongRunningRecognizeRequest, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeRequestObjectAsync()
{
// Snippet: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CallSettings)
// Additional: LongRunningRecognizeAsync(LongRunningRecognizeRequest, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
LongRunningRecognizeRequest request = new LongRunningRecognizeRequest
{
Config = new RecognitionConfig(),
Audio = new RecognitionAudio(),
OutputConfig = new TranscriptOutputConfig(),
};
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(request);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognize</summary>
public void LongRunningRecognize()
{
// Snippet: LongRunningRecognize(RecognitionConfig, RecognitionAudio, CallSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = speechClient.LongRunningRecognize(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = speechClient.PollOnceLongRunningRecognize(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for LongRunningRecognizeAsync</summary>
public async Task LongRunningRecognizeAsync()
{
// Snippet: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CallSettings)
// Additional: LongRunningRecognizeAsync(RecognitionConfig, RecognitionAudio, CancellationToken)
// Create client
SpeechClient speechClient = await SpeechClient.CreateAsync();
// Initialize request argument(s)
RecognitionConfig config = new RecognitionConfig();
RecognitionAudio audio = new RecognitionAudio();
// Make the request
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> response = await speechClient.LongRunningRecognizeAsync(config, audio);
// Poll until the returned long-running operation is complete
Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
LongRunningRecognizeResponse 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<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> retrievedResponse = await speechClient.PollOnceLongRunningRecognizeAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
LongRunningRecognizeResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for StreamingRecognize</summary>
public async Task StreamingRecognize()
{
// Snippet: StreamingRecognize(CallSettings, BidirectionalStreamingSettings)
// Create client
SpeechClient speechClient = SpeechClient.Create();
// Initialize streaming call, retrieving the stream object
SpeechClient.StreamingRecognizeStream response = speechClient.StreamingRecognize();
// Sending requests and retrieving responses can be arbitrarily interleaved
// Exact sequence will depend on client/server behavior
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
// Note that C# 8 code can use await foreach
AsyncResponseStream<StreamingRecognizeResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
StreamingRecognizeResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
StreamingRecognizeRequest request = new StreamingRecognizeRequest
{
StreamingConfig = new StreamingRecognitionConfig(),
};
// Stream a request to the server
await response.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await response.WriteCompleteAsync();
// Await the response handler
// This will complete once all server responses have been processed
await responseHandlerTask;
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost.Utils;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.StreamingTests;
using FluentAssertions;
namespace Tester.StreamingTests
{
public abstract class StreamFilteringTestsBase : OrleansTestingBase
{
protected Guid StreamId;
protected string StreamNamespace;
protected string streamProviderName;
private static readonly TimeSpan timeout = TimeSpan.FromSeconds(30);
protected StreamFilteringTestsBase()
{
StreamId = Guid.NewGuid();
StreamNamespace = Guid.NewGuid().ToString();
}
// Test support functions
protected async Task Test_Filter_EvenOdd(bool allCheckEven = false)
{
streamProviderName.Should().NotBeNull("Stream provider name not set.");
// Consumers
const int numConsumers = 10;
var consumers = new IFilteredStreamConsumerGrain[numConsumers];
var promises = new List<Task>();
for (int loopCount = 0; loopCount < numConsumers; loopCount++)
{
IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(Guid.NewGuid());
consumers[loopCount] = grain;
bool isEven = allCheckEven || loopCount % 2 == 0;
Task promise = grain.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, isEven);
promises.Add(promise);
}
await Task.WhenAll(promises);
// Producer
IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid());
await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName);
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 1, timeout);
}
// Check initial counts
var sb = new StringBuilder();
int[] counts = new int[numConsumers];
for (int i = 0; i < numConsumers; i++)
{
counts[i] = await consumers[i].GetReceivedCount();
sb.AppendFormat("Baseline count = {0} for consumer {1}", counts[i], i);
sb.AppendLine();
}
logger.Info(sb.ToString());
// Get producer to send some messages
for (int round = 1; round <= 10; round++)
{
bool roundIsEven = round % 2 == 0;
await producer.SendItem(round);
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout);
}
for (int i = 0; i < numConsumers; i++)
{
bool indexIsEven = i % 2 == 0;
int expected = counts[i];
if (roundIsEven)
{
if (indexIsEven || allCheckEven) expected += 1;
}
else if (allCheckEven)
{
// No change to expected counts for odd rounds
}
else
{
if (!indexIsEven) expected += 1;
}
int count = await consumers[i].GetReceivedCount();
logger.Info("Received count = {0} in round {1} for consumer {2}", count, round, i);
count.Should().Be(expected, "Expected count in round {0} for consumer {1}", round, i);
counts[i] = expected; // Set new baseline
}
}
}
protected async Task Test_Filter_BadFunc()
{
streamProviderName.Should().NotBeNull("Stream provider name not set.");
Guid id = Guid.NewGuid();
IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id);
try
{
await grain.Ping();
await grain.SubscribeWithBadFunc(id, StreamNamespace, streamProviderName);
}
catch (AggregateException ae)
{
Exception exc = ae.GetBaseException();
logger.Info("Got exception " + exc);
throw exc;
}
}
protected async Task Test_Filter_TwoObsv_Different()
{
streamProviderName.Should().NotBeNull("Stream provider name not set.");
Guid id1 = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
// Same consumer grain subscribes twice, with two different filters
IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1);
await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even
await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, false); // Odd
IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2);
await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName);
int expectedCount = 1; // Producer always sends first message when it becomes active
await producer.SendItem(1);
expectedCount++; // One observer receives, the other does not.
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout);
}
int count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after first send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after first send");
await producer.SendItem(2);
expectedCount++;
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout);
}
count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after second send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after second send");
await producer.SendItem(3);
expectedCount++;
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout);
}
count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after third send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after second send");
}
protected async Task Test_Filter_TwoObsv_Same()
{
streamProviderName.Should().NotBeNull("Stream provider name not set.");
Guid id1 = Guid.NewGuid();
Guid id2 = Guid.NewGuid();
// Same consumer grain subscribes twice, with two identical filters
IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1);
await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even
await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even
IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2);
await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName);
int expectedCount = 2; // When Producer becomes active, it always sends first message to each subscriber
await producer.SendItem(1);
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout);
}
int count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after first send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after first send");
await producer.SendItem(2);
expectedCount += 2;
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout);
}
count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after second send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after second send");
await producer.SendItem(3);
if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName))
{
// Allow some time for messages to propagate through the system
await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout);
}
count = await consumer.GetReceivedCount();
logger.Info("Received count = {0} after third send for consumer {1}", count, consumer);
count.Should().Be(expectedCount, "Expected count after second send");
}
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.Mac.Drawing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using nnint = System.Int32;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
using nnint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
using nnint = System.Int32;
#endif
#endif
namespace Eto.Mac.Forms.Controls
{
public class TextAreaHandler : TextAreaHandler<TextArea, TextArea.ICallback>, TextArea.IHandler
{
}
public interface ITextAreaHandler
{
TextArea.ICallback Callback { get; }
TextArea Widget { get; }
Range<int> Selection { get; }
int CaretIndex { get; }
Range<int> lastSelection { get; set; }
int? lastCaretIndex { get; set; }
}
public class EtoTextAreaDelegate : NSTextViewDelegate
{
WeakReference handler;
public ITextAreaHandler Handler { get { return (ITextAreaHandler)handler.Target; } set { handler = new WeakReference(value); } }
public override void TextDidChange(NSNotification notification)
{
Handler.Callback.OnTextChanged(Handler.Widget, EventArgs.Empty);
}
public override void DidChangeSelection(NSNotification notification)
{
var selection = Handler.Selection;
if (selection != Handler.lastSelection)
{
Handler.Callback.OnSelectionChanged(Handler.Widget, EventArgs.Empty);
Handler.lastSelection = selection;
}
var caretIndex = Handler.CaretIndex;
if (caretIndex != Handler.lastCaretIndex)
{
Handler.Callback.OnCaretIndexChanged(Handler.Widget, EventArgs.Empty);
Handler.lastCaretIndex = caretIndex;
}
}
}
public class EtoTextView : NSTextView, IMacControl
{
public WeakReference WeakHandler { get; set; }
public object Handler
{
get { return WeakHandler.Target; }
set { WeakHandler = new WeakReference(value); }
}
public override void ChangeColor(NSObject sender)
{
// ignore color changes
}
}
public class TextAreaHandler<TControl, TCallback> : MacView<NSTextView, TControl, TCallback>, TextArea.IHandler, ITextAreaHandler
where TControl: TextArea
where TCallback: TextArea.ICallback
{
int? ITextAreaHandler.lastCaretIndex { get; set; }
Range<int> ITextAreaHandler.lastSelection { get; set; }
public override void OnKeyDown(KeyEventArgs e)
{
if (!AcceptsTab)
{
if (e.KeyData == Keys.Tab)
{
if (Control.Window != null)
Control.Window.SelectNextKeyView(Control);
return;
}
if (e.KeyData == (Keys.Tab | Keys.Shift))
{
if (Control.Window != null)
Control.Window.SelectPreviousKeyView(Control);
return;
}
}
if (!AcceptsReturn && e.KeyData == Keys.Enter)
{
return;
}
base.OnKeyDown(e);
}
public NSScrollView Scroll { get; private set; }
public override NSView ContainerControl
{
get { return Scroll; }
}
public TextAreaHandler()
{
Control = new EtoTextView
{
Handler = this,
Delegate = new EtoTextAreaDelegate { Handler = this },
AutoresizingMask = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable,
HorizontallyResizable = true,
VerticallyResizable = true,
Editable = true,
RichText = false,
AllowsDocumentBackgroundColorChange = false,
Selectable = true,
AllowsUndo = true,
MinSize = CGSize.Empty,
MaxSize = new CGSize(float.MaxValue, float.MaxValue)
};
Control.TextContainer.WidthTracksTextView = true;
Scroll = new EtoScrollView
{
Handler = this,
AutoresizesSubviews = true,
HasVerticalScroller = true,
HasHorizontalScroller = true,
AutohidesScrollers = true,
BorderType = NSBorderType.BezelBorder,
DocumentView = Control
};
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
return new SizeF(100, 60);
}
public override void AttachEvent(string id)
{
switch (id)
{
case TextControl.TextChangedEvent:
/*Control.TextDidChange += (sender, e) => {
Widget.OnTextChanged (EventArgs.Empty);
};*/
break;
case TextArea.SelectionChangedEvent:
/*Control.DidChangeSelection += (sender, e) => {
var selection = this.Selection;
if (selection != lastSelection) {
Widget.OnSelectionChanged (EventArgs.Empty);
lastSelection = selection;
}
};*/
break;
case TextArea.CaretIndexChangedEvent:
/*Control.DidChangeSelection += (sender, e) => {
var caretIndex = Handler.CaretIndex;
if (caretIndex != lastCaretIndex) {
Handler.Widget.OnCaretIndexChanged (EventArgs.Empty);
lastCaretIndex = caretIndex;
}
};*/
break;
default:
base.AttachEvent(id);
break;
}
}
public bool ReadOnly
{
get { return !Control.Editable; }
set { Control.Editable = !value; }
}
public override bool Enabled
{
get { return Control.Selectable; }
set
{
Control.Selectable = value;
if (!value)
{
Control.TextColor = NSColor.DisabledControlText;
Control.BackgroundColor = NSColor.ControlBackground;
}
else
{
Control.TextColor = TextColor.ToNSUI();
Control.BackgroundColor = BackgroundColor.ToNSUI();
}
}
}
public virtual string Text
{
get
{
return Control.Value;
}
set
{
Control.Value = value ?? string.Empty;
Control.DisplayIfNeeded();
}
}
static readonly object TextColor_Key = new object();
public Color TextColor
{
get { return Widget.Properties.Get(TextColor_Key, () => NSColor.ControlText.ToEto()); }
set
{
Widget.Properties.Set(TextColor_Key, value, () =>
{
Control.TextColor = Control.InsertionPointColor = value.ToNSUI();
});
}
}
static readonly object BackgroundColor_Key = new object();
public override Color BackgroundColor
{
get { return Widget.Properties.Get<Color>(BackgroundColor_Key, () => NSColor.ControlBackground.ToEto()); }
set
{
Widget.Properties.Set(BackgroundColor_Key, value, () =>
{
Control.BackgroundColor = value.ToNSUI();
});
}
}
static readonly object Font_Key = new object();
public Font Font
{
get { return Widget.Properties.Create(Font_Key, () => new Font(new FontHandler(Control.Font))); }
set
{
Widget.Properties.Set(Font_Key, value, () =>
{
Control.Font = value.ToNSFont();
LayoutIfNeeded();
});
}
}
public bool Wrap
{
get
{
return Control.TextContainer.WidthTracksTextView;
}
set
{
if (value)
{
Control.TextContainer.WidthTracksTextView = true;
Control.TextContainer.ContainerSize = new CGSize(Scroll.DocumentVisibleRect.Size.Width, float.MaxValue);
}
else
{
Control.TextContainer.WidthTracksTextView = false;
Control.TextContainer.ContainerSize = new CGSize(float.MaxValue, float.MaxValue);
}
}
}
public string SelectedText
{
get
{
var range = Control.SelectedRange;
if (range.Location >= 0 && range.Length > 0)
return Control.Value.Substring((int)range.Location, (int)range.Length);
return null;
}
set
{
if (value != null)
{
var range = Control.SelectedRange;
Control.Replace(range, value);
range.Length = (nnint)value.Length;
Control.SelectedRange = range;
}
}
}
public Range<int> Selection
{
get { return Control.SelectedRange.ToEto(); }
set { Control.SelectedRange = value.ToNS(); }
}
public void SelectAll()
{
Control.SelectAll(Control);
}
public int CaretIndex
{
get { return (int)Control.SelectedRange.Location; }
set { Control.SelectedRange = new NSRange(value, 0); }
}
static readonly object AcceptsTab_Key = new object();
public bool AcceptsTab
{
get { return Widget.Properties.Get<bool?>(AcceptsTab_Key) ?? true; }
set
{
Widget.Properties[AcceptsTab_Key] = value;
if (!value)
HandleEvent(Eto.Forms.Control.KeyDownEvent);
}
}
static readonly object AcceptsReturn_Key = new object();
public bool AcceptsReturn
{
get { return Widget.Properties.Get<bool?>(AcceptsReturn_Key) ?? true; }
set
{
Widget.Properties[AcceptsReturn_Key] = value;
if (!value)
HandleEvent(Eto.Forms.Control.KeyDownEvent);
}
}
public void Append(string text, bool scrollToCursor)
{
var range = new NSRange(Control.Value.Length, 0);
Control.Replace(range, text);
range = new NSRange(Control.Value.Length, 0);
Control.SelectedRange = range;
if (scrollToCursor)
Control.ScrollRangeToVisible(range);
}
public TextAlignment TextAlignment
{
get { return Control.Alignment.ToEto(); }
set { Control.Alignment = value.ToNS(); }
}
public bool SpellCheck
{
get { return Control.ContinuousSpellCheckingEnabled; }
set { Control.ContinuousSpellCheckingEnabled = value; }
}
public bool SpellCheckIsSupported { get { return true; } }
TextArea.ICallback ITextAreaHandler.Callback
{
get { return Callback; }
}
TextArea ITextAreaHandler.Widget
{
get { return Widget; }
}
}
}
| |
// 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.Contracts;
using System.Net;
using System.Net.Http;
namespace System.ServiceModel.Channels
{
public sealed class HttpResponseMessageProperty : IMessageProperty, IMergeEnabledMessageProperty
{
private TraditionalHttpResponseMessageProperty _traditionalProperty;
private HttpResponseMessageBackedProperty _httpBackedProperty;
private bool _useHttpBackedProperty;
private bool _initialCopyPerformed;
public HttpResponseMessageProperty()
{
_traditionalProperty = new TraditionalHttpResponseMessageProperty();
_useHttpBackedProperty = false;
}
internal HttpResponseMessageProperty(WebHeaderCollection originalHeaders)
{
_traditionalProperty = new TraditionalHttpResponseMessageProperty(originalHeaders);
_useHttpBackedProperty = false;
}
internal HttpResponseMessageProperty(HttpResponseMessage httpResponseMessage)
{
_httpBackedProperty = new HttpResponseMessageBackedProperty(httpResponseMessage);
_useHttpBackedProperty = true;
}
public static string Name
{
get { return "httpResponse"; }
}
public WebHeaderCollection Headers
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.Headers :
_traditionalProperty.Headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.StatusCode :
_traditionalProperty.StatusCode;
}
set
{
int valueInt = (int)value;
if (valueInt < 100 || valueInt > 599)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.Format(SR.ValueMustBeInRange, 100, 599)));
}
if (_useHttpBackedProperty)
{
_httpBackedProperty.StatusCode = value;
}
else
{
_traditionalProperty.StatusCode = value;
}
}
}
internal bool HasStatusCodeBeenSet
{
get
{
return _useHttpBackedProperty ?
true :
_traditionalProperty.HasStatusCodeBeenSet;
}
}
public string StatusDescription
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.StatusDescription :
_traditionalProperty.StatusDescription;
}
set
{
if (_useHttpBackedProperty)
{
_httpBackedProperty.StatusDescription = value;
}
else
{
_traditionalProperty.StatusDescription = value;
}
}
}
public bool SuppressEntityBody
{
get
{
return _useHttpBackedProperty ?
_httpBackedProperty.SuppressEntityBody :
_traditionalProperty.SuppressEntityBody;
}
set
{
if (_useHttpBackedProperty)
{
_httpBackedProperty.SuppressEntityBody = value;
}
else
{
_traditionalProperty.SuppressEntityBody = value;
}
}
}
public bool SuppressPreamble
{
get
{
return _useHttpBackedProperty ?
false :
_traditionalProperty.SuppressPreamble;
}
set
{
if (!_useHttpBackedProperty)
{
_traditionalProperty.SuppressPreamble = value;
}
}
}
public HttpResponseMessage HttpResponseMessage
{
get
{
if (_useHttpBackedProperty)
{
return _httpBackedProperty.HttpResponseMessage;
}
return null;
}
}
internal static HttpResponseMessage GetHttpResponseMessageFromMessage(Message message)
{
HttpResponseMessage httpResponseMessage = null;
HttpResponseMessageProperty property = message.Properties.GetValue<HttpResponseMessageProperty>(HttpResponseMessageProperty.Name);
if (property != null)
{
httpResponseMessage = property.HttpResponseMessage;
if (httpResponseMessage != null)
{
httpResponseMessage.CopyPropertiesFromMessage(message);
message.EnsureReadMessageState();
}
}
return httpResponseMessage;
}
IMessageProperty IMessageProperty.CreateCopy()
{
if (!_useHttpBackedProperty ||
!_initialCopyPerformed)
{
_initialCopyPerformed = true;
return this;
}
return _httpBackedProperty.CreateTraditionalResponseMessageProperty();
}
bool IMergeEnabledMessageProperty.TryMergeWithProperty(object propertyToMerge)
{
// The ImmutableDispatchRuntime will merge MessageProperty instances from the
// OperationContext (that were created before the response message was created) with
// MessageProperty instances on the message itself. The message's version of the
// HttpResponseMessageProperty may hold a reference to an HttpResponseMessage, and this
// cannot be discarded, so values from the OperationContext's property must be set on
// the message's version without completely replacing the message's property.
if (_useHttpBackedProperty)
{
HttpResponseMessageProperty responseProperty = propertyToMerge as HttpResponseMessageProperty;
if (responseProperty != null)
{
if (!responseProperty._useHttpBackedProperty)
{
_httpBackedProperty.MergeWithTraditionalProperty(responseProperty._traditionalProperty);
responseProperty._traditionalProperty = null;
responseProperty._httpBackedProperty = _httpBackedProperty;
responseProperty._useHttpBackedProperty = true;
}
return true;
}
}
return false;
}
private class TraditionalHttpResponseMessageProperty
{
public const HttpStatusCode DefaultStatusCode = HttpStatusCode.OK;
public const string DefaultStatusDescription = null; // null means use description from status code
private HttpStatusCode _statusCode;
public TraditionalHttpResponseMessageProperty()
{
_statusCode = DefaultStatusCode;
this.StatusDescription = DefaultStatusDescription;
}
private WebHeaderCollection _headers;
private WebHeaderCollection _originalHeaders;
public TraditionalHttpResponseMessageProperty(WebHeaderCollection originalHeaders) : this()
{
_originalHeaders = originalHeaders;
}
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new WebHeaderCollection();
if (_originalHeaders != null)
{
foreach (var headerKey in _originalHeaders.AllKeys)
{
_headers[headerKey] = _originalHeaders[headerKey];
}
_originalHeaders = null;
}
}
return _headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return _statusCode;
}
set
{
_statusCode = value;
this.HasStatusCodeBeenSet = true;
}
}
public bool HasStatusCodeBeenSet { get; private set; }
public string StatusDescription { get; set; }
public bool SuppressEntityBody { get; set; }
public bool SuppressPreamble { get; set; }
}
private class HttpResponseMessageBackedProperty
{
public HttpResponseMessageBackedProperty(HttpResponseMessage httpResponseMessage)
{
Contract.Assert(httpResponseMessage != null, "The 'httpResponseMessage' property should never be null.");
this.HttpResponseMessage = httpResponseMessage;
}
public HttpResponseMessage HttpResponseMessage { get; private set; }
private WebHeaderCollection _headers;
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = this.HttpResponseMessage.ToWebHeaderCollection();
}
return _headers;
}
}
public HttpStatusCode StatusCode
{
get
{
return this.HttpResponseMessage.StatusCode;
}
set
{
this.HttpResponseMessage.StatusCode = value;
}
}
public string StatusDescription
{
get
{
return this.HttpResponseMessage.ReasonPhrase;
}
set
{
this.HttpResponseMessage.ReasonPhrase = value;
}
}
public bool SuppressEntityBody
{
get
{
HttpContent content = this.HttpResponseMessage.Content;
if (content != null)
{
long? contentLength = content.Headers.ContentLength;
if (!contentLength.HasValue ||
(contentLength.HasValue && contentLength.Value > 0))
{
return false;
}
}
return true;
}
set
{
HttpContent content = this.HttpResponseMessage.Content;
if (value && content != null &&
(!content.Headers.ContentLength.HasValue ||
content.Headers.ContentLength.Value > 0))
{
HttpContent newContent = new ByteArrayContent(Array.Empty<byte>());
foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
{
newContent.Headers.AddHeaderWithoutValidation(header);
}
this.HttpResponseMessage.Content = newContent;
content.Dispose();
}
else if (!value && content == null)
{
this.HttpResponseMessage.Content = new ByteArrayContent(Array.Empty<byte>());
}
}
}
public HttpResponseMessageProperty CreateTraditionalResponseMessageProperty()
{
HttpResponseMessageProperty copiedProperty = new HttpResponseMessageProperty();
foreach (var headerKey in this.Headers.AllKeys)
{
copiedProperty.Headers[headerKey] = this.Headers[headerKey];
}
if (this.StatusCode != TraditionalHttpResponseMessageProperty.DefaultStatusCode)
{
copiedProperty.StatusCode = this.StatusCode;
}
copiedProperty.StatusDescription = this.StatusDescription;
copiedProperty.SuppressEntityBody = this.SuppressEntityBody;
return copiedProperty;
}
public void MergeWithTraditionalProperty(TraditionalHttpResponseMessageProperty propertyToMerge)
{
if (propertyToMerge.HasStatusCodeBeenSet)
{
this.StatusCode = propertyToMerge.StatusCode;
}
if (propertyToMerge.StatusDescription != TraditionalHttpResponseMessageProperty.DefaultStatusDescription)
{
this.StatusDescription = propertyToMerge.StatusDescription;
}
this.SuppressEntityBody = propertyToMerge.SuppressEntityBody;
this.HttpResponseMessage.MergeWebHeaderCollection(propertyToMerge.Headers);
}
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
using Amazon.S3.Util;
namespace Amazon.S3.Model
{
/// <summary>
/// Returns information about the HeadObject response and response metadata.
/// </summary>
public class GetObjectMetadataResponse : AmazonWebServiceResponse
{
private string deleteMarker;
private string acceptRanges;
private Expiration expiration;
private DateTime? restoreExpiration;
private bool restoreInProgress;
private DateTime? lastModified;
private string eTag;
private int? missingMeta;
private string versionId;
private DateTime? expires;
private string websiteRedirectLocation;
private string serverSideEncryptionKeyManagementServiceKeyId;
private ServerSideEncryptionMethod serverSideEncryption;
private ServerSideEncryptionCustomerMethod serverSideEncryptionCustomerMethod;
private HeadersCollection headersCollection = new HeadersCollection();
private MetadataCollection metadataCollection = new MetadataCollection();
private ReplicationStatus replicationStatus;
private S3StorageClass storageClass;
/// <summary>
/// Flag which returns true if the Expires property has been unmarshalled
/// from the raw value or set by user code.
/// </summary>
private bool isExpiresUnmarshalled;
internal string RawExpires { get; set; }
/// <summary>
/// The collection of headers for the request.
/// </summary>
public HeadersCollection Headers
{
get
{
if (this.headersCollection == null)
this.headersCollection = new HeadersCollection();
return this.headersCollection;
}
}
/// <summary>
/// The collection of meta data for the request.
/// </summary>
public MetadataCollection Metadata
{
get
{
if (this.metadataCollection == null)
this.metadataCollection = new MetadataCollection();
return this.metadataCollection;
}
}
/// <summary>
/// Specifies whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the
/// response.
///
/// </summary>
public string DeleteMarker
{
get { return this.deleteMarker; }
set { this.deleteMarker = value; }
}
// Check to see if DeleteMarker property is set
internal bool IsSetDeleteMarker()
{
return this.deleteMarker != null;
}
/// <summary>
/// Gets and sets the AcceptRanges.
/// </summary>
public string AcceptRanges
{
get { return this.acceptRanges; }
set { this.acceptRanges = value; }
}
// Check to see if AcceptRanges property is set
internal bool IsSetAcceptRanges()
{
return this.acceptRanges != null;
}
/// <summary>
/// Gets and sets the Expiration property.
/// Specifies the expiration date for the object and the
/// rule governing the expiration.
/// Is null if expiration is not applicable.
/// </summary>
public Expiration Expiration
{
get { return this.expiration; }
set { this.expiration = value; }
}
// Check to see if Expiration property is set
internal bool IsSetExpiration()
{
return this.expiration != null;
}
/// <summary>
/// Gets and sets the RestoreExpiration property.
/// RestoreExpiration will be set for objects that have been restored from Amazon Glacier.
/// It indiciates for those objects how long the restored object will exist.
/// </summary>
public DateTime? RestoreExpiration
{
get { return this.restoreExpiration; }
set { this.restoreExpiration = value; }
}
/// <summary>
/// Gets and sets the RestoreInProgress
/// Will be true when the object is in the process of being restored from Amazon Glacier.
/// </summary>
public bool RestoreInProgress
{
get { return this.restoreInProgress; }
set { this.restoreInProgress = value; }
}
/// <summary>
/// Last modified date of the object
///
/// </summary>
public DateTime LastModified
{
get { return this.lastModified ?? default(DateTime); }
set { this.lastModified = value; }
}
// Check to see if LastModified property is set
internal bool IsSetLastModified()
{
return this.lastModified.HasValue;
}
/// <summary>
/// An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL
///
/// </summary>
public string ETag
{
get { return this.eTag; }
set { this.eTag = value; }
}
// Check to see if ETag property is set
internal bool IsSetETag()
{
return this.eTag != null;
}
/// <summary>
/// This is set to the number of metadata entries not returned in x-amz-meta headers. This can happen if you create metadata using an API like
/// SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal
/// HTTP headers.
///
/// </summary>
public int MissingMeta
{
get { return this.missingMeta ?? default(int); }
set { this.missingMeta = value; }
}
// Check to see if MissingMeta property is set
internal bool IsSetMissingMeta()
{
return this.missingMeta.HasValue;
}
/// <summary>
/// Version of the object.
///
/// </summary>
public string VersionId
{
get { return this.versionId; }
set { this.versionId = value; }
}
// Check to see if VersionId property is set
internal bool IsSetVersionId()
{
return this.versionId != null;
}
/// <summary>
/// The date and time at which the object is no longer cacheable.
///
/// </summary>
public DateTime Expires
{
get
{
if (this.isExpiresUnmarshalled)
{
return this.expires.Value;
}
else
{
this.expires = AmazonS3Util.ParseExpiresHeader(this.RawExpires, this.ResponseMetadata.RequestId);
this.isExpiresUnmarshalled = true;
return this.expires.Value;
}
}
set { this.expires = value; this.isExpiresUnmarshalled = true; }
}
// Check to see if Expires property is set
internal bool IsSetExpires()
{
return this.expires.HasValue;
}
/// <summary>
/// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL.
/// Amazon S3 stores the value of this header in the object metadata.
///
/// </summary>
public string WebsiteRedirectLocation
{
get { return this.websiteRedirectLocation; }
set { this.websiteRedirectLocation = value; }
}
// Check to see if WebsiteRedirectLocation property is set
internal bool IsSetWebsiteRedirectLocation()
{
return this.websiteRedirectLocation != null;
}
/// <summary>
/// The Server-side encryption algorithm used when storing this object in S3.
///
/// </summary>
public ServerSideEncryptionMethod ServerSideEncryptionMethod
{
get
{
if (this.serverSideEncryption == null)
return ServerSideEncryptionMethod.None;
return this.serverSideEncryption;
}
set { this.serverSideEncryption = value; }
}
// Check to see if ServerSideEncryptionCustomerMethod property is set
internal bool IsSetServerSideEncryptionMethod()
{
return this.serverSideEncryptionCustomerMethod != null;
}
/// <summary>
/// The Server-side encryption algorithm to be used with the customer provided key.
///
/// </summary>
public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod
{
get
{
if (this.serverSideEncryptionCustomerMethod == null)
return ServerSideEncryptionCustomerMethod.None;
return this.serverSideEncryptionCustomerMethod;
}
set { this.serverSideEncryptionCustomerMethod = value; }
}
// Check to see if ServerSideEncryptionCustomerMethod property is set
internal bool IsSetServerSideEncryptionCustomerMethod()
{
return this.serverSideEncryptionCustomerMethod != null;
}
/// <summary>
/// The id of the AWS Key Management Service key that Amazon S3 uses to encrypt and decrypt the object.
/// </summary>
public string ServerSideEncryptionKeyManagementServiceKeyId
{
get { return this.serverSideEncryptionKeyManagementServiceKeyId; }
set { this.serverSideEncryptionKeyManagementServiceKeyId = value; }
}
/// <summary>
/// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set.
/// </summary>
/// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns>
internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId()
{
return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId);
}
/// <summary>
/// The status of the replication job associated with this source object.
/// </summary>
public ReplicationStatus ReplicationStatus
{
get { return this.replicationStatus; }
set { this.replicationStatus = value; }
}
/// <summary>
/// Checks if ReplicationStatus property is set.
/// </summary>
/// <returns>true if ReplicationStatus property is set.</returns>
internal bool IsSetReplicationStatus()
{
return ReplicationStatus != null;
}
/// <summary>
/// The class of storage used to store the object.
///
/// </summary>
public S3StorageClass StorageClass
{
get { return this.storageClass; }
set { this.storageClass = value; }
}
// Check to see if StorageClass property is set
internal bool IsSetStorageClass()
{
return this.storageClass != null;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.World.NPC
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NPCModule")]
public class NPCModule : INPCModule, ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, NPCAvatar> m_avatars =
new Dictionary<UUID, NPCAvatar>();
public bool Enabled { get; private set; }
public string Name
{
get { return "NPCModule"; }
}
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
if (Enabled)
scene.RegisterModuleInterface<INPCModule>(this);
}
public bool CheckPermissions(UUID npcID, UUID callerID)
{
lock (m_avatars)
{
NPCAvatar av;
if (m_avatars.TryGetValue(npcID, out av))
return CheckPermissions(av, callerID);
else
return false;
}
}
public void Close()
{
}
public UUID CreateNPC(string firstname, string lastname,
Vector3 position, UUID owner, bool senseAsAgent, Scene scene,
AvatarAppearance appearance)
{
return CreateNPC(firstname, lastname, position, UUID.Zero, owner, senseAsAgent, scene, appearance);
}
public UUID CreateNPC(string firstname, string lastname,
Vector3 position, UUID agentID, UUID owner, bool senseAsAgent, Scene scene,
AvatarAppearance appearance)
{
NPCAvatar npcAvatar = null;
try
{
if (agentID == UUID.Zero)
npcAvatar = new NPCAvatar(firstname, lastname, position,
owner, senseAsAgent, scene);
else
npcAvatar = new NPCAvatar(firstname, lastname, agentID, position,
owner, senseAsAgent, scene);
}
catch (Exception e)
{
m_log.Info("[NPC MODULE]: exception creating NPC avatar: " + e.ToString());
return UUID.Zero;
}
npcAvatar.CircuitCode = (uint)Util.RandomClass.Next(0,
int.MaxValue);
m_log.DebugFormat(
"[NPC MODULE]: Creating NPC {0} {1} {2}, owner={3}, senseAsAgent={4} at {5} in {6}",
firstname, lastname, npcAvatar.AgentId, owner,
senseAsAgent, position, scene.RegionInfo.RegionName);
AgentCircuitData acd = new AgentCircuitData();
acd.AgentID = npcAvatar.AgentId;
acd.firstname = firstname;
acd.lastname = lastname;
acd.ServiceURLs = new Dictionary<string, object>();
AvatarAppearance npcAppearance = new AvatarAppearance(appearance,
true);
acd.Appearance = npcAppearance;
/*
for (int i = 0;
i < acd.Appearance.Texture.FaceTextures.Length; i++)
{
m_log.DebugFormat(
"[NPC MODULE]: NPC avatar {0} has texture id {1} : {2}",
acd.AgentID, i,
acd.Appearance.Texture.FaceTextures[i]);
}
*/
lock (m_avatars)
{
scene.AuthenticateHandler.AddNewCircuit(npcAvatar.CircuitCode,
acd);
scene.AddNewAgent(npcAvatar, PresenceType.Npc);
ScenePresence sp;
if (scene.TryGetScenePresence(npcAvatar.AgentId, out sp))
{
/*
m_log.DebugFormat(
"[NPC MODULE]: Successfully retrieved scene presence for NPC {0} {1}",
sp.Name, sp.UUID);
*/
sp.CompleteMovement(npcAvatar, false);
m_avatars.Add(npcAvatar.AgentId, npcAvatar);
m_log.DebugFormat("[NPC MODULE]: Created NPC {0} {1}", npcAvatar.AgentId, sp.Name);
return npcAvatar.AgentId;
}
else
{
m_log.WarnFormat(
"[NPC MODULE]: Could not find scene presence for NPC {0} {1}",
sp.Name, sp.UUID);
return UUID.Zero;
}
}
}
public bool DeleteNPC(UUID agentID, Scene scene)
{
lock (m_avatars)
{
NPCAvatar av;
if (m_avatars.TryGetValue(agentID, out av))
{
/*
m_log.DebugFormat("[NPC MODULE]: Found {0} {1} to remove",
agentID, av.Name);
*/
scene.CloseAgent(agentID, false);
m_avatars.Remove(agentID);
/*
m_log.DebugFormat("[NPC MODULE]: Removed NPC {0} {1}",
agentID, av.Name);
*/
return true;
}
}
/*
m_log.DebugFormat("[NPC MODULE]: Could not find {0} to remove",
agentID);
*/
return false;
}
public INPC GetNPC(UUID agentID, Scene scene)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
return m_avatars[agentID];
else
return null;
}
}
public UUID GetOwner(UUID agentID)
{
lock (m_avatars)
{
NPCAvatar av;
if (m_avatars.TryGetValue(agentID, out av))
return av.OwnerID;
}
return UUID.Zero;
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["NPC"];
Enabled = (config != null && config.GetBoolean("Enabled", false));
}
public bool IsNPC(UUID agentId, Scene scene)
{
// FIXME: This implementation could not just use the
// ScenePresence.PresenceType (and callers could inspect that
// directly).
ScenePresence sp = scene.GetScenePresence(agentId);
if (sp == null || sp.IsChildAgent)
return false;
lock (m_avatars)
return m_avatars.ContainsKey(agentId);
}
public bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos,
bool noFly, bool landAtTarget, bool running)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
ScenePresence sp;
if (scene.TryGetScenePresence(agentID, out sp))
{
// m_log.DebugFormat(
// "[NPC MODULE]: Moving {0} to {1} in {2}, noFly {3}, landAtTarget {4}",
// sp.Name, pos, scene.RegionInfo.RegionName,
// noFly, landAtTarget);
sp.MoveToTarget(pos, noFly, landAtTarget);
sp.SetAlwaysRun = running;
return true;
}
}
}
return false;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<INPCModule>(this);
}
public bool Say(UUID agentID, Scene scene, string text)
{
return Say(agentID, scene, text, 0);
}
public bool Say(UUID agentID, Scene scene, string text, int channel)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
m_avatars[agentID].Say(channel, text);
return true;
}
}
return false;
}
public bool SetNPCAppearance(UUID agentId,
AvatarAppearance appearance, Scene scene)
{
ScenePresence npc = scene.GetScenePresence(agentId);
if (npc == null || npc.IsChildAgent)
return false;
lock (m_avatars)
if (!m_avatars.ContainsKey(agentId))
return false;
// Delete existing npc attachments
if (scene.AttachmentsModule != null)
scene.AttachmentsModule.DeleteAttachmentsFromScene(npc, false);
// XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet
// since it doesn't transfer attachments
AvatarAppearance npcAppearance = new AvatarAppearance(appearance,
true);
npc.Appearance = npcAppearance;
// Rez needed npc attachments
if (scene.AttachmentsModule != null)
scene.AttachmentsModule.RezAttachments(npc);
IAvatarFactoryModule module =
scene.RequestModuleInterface<IAvatarFactoryModule>();
module.SendAppearance(npc.UUID);
return true;
}
public bool Shout(UUID agentID, Scene scene, string text, int channel)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
m_avatars[agentID].Shout(channel, text);
return true;
}
}
return false;
}
public bool Sit(UUID agentID, UUID partID, Scene scene)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
ScenePresence sp;
if (scene.TryGetScenePresence(agentID, out sp))
{
sp.HandleAgentRequestSit(m_avatars[agentID], agentID, partID, Vector3.Zero);
return true;
}
}
}
return false;
}
public bool Stand(UUID agentID, Scene scene)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
ScenePresence sp;
if (scene.TryGetScenePresence(agentID, out sp))
{
sp.StandUp();
return true;
}
}
}
return false;
}
public bool StopMoveToTarget(UUID agentID, Scene scene)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
ScenePresence sp;
if (scene.TryGetScenePresence(agentID, out sp))
{
sp.Velocity = Vector3.Zero;
sp.ResetMoveToTarget();
return true;
}
}
}
return false;
}
public bool Touch(UUID agentID, UUID objectID)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
return m_avatars[agentID].Touch(objectID);
return false;
}
}
public bool Whisper(UUID agentID, Scene scene, string text,
int channel)
{
lock (m_avatars)
{
if (m_avatars.ContainsKey(agentID))
{
m_avatars[agentID].Whisper(channel, text);
return true;
}
}
return false;
}
/// <summary>
/// Check if the caller has permission to manipulate the given NPC.
/// </summary>
/// <param name="av"></param>
/// <param name="callerID"></param>
/// <returns>true if they do, false if they don't.</returns>
private bool CheckPermissions(NPCAvatar av, UUID callerID)
{
return callerID == UUID.Zero || av.OwnerID == UUID.Zero ||
av.OwnerID == callerID;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text; // StringBuilder
namespace System.Data.SqlClient
{
[Serializable]
public sealed class SqlException : System.Data.Common.DbException
{
private const string OriginalClientConnectionIdKey = "OriginalClientConnectionId";
private const string RoutingDestinationKey = "RoutingDestination";
private const int SqlExceptionHResult = unchecked((int)0x80131904);
private SqlErrorCollection _errors;
private Guid _clientConnectionId = Guid.Empty;
private SqlException(string message, SqlErrorCollection errorCollection, Exception innerException, Guid conId) : base(message, innerException)
{
HResult = SqlExceptionHResult;
_errors = errorCollection;
_clientConnectionId = conId;
}
private SqlException(SerializationInfo si, StreamingContext sc) : base(si, sc)
{
HResult = SqlExceptionHResult;
_errors = (SqlErrorCollection)si.GetValue("Errors", typeof(SqlErrorCollection));
_clientConnectionId = (Guid)si.GetValue("ClientConnectionId", typeof(Guid));
}
public override void GetObjectData(SerializationInfo si, StreamingContext context)
{
if (null == si)
{
throw new ArgumentNullException(nameof(si));
}
si.AddValue("Errors", _errors, typeof(SqlErrorCollection));
si.AddValue("ClientConnectionId", _clientConnectionId, typeof(Guid));
base.GetObjectData(si, context);
}
// runtime will call even if private...
public SqlErrorCollection Errors
{
get
{
if (_errors == null)
{
_errors = new SqlErrorCollection();
}
return _errors;
}
}
public Guid ClientConnectionId
{
get
{
return _clientConnectionId;
}
}
public byte Class
{
get { return this.Errors[0].Class; }
}
public int LineNumber
{
get { return this.Errors[0].LineNumber; }
}
public int Number
{
get { return this.Errors[0].Number; }
}
public string Procedure
{
get { return this.Errors[0].Procedure; }
}
public string Server
{
get { return this.Errors[0].Server; }
}
public byte State
{
get { return this.Errors[0].State; }
}
override public string Source
{
get { return this.Errors[0].Source; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(base.ToString());
sb.AppendLine();
sb.AppendFormat(SQLMessage.ExClientConnectionId(), _clientConnectionId);
// Append the error number, state and class if the server provided it
if (Number != 0)
{
sb.AppendLine();
sb.AppendFormat(SQLMessage.ExErrorNumberStateClass(), Number, State, Class);
}
// If routed, include the original client connection id
if (Data.Contains(OriginalClientConnectionIdKey))
{
sb.AppendLine();
sb.AppendFormat(SQLMessage.ExOriginalClientConnectionId(), Data[OriginalClientConnectionIdKey]);
}
// If routed, provide the routing destination
if (Data.Contains(RoutingDestinationKey))
{
sb.AppendLine();
sb.AppendFormat(SQLMessage.ExRoutingDestination(), Data[RoutingDestinationKey]);
}
return sb.ToString();
}
internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion)
{
return CreateException(errorCollection, serverVersion, Guid.Empty);
}
internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, SqlInternalConnectionTds internalConnection, Exception innerException = null)
{
Guid connectionId = (internalConnection == null) ? Guid.Empty : internalConnection._clientConnectionId;
var exception = CreateException(errorCollection, serverVersion, connectionId, innerException);
if (internalConnection != null)
{
if ((internalConnection.OriginalClientConnectionId != Guid.Empty) && (internalConnection.OriginalClientConnectionId != internalConnection.ClientConnectionId))
{
exception.Data.Add(OriginalClientConnectionIdKey, internalConnection.OriginalClientConnectionId);
}
if (!string.IsNullOrEmpty(internalConnection.RoutingDestination))
{
exception.Data.Add(RoutingDestinationKey, internalConnection.RoutingDestination);
}
}
return exception;
}
internal static SqlException CreateException(SqlErrorCollection errorCollection, string serverVersion, Guid conId, Exception innerException = null)
{
Debug.Assert(null != errorCollection && errorCollection.Count > 0, "no errorCollection?");
StringBuilder message = new StringBuilder();
for (int i = 0; i < errorCollection.Count; i++)
{
if (i > 0)
{
message.Append(Environment.NewLine);
}
message.Append(errorCollection[i].Message);
}
if (innerException == null && errorCollection[0].Win32ErrorCode != 0 && errorCollection[0].Win32ErrorCode != -1)
{
innerException = new Win32Exception(errorCollection[0].Win32ErrorCode);
}
SqlException exception = new SqlException(message.ToString(), errorCollection, innerException, conId);
exception.Data.Add("HelpLink.ProdName", "Microsoft SQL Server");
if (!string.IsNullOrEmpty(serverVersion))
{
exception.Data.Add("HelpLink.ProdVer", serverVersion);
}
exception.Data.Add("HelpLink.EvtSrc", "MSSQLServer");
exception.Data.Add("HelpLink.EvtID", errorCollection[0].Number.ToString(CultureInfo.InvariantCulture));
exception.Data.Add("HelpLink.BaseHelpUrl", "http://go.microsoft.com/fwlink");
exception.Data.Add("HelpLink.LinkId", "20476");
return exception;
}
internal SqlException InternalClone()
{
SqlException exception = new SqlException(Message, _errors, InnerException, _clientConnectionId);
if (this.Data != null)
foreach (DictionaryEntry entry in this.Data)
exception.Data.Add(entry.Key, entry.Value);
exception._doNotReconnect = this._doNotReconnect;
return exception;
}
// Do not serialize this field! It is used to indicate that no reconnection attempts are required
internal bool _doNotReconnect = false;
}
}
| |
using Android.Util;
using OpenCV.Core;
using OpenCV.ImgProc;
using OpenCV.SDKDemo.Utilities;
using System;
namespace OpenCV.SDKDemo.Puzzle
{
public class Puzzle15Processor
{
private const int GridSize = 4;
private const int GridArea = GridSize * GridSize;
private const int GridEmptyIndex = GridArea - 1;
private static readonly Scalar GridEmptyColor = new Scalar(0x33, 0x33, 0x33, 0xFF);
Random random = new Random();
private int[] _indexes;
private int[] _textWidths;
private int[] _textHeights;
private Mat _rgba15;
private Mat[] _cells15;
private bool _showTileNumbers = true;
private readonly object _lock = new object();
public Puzzle15Processor()
{
_textWidths = new int[GridArea];
_textHeights = new int[GridArea];
_indexes = new int[GridArea];
for (int i = 0; i < GridArea; i++)
{
_indexes[i] = i;
}
}
public void PrepareNewGame()
{
lock (_lock)
{
do
{
Shuffle(_indexes);
} while (!isPuzzleSolvable());
}
}
private void Shuffle(int[] array)
{
for (int i = array.Length; i > 1; i--)
{
int temp = array[i - 1];
int randIx = (int)(random.NextDouble() * i);
array[i - 1] = array[randIx];
array[randIx] = temp;
}
}
private bool isPuzzleSolvable()
{
int sum = 0;
for (int i = 0; i < GridArea; i++)
{
if (_indexes[i] == GridEmptyIndex)
sum += (i / GridSize) + 1;
else
{
int smaller = 0;
for (int j = i + 1; j < GridArea; j++)
{
if (_indexes[j] < _indexes[i])
smaller++;
}
sum += smaller;
}
}
return sum % 2 == 0;
}
private void DrawGrid(int cols, int rows, Mat drawMat)
{
for (int i = 1; i < GridSize; i++)
{
Imgproc.Line(drawMat, new Point(0, i * rows / GridSize), new Point(cols, i * rows / GridSize), new Scalar(0, 255, 0, 255), 3);
Imgproc.Line(drawMat, new Point(i * cols / GridSize, 0), new Point(i * cols / GridSize, rows), new Scalar(0, 255, 0, 255), 3);
}
}
internal void ToggleTileNumbers()
{
_showTileNumbers = !_showTileNumbers;
}
internal void PrepareGameSize(int width, int height)
{
lock (_lock)
{
_rgba15 = new Mat(height, width, CvType.Cv8uc4);
_cells15 = new Mat[GridArea];
for (int i = 0; i < GridSize; i++)
{
for (int j = 0; j < GridSize; j++)
{
int k = i * GridSize + j;
_cells15[k] = _rgba15.Submat(i * height / GridSize, (i + 1) * height / GridSize, j * width / GridSize, (j + 1) * width / GridSize);
}
}
for (int i = 0; i < GridArea; i++)
{
var s = Imgproc.GetTextSize((i + 1).ToString(), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, 2, null);
_textHeights[i] = (int)s.Height;
_textWidths[i] = (int)s.Width;
}
}
}
internal Mat PuzzleFrame(Mat inputPicture)
{
lock (_lock)
{
Mat[] cells = new Mat[GridArea];
int rows = inputPicture.Rows();
int cols = inputPicture.Cols();
rows = rows - rows % 4;
cols = cols - cols % 4;
for (int i = 0; i < GridSize; i++)
{
for (int j = 0; j < GridSize; j++)
{
int k = i * GridSize + j;
cells[k] = inputPicture.Submat(i * inputPicture.Rows() / GridSize,
(i + 1) * inputPicture.Rows() / GridSize, j * inputPicture.Cols() / GridSize,
(j + 1) * inputPicture.Cols() / GridSize);
}
}
rows = rows - rows % 4;
cols = cols - cols % 4;
// copy shuffled tiles
for (int i = 0; i < GridArea; i++)
{
int idx = _indexes[i];
if (idx == GridEmptyIndex)
_cells15[i].SetTo(GridEmptyColor);
else
{
cells[idx].CopyTo(_cells15[i]);
if (_showTileNumbers)
{
Imgproc.PutText(_cells15[i], (1 + idx).ToString(), new Point((cols / GridSize - _textWidths[idx]) / 2,
(rows / GridSize + _textHeights[idx]) / 2), 3/* CV_FONT_HERSHEY_COMPLEX */, 1, new Scalar(255, 0, 0, 255), 2);
}
}
}
for (int i = 0; i < GridArea; i++)
cells[i].Release();
DrawGrid(cols, rows, _rgba15);
return _rgba15;
}
}
internal void DeliverTouchEvent(int x, int y)
{
int rows = _rgba15.Rows();
int cols = _rgba15.Cols();
int row = (int)Math.Floor((double)(y * GridSize / rows));
int col = (int)Math.Floor((double)(x * GridSize / cols));
if (row < 0 || row >= GridSize || col < 0 || col >= GridSize)
{
Log.Error(ActivityTags.Puzzle, "It is not expected to get touch event outside of picture");
return;
}
int idx = row * GridSize + col;
int idxtoswap = -1;
// left
if (idxtoswap < 0 && col > 0)
if (_indexes[idx - 1] == GridEmptyIndex)
idxtoswap = idx - 1;
// right
if (idxtoswap < 0 && col < GridSize - 1)
if (_indexes[idx + 1] == GridEmptyIndex)
idxtoswap = idx + 1;
// top
if (idxtoswap < 0 && row > 0)
if (_indexes[idx - GridSize] == GridEmptyIndex)
idxtoswap = idx - GridSize;
// bottom
if (idxtoswap < 0 && row < GridSize - 1)
if (_indexes[idx + GridSize] == GridEmptyIndex)
idxtoswap = idx + GridSize;
// swap
if (idxtoswap >= 0)
{
lock (_lock)
{
int touched = _indexes[idx];
_indexes[idx] = _indexes[idxtoswap];
_indexes[idxtoswap] = touched;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
using Xunit;
namespace System.IO
{
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))]
public class AsWinRTStreamTests
{
[Fact]
public static void AsInputStream_FromReadOnlyStream()
{
Stream managedStream = TestStreamProvider.CreateReadOnlyStream();
using (IInputStream ins = managedStream.AsInputStream())
{
Assert.NotNull(ins);
// Adapting a read-only managed Stream to IOutputStream must throw a NotSupportedException
Assert.Throws<NotSupportedException>(() => { IOutputStream outs = managedStream.AsOutputStream(); });
}
}
[Fact]
public static void AsOutputStream_FromWriteOnlyStream()
{
Stream managedStream = TestStreamProvider.CreateWriteOnlyStream();
using (IOutputStream outs = managedStream.AsOutputStream())
{
Assert.NotNull(outs);
// Adapting a write-only managed Stream to IInputStream must throw a NotSupportedException
Assert.Throws<NotSupportedException>(() => { IInputStream ins = managedStream.AsInputStream(); });
}
}
[Fact]
public static void AsInputStream_WrapsToSameInstance()
{
Stream managedStream = TestStreamProvider.CreateReadOnlyStream();
using (IInputStream ins = managedStream.AsInputStream())
{
Assert.NotNull(ins);
Assert.Same(ins, managedStream.AsInputStream());
}
}
[Fact]
public static void AsOutputStream_WrapsToSameInstance()
{
Stream managedStream = TestStreamProvider.CreateWriteOnlyStream();
using (IOutputStream outs = managedStream.AsOutputStream())
{
Assert.NotNull(outs);
Assert.Same(outs, managedStream.AsOutputStream());
}
}
[Fact]
public static void AsInputStream_RoundtripUnwrap()
{
// NetFx Stream -> IInputStream -> NetFx Stream -> roundtrip reference equality is preserved
Stream managedStream = TestStreamProvider.CreateReadOnlyStream();
using (IInputStream ins = managedStream.AsInputStream())
{
Assert.Same(managedStream, ins.AsStreamForRead());
}
}
[Fact]
public static void AsOutputStream_RoundtripUnwrap()
{
// NetFx Stream -> IOutputStream -> NetFx Stream -> roundtrip reference equality is preserved
Stream managedStream = TestStreamProvider.CreateWriteOnlyStream();
using (IOutputStream outs = managedStream.AsOutputStream())
{
Assert.Same(managedStream, outs.AsStreamForWrite());
}
}
[Fact]
public static void AsInputStream_Equal()
{
Stream stream = TestStreamProvider.CreateReadOnlyStream();
using (IInputStream insOne = stream.AsInputStream())
using (IInputStream insTwo = stream.AsInputStream())
{
Assert.Equal(insOne, insTwo);
}
}
[Fact]
public static void AsInputStream_NotEqual()
{
Stream streamOne = TestStreamProvider.CreateReadOnlyStream();
Stream streamTwo = TestStreamProvider.CreateReadOnlyStream();
Assert.NotEqual(streamOne, streamTwo);
using (IInputStream insOne = streamOne.AsInputStream())
using (IInputStream insTwo = streamTwo.AsInputStream())
{
Assert.NotEqual(insOne, insTwo);
}
}
[Fact]
public static void AsOutputStream_Equal()
{
Stream stream = TestStreamProvider.CreateWriteOnlyStream();
using (IOutputStream outsOne = stream.AsOutputStream())
using (IOutputStream outsTwo = stream.AsOutputStream())
{
Assert.Equal(outsOne, outsOne);
}
}
[Fact]
public static void AsOutputStream_NotEqual()
{
Stream streamOne = TestStreamProvider.CreateWriteOnlyStream();
Stream streamTwo = TestStreamProvider.CreateWriteOnlyStream();
Assert.NotEqual(streamOne, streamTwo);
using (IOutputStream outsOne = streamOne.AsOutputStream())
using (IOutputStream outsTwo = streamTwo.AsOutputStream())
{
Assert.NotEqual(outsOne, outsTwo);
}
}
[Fact]
public static void TestRead_MemoryStream_None()
{
DoTestRead(TestStreamProvider.CreateMemoryStreamAsInputStream, InputStreamOptions.None, mustInvokeProgressHandler: false, completesSynchronously: true);
}
[Fact]
public static void TestRead_MemoryStream_Partial()
{
DoTestRead(TestStreamProvider.CreateMemoryStreamAsInputStream, InputStreamOptions.Partial, mustInvokeProgressHandler: false, completesSynchronously: true);
}
[Fact]
public static void TestWrite_MemoryStream()
{
DoTestWrite(TestStreamProvider.CreateMemoryStream, mustInvokeProgressHandler: false);
}
private static void DoTestRead(Func<IInputStream> createStreamFunc, InputStreamOptions inputStreamOptions, bool mustInvokeProgressHandler, bool completesSynchronously)
{
IInputStream stream = createStreamFunc();
IBuffer buffer = WindowsRuntimeBuffer.Create(TestStreamProvider.ModelStreamLength);
IAsyncOperationWithProgress<IBuffer, uint> readOp = stream.ReadAsync(buffer, (uint)TestStreamProvider.ModelStreamLength, inputStreamOptions);
if (completesSynchronously)
{
// New readOp for a stream where we know that reading is sycnhronous must have Status = Completed
Assert.Equal(AsyncStatus.Completed, readOp.Status);
}
else
{
// Note the race. By the tie we get here, the status of the op may be started or already completed.
AsyncStatus readOpStatus = readOp.Status;
Assert.True(readOpStatus == AsyncStatus.Completed || readOpStatus == AsyncStatus.Started, "New readOp must have Status = Started or Completed (race)");
}
bool progressCallbackInvoked = false;
bool completedCallbackInvoked = false;
uint readOpId = readOp.Id;
EventWaitHandle waitHandle = new ManualResetEvent(false);
readOp.Progress = (asyncReadOp, bytesCompleted) =>
{
progressCallbackInvoked = true;
// asyncReadOp.Id in a progress callback must match the ID of the asyncReadOp to which the callback was assigned
Assert.Equal(readOpId, asyncReadOp.Id);
// asyncReadOp.Status must be 'Started' for an asyncReadOp in progress
Assert.Equal(AsyncStatus.Started, asyncReadOp.Status);
// bytesCompleted must be in range [0, maxBytesToRead] asyncReadOp in progress
Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength);
};
readOp.Completed = (asyncReadOp, passedStatus) =>
{
try
{
completedCallbackInvoked = true;
// asyncReadOp.Id in a completion callback must match the ID of the asyncReadOp to which the callback was assigned
Assert.Equal(readOpId, asyncReadOp.Id);
// asyncReadOp.Status must match passedStatus for a completed asyncReadOp
Assert.Equal(passedStatus, asyncReadOp.Status);
// asyncReadOp.Status must be 'Completed' for a completed asyncReadOp
Assert.Equal(AsyncStatus.Completed, asyncReadOp.Status);
IBuffer resultBuffer = asyncReadOp.GetResults();
// asyncReadOp.GetResults() must not return null for a completed asyncReadOp
Assert.NotNull(resultBuffer);
AssertExtensions.GreaterThan(resultBuffer.Capacity, 0u, "resultBuffer.Capacity should be more than zero in completed callback");
AssertExtensions.GreaterThan(resultBuffer.Length, 0u, "resultBuffer.Length should be more than zero in completed callback");
AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, resultBuffer.Capacity, "resultBuffer.Length should be <= Capacity in completed callback");
if (inputStreamOptions == InputStreamOptions.None)
{
// resultBuffer.Length must be equal to requested number of bytes when an asyncReadOp with
// InputStreamOptions.None completes successfully
Assert.Equal(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength);
}
if (inputStreamOptions == InputStreamOptions.Partial)
{
AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength,
"resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial in completed callback");
}
buffer = resultBuffer;
}
finally
{
waitHandle.Set();
}
};
// Now, let's block until the read op is complete.
// We speculate that it will complete within 3500 msec, although under high load it may not be.
// If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow.
waitHandle.WaitOne(500);
waitHandle.WaitOne(1000);
waitHandle.WaitOne(2000);
if (mustInvokeProgressHandler)
{
Assert.True(progressCallbackInvoked,
"Progress callback specified to ReadAsync callback must be invoked when reading from this kind of stream");
}
Assert.True(completedCallbackInvoked,
"Completion callback specified to ReadAsync callback must be invoked");
// readOp.Status must be 'Completed' for a completed async readOp
Assert.Equal(AsyncStatus.Completed, readOp.Status);
AssertExtensions.GreaterThan(buffer.Capacity, 0u, "buffer.Capacity should be greater than zero bytes");
AssertExtensions.GreaterThan(buffer.Length, 0u, "buffer.Length should be greater than zero bytes");
AssertExtensions.LessThanOrEqualTo(buffer.Length, buffer.Capacity, "buffer.Length <= buffer.Capacity is required for a completed async readOp");
if (inputStreamOptions == InputStreamOptions.None)
{
// buffer.Length must be equal to requested number of bytes when an async readOp with
// InputStreamOptions.None completes successfully
Assert.Equal((uint)TestStreamProvider.ModelStreamLength, buffer.Length);
}
if (inputStreamOptions == InputStreamOptions.Partial)
{
AssertExtensions.LessThanOrEqualTo(buffer.Length, (uint)TestStreamProvider.ModelStreamLength,
"resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial");
}
byte[] results = new byte[buffer.Length];
buffer.CopyTo(0, results, 0, (int)buffer.Length);
Assert.True(TestStreamProvider.CheckContent(results, 0, (int)buffer.Length),
"Result data returned from AsyncRead must be the same as expected from the test data source");
}
private static void DoTestWrite(Func<Stream> createStreamFunc, bool mustInvokeProgressHandler)
{
Stream backingStream = createStreamFunc();
using (IOutputStream stream = backingStream.AsOutputStream())
{
// Create test data
Random rnd = new Random(20100720); // Must be a different seed than used for TestStreamProvider.ModelStreamContents
byte[] modelWriteData = new byte[0xA000];
rnd.NextBytes(modelWriteData);
// Start test
IBuffer buffer = modelWriteData.AsBuffer();
// ibuffer.Length for IBuffer created by Array.ToBuffer(void) must equal to array.Length
Assert.Equal((uint)modelWriteData.Length, buffer.Length);
// ibuffer.Capacity for IBuffer created by Array.ToBuffer(void) must equal to array.Length
Assert.Equal((uint)modelWriteData.Length, buffer.Capacity);
IAsyncOperationWithProgress<uint, uint> writeOp = stream.WriteAsync(buffer);
// Note the race. By the tie we get here, the status of the op may be started or already completed.
AsyncStatus writeOpStatus = writeOp.Status;
Assert.True(writeOpStatus == AsyncStatus.Completed || writeOpStatus == AsyncStatus.Started, "New writeOp must have Status = Started or Completed (race)");
uint writeOpId = writeOp.Id;
bool progressCallbackInvoked = false;
bool completedCallbackInvoked = false;
uint resultBytesWritten = 0;
EventWaitHandle waitHandle = new ManualResetEvent(false);
writeOp.Progress = (asyncWriteOp, bytesCompleted) =>
{
progressCallbackInvoked = true;
// asyncWriteOp.Id in a progress callback must match the ID of the asyncWriteOp to which the callback was assigned
Assert.Equal(writeOpId, asyncWriteOp.Id);
// asyncWriteOp.Status must be 'Started' for an asyncWriteOp in progress
Assert.Equal(AsyncStatus.Started, asyncWriteOp.Status);
// bytesCompleted must be in range [0, maxBytesToWrite] asyncWriteOp in progress
Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength);
};
writeOp.Completed = (asyncWriteOp, passedStatus) =>
{
try
{
completedCallbackInvoked = true;
// asyncWriteOp.Id in a completion callback must match the ID of the asyncWriteOp to which the callback was assigned
Assert.Equal(writeOpId, asyncWriteOp.Id);
// asyncWriteOp.Status must match passedStatus for a completed asyncWriteOp
Assert.Equal(passedStatus, asyncWriteOp.Status);
// asyncWriteOp.Status must be 'Completed' for a completed asyncWriteOp
Assert.Equal(AsyncStatus.Completed, asyncWriteOp.Status);
uint bytesWritten = asyncWriteOp.GetResults();
// asyncWriteOp.GetResults() must return that all required bytes were written for a completed asyncWriteOp
Assert.Equal((uint)modelWriteData.Length, bytesWritten);
resultBytesWritten = bytesWritten;
}
finally
{
waitHandle.Set();
}
};
// Now, let's block until the write op is complete.
// We speculate that it will complete within 3500 msec, although under high load it may not be.
// If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow.
waitHandle.WaitOne(500);
waitHandle.WaitOne(1000);
waitHandle.WaitOne(2000);
if (mustInvokeProgressHandler)
{
Assert.True(progressCallbackInvoked,
"Progress callback specified to WriteAsync callback must be invoked when reading from this kind of stream");
}
Assert.True(completedCallbackInvoked, "Completion callback specified to WriteAsync callback must be invoked");
// writeOp.Status must be 'Completed' for a completed async writeOp
Assert.Equal(AsyncStatus.Completed, writeOp.Status);
// writeOp.GetResults() must return that all required bytes were written for a completed async writeOp
Assert.Equal((uint)modelWriteData.Length, resultBytesWritten);
// Check contents
backingStream.Seek(0, SeekOrigin.Begin);
byte[] verifyBuff = new byte[modelWriteData.Length + 1024];
int r = backingStream.Read(verifyBuff, 0, verifyBuff.Length);
for (int i = 0; i < modelWriteData.Length; i++)
{
Assert.Equal(modelWriteData[i], verifyBuff[i]);
}
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.GradientStopCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media
{
sealed public partial class GradientStopCollection : System.Windows.Media.Animation.Animatable, IFormattable, System.Collections.IList, System.Collections.ICollection, IList<GradientStop>, ICollection<GradientStop>, IEnumerable<GradientStop>, System.Collections.IEnumerable
{
#region Methods and constructors
public void Add(GradientStop value)
{
}
public void Clear()
{
}
public GradientStopCollection Clone()
{
return default(GradientStopCollection);
}
protected override void CloneCore(System.Windows.Freezable source)
{
}
public GradientStopCollection CloneCurrentValue()
{
return default(GradientStopCollection);
}
protected override void CloneCurrentValueCore(System.Windows.Freezable source)
{
}
public bool Contains(GradientStop value)
{
return default(bool);
}
public void CopyTo(GradientStop[] array, int index)
{
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable source)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source)
{
}
public GradientStopCollection.Enumerator GetEnumerator()
{
return default(GradientStopCollection.Enumerator);
}
public GradientStopCollection()
{
}
public GradientStopCollection(int capacity)
{
}
public GradientStopCollection(IEnumerable<GradientStop> collection)
{
}
public int IndexOf(GradientStop value)
{
return default(int);
}
public void Insert(int index, GradientStop value)
{
}
public static GradientStopCollection Parse(string source)
{
return default(GradientStopCollection);
}
public bool Remove(GradientStop value)
{
return default(bool);
}
public void RemoveAt(int index)
{
}
IEnumerator<GradientStop> System.Collections.Generic.IEnumerable<System.Windows.Media.GradientStop>.GetEnumerator()
{
return default(IEnumerator<GradientStop>);
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
int System.Collections.IList.Add(Object value)
{
return default(int);
}
bool System.Collections.IList.Contains(Object value)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object value)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object value)
{
}
void System.Collections.IList.Remove(Object value)
{
}
string System.IFormattable.ToString(string format, IFormatProvider provider)
{
return default(string);
}
public string ToString(IFormatProvider provider)
{
return default(string);
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public GradientStop this [int index]
{
get
{
return default(GradientStop);
}
set
{
}
}
bool System.Collections.Generic.ICollection<System.Windows.Media.GradientStop>.IsReadOnly
{
get
{
return default(bool);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IList.IsFixedSize
{
get
{
return default(bool);
}
}
bool System.Collections.IList.IsReadOnly
{
get
{
return default(bool);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocols.Entities;
using Thrift.Transports;
namespace Thrift.Protocols
{
//TODO: implementation of TProtocol
// ReSharper disable once InconsistentNaming
public class TCompactProtocol : TProtocol
{
private const byte ProtocolId = 0x82;
private const byte Version = 1;
private const byte VersionMask = 0x1f; // 0001 1111
private const byte TypeMask = 0xE0; // 1110 0000
private const byte TypeBits = 0x07; // 0000 0111
private const int TypeShiftAmount = 5;
private static readonly TStruct AnonymousStruct = new TStruct(string.Empty);
private static readonly TField Tstop = new TField(string.Empty, TType.Stop, 0);
// ReSharper disable once InconsistentNaming
private static readonly byte[] TTypeToCompactType = new byte[16];
/// <summary>
/// Used to keep track of the last field for the current and previous structs, so we can do the delta stuff.
/// </summary>
private readonly Stack<short> _lastField = new Stack<short>(15);
/// <summary>
/// If we encounter a boolean field begin, save the TField here so it can have the value incorporated.
/// </summary>
private TField? _booleanField;
/// <summary>
/// If we Read a field header, and it's a boolean field, save the boolean value here so that ReadBool can use it.
/// </summary>
private bool? _boolValue;
private short _lastFieldId;
public TCompactProtocol(TClientTransport trans)
: base(trans)
{
TTypeToCompactType[(int) TType.Stop] = Types.Stop;
TTypeToCompactType[(int) TType.Bool] = Types.BooleanTrue;
TTypeToCompactType[(int) TType.Byte] = Types.Byte;
TTypeToCompactType[(int) TType.I16] = Types.I16;
TTypeToCompactType[(int) TType.I32] = Types.I32;
TTypeToCompactType[(int) TType.I64] = Types.I64;
TTypeToCompactType[(int) TType.Double] = Types.Double;
TTypeToCompactType[(int) TType.String] = Types.Binary;
TTypeToCompactType[(int) TType.List] = Types.List;
TTypeToCompactType[(int) TType.Set] = Types.Set;
TTypeToCompactType[(int) TType.Map] = Types.Map;
TTypeToCompactType[(int) TType.Struct] = Types.Struct;
}
public void Reset()
{
_lastField.Clear();
_lastFieldId = 0;
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await Trans.WriteAsync(new[] {ProtocolId}, cancellationToken);
await
Trans.WriteAsync(
new[] {(byte) ((Version & VersionMask) | (((uint) message.Type << TypeShiftAmount) & TypeMask))},
cancellationToken);
var bufferTuple = CreateWriteVarInt32((uint) message.SeqID);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
await WriteStringAsync(message.Name, cancellationToken);
}
public override async Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
/// <summary>
/// Write a struct begin. This doesn't actually put anything on the wire. We
/// use it as an opportunity to put special placeholder markers on the field
/// stack so we can get the field id deltas correct.
/// </summary>
public override async Task WriteStructBeginAsync(TStruct struc, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
_lastField.Push(_lastFieldId);
_lastFieldId = 0;
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
_lastFieldId = _lastField.Pop();
}
private async Task WriteFieldBeginInternalAsync(TField field, byte typeOverride,
CancellationToken cancellationToken)
{
// if there's a exType override, use that.
var typeToWrite = typeOverride == 0xFF ? GetCompactType(field.Type) : typeOverride;
// check if we can use delta encoding for the field id
if ((field.ID > _lastFieldId) && (field.ID - _lastFieldId <= 15))
{
var b = (byte) (((field.ID - _lastFieldId) << 4) | typeToWrite);
// Write them together
await Trans.WriteAsync(new[] {b}, cancellationToken);
}
else
{
// Write them separate
await Trans.WriteAsync(new[] {typeToWrite}, cancellationToken);
await WriteI16Async(field.ID, cancellationToken);
}
_lastFieldId = field.ID;
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
if (field.Type == TType.Bool)
{
_booleanField = field;
}
else
{
await WriteFieldBeginInternalAsync(field, 0xFF, cancellationToken);
}
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await Trans.WriteAsync(new[] {Types.Stop}, cancellationToken);
}
protected async Task WriteCollectionBeginAsync(TType elemType, int size, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
/*
Abstract method for writing the start of lists and sets. List and sets on
the wire differ only by the exType indicator.
*/
if (size <= 14)
{
await Trans.WriteAsync(new[] {(byte) ((size << 4) | GetCompactType(elemType))}, cancellationToken);
}
else
{
await Trans.WriteAsync(new[] {(byte) (0xf0 | GetCompactType(elemType))}, cancellationToken);
var bufferTuple = CreateWriteVarInt32((uint) size);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
}
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
await WriteCollectionBeginAsync(list.ElementType, list.Count, cancellationToken);
}
public override async Task WriteListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteCollectionBeginAsync(set.ElementType, set.Count, cancellationToken);
}
public override async Task WriteSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
/*
Write a boolean value. Potentially, this could be a boolean field, in
which case the field header info isn't written yet. If so, decide what the
right exType header is for the value and then Write the field header.
Otherwise, Write a single byte.
*/
if (_booleanField != null)
{
// we haven't written the field header yet
await
WriteFieldBeginInternalAsync(_booleanField.Value, b ? Types.BooleanTrue : Types.BooleanFalse,
cancellationToken);
_booleanField = null;
}
else
{
// we're not part of a field, so just Write the value.
await Trans.WriteAsync(new[] {b ? Types.BooleanTrue : Types.BooleanFalse}, cancellationToken);
}
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await Trans.WriteAsync(new[] {(byte) b}, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bufferTuple = CreateWriteVarInt32(IntToZigzag(i16));
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
}
protected internal Tuple<byte[], int> CreateWriteVarInt32(uint n)
{
// Write an i32 as a varint.Results in 1 - 5 bytes on the wire.
var i32Buf = new byte[5];
var idx = 0;
while (true)
{
if ((n & ~0x7F) == 0)
{
i32Buf[idx++] = (byte) n;
break;
}
i32Buf[idx++] = (byte) ((n & 0x7F) | 0x80);
n >>= 7;
}
return new Tuple<byte[], int>(i32Buf, idx);
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bufferTuple = CreateWriteVarInt32(IntToZigzag(i32));
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
}
protected internal Tuple<byte[], int> CreateWriteVarInt64(ulong n)
{
// Write an i64 as a varint. Results in 1-10 bytes on the wire.
var buf = new byte[10];
var idx = 0;
while (true)
{
if ((n & ~(ulong) 0x7FL) == 0)
{
buf[idx++] = (byte) n;
break;
}
buf[idx++] = (byte) ((n & 0x7F) | 0x80);
n >>= 7;
}
return new Tuple<byte[], int>(buf, idx);
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bufferTuple = CreateWriteVarInt64(LongToZigzag(i64));
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var data = new byte[8];
FixedLongToBytes(BitConverter.DoubleToInt64Bits(d), data, 0);
await Trans.WriteAsync(data, cancellationToken);
}
public override async Task WriteStringAsync(string str, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bytes = Encoding.UTF8.GetBytes(str);
var bufferTuple = CreateWriteVarInt32((uint) bytes.Length);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bufferTuple = CreateWriteVarInt32((uint) b.Length);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
await Trans.WriteAsync(b, 0, b.Length, cancellationToken);
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (map.Count == 0)
{
await Trans.WriteAsync(new[] {(byte) 0}, cancellationToken);
}
else
{
var bufferTuple = CreateWriteVarInt32((uint) map.Count);
await Trans.WriteAsync(bufferTuple.Item1, 0, bufferTuple.Item2, cancellationToken);
await
Trans.WriteAsync(
new[] {(byte) ((GetCompactType(map.KeyType) << 4) | GetCompactType(map.ValueType))},
cancellationToken);
}
}
public override async Task WriteMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TMessage>(cancellationToken);
}
var protocolId = (byte) await ReadByteAsync(cancellationToken);
if (protocolId != ProtocolId)
{
throw new TProtocolException($"Expected protocol id {ProtocolId:X} but got {protocolId:X}");
}
var versionAndType = (byte) await ReadByteAsync(cancellationToken);
var version = (byte) (versionAndType & VersionMask);
if (version != Version)
{
throw new TProtocolException($"Expected version {Version} but got {version}");
}
var type = (byte) ((versionAndType >> TypeShiftAmount) & TypeBits);
var seqid = (int) await ReadVarInt32Async(cancellationToken);
var messageName = await ReadStringAsync(cancellationToken);
return new TMessage(messageName, (TMessageType) type, seqid);
}
public override async Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TStruct>(cancellationToken);
}
// some magic is here )
_lastField.Push(_lastFieldId);
_lastFieldId = 0;
return AnonymousStruct;
}
public override async Task ReadStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
/*
Doesn't actually consume any wire data, just removes the last field for
this struct from the field stack.
*/
// consume the last field we Read off the wire.
_lastFieldId = _lastField.Pop();
}
public override async Task<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
// Read a field header off the wire.
var type = (byte) await ReadByteAsync(cancellationToken);
// if it's a stop, then we can return immediately, as the struct is over.
if (type == Types.Stop)
{
return Tstop;
}
short fieldId;
// mask off the 4 MSB of the exType header. it could contain a field id delta.
var modifier = (short) ((type & 0xf0) >> 4);
if (modifier == 0)
{
fieldId = await ReadI16Async(cancellationToken);
}
else
{
fieldId = (short) (_lastFieldId + modifier);
}
var field = new TField(string.Empty, GetTType((byte) (type & 0x0f)), fieldId);
// if this happens to be a boolean field, the value is encoded in the exType
if (IsBoolType(type))
{
_boolValue = (byte) (type & 0x0f) == Types.BooleanTrue;
}
// push the new field onto the field stack so we can keep the deltas going.
_lastFieldId = field.ID;
return field;
}
public override async Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<TMap>(cancellationToken);
}
/*
Read a map header off the wire. If the size is zero, skip Reading the key
and value exType. This means that 0-length maps will yield TMaps without the
"correct" types.
*/
var size = (int) await ReadVarInt32Async(cancellationToken);
var keyAndValueType = size == 0 ? (byte) 0 : (byte) await ReadByteAsync(cancellationToken);
return new TMap(GetTType((byte) (keyAndValueType >> 4)), GetTType((byte) (keyAndValueType & 0xf)), size);
}
public override async Task ReadMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
/*
Read a set header off the wire. If the set size is 0-14, the size will
be packed into the element exType header. If it's a longer set, the 4 MSB
of the element exType header will be 0xF, and a varint will follow with the
true size.
*/
return new TSet(await ReadListBeginAsync(cancellationToken));
}
public override async Task<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<bool>(cancellationToken);
}
/*
Read a boolean off the wire. If this is a boolean field, the value should
already have been Read during ReadFieldBegin, so we'll just consume the
pre-stored value. Otherwise, Read a byte.
*/
if (_boolValue != null)
{
var result = _boolValue.Value;
_boolValue = null;
return result;
}
return await ReadByteAsync(cancellationToken) == Types.BooleanTrue;
}
public override async Task<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<sbyte>(cancellationToken);
}
// Read a single byte off the wire. Nothing interesting here.
var buf = new byte[1];
await Trans.ReadAllAsync(buf, 0, 1, cancellationToken);
return (sbyte) buf[0];
}
public override async Task<short> ReadI16Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<short>(cancellationToken);
}
return (short) ZigzagToInt(await ReadVarInt32Async(cancellationToken));
}
public override async Task<int> ReadI32Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<int>(cancellationToken);
}
return ZigzagToInt(await ReadVarInt32Async(cancellationToken));
}
public override async Task<long> ReadI64Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<long>(cancellationToken);
}
return ZigzagToLong(await ReadVarInt64Async(cancellationToken));
}
public override async Task<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<double>(cancellationToken);
}
var longBits = new byte[8];
await Trans.ReadAllAsync(longBits, 0, 8, cancellationToken);
return BitConverter.Int64BitsToDouble(BytesToLong(longBits));
}
public override async Task<string> ReadStringAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<string>(cancellationToken);
}
// Reads a byte[] (via ReadBinary), and then UTF-8 decodes it.
var length = (int) await ReadVarInt32Async(cancellationToken);
if (length == 0)
{
return string.Empty;
}
var buf = new byte[length];
await Trans.ReadAllAsync(buf, 0, length, cancellationToken);
return Encoding.UTF8.GetString(buf);
}
public override async Task<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<byte[]>(cancellationToken);
}
// Read a byte[] from the wire.
var length = (int) await ReadVarInt32Async(cancellationToken);
if (length == 0)
{
return new byte[0];
}
var buf = new byte[length];
await Trans.ReadAllAsync(buf, 0, length, cancellationToken);
return buf;
}
public override async Task<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<TList>(cancellationToken);
}
/*
Read a list header off the wire. If the list size is 0-14, the size will
be packed into the element exType header. If it's a longer list, the 4 MSB
of the element exType header will be 0xF, and a varint will follow with the
true size.
*/
var sizeAndType = (byte) await ReadByteAsync(cancellationToken);
var size = (sizeAndType >> 4) & 0x0f;
if (size == 15)
{
size = (int) await ReadVarInt32Async(cancellationToken);
}
var type = GetTType(sizeAndType);
return new TList(type, size);
}
public override async Task ReadListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task ReadSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
private static byte GetCompactType(TType ttype)
{
// Given a TType value, find the appropriate TCompactProtocol.Types constant.
return TTypeToCompactType[(int) ttype];
}
private async Task<uint> ReadVarInt32Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<uint>(cancellationToken);
}
/*
Read an i32 from the wire as a varint. The MSB of each byte is set
if there is another byte to follow. This can Read up to 5 bytes.
*/
uint result = 0;
var shift = 0;
while (true)
{
var b = (byte) await ReadByteAsync(cancellationToken);
result |= (uint) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80)
{
break;
}
shift += 7;
}
return result;
}
private async Task<ulong> ReadVarInt64Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<uint>(cancellationToken);
}
/*
Read an i64 from the wire as a proper varint. The MSB of each byte is set
if there is another byte to follow. This can Read up to 10 bytes.
*/
var shift = 0;
ulong result = 0;
while (true)
{
var b = (byte) await ReadByteAsync(cancellationToken);
result |= (ulong) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80)
{
break;
}
shift += 7;
}
return result;
}
private static int ZigzagToInt(uint n)
{
return (int) (n >> 1) ^ -(int) (n & 1);
}
private static long ZigzagToLong(ulong n)
{
return (long) (n >> 1) ^ -(long) (n & 1);
}
private static long BytesToLong(byte[] bytes)
{
/*
Note that it's important that the mask bytes are long literals,
otherwise they'll default to ints, and when you shift an int left 56 bits,
you just get a messed up int.
*/
return
((bytes[7] & 0xffL) << 56) |
((bytes[6] & 0xffL) << 48) |
((bytes[5] & 0xffL) << 40) |
((bytes[4] & 0xffL) << 32) |
((bytes[3] & 0xffL) << 24) |
((bytes[2] & 0xffL) << 16) |
((bytes[1] & 0xffL) << 8) |
(bytes[0] & 0xffL);
}
private static bool IsBoolType(byte b)
{
var lowerNibble = b & 0x0f;
return (lowerNibble == Types.BooleanTrue) || (lowerNibble == Types.BooleanFalse);
}
private static TType GetTType(byte type)
{
// Given a TCompactProtocol.Types constant, convert it to its corresponding TType value.
switch ((byte) (type & 0x0f))
{
case Types.Stop:
return TType.Stop;
case Types.BooleanFalse:
case Types.BooleanTrue:
return TType.Bool;
case Types.Byte:
return TType.Byte;
case Types.I16:
return TType.I16;
case Types.I32:
return TType.I32;
case Types.I64:
return TType.I64;
case Types.Double:
return TType.Double;
case Types.Binary:
return TType.String;
case Types.List:
return TType.List;
case Types.Set:
return TType.Set;
case Types.Map:
return TType.Map;
case Types.Struct:
return TType.Struct;
default:
throw new TProtocolException($"Don't know what exType: {(byte) (type & 0x0f)}");
}
}
private static ulong LongToZigzag(long n)
{
// Convert l into a zigzag long. This allows negative numbers to be represented compactly as a varint
return (ulong) (n << 1) ^ (ulong) (n >> 63);
}
private static uint IntToZigzag(int n)
{
// Convert n into a zigzag int. This allows negative numbers to be represented compactly as a varint
return (uint) (n << 1) ^ (uint) (n >> 31);
}
private static void FixedLongToBytes(long n, byte[] buf, int off)
{
// Convert a long into little-endian bytes in buf starting at off and going until off+7.
buf[off + 0] = (byte) (n & 0xff);
buf[off + 1] = (byte) ((n >> 8) & 0xff);
buf[off + 2] = (byte) ((n >> 16) & 0xff);
buf[off + 3] = (byte) ((n >> 24) & 0xff);
buf[off + 4] = (byte) ((n >> 32) & 0xff);
buf[off + 5] = (byte) ((n >> 40) & 0xff);
buf[off + 6] = (byte) ((n >> 48) & 0xff);
buf[off + 7] = (byte) ((n >> 56) & 0xff);
}
public class Factory : ITProtocolFactory
{
public TProtocol GetProtocol(TClientTransport trans)
{
return new TCompactProtocol(trans);
}
}
/// <summary>
/// All of the on-wire exType codes.
/// </summary>
private static class Types
{
public const byte Stop = 0x00;
public const byte BooleanTrue = 0x01;
public const byte BooleanFalse = 0x02;
public const byte Byte = 0x03;
public const byte I16 = 0x04;
public const byte I32 = 0x05;
public const byte I64 = 0x06;
public const byte Double = 0x07;
public const byte Binary = 0x08;
public const byte List = 0x09;
public const byte Set = 0x0A;
public const byte Map = 0x0B;
public const byte Struct = 0x0C;
}
}
}
| |
using System.Threading.Tasks;
using Abp.Application.Editions;
using Abp.Authorization.Users;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using Abp.MultiTenancy;
using Abp.Runtime.Caching;
namespace Abp.Application.Features
{
/// <summary>
/// Implements <see cref="IFeatureValueStore"/>.
/// </summary>
public class AbpFeatureValueStore<TTenant, TUser> :
IAbpZeroFeatureValueStore,
ITransientDependency,
IEventHandler<EntityChangedEventData<Edition>>,
IEventHandler<EntityChangedEventData<EditionFeatureSetting>>
where TTenant : AbpTenant<TUser>
where TUser : AbpUserBase
{
private readonly ICacheManager _cacheManager;
private readonly IRepository<TenantFeatureSetting, long> _tenantFeatureRepository;
private readonly IRepository<TTenant> _tenantRepository;
private readonly IRepository<EditionFeatureSetting, long> _editionFeatureRepository;
private readonly IFeatureManager _featureManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
/// <summary>
/// Initializes a new instance of the <see cref="AbpFeatureValueStore{TTenant, TUser}"/> class.
/// </summary>
public AbpFeatureValueStore(
ICacheManager cacheManager,
IRepository<TenantFeatureSetting, long> tenantFeatureRepository,
IRepository<TTenant> tenantRepository,
IRepository<EditionFeatureSetting, long> editionFeatureRepository,
IFeatureManager featureManager,
IUnitOfWorkManager unitOfWorkManager)
{
_cacheManager = cacheManager;
_tenantFeatureRepository = tenantFeatureRepository;
_tenantRepository = tenantRepository;
_editionFeatureRepository = editionFeatureRepository;
_featureManager = featureManager;
_unitOfWorkManager = unitOfWorkManager;
}
/// <inheritdoc/>
public virtual Task<string> GetValueOrNullAsync(int tenantId, Feature feature)
{
return GetValueOrNullAsync(tenantId, feature.Name);
}
public virtual async Task<string> GetEditionValueOrNullAsync(int editionId, string featureName)
{
var cacheItem = await GetEditionFeatureCacheItemAsync(editionId);
return cacheItem.FeatureValues.GetOrDefault(featureName);
}
public virtual async Task<string> GetValueOrNullAsync(int tenantId, string featureName)
{
var cacheItem = await GetTenantFeatureCacheItemAsync(tenantId);
var value = cacheItem.FeatureValues.GetOrDefault(featureName);
if (value != null)
{
return value;
}
if (cacheItem.EditionId.HasValue)
{
value = await GetEditionValueOrNullAsync(cacheItem.EditionId.Value, featureName);
if (value != null)
{
return value;
}
}
return null;
}
[UnitOfWork]
public virtual async Task SetEditionFeatureValueAsync(int editionId, string featureName, string value)
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
if (await GetEditionValueOrNullAsync(editionId, featureName) == value)
{
return;
}
var currentFeature = await _editionFeatureRepository.FirstOrDefaultAsync(f => f.EditionId == editionId && f.Name == featureName);
var feature = _featureManager.GetOrNull(featureName);
if (feature == null || feature.DefaultValue == value)
{
if (currentFeature != null)
{
await _editionFeatureRepository.DeleteAsync(currentFeature);
}
return;
}
if (currentFeature == null)
{
await _editionFeatureRepository.InsertAsync(new EditionFeatureSetting(editionId, featureName, value));
}
else
{
currentFeature.Value = value;
}
}
}
protected virtual async Task<TenantFeatureCacheItem> GetTenantFeatureCacheItemAsync(int tenantId)
{
return await _cacheManager.GetTenantFeatureCache().GetAsync(tenantId, async () =>
{
TTenant tenant;
using (var uow = _unitOfWorkManager.Begin())
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
tenant = await _tenantRepository.GetAsync(tenantId);
await uow.CompleteAsync();
}
}
var newCacheItem = new TenantFeatureCacheItem { EditionId = tenant.EditionId };
using (var uow = _unitOfWorkManager.Begin())
{
using (_unitOfWorkManager.Current.SetTenantId(tenantId))
{
var featureSettings = await _tenantFeatureRepository.GetAllListAsync();
foreach (var featureSetting in featureSettings)
{
newCacheItem.FeatureValues[featureSetting.Name] = featureSetting.Value;
}
await uow.CompleteAsync();
}
}
return newCacheItem;
});
}
protected virtual async Task<EditionfeatureCacheItem> GetEditionFeatureCacheItemAsync(int editionId)
{
return await _cacheManager
.GetEditionFeatureCache()
.GetAsync(
editionId,
async () => await CreateEditionFeatureCacheItem(editionId)
);
}
protected virtual async Task<EditionfeatureCacheItem> CreateEditionFeatureCacheItem(int editionId)
{
var newCacheItem = new EditionfeatureCacheItem();
using (var uow = _unitOfWorkManager.Begin())
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
var featureSettings = await _editionFeatureRepository.GetAllListAsync(f => f.EditionId == editionId);
foreach (var featureSetting in featureSettings)
{
newCacheItem.FeatureValues[featureSetting.Name] = featureSetting.Value;
}
await uow.CompleteAsync();
}
}
return newCacheItem;
}
public virtual void HandleEvent(EntityChangedEventData<EditionFeatureSetting> eventData)
{
_cacheManager.GetEditionFeatureCache().Remove(eventData.Entity.EditionId);
}
public virtual void HandleEvent(EntityChangedEventData<Edition> eventData)
{
if (eventData.Entity.IsTransient())
{
return;
}
_cacheManager.GetEditionFeatureCache().Remove(eventData.Entity.Id);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
namespace WebsitePanel.Providers.FTP {
using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="FTPServerSoap", Namespace="http://smbsaas/websitepanel/server/")]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))]
public partial class FTPServer : Microsoft.Web.Services3.WebServicesClientProtocol {
public ServiceProviderSettingsSoapHeader ServiceProviderSettingsSoapHeaderValue;
private System.Threading.SendOrPostCallback ChangeSiteStateOperationCompleted;
private System.Threading.SendOrPostCallback GetSiteStateOperationCompleted;
private System.Threading.SendOrPostCallback SiteExistsOperationCompleted;
private System.Threading.SendOrPostCallback GetSitesOperationCompleted;
private System.Threading.SendOrPostCallback GetSiteOperationCompleted;
private System.Threading.SendOrPostCallback CreateSiteOperationCompleted;
private System.Threading.SendOrPostCallback UpdateSiteOperationCompleted;
private System.Threading.SendOrPostCallback DeleteSiteOperationCompleted;
private System.Threading.SendOrPostCallback AccountExistsOperationCompleted;
private System.Threading.SendOrPostCallback GetAccountsOperationCompleted;
private System.Threading.SendOrPostCallback GetAccountOperationCompleted;
private System.Threading.SendOrPostCallback CreateAccountOperationCompleted;
private System.Threading.SendOrPostCallback UpdateAccountOperationCompleted;
private System.Threading.SendOrPostCallback DeleteAccountOperationCompleted;
/// <remarks/>
public FTPServer() {
this.Url = "http://localhost/WebsitePanelServer11/FtpServer.asmx";
}
/// <remarks/>
public event ChangeSiteStateCompletedEventHandler ChangeSiteStateCompleted;
/// <remarks/>
public event GetSiteStateCompletedEventHandler GetSiteStateCompleted;
/// <remarks/>
public event SiteExistsCompletedEventHandler SiteExistsCompleted;
/// <remarks/>
public event GetSitesCompletedEventHandler GetSitesCompleted;
/// <remarks/>
public event GetSiteCompletedEventHandler GetSiteCompleted;
/// <remarks/>
public event CreateSiteCompletedEventHandler CreateSiteCompleted;
/// <remarks/>
public event UpdateSiteCompletedEventHandler UpdateSiteCompleted;
/// <remarks/>
public event DeleteSiteCompletedEventHandler DeleteSiteCompleted;
/// <remarks/>
public event AccountExistsCompletedEventHandler AccountExistsCompleted;
/// <remarks/>
public event GetAccountsCompletedEventHandler GetAccountsCompleted;
/// <remarks/>
public event GetAccountCompletedEventHandler GetAccountCompleted;
/// <remarks/>
public event CreateAccountCompletedEventHandler CreateAccountCompleted;
/// <remarks/>
public event UpdateAccountCompletedEventHandler UpdateAccountCompleted;
/// <remarks/>
public event DeleteAccountCompletedEventHandler DeleteAccountCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/ChangeSiteState", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void ChangeSiteState(string siteId, ServerState state) {
this.Invoke("ChangeSiteState", new object[] {
siteId,
state});
}
/// <remarks/>
public System.IAsyncResult BeginChangeSiteState(string siteId, ServerState state, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("ChangeSiteState", new object[] {
siteId,
state}, callback, asyncState);
}
/// <remarks/>
public void EndChangeSiteState(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void ChangeSiteStateAsync(string siteId, ServerState state) {
this.ChangeSiteStateAsync(siteId, state, null);
}
/// <remarks/>
public void ChangeSiteStateAsync(string siteId, ServerState state, object userState) {
if ((this.ChangeSiteStateOperationCompleted == null)) {
this.ChangeSiteStateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnChangeSiteStateOperationCompleted);
}
this.InvokeAsync("ChangeSiteState", new object[] {
siteId,
state}, this.ChangeSiteStateOperationCompleted, userState);
}
private void OnChangeSiteStateOperationCompleted(object arg) {
if ((this.ChangeSiteStateCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.ChangeSiteStateCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSiteState", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public ServerState GetSiteState(string siteId) {
object[] results = this.Invoke("GetSiteState", new object[] {
siteId});
return ((ServerState)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSiteState(string siteId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetSiteState", new object[] {
siteId}, callback, asyncState);
}
/// <remarks/>
public ServerState EndGetSiteState(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((ServerState)(results[0]));
}
/// <remarks/>
public void GetSiteStateAsync(string siteId) {
this.GetSiteStateAsync(siteId, null);
}
/// <remarks/>
public void GetSiteStateAsync(string siteId, object userState) {
if ((this.GetSiteStateOperationCompleted == null)) {
this.GetSiteStateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteStateOperationCompleted);
}
this.InvokeAsync("GetSiteState", new object[] {
siteId}, this.GetSiteStateOperationCompleted, userState);
}
private void OnGetSiteStateOperationCompleted(object arg) {
if ((this.GetSiteStateCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSiteStateCompleted(this, new GetSiteStateCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/SiteExists", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool SiteExists(string siteId) {
object[] results = this.Invoke("SiteExists", new object[] {
siteId});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginSiteExists(string siteId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SiteExists", new object[] {
siteId}, callback, asyncState);
}
/// <remarks/>
public bool EndSiteExists(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void SiteExistsAsync(string siteId) {
this.SiteExistsAsync(siteId, null);
}
/// <remarks/>
public void SiteExistsAsync(string siteId, object userState) {
if ((this.SiteExistsOperationCompleted == null)) {
this.SiteExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSiteExistsOperationCompleted);
}
this.InvokeAsync("SiteExists", new object[] {
siteId}, this.SiteExistsOperationCompleted, userState);
}
private void OnSiteExistsOperationCompleted(object arg) {
if ((this.SiteExistsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SiteExistsCompleted(this, new SiteExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSites", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public FtpSite[] GetSites() {
object[] results = this.Invoke("GetSites", new object[0]);
return ((FtpSite[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSites(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetSites", new object[0], callback, asyncState);
}
/// <remarks/>
public FtpSite[] EndGetSites(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((FtpSite[])(results[0]));
}
/// <remarks/>
public void GetSitesAsync() {
this.GetSitesAsync(null);
}
/// <remarks/>
public void GetSitesAsync(object userState) {
if ((this.GetSitesOperationCompleted == null)) {
this.GetSitesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSitesOperationCompleted);
}
this.InvokeAsync("GetSites", new object[0], this.GetSitesOperationCompleted, userState);
}
private void OnGetSitesOperationCompleted(object arg) {
if ((this.GetSitesCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSitesCompleted(this, new GetSitesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public FtpSite GetSite(string siteId) {
object[] results = this.Invoke("GetSite", new object[] {
siteId});
return ((FtpSite)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetSite(string siteId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetSite", new object[] {
siteId}, callback, asyncState);
}
/// <remarks/>
public FtpSite EndGetSite(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((FtpSite)(results[0]));
}
/// <remarks/>
public void GetSiteAsync(string siteId) {
this.GetSiteAsync(siteId, null);
}
/// <remarks/>
public void GetSiteAsync(string siteId, object userState) {
if ((this.GetSiteOperationCompleted == null)) {
this.GetSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteOperationCompleted);
}
this.InvokeAsync("GetSite", new object[] {
siteId}, this.GetSiteOperationCompleted, userState);
}
private void OnGetSiteOperationCompleted(object arg) {
if ((this.GetSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetSiteCompleted(this, new GetSiteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CreateSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public string CreateSite(FtpSite site) {
object[] results = this.Invoke("CreateSite", new object[] {
site});
return ((string)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginCreateSite(FtpSite site, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("CreateSite", new object[] {
site}, callback, asyncState);
}
/// <remarks/>
public string EndCreateSite(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
/// <remarks/>
public void CreateSiteAsync(FtpSite site) {
this.CreateSiteAsync(site, null);
}
/// <remarks/>
public void CreateSiteAsync(FtpSite site, object userState) {
if ((this.CreateSiteOperationCompleted == null)) {
this.CreateSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateSiteOperationCompleted);
}
this.InvokeAsync("CreateSite", new object[] {
site}, this.CreateSiteOperationCompleted, userState);
}
private void OnCreateSiteOperationCompleted(object arg) {
if ((this.CreateSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateSiteCompleted(this, new CreateSiteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateSite(FtpSite site) {
this.Invoke("UpdateSite", new object[] {
site});
}
/// <remarks/>
public System.IAsyncResult BeginUpdateSite(FtpSite site, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("UpdateSite", new object[] {
site}, callback, asyncState);
}
/// <remarks/>
public void EndUpdateSite(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UpdateSiteAsync(FtpSite site) {
this.UpdateSiteAsync(site, null);
}
/// <remarks/>
public void UpdateSiteAsync(FtpSite site, object userState) {
if ((this.UpdateSiteOperationCompleted == null)) {
this.UpdateSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateSiteOperationCompleted);
}
this.InvokeAsync("UpdateSite", new object[] {
site}, this.UpdateSiteOperationCompleted, userState);
}
private void OnUpdateSiteOperationCompleted(object arg) {
if ((this.UpdateSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UpdateSiteCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteSite", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteSite(string siteId) {
this.Invoke("DeleteSite", new object[] {
siteId});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteSite(string siteId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("DeleteSite", new object[] {
siteId}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteSite(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteSiteAsync(string siteId) {
this.DeleteSiteAsync(siteId, null);
}
/// <remarks/>
public void DeleteSiteAsync(string siteId, object userState) {
if ((this.DeleteSiteOperationCompleted == null)) {
this.DeleteSiteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteSiteOperationCompleted);
}
this.InvokeAsync("DeleteSite", new object[] {
siteId}, this.DeleteSiteOperationCompleted, userState);
}
private void OnDeleteSiteOperationCompleted(object arg) {
if ((this.DeleteSiteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteSiteCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/AccountExists", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public bool AccountExists(string accountName) {
object[] results = this.Invoke("AccountExists", new object[] {
accountName});
return ((bool)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginAccountExists(string accountName, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("AccountExists", new object[] {
accountName}, callback, asyncState);
}
/// <remarks/>
public bool EndAccountExists(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((bool)(results[0]));
}
/// <remarks/>
public void AccountExistsAsync(string accountName) {
this.AccountExistsAsync(accountName, null);
}
/// <remarks/>
public void AccountExistsAsync(string accountName, object userState) {
if ((this.AccountExistsOperationCompleted == null)) {
this.AccountExistsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAccountExistsOperationCompleted);
}
this.InvokeAsync("AccountExists", new object[] {
accountName}, this.AccountExistsOperationCompleted, userState);
}
private void OnAccountExistsOperationCompleted(object arg) {
if ((this.AccountExistsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.AccountExistsCompleted(this, new AccountExistsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetAccounts", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public FtpAccount[] GetAccounts() {
object[] results = this.Invoke("GetAccounts", new object[0]);
return ((FtpAccount[])(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAccounts(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAccounts", new object[0], callback, asyncState);
}
/// <remarks/>
public FtpAccount[] EndGetAccounts(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((FtpAccount[])(results[0]));
}
/// <remarks/>
public void GetAccountsAsync() {
this.GetAccountsAsync(null);
}
/// <remarks/>
public void GetAccountsAsync(object userState) {
if ((this.GetAccountsOperationCompleted == null)) {
this.GetAccountsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAccountsOperationCompleted);
}
this.InvokeAsync("GetAccounts", new object[0], this.GetAccountsOperationCompleted, userState);
}
private void OnGetAccountsOperationCompleted(object arg) {
if ((this.GetAccountsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAccountsCompleted(this, new GetAccountsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/GetAccount", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public FtpAccount GetAccount(string accountName) {
object[] results = this.Invoke("GetAccount", new object[] {
accountName});
return ((FtpAccount)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetAccount(string accountName, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetAccount", new object[] {
accountName}, callback, asyncState);
}
/// <remarks/>
public FtpAccount EndGetAccount(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((FtpAccount)(results[0]));
}
/// <remarks/>
public void GetAccountAsync(string accountName) {
this.GetAccountAsync(accountName, null);
}
/// <remarks/>
public void GetAccountAsync(string accountName, object userState) {
if ((this.GetAccountOperationCompleted == null)) {
this.GetAccountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAccountOperationCompleted);
}
this.InvokeAsync("GetAccount", new object[] {
accountName}, this.GetAccountOperationCompleted, userState);
}
private void OnGetAccountOperationCompleted(object arg) {
if ((this.GetAccountCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetAccountCompleted(this, new GetAccountCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/CreateAccount", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void CreateAccount(FtpAccount account) {
this.Invoke("CreateAccount", new object[] {
account});
}
/// <remarks/>
public System.IAsyncResult BeginCreateAccount(FtpAccount account, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("CreateAccount", new object[] {
account}, callback, asyncState);
}
/// <remarks/>
public void EndCreateAccount(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void CreateAccountAsync(FtpAccount account) {
this.CreateAccountAsync(account, null);
}
/// <remarks/>
public void CreateAccountAsync(FtpAccount account, object userState) {
if ((this.CreateAccountOperationCompleted == null)) {
this.CreateAccountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateAccountOperationCompleted);
}
this.InvokeAsync("CreateAccount", new object[] {
account}, this.CreateAccountOperationCompleted, userState);
}
private void OnCreateAccountOperationCompleted(object arg) {
if ((this.CreateAccountCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateAccountCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/UpdateAccount", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void UpdateAccount(FtpAccount account) {
this.Invoke("UpdateAccount", new object[] {
account});
}
/// <remarks/>
public System.IAsyncResult BeginUpdateAccount(FtpAccount account, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("UpdateAccount", new object[] {
account}, callback, asyncState);
}
/// <remarks/>
public void EndUpdateAccount(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void UpdateAccountAsync(FtpAccount account) {
this.UpdateAccountAsync(account, null);
}
/// <remarks/>
public void UpdateAccountAsync(FtpAccount account, object userState) {
if ((this.UpdateAccountOperationCompleted == null)) {
this.UpdateAccountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateAccountOperationCompleted);
}
this.InvokeAsync("UpdateAccount", new object[] {
account}, this.UpdateAccountOperationCompleted, userState);
}
private void OnUpdateAccountOperationCompleted(object arg) {
if ((this.UpdateAccountCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.UpdateAccountCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapHeaderAttribute("ServiceProviderSettingsSoapHeaderValue")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/server/DeleteAccount", RequestNamespace="http://smbsaas/websitepanel/server/", ResponseNamespace="http://smbsaas/websitepanel/server/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void DeleteAccount(string accountName) {
this.Invoke("DeleteAccount", new object[] {
accountName});
}
/// <remarks/>
public System.IAsyncResult BeginDeleteAccount(string accountName, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("DeleteAccount", new object[] {
accountName}, callback, asyncState);
}
/// <remarks/>
public void EndDeleteAccount(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void DeleteAccountAsync(string accountName) {
this.DeleteAccountAsync(accountName, null);
}
/// <remarks/>
public void DeleteAccountAsync(string accountName, object userState) {
if ((this.DeleteAccountOperationCompleted == null)) {
this.DeleteAccountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteAccountOperationCompleted);
}
this.InvokeAsync("DeleteAccount", new object[] {
accountName}, this.DeleteAccountOperationCompleted, userState);
}
private void OnDeleteAccountOperationCompleted(object arg) {
if ((this.DeleteAccountCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteAccountCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void ChangeSiteStateCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSiteStateCompletedEventHandler(object sender, GetSiteStateCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSiteStateCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetSiteStateCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public ServerState Result {
get {
this.RaiseExceptionIfNecessary();
return ((ServerState)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SiteExistsCompletedEventHandler(object sender, SiteExistsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class SiteExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal SiteExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public bool Result {
get {
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSitesCompletedEventHandler(object sender, GetSitesCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSitesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetSitesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public FtpSite[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((FtpSite[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetSiteCompletedEventHandler(object sender, GetSiteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetSiteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetSiteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public FtpSite Result {
get {
this.RaiseExceptionIfNecessary();
return ((FtpSite)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateSiteCompletedEventHandler(object sender, CreateSiteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class CreateSiteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal CreateSiteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public string Result {
get {
this.RaiseExceptionIfNecessary();
return ((string)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UpdateSiteCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteSiteCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void AccountExistsCompletedEventHandler(object sender, AccountExistsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class AccountExistsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal AccountExistsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public bool Result {
get {
this.RaiseExceptionIfNecessary();
return ((bool)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAccountsCompletedEventHandler(object sender, GetAccountsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAccountsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAccountsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public FtpAccount[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((FtpAccount[])(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetAccountCompletedEventHandler(object sender, GetAccountCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetAccountCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetAccountCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public FtpAccount Result {
get {
this.RaiseExceptionIfNecessary();
return ((FtpAccount)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateAccountCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void UpdateAccountCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteAccountCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.RecoveryServices.Backup;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
public static partial class ContainerOperationsExtensions
{
/// <summary>
/// The Begin Refresh Operation triggers an operation in the service
/// which would discover all the containers in the subscription that
/// are ready to be protected by your Recovery Services Vault. This is
/// an asynchronous operation. To determine whether the backend
/// service has finished processing the request, call Get Refresh
/// Operation Result APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Nme of your recovery services vault.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name for the protection containers.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static BaseRecoveryServicesJobResponse BeginRefresh(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Refresh Operation triggers an operation in the service
/// which would discover all the containers in the subscription that
/// are ready to be protected by your Recovery Services Vault. This is
/// an asynchronous operation. To determine whether the backend
/// service has finished processing the request, call Get Refresh
/// Operation Result APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Nme of your recovery services vault.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name for the protection containers.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static Task<BaseRecoveryServicesJobResponse> BeginRefreshAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
{
return operations.BeginRefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, CancellationToken.None);
}
/// <summary>
/// Fetches the result of any operation on the container given the ID
/// of operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name of the protected item.
/// </param>
/// <param name='containerName'>
/// Required. Name of the container where the protected item belongs to.
/// </param>
/// <param name='operationId'>
/// Required. ID of the container operation whose result has to be
/// fetched.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Protection container response.
/// </returns>
public static ProtectionContainerResponse GetContainerOperationResult(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fetches the result of any operation on the container given the ID
/// of operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name of the protected item.
/// </param>
/// <param name='containerName'>
/// Required. Name of the container where the protected item belongs to.
/// </param>
/// <param name='operationId'>
/// Required. ID of the container operation whose result has to be
/// fetched.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Protection container response.
/// </returns>
public static Task<ProtectionContainerResponse> GetContainerOperationResultAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string containerName, string operationId, CustomRequestHeaders customRequestHeaders)
{
return operations.GetContainerOperationResultAsync(resourceGroupName, resourceName, fabricName, containerName, operationId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Fetches the result of any operation on the container given the URL
/// for tracking the operation as returned by APIs such as Unregister
/// etc.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='operationResultLink'>
/// Required. Location value returned by operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Protection container response.
/// </returns>
public static ProtectionContainerResponse GetContainerOperationResultByURL(this IContainerOperations operations, string operationResultLink, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).GetContainerOperationResultByURLAsync(operationResultLink, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fetches the result of any operation on the container given the URL
/// for tracking the operation as returned by APIs such as Unregister
/// etc.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='operationResultLink'>
/// Required. Location value returned by operation.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Protection container response.
/// </returns>
public static Task<ProtectionContainerResponse> GetContainerOperationResultByURLAsync(this IContainerOperations operations, string operationResultLink, CustomRequestHeaders customRequestHeaders)
{
return operations.GetContainerOperationResultByURLAsync(operationResultLink, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Fetches the result of the refresh operation triggered by the Begin
/// Refresh API given the ID of the operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name of the protected item.
/// </param>
/// <param name='operationId'>
/// Required. ID of the container operation whose result has to be
/// fetched.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static BaseRecoveryServicesJobResponse GetRefreshOperationResult(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string operationId, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).GetRefreshOperationResultAsync(resourceGroupName, resourceName, fabricName, operationId, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fetches the result of the refresh operation triggered by the Begin
/// Refresh API given the ID of the operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name of the protected item.
/// </param>
/// <param name='operationId'>
/// Required. ID of the container operation whose result has to be
/// fetched.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static Task<BaseRecoveryServicesJobResponse> GetRefreshOperationResultAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string fabricName, string operationId, CustomRequestHeaders customRequestHeaders)
{
return operations.GetRefreshOperationResultAsync(resourceGroupName, resourceName, fabricName, operationId, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// Fetches the result of the refresh operation triggered by the Begin
/// Refresh operation given the URL for tracking the operation as
/// returned by the Begin Refresh operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='operationResultLink'>
/// Required. Location value returned by operation.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static BaseRecoveryServicesJobResponse GetRefreshOperationResultByURL(this IContainerOperations operations, string operationResultLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).GetRefreshOperationResultByURLAsync(operationResultLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Fetches the result of the refresh operation triggered by the Begin
/// Refresh operation given the URL for tracking the operation as
/// returned by the Begin Refresh operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='operationResultLink'>
/// Required. Location value returned by operation.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static Task<BaseRecoveryServicesJobResponse> GetRefreshOperationResultByURLAsync(this IContainerOperations operations, string operationResultLink)
{
return operations.GetRefreshOperationResultByURLAsync(operationResultLink, CancellationToken.None);
}
/// <summary>
/// Lists all the containers registered to your Recovery Services Vault
/// according to the query parameters supplied in the arguments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='queryParams'>
/// Required. Query parameters for listing protection containers.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <returns>
/// List of protection containers returned as a response by the list
/// protection containers API.
/// </returns>
public static ProtectionContainerListResponse List(this IContainerOperations operations, string resourceGroupName, string resourceName, ProtectionContainerListQueryParams queryParams, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).ListAsync(resourceGroupName, resourceName, queryParams, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the containers registered to your Recovery Services Vault
/// according to the query parameters supplied in the arguments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='queryParams'>
/// Required. Query parameters for listing protection containers.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <returns>
/// List of protection containers returned as a response by the list
/// protection containers API.
/// </returns>
public static Task<ProtectionContainerListResponse> ListAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, ProtectionContainerListQueryParams queryParams, CustomRequestHeaders customRequestHeaders)
{
return operations.ListAsync(resourceGroupName, resourceName, queryParams, customRequestHeaders, CancellationToken.None);
}
/// <summary>
/// The Refresh Operation triggers an operation in the service which
/// would discover all the containers in the subscription that are
/// ready to be protected by your Recovery Services Vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name for the protection containers.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static BaseRecoveryServicesJobResponse Refresh(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).RefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Refresh Operation triggers an operation in the service which
/// would discover all the containers in the subscription that are
/// ready to be protected by your Recovery Services Vault.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='customRequestHeaders'>
/// Required. Request header parameters.
/// </param>
/// <param name='fabricName'>
/// Optional. Fabric name for the protection containers.
/// </param>
/// <returns>
/// Base recovery job response for all the asynchronous operations.
/// </returns>
public static Task<BaseRecoveryServicesJobResponse> RefreshAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName)
{
return operations.RefreshAsync(resourceGroupName, resourceName, customRequestHeaders, fabricName, CancellationToken.None);
}
/// <summary>
/// The Begin Unregister Operation unregisters the given container from
/// your Recovery Services Vault. This is an asynchronous operation.
/// To determine whether the backend service has finished processing
/// the request, call Get Container Operation Result API.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='identityName'>
/// Required. Name of the protection container to unregister.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Unregister(this IContainerOperations operations, string resourceGroupName, string resourceName, string identityName, CustomRequestHeaders customRequestHeaders)
{
return Task.Factory.StartNew((object s) =>
{
return ((IContainerOperations)s).UnregisterAsync(resourceGroupName, resourceName, identityName, customRequestHeaders);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Unregister Operation unregisters the given container from
/// your Recovery Services Vault. This is an asynchronous operation.
/// To determine whether the backend service has finished processing
/// the request, call Get Container Operation Result API.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.RecoveryServices.Backup.IContainerOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. Resource group name of your recovery services vault.
/// </param>
/// <param name='resourceName'>
/// Required. Name of your recovery services vault.
/// </param>
/// <param name='identityName'>
/// Required. Name of the protection container to unregister.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UnregisterAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string identityName, CustomRequestHeaders customRequestHeaders)
{
return operations.UnregisterAsync(resourceGroupName, resourceName, identityName, customRequestHeaders, CancellationToken.None);
}
}
}
| |
using org.dmxc.lumos.Kernel.Input;
using org.dmxc.lumos.Kernel.Resource;
using System;
using System.Xml.Linq;
namespace MidiPlugin
{
[FriendlyName("Button")]
public class ButtonRule : DeviceRule
{
private const string nolearn = "LearnMode disabled.";
private const string learn1 = "Press the button now.";
private const string learn2 = "Release the button now.";
private bool state;
private MidiInputChannel c = null;
private bool first = true;
public override event EventHandler LearningFinished;
public override string ControlType
{
get
{
return "Button";
}
}
public bool State
{
get
{
return this.state;
}
private set
{
this.state = value;
this.UpdateBacktrack();
}
}
public MidiMessage EnableMessage
{
get;
set;
}
public MidiMessage EnabledBacktrack
{
get;
set;
}
public MidiMessage DisableMessage
{
get;
set;
}
public MidiMessage DisabledBacktrack
{
get;
set;
}
public byte Treshold
{
get;
set;
}
public bool IsToggle
{
get;
set;
}
public override string LearnStatus
{
get;
protected set;
}
public bool LearnMode
{
get;
private set;
}
public override double Value
{
get
{
return (double)(this.State ? 1 : 0);
}
set
{
this.State = (value >= 0.5);
}
}
public ButtonRule()
{
this.LearnStatus = "LearnMode disabled.";
}
public override MidiInputChannel GetInputChannel(IInputLayer parent)
{
if (this.c == null)
{
this.c = new ButtonInputChannel(this, parent);
}
return this.c;
}
public override void BeginLearn()
{
this.LearnMode = true;
this.first = true;
this.LearnStatus = "Press the button now.";
}
public override void CancelLearn()
{
this.EndLearn();
}
private void EndLearn()
{
this.LearnMode = false;
this.LearnStatus = "LearnMode disabled.";
if (this.LearningFinished != null)
{
this.LearningFinished(this, EventArgs.Empty);
}
}
public override bool TryLearnMessage(MidiMessage m)
{
bool result;
if (!this.LearnMode)
{
result = false;
}
else
{
if (this.first)
{
this.EnableMessage = m;
this.first = false;
this.LearnStatus = "Release the button now.";
this.Treshold = (byte)(m.data2 - 1);
if (base.UseBacktrack)
{
this.EnabledBacktrack = m;
}
if (this.IsToggle)
{
this.DisableMessage = m;
if (base.UseBacktrack)
{
MidiMessage m2 = m;
m2.data2 = 0;
this.DisabledBacktrack = m2;
}
this.EndLearn();
}
}
else
{
if (m == this.EnableMessage)
{
result = false;
return result;
}
this.DisableMessage = m;
if (base.UseBacktrack)
{
this.DisabledBacktrack = m;
}
this.EndLearn();
}
result = true;
}
return result;
}
public override void Process(MidiMessage m)
{
if (this.State)
{
if (this.IsToggle)
{
if ((m.EqualsSimple(this.EnableMessage) && m.data2 > this.Treshold) || m == this.EnableMessage)
{
this.State = false;
}
base.OnValueChanged();
}
else
{
if (m.EqualsSimple(this.DisableMessage))
{
this.State = false;
}
base.OnValueChanged();
}
}
else
{
if (m.EqualsSimple(this.EnableMessage) && m.data2 > this.Treshold)
{
this.State = true;
}
base.OnValueChanged();
}
}
public override void Init(ManagedTreeItem i)
{
base.Init(i);
if (i.hasValue<byte>("Treshold"))
{
this.Treshold = i.getValue<byte>("Treshold");
}
if (i.hasValue<bool>("IsToggle"))
{
this.IsToggle = i.getValue<bool>("IsToggle");
}
if (i.hasValue<int>("EnableMessage"))
{
this.EnableMessage = new MidiMessage
{
Data = i.getValue<int>("EnableMessage")
};
}
if (i.hasValue<int>("EnabledBacktrack"))
{
this.EnabledBacktrack = new MidiMessage
{
Data = i.getValue<int>("EnabledBacktrack")
};
}
if (i.hasValue<int>("DisableMessage"))
{
this.DisableMessage = new MidiMessage
{
Data = i.getValue<int>("DisableMessage")
};
}
if (i.hasValue<int>("DisabledBacktrack"))
{
this.DisabledBacktrack = new MidiMessage
{
Data = i.getValue<int>("DisabledBacktrack")
};
}
if (i.hasValue<bool>("State"))
{
this.State = i.getValue<bool>("State");
}
}
public override void Save(ManagedTreeItem i)
{
ContextManager.log.Debug("Saving ButtonRule {0}, {1}, {2}", EnableMessage.Data, DisableMessage.Data, Treshold);
base.Save(i);
i.setValue<bool>("State", this.State);
i.setValue<byte>("Treshold", this.Treshold);
i.setValue<bool>("IsToggle", this.IsToggle);
i.setValue<int>("EnableMessage", this.EnableMessage.Data);
i.setValue<int>("EnabledBacktrack", this.EnabledBacktrack.Data);
i.setValue<int>("DisableMessage", this.DisableMessage.Data);
i.setValue<int>("DisabledBacktrack", this.DisabledBacktrack.Data);
}
protected override void Serialize(XElement item)
{
item.Add(new XAttribute("Treshold", this.Treshold));
item.Add(new XAttribute("IsToggle", this.IsToggle));
item.Add(new XAttribute("EnableMessage", this.EnableMessage.Data));
item.Add(new XAttribute("EnabledBacktrack", this.EnabledBacktrack.Data));
item.Add(new XAttribute("DisableMessage", this.DisableMessage.Data));
item.Add(new XAttribute("DisabledBacktrack", this.DisabledBacktrack.Data));
}
protected override void Deserialize(XElement item)
{
this.Treshold = byte.Parse(item.Attribute("Treshold").Value);
this.IsToggle = bool.Parse(item.Attribute("IsToggle").Value);
this.EnableMessage = new MidiMessage { Data = int.Parse(item.Attribute("EnableMessage").Value) };
this.EnabledBacktrack = new MidiMessage { Data = int.Parse(item.Attribute("EnableMessage").Value) };
this.DisableMessage = new MidiMessage { Data = int.Parse(item.Attribute("DisableMessage").Value) };
this.DisabledBacktrack = new MidiMessage { Data = int.Parse(item.Attribute("DisabledBacktrack").Value) };
}
public override void UpdateBacktrack()
{
if (base.UseBacktrack)
{
if (this.State)
{
base.OnSendMessage(this.EnabledBacktrack);
}
else
{
base.OnSendMessage(this.DisabledBacktrack);
}
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmMakeFinishItem
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmMakeFinishItem() : base()
{
KeyPress += frmMakeFinishItem_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.CheckBox chkSaleQTY;
private System.Windows.Forms.TextBox withEventsField_txtQty;
public System.Windows.Forms.TextBox txtQty {
get { return withEventsField_txtQty; }
set {
if (withEventsField_txtQty != null) {
withEventsField_txtQty.KeyPress -= txtQty_KeyPress;
withEventsField_txtQty.Enter -= txtQty_Enter;
withEventsField_txtQty.Leave -= txtQty_Leave;
}
withEventsField_txtQty = value;
if (withEventsField_txtQty != null) {
withEventsField_txtQty.KeyPress += txtQty_KeyPress;
withEventsField_txtQty.Enter += txtQty_Enter;
withEventsField_txtQty.Leave += txtQty_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtPrice;
public System.Windows.Forms.TextBox txtPrice {
get { return withEventsField_txtPrice; }
set {
if (withEventsField_txtPrice != null) {
withEventsField_txtPrice.Enter -= txtPrice_Enter;
withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress;
withEventsField_txtPrice.Leave -= txtPrice_Leave;
}
withEventsField_txtPrice = value;
if (withEventsField_txtPrice != null) {
withEventsField_txtPrice.Enter += txtPrice_Enter;
withEventsField_txtPrice.KeyPress += txtPrice_KeyPress;
withEventsField_txtPrice.Leave += txtPrice_Leave;
}
}
}
public System.Windows.Forms.ComboBox cmbQuantity;
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label lblSaleQty;
public System.Windows.Forms.Label lblPComp;
public System.Windows.Forms.Label _LBL_3;
public System.Windows.Forms.Label _LBL_2;
public System.Windows.Forms.Label _LBL_1;
public System.Windows.Forms.Label lblStockItem;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
//Public WithEvents LBL As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMakeFinishItem));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this.chkSaleQTY = new System.Windows.Forms.CheckBox();
this.txtQty = new System.Windows.Forms.TextBox();
this.txtPrice = new System.Windows.Forms.TextBox();
this.cmbQuantity = new System.Windows.Forms.ComboBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this.lblSaleQty = new System.Windows.Forms.Label();
this.lblPComp = new System.Windows.Forms.Label();
this._LBL_3 = new System.Windows.Forms.Label();
this._LBL_2 = new System.Windows.Forms.Label();
this._LBL_1 = new System.Windows.Forms.Label();
this.lblStockItem = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
//Me.LBL = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.LBL, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Make Finished Product";
this.ClientSize = new System.Drawing.Size(400, 152);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmMakeFinishItem";
this.chkSaleQTY.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkSaleQTY.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.chkSaleQTY.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this.chkSaleQTY.Text = "Apply Sales Qty:";
this.chkSaleQTY.ForeColor = System.Drawing.SystemColors.WindowText;
this.chkSaleQTY.Size = new System.Drawing.Size(102, 19);
this.chkSaleQTY.Location = new System.Drawing.Point(16, 120);
this.chkSaleQTY.TabIndex = 11;
this.chkSaleQTY.CausesValidation = true;
this.chkSaleQTY.Enabled = true;
this.chkSaleQTY.Cursor = System.Windows.Forms.Cursors.Default;
this.chkSaleQTY.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.chkSaleQTY.Appearance = System.Windows.Forms.Appearance.Normal;
this.chkSaleQTY.TabStop = true;
this.chkSaleQTY.CheckState = System.Windows.Forms.CheckState.Unchecked;
this.chkSaleQTY.Visible = true;
this.chkSaleQTY.Name = "chkSaleQTY";
this.txtQty.AutoSize = false;
this.txtQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtQty.Size = new System.Drawing.Size(67, 19);
this.txtQty.Location = new System.Drawing.Point(104, 97);
this.txtQty.TabIndex = 8;
this.txtQty.Text = "0";
this.txtQty.AcceptsReturn = true;
this.txtQty.BackColor = System.Drawing.SystemColors.Window;
this.txtQty.CausesValidation = true;
this.txtQty.Enabled = true;
this.txtQty.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtQty.HideSelection = true;
this.txtQty.ReadOnly = false;
this.txtQty.MaxLength = 0;
this.txtQty.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQty.Multiline = false;
this.txtQty.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtQty.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtQty.TabStop = true;
this.txtQty.Visible = true;
this.txtQty.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtQty.Name = "txtQty";
this.txtPrice.AutoSize = false;
this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtPrice.Enabled = false;
this.txtPrice.Size = new System.Drawing.Size(91, 19);
this.txtPrice.Location = new System.Drawing.Point(293, 97);
this.txtPrice.TabIndex = 4;
this.txtPrice.Text = "0.00";
this.txtPrice.AcceptsReturn = true;
this.txtPrice.BackColor = System.Drawing.SystemColors.Window;
this.txtPrice.CausesValidation = true;
this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPrice.HideSelection = true;
this.txtPrice.ReadOnly = false;
this.txtPrice.MaxLength = 0;
this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPrice.Multiline = false;
this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPrice.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtPrice.TabStop = true;
this.txtPrice.Visible = true;
this.txtPrice.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtPrice.Name = "txtPrice";
this.cmbQuantity.Size = new System.Drawing.Size(79, 21);
this.cmbQuantity.Location = new System.Drawing.Point(184, 96);
this.cmbQuantity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbQuantity.TabIndex = 3;
this.cmbQuantity.Visible = false;
this.cmbQuantity.BackColor = System.Drawing.SystemColors.Window;
this.cmbQuantity.CausesValidation = true;
this.cmbQuantity.Enabled = true;
this.cmbQuantity.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbQuantity.IntegralHeight = true;
this.cmbQuantity.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbQuantity.Sorted = false;
this.cmbQuantity.TabStop = true;
this.cmbQuantity.Name = "cmbQuantity";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(400, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 0;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(8, 3);
this.cmdCancel.TabIndex = 10;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(312, 3);
this.cmdClose.TabIndex = 1;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this.lblSaleQty.Text = "[ 0 ]";
this.lblSaleQty.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblSaleQty.Size = new System.Drawing.Size(256, 20);
this.lblSaleQty.Location = new System.Drawing.Point(128, 122);
this.lblSaleQty.TabIndex = 12;
this.lblSaleQty.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblSaleQty.BackColor = System.Drawing.Color.Transparent;
this.lblSaleQty.Enabled = true;
this.lblSaleQty.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblSaleQty.Cursor = System.Windows.Forms.Cursors.Default;
this.lblSaleQty.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblSaleQty.UseMnemonic = true;
this.lblSaleQty.Visible = true;
this.lblSaleQty.AutoSize = false;
this.lblSaleQty.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblSaleQty.Name = "lblSaleQty";
this.lblPComp.Text = "Please enter the Qty you wish to make:";
this.lblPComp.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblPComp.Size = new System.Drawing.Size(352, 20);
this.lblPComp.Location = new System.Drawing.Point(10, 56);
this.lblPComp.TabIndex = 9;
this.lblPComp.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblPComp.BackColor = System.Drawing.Color.Transparent;
this.lblPComp.Enabled = true;
this.lblPComp.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPComp.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPComp.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPComp.UseMnemonic = true;
this.lblPComp.Visible = true;
this.lblPComp.AutoSize = false;
this.lblPComp.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblPComp.Name = "lblPComp";
this._LBL_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_3.Text = "Price:";
this._LBL_3.Size = new System.Drawing.Size(27, 13);
this._LBL_3.Location = new System.Drawing.Point(262, 100);
this._LBL_3.TabIndex = 7;
this._LBL_3.BackColor = System.Drawing.Color.Transparent;
this._LBL_3.Enabled = true;
this._LBL_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_3.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_3.UseMnemonic = true;
this._LBL_3.Visible = true;
this._LBL_3.AutoSize = true;
this._LBL_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._LBL_3.Name = "_LBL_3";
this._LBL_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_2.Text = "Item Qty:";
this._LBL_2.Size = new System.Drawing.Size(42, 13);
this._LBL_2.Location = new System.Drawing.Point(53, 100);
this._LBL_2.TabIndex = 6;
this._LBL_2.BackColor = System.Drawing.Color.Transparent;
this._LBL_2.Enabled = true;
this._LBL_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_2.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_2.UseMnemonic = true;
this._LBL_2.Visible = true;
this._LBL_2.AutoSize = true;
this._LBL_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._LBL_2.Name = "_LBL_2";
this._LBL_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_1.Text = "Stock Item Name:";
this._LBL_1.Size = new System.Drawing.Size(85, 13);
this._LBL_1.Location = new System.Drawing.Point(10, 79);
this._LBL_1.TabIndex = 5;
this._LBL_1.BackColor = System.Drawing.Color.Transparent;
this._LBL_1.Enabled = true;
this._LBL_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_1.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_1.UseMnemonic = true;
this._LBL_1.Visible = true;
this._LBL_1.AutoSize = true;
this._LBL_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._LBL_1.Name = "_LBL_1";
this.lblStockItem.Text = "Label1";
this.lblStockItem.Size = new System.Drawing.Size(278, 17);
this.lblStockItem.Location = new System.Drawing.Point(105, 79);
this.lblStockItem.TabIndex = 2;
this.lblStockItem.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblStockItem.BackColor = System.Drawing.SystemColors.Control;
this.lblStockItem.Enabled = true;
this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default;
this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblStockItem.UseMnemonic = true;
this.lblStockItem.Visible = true;
this.lblStockItem.AutoSize = false;
this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblStockItem.Name = "lblStockItem";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(383, 96);
this._Shape1_2.Location = new System.Drawing.Point(7, 48);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this.Controls.Add(chkSaleQTY);
this.Controls.Add(txtQty);
this.Controls.Add(txtPrice);
this.Controls.Add(cmbQuantity);
this.Controls.Add(picButtons);
this.Controls.Add(lblSaleQty);
this.Controls.Add(lblPComp);
this.Controls.Add(_LBL_3);
this.Controls.Add(_LBL_2);
this.Controls.Add(_LBL_1);
this.Controls.Add(lblStockItem);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this.Controls.Add(ShapeContainer1);
this.picButtons.Controls.Add(cmdCancel);
this.picButtons.Controls.Add(cmdClose);
//Me.LBL.SetIndex(_LBL_3, CType(3, Short))
//Me.LBL.SetIndex(_LBL_2, CType(2, Short))
//Me.LBL.SetIndex(_LBL_1, CType(1, Short))
this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.LBL, System.ComponentModel.ISupportInitialize).EndInit()
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class HttpRequestStreamTests : IDisposable
{
private HttpListenerFactory _factory;
private HttpListener _listener;
private GetContextHelper _helper;
public HttpRequestStreamTests()
{
_factory = new HttpListenerFactory();
_listener = _factory.GetListener();
_helper = new GetContextHelper(_listener, _factory.ListeningUrl);
}
public void Dispose()
{
_factory.Dispose();
_helper.Dispose();
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthAsynchronous_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
byte[] buffer = new byte[expected.Length];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer);
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthAsynchronous_PadBuffer_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
const int pad = 128;
// Add padding at beginning and end to test for correct offset/size handling
byte[] buffer = new byte[pad + expected.Length + pad];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, pad, expected.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer.Skip(pad).Take(bytesRead));
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, pad, 1));
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
[InlineData(false, "Non-Empty")]
public async Task Read_FullLengthSynchronous_Success(bool transferEncodingChunked, string text)
{
byte[] expected = Encoding.UTF8.GetBytes(text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text));
HttpListenerContext context = await contextTask;
if (transferEncodingChunked)
{
Assert.Equal(-1, context.Request.ContentLength64);
Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]);
}
else
{
Assert.Equal(expected.Length, context.Request.ContentLength64);
Assert.Null(context.Request.Headers["Transfer-Encoding"]);
}
byte[] buffer = new byte[expected.Length];
int bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected, buffer);
// Subsequent reads don't do anything.
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(200, (int)response.StatusCode);
}
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthAsynchronous_Success(bool transferEncodingChunked)
{
var rand = new Random(42);
byte[] expected = Enumerable
.Range(0, 128*1024 + 1) // More than 128kb
.Select(_ => (byte)('a' + rand.Next(0, 26)))
.ToArray();
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected));
HttpListenerContext context = await contextTask;
// If the size is greater than 128K, then we limit the size, and have to do multiple reads on
// Windows, which uses http.sys internally.
byte[] buffer = new byte[expected.Length];
int totalRead = 0;
while (totalRead < expected.Length)
{
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, totalRead, expected.Length - totalRead);
Assert.InRange(bytesRead, 1, expected.Length - totalRead);
totalRead += bytesRead;
}
// Subsequent reads don't do anything.
Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthSynchronous_Success(bool transferEncodingChunked)
{
var rand = new Random(42);
byte[] expected = Enumerable
.Range(0, 128 * 1024 + 1) // More than 128kb
.Select(_ => (byte)('a' + rand.Next(0, 26)))
.ToArray();
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected));
HttpListenerContext context = await contextTask;
// If the size is greater than 128K, then we limit the size, and have to do multiple reads on
// Windows, which uses http.sys internally.
byte[] buffer = new byte[expected.Length];
int totalRead = 0;
while (totalRead < expected.Length)
{
int bytesRead = context.Request.InputStream.Read(buffer, totalRead, expected.Length - totalRead);
Assert.InRange(bytesRead, 1, expected.Length - totalRead);
totalRead += bytesRead;
}
// Subsequent reads don't do anything.
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(expected, buffer);
context.Response.Close();
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchAsynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length + 5];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected.Concat(new byte[5]), buffer);
context.Response.Close();
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchSynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length + 5];
int bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length);
Assert.Equal(expected.Length, bytesRead);
Assert.Equal(expected.Concat(new byte[5]), buffer);
context.Response.Close();
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NotEnoughThenCloseAsynchronous_Success(bool transferEncodingChunked)
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
byte[] buffer = new byte[expected.Length - 5];
int bytesRead = await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length);
Assert.Equal(buffer.Length, bytesRead);
context.Response.Close();
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_Disposed_ReturnsZero(bool transferEncodingChunked)
{
const string Text = "Some-String";
int bufferSize = Encoding.UTF8.GetByteCount(Text);
Task<HttpListenerContext> contextTask = _listener.GetContextAsync();
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked;
Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text));
HttpListenerContext context = await contextTask;
context.Request.InputStream.Close();
byte[] buffer = new byte[bufferSize];
Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Equal(new byte[bufferSize], buffer);
IAsyncResult result = context.Request.InputStream.BeginRead(buffer, 0, buffer.Length, null, null);
Assert.Equal(0, context.Request.InputStream.EndRead(result));
Assert.Equal(new byte[bufferSize], buffer);
context.Response.Close();
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanSeek_Get_ReturnsFalse()
{
HttpListenerRequest response = await _helper.GetRequest(chunked: true);
using (Stream inputStream = response.InputStream)
{
Assert.False(inputStream.CanSeek);
Assert.Throws<NotSupportedException>(() => inputStream.Length);
Assert.Throws<NotSupportedException>(() => inputStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => inputStream.Position);
Assert.Throws<NotSupportedException>(() => inputStream.Position = 1);
Assert.Throws<NotSupportedException>(() => inputStream.Seek(0, SeekOrigin.Begin));
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanRead_Get_ReturnsTrue()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
using (Stream inputStream = request.InputStream)
{
Assert.True(inputStream.CanRead);
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanWrite_Get_ReturnsFalse()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
using (Stream inputStream = request.InputStream)
{
Assert.False(inputStream.CanWrite);
Assert.Throws<InvalidOperationException>(() => inputStream.Write(new byte[0], 0, 0));
await Assert.ThrowsAsync<InvalidOperationException>(() => inputStream.WriteAsync(new byte[0], 0, 0));
Assert.Throws<InvalidOperationException>(() => inputStream.EndWrite(null));
// Flushing the output stream is a no-op.
inputStream.Flush();
Assert.Equal(Task.CompletedTask, inputStream.FlushAsync(CancellationToken.None));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NullBuffer_ThrowsArgumentNullException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => inputStream.Read(null, 0, 0));
await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => inputStream.ReadAsync(null, 0, 0));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1, true)]
[InlineData(3, true)]
[InlineData(-1, false)]
[InlineData(3, false)]
public async Task Read_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset, bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => inputStream.Read(new byte[2], offset, 0));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => inputStream.ReadAsync(new byte[2], offset, 0));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0, 3, true)]
[InlineData(1, 2, true)]
[InlineData(2, 1, true)]
[InlineData(0, 3, false)]
[InlineData(1, 2, false)]
[InlineData(2, 1, false)]
public async Task Read_InvalidOffsetSize_ThrowsArgumentOutOfRangeException(int offset, int size, bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => inputStream.Read(new byte[2], offset, size));
await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => inputStream.ReadAsync(new byte[2], offset, size));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_NullAsyncResult_ThrowsArgumentNullException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => inputStream.EndRead(null));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_InvalidAsyncResult_ThrowsArgumentException(bool chunked)
{
HttpListenerRequest request1 = await _helper.GetRequest(chunked);
HttpListenerRequest request2 = await _helper.GetRequest(chunked);
using (Stream inputStream1 = request1.InputStream)
using (Stream inputStream2 = request2.InputStream)
{
IAsyncResult beginReadResult = inputStream1.BeginRead(new byte[0], 0, 0, null, null);
AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(new CustomAsyncResult()));
AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(beginReadResult));
}
}
[Theory]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_CalledTwice_ThrowsInvalidOperationException(bool chunked)
{
HttpListenerRequest request = await _helper.GetRequest(chunked);
using (Stream inputStream = request.InputStream)
{
IAsyncResult beginReadResult = inputStream.BeginRead(new byte[0], 0, 0, null, null);
inputStream.EndRead(beginReadResult);
Assert.Throws<InvalidOperationException>(() => inputStream.EndRead(beginReadResult));
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Read_FromClosedConnectionAsynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
using (Socket client = _factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
// Note: It's important here that we don't send the content.
// If the content is missing, then the HttpListener needs
// to get the content. However, the socket has been closed
// before the reading of the content, so reading should fail.
client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListenerContext context = await _listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Reading from a closed connection should fail.
byte[] buffer = new byte[expected.Length];
await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length));
}
}
[Fact]
[ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Read_FromClosedConnectionSynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
byte[] expected = Encoding.UTF8.GetBytes(Text);
using (Socket client = _factory.GetConnectedSocket())
{
// Send a header to the HttpListener to give it a context.
// Note: It's important here that we don't send the content.
// If the content is missing, then the HttpListener needs
// to get the content. However, the socket has been closed
// before the reading of the content, so reading should fail.
client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true));
HttpListenerContext context = await _listener.GetContextAsync();
// Disconnect the Socket from the HttpListener.
Helpers.WaitForSocketShutdown(client);
// Reading from a closed connection should fail.
byte[] buffer = new byte[expected.Length];
Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length));
Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length));
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The MatchCollection lists the successful matches that
// result when searching a string for a regular expression.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Text.RegularExpressions
{
/*
* This collection returns a sequence of successful match results, either
* from GetMatchCollection() or GetExecuteCollection(). It stops when the
* first failure is encountered (it does not return the failed match).
*/
/// <summary>
/// Represents the set of names appearing as capturing group
/// names in a regular expression.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Match>))]
public class MatchCollection : IList<Match>, IReadOnlyList<Match>, IList
{
private readonly Regex _regex;
private readonly List<Match> _matches;
private bool _done;
private readonly string _input;
private readonly int _beginning;
private readonly int _length;
private int _startat;
private int _prevlen;
internal MatchCollection(Regex regex, string input, int beginning, int length, int startat)
{
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException("startat", SR.BeginIndexNotNegative);
_regex = regex;
_input = input;
_beginning = beginning;
_length = length;
_startat = startat;
_prevlen = -1;
_matches = new List<Match>();
_done = false;
}
/// <summary>
/// Returns the number of captures.
/// </summary>
public int Count
{
get
{
EnsureInitialized();
return _matches.Count;
}
}
/// <summary>
/// Returns the ith Match in the collection.
/// </summary>
public virtual Match this[int i]
{
get
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
Match match = GetMatch(i);
if (match == null)
throw new ArgumentOutOfRangeException("i");
return match;
}
}
/// <summary>
/// Copies all the elements of the collection to the given array
/// starting at the given index.
/// </summary>
public void CopyTo(Match[] array, int arrayIndex)
{
EnsureInitialized();
_matches.CopyTo(array, arrayIndex);
}
/// <summary>
/// Provides an enumerator in the same order as Item[i].
/// </summary>
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<Match> IEnumerable<Match>.GetEnumerator()
{
return new Enumerator(this);
}
private Match GetMatch(int i)
{
Debug.Assert(i >= 0, "i cannot be negative.");
if (_matches.Count > i)
return _matches[i];
if (_done)
return null;
Match match;
do
{
match = _regex.Run(false, _prevlen, _input, _beginning, _length, _startat);
if (!match.Success)
{
_done = true;
return null;
}
_matches.Add(match);
_prevlen = match._length;
_startat = match._textpos;
} while (_matches.Count <= i);
return match;
}
private void EnsureInitialized()
{
if (!_done)
{
GetMatch(int.MaxValue);
}
}
int IList<Match>.IndexOf(Match item)
{
var comparer = EqualityComparer<Match>.Default;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
void IList<Match>.Insert(int index, Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList<Match>.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
Match IList<Match>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
void ICollection<Match>.Add(Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<Match>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<Match>.Contains(Match item)
{
return ((IList<Match>)this).IndexOf(item) >= 0;
}
bool ICollection<Match>.IsReadOnly
{
get { return true; }
}
bool ICollection<Match>.Remove(Match item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
int IList.Add(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.Contains(object value)
{
return value is Match && ((ICollection<Match>)this).Contains((Match)value);
}
int IList.IndexOf(object value)
{
return value is Match ? ((IList<Match>)this).IndexOf((Match)value) : -1;
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.IsFixedSize
{
get { return true; }
}
bool IList.IsReadOnly
{
get { return true; }
}
void IList.Remove(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
EnsureInitialized();
((ICollection)_matches).CopyTo(array, arrayIndex);
}
private class Enumerator : IEnumerator<Match>
{
private readonly MatchCollection _collection;
private int _index;
internal Enumerator(MatchCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
if (_index == -2)
return false;
_index++;
Match match = _collection.GetMatch(_index);
if (match == null)
{
_index = -2;
return false;
}
return true;
}
public Match Current
{
get
{
if (_index < 0)
throw new InvalidOperationException(SR.EnumNotStarted);
return _collection.GetMatch(_index);
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose()
{
}
}
}
}
| |
// Copyright (c) 2016-2018 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.IO;
using Autofac;
using Chorus.Utilities;
using LfMerge.Core.Actions;
using LfMerge.Core.Actions.Infrastructure;
using LfMerge.Core.Settings;
using Microsoft.DotNet.PlatformAbstractions;
using NUnit.Framework;
using SIL.LCModel;
using SIL.TestUtilities;
namespace LfMerge.Core.Tests.Actions
{
/// <summary>
/// These tests test the LfMergeBridge interface. Because LfMergeBridge uses a single method
/// and dictionary for input and a string for output the compiler won't complain when the
/// "interface" changes (e.g. when we suddenly get a different string back than before, or
/// the name for an expected key changes). These tests try to cover different scenarios so
/// that we get test failures if the interface changes.
/// </summary>
[TestFixture]
[Platform(Exclude = "Win")]
[Category("IntegrationTests")]
public class SynchronizeActionBridgeIntegrationTests
{
private TestEnvironment _env;
private LfMergeSettings _lDSettings;
private TemporaryFolder _languageDepotFolder;
private LanguageForgeProject _lfProject;
private SynchronizeAction _synchronizeAction;
private string _workDir;
private const string TestLangProj = "testlangproj";
private const string TestLangProjModified = "testlangproj-modified";
private string CopyModifiedProjectAsTestLangProj(string webWorkDirectory)
{
var repoDir = Path.Combine(webWorkDirectory, TestLangProj);
if (Directory.Exists(repoDir))
Directory.Delete(repoDir, true);
TestEnvironment.CopyFwProjectTo(TestLangProjModified, webWorkDirectory);
Directory.Move(Path.Combine(webWorkDirectory, TestLangProjModified), repoDir);
return repoDir;
}
private static int ModelVersion
{
get
{
var chorusHelper = MainClass.Container.Resolve<ChorusHelper>();
return chorusHelper.ModelVersion;
}
}
[SetUp]
public void Setup()
{
MagicStrings.SetMinimalModelVersion(LcmCache.ModelVersion);
_env = new TestEnvironment();
_languageDepotFolder = new TemporaryFolder(TestContext.CurrentContext.Test.Name + Path.GetRandomFileName());
_lDSettings = new LfMergeSettingsDouble(_languageDepotFolder.Path);
Directory.CreateDirectory(_lDSettings.WebWorkDirectory);
LanguageDepotMock.ProjectFolderPath =
Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
Directory.CreateDirectory(LanguageDepotMock.ProjectFolderPath);
_lfProject = LanguageForgeProject.Create(TestLangProj);
_synchronizeAction = new SynchronizeAction(_env.Settings, _env.Logger);
_workDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(ExecutionEnvironment.DirectoryOfExecutingAssembly);
LanguageDepotMock.Server = new MercurialServer(LanguageDepotMock.ProjectFolderPath);
}
[TearDown]
public void Teardown()
{
// Reset workdir, otherwise NUnit will get confused when it tries to reset the
// workdir after running the test but the current dir got deleted in the teardown.
Directory.SetCurrentDirectory(_workDir);
LanguageForgeProject.DisposeFwProject(_lfProject);
if (_languageDepotFolder != null)
_languageDepotFolder.Dispose();
_env.Dispose();
if (LanguageDepotMock.Server != null)
{
LanguageDepotMock.Server.Stop();
LanguageDepotMock.Server = null;
}
}
[Test]
public void MissingFwDataFixer_Throws()
{
// Setup
var tmpFolder = Path.Combine(_languageDepotFolder.Path, "WorkDir");
Directory.CreateDirectory(tmpFolder);
Directory.SetCurrentDirectory(tmpFolder);
// Execute/Verify
Assert.That(() => _synchronizeAction.Run(_lfProject),
// This can't happen in real life because we ensure that we have a clone
// before we call sync. Therefore it is acceptable to get an exception.
Throws.TypeOf<InvalidOperationException>());
}
[Test]
public void Error_NoHgRepo()
{
// Setup
Directory.CreateDirectory(_lfProject.ProjectDir);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetErrors(),
Does.Contain("Cannot create a repository at this point in LF development."));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.HOLD));
}
[Test]
public void Error_NoCommitsInRepository()
{
// Setup
// Create a empty hg repo
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, LcmCache.ModelVersion);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetErrors(),
Does.Contain("Cannot do first commit."));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.HOLD));
}
[Test]
public void Error_DifferentBranch()
{
// Setup
// Create a hg repo that doesn't contain a branch for the current model version
const int modelVersion = 7000067;
MagicStrings.SetMinimalModelVersion(modelVersion);
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, modelVersion);
MercurialTestHelper.CreateFlexRepo(lDProjectFolderPath, modelVersion);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
Assert.That(ModelVersion, Is.EqualTo(modelVersion));
}
[Test]
public void Error_NewerBranch()
{
// Setup
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, LcmCache.ModelVersion);
MercurialTestHelper.CreateFlexRepo(lDProjectFolderPath);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
// Simulate a user with a newer FLEx version doing a S/R
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, 7600000);
MercurialTestHelper.HgCommit(lDProjectFolderPath, "Commit with newer FLEx version");
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetMessages(), Does.Contain("Allow data migration for project"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Error_InvalidUtf8InXml()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
var fwdataPath = Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, TestLangProj + ".fwdata");
TestEnvironment.OverwriteBytesInFile(fwdataPath, new byte[] {0xc0, 0xc1}, 25); // 0xC0 and 0xC1 are always invalid byte values in UTF-8
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
string errors = _env.Logger.GetErrors();
Assert.That(errors, Does.Contain("System.Xml.XmlException"));
// Stack trace should also have been logged
Assert.That(errors, Does.Contain("\n at Chorus.sync.Synchronizer.SyncNow (Chorus.sync.SyncOptions options)"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Error_WrongXmlEncoding()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
var fwdataPath = Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, TestLangProj + ".fwdata");
TestEnvironment.ChangeFileEncoding(fwdataPath, System.Text.Encoding.UTF8, System.Text.Encoding.UTF32);
// Note that the XML file will still claim the encoding is UTF-8!
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
string errors = _env.Logger.GetErrors();
Assert.That(errors, Does.Contain("System.Xml.XmlException: '.', hexadecimal value 0x00, is an invalid character."));
// Stack trace should also have been logged
Assert.That(errors, Does.Contain("\n at Chorus.sync.Synchronizer.SyncNow (Chorus.sync.SyncOptions options)"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
public void Success_NewBranchFormat_LfMerge68()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000068}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
}
public void Success_NewBranchFormat_LfMerge69()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000069}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
// Stack trace should also have been logged
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Success_NewBranchFormat_LfMerge70()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000070}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_NoNewChangesFromOthersAndUs()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("No changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_ChangesFromOthersNoChangesFromUs()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_ChangesFromUsNoChangesFromOthers()
{
// Setup
CopyModifiedProjectAsTestLangProj(_env.Settings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var oldHashOfUs = MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(oldHashOfUs));
Assert.That(MercurialTestHelper.GetRevisionOfTip(
Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj)),
Is.EqualTo(oldHashOfUs), "LanguageDepot doesn't have our changes");
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("No changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Delegate used to delay evaluation of the actual value
/// to be used in evaluating a constraint
/// </summary>
public delegate object ActualValueDelegate();
/// <summary>
/// The Constraint class is the base of all built-in constraints
/// within NUnit. It provides the operator overloads used to combine
/// constraints.
/// </summary>
public abstract class Constraint : IResolveConstraint
{
#region UnsetObject Class
/// <summary>
/// Class used to detect any derived constraints
/// that fail to set the actual value in their
/// Matches override.
/// </summary>
private class UnsetObject
{
public override string ToString()
{
return "UNSET";
}
}
#endregion
#region Static and Instance Fields
/// <summary>
/// Static UnsetObject used to detect derived constraints
/// failing to set the actual value.
/// </summary>
protected static object UNSET = new UnsetObject();
/// <summary>
/// The actual value being tested against a constraint
/// </summary>
protected object actual = UNSET;
/// <summary>
/// The display name of this Constraint for use by ToString()
/// </summary>
private string displayName;
/// <summary>
/// Argument fields used by ToString();
/// </summary>
private readonly int argcnt;
private readonly object arg1;
private readonly object arg2;
/// <summary>
/// The builder holding this constraint
/// </summary>
private ConstraintBuilder builder;
#endregion
#region Constructors
/// <summary>
/// Construct a constraint with no arguments
/// </summary>
protected Constraint()
{
argcnt = 0;
}
/// <summary>
/// Construct a constraint with one argument
/// </summary>
protected Constraint(object arg)
{
argcnt = 1;
this.arg1 = arg;
}
/// <summary>
/// Construct a constraint with two arguments
/// </summary>
protected Constraint(object arg1, object arg2)
{
argcnt = 2;
this.arg1 = arg1;
this.arg2 = arg2;
}
#endregion
#region Set Containing ConstraintBuilder
/// <summary>
/// Sets the ConstraintBuilder holding this constraint
/// </summary>
internal void SetBuilder(ConstraintBuilder builder)
{
this.builder = builder;
}
#endregion
#region Properties
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
protected string DisplayName
{
get
{
if (displayName == null)
{
displayName = this.GetType().Name.ToLower();
if (displayName.EndsWith("`1") || displayName.EndsWith("`2"))
displayName = displayName.Substring(0, displayName.Length - 2);
if (displayName.EndsWith("constraint"))
displayName = displayName.Substring(0, displayName.Length - 10);
}
return displayName;
}
set { displayName = value; }
}
#endregion
#region Abstract and Virtual Methods
/// <summary>
/// Write the failure message to the MessageWriter provided
/// as an argument. The default implementation simply passes
/// the constraint and the actual value to the writer, which
/// then displays the constraint description and the value.
///
/// Constraints that need to provide additional details,
/// such as where the error occured can override this.
/// </summary>
/// <param name="writer">The MessageWriter on which to display the message</param>
public virtual void WriteMessageTo(MessageWriter writer)
{
writer.DisplayDifferences(this);
}
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for success, false for failure</returns>
public abstract bool Matches(object actual);
/// <summary>
/// Test whether the constraint is satisfied by an
/// ActualValueDelegate that returns the value to be tested.
/// The default implementation simply evaluates the delegate
/// but derived classes may override it to provide for delayed
/// processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>True for success, false for failure</returns>
public virtual bool Matches(ActualValueDelegate del)
{
return Matches(del());
}
/// <summary>
/// Test whether the constraint is satisfied by a given reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>True for success, false for failure</returns>
#if true
public virtual bool Matches<T>(ref T actual)
#else
public virtual bool Matches(ref bool actual)
#endif
{
return Matches(actual);
}
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer">The writer on which the description is displayed</param>
public abstract void WriteDescriptionTo(MessageWriter writer);
/// <summary>
/// Write the actual value for a failing constraint test to a
/// MessageWriter. The default implementation simply writes
/// the raw value of actual, leaving it to the writer to
/// perform any formatting.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public virtual void WriteActualValueTo(MessageWriter writer)
{
writer.WriteActualValue(actual);
}
#endregion
#region ToString Override
/// <summary>
/// Default override of ToString returns the constraint DisplayName
/// followed by any arguments within angle brackets.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string rep = GetStringRepresentation();
return this.builder == null ? rep : string.Format("<unresolved {0}>", rep);
}
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
/// <returns></returns>
protected virtual string GetStringRepresentation()
{
switch (argcnt)
{
default:
case 0:
return string.Format("<{0}>", DisplayName);
case 1:
return string.Format("<{0} {1}>", DisplayName, _displayable(arg1));
case 2:
return string.Format("<{0} {1} {2}>", DisplayName, _displayable(arg1), _displayable(arg2));
}
}
private static string _displayable(object o)
{
if (o == null) return "null";
string fmt = o is string ? "\"{0}\"" : "{0}";
return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
}
#endregion
#region Operator Overloads
/// <summary>
/// This operator creates a constraint that is satisfied only if both
/// argument constraints are satisfied.
/// </summary>
public static Constraint operator &(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new AndConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if either
/// of the argument constraints is satisfied.
/// </summary>
public static Constraint operator |(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new OrConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if the
/// argument constraint is not satisfied.
/// </summary>
public static Constraint operator !(Constraint constraint)
{
IResolveConstraint r = constraint as IResolveConstraint;
return new NotConstraint(r == null ? new NullConstraint() : r.Resolve());
}
#endregion
#region Binary Operators
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression And
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new AndOperator());
return new ConstraintExpression(builder);
}
}
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression With
{
get { return this.And; }
}
/// <summary>
/// Returns a ConstraintExpression by appending Or
/// to the current constraint.
/// </summary>
public ConstraintExpression Or
{
get
{
ConstraintBuilder builder = this.builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new OrOperator());
return new ConstraintExpression(builder);
}
}
#endregion
#region After Modifier
#if !NUNITLITE && false
/// <summary>
/// Returns a DelayedConstraint with the specified delay time.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds)
{
return new DelayedConstraint(
builder == null ? this : builder.Resolve(),
delayInMilliseconds);
}
/// <summary>
/// Returns a DelayedConstraint with the specified delay time
/// and polling interval.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <param name="pollingInterval">The interval at which to test the constraint.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds, int pollingInterval)
{
return new DelayedConstraint(
builder == null ? this : builder.Resolve(),
delayInMilliseconds,
pollingInterval);
}
#endif
#endregion
#region IResolveConstraint Members
Constraint IResolveConstraint.Resolve()
{
return builder == null ? this : builder.Resolve();
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CustomLineCap.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Drawing.Drawing2D {
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Internal;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap"]/*' />
/// <devdoc>
/// Encapsulates a custom user-defined line
/// cap.
/// </devdoc>
public class CustomLineCap : MarshalByRefObject, ICloneable, IDisposable {
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
/*
* Handle to native line cap object
*/
internal SafeCustomLineCapHandle nativeCap = null;
private bool disposed = false;
// For subclass creation
internal CustomLineCap() {}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.CustomLineCap"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.CustomLineCap'/> class with the specified outline
/// and fill.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public CustomLineCap(GraphicsPath fillPath,
GraphicsPath strokePath) :
this(fillPath, strokePath, LineCap.Flat) {}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.CustomLineCap1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.CustomLineCap'/> class from the
/// specified existing <see cref='System.Drawing.Drawing2D.LineCap'/> with the specified outline and
/// fill.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public CustomLineCap(GraphicsPath fillPath,
GraphicsPath strokePath,
LineCap baseCap) :
this(fillPath, strokePath, baseCap, 0) {}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.CustomLineCap2"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Drawing2D.CustomLineCap'/> class from the
/// specified existing <see cref='System.Drawing.Drawing2D.LineCap'/> with the specified outline, fill, and
/// inset.
/// </para>
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public CustomLineCap(GraphicsPath fillPath,
GraphicsPath strokePath,
LineCap baseCap,
float baseInset)
{
IntPtr nativeLineCap = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateCustomLineCap(
new HandleRef(fillPath, (fillPath == null) ? IntPtr.Zero : fillPath.nativePath),
new HandleRef(strokePath, (strokePath == null) ? IntPtr.Zero : strokePath.nativePath),
baseCap, baseInset, out nativeLineCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
SetNativeLineCap(nativeLineCap);
}
internal CustomLineCap(IntPtr nativeLineCap)
{
SetNativeLineCap(nativeLineCap);
}
internal void SetNativeLineCap(IntPtr handle) {
if (handle == IntPtr.Zero)
throw new ArgumentNullException("handle");
nativeCap = new SafeCustomLineCapHandle(handle);
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.Dispose"]/*' />
/// <devdoc>
/// Cleans up Windows resources for this
/// <see cref='System.Drawing.Drawing2D.CustomLineCap'/>.
/// </devdoc>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.Dispose2"]/*' />
protected virtual void Dispose(bool disposing) {
if (disposed)
return;
#if FINALIZATION_WATCH
if (!disposing && nativeCap != null)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
// propagate the explicit dispose call to the child
if (disposing && nativeCap != null) {
nativeCap.Dispose();
}
disposed = true;
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.Finalize"]/*' />
/// <devdoc>
/// Cleans up Windows resources for this
/// <see cref='System.Drawing.Drawing2D.CustomLineCap'/>.
/// </devdoc>
~CustomLineCap() {
Dispose(false);
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.Clone"]/*' />
/// <devdoc>
/// Creates an exact copy of this <see cref='System.Drawing.Drawing2D.CustomLineCap'/>.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public object Clone()
{
IntPtr cloneCap = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneCustomLineCap(new HandleRef(this, nativeCap), out cloneCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return CustomLineCap.CreateCustomLineCapObject(cloneCap);
}
internal static CustomLineCap CreateCustomLineCapObject(IntPtr cap)
{
CustomLineCapType capType = 0;
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapType(new HandleRef(null, cap), out capType);
if (status != SafeNativeMethods.Gdip.Ok)
{
SafeNativeMethods.Gdip.GdipDeleteCustomLineCap(new HandleRef(null, cap));
throw SafeNativeMethods.Gdip.StatusException(status);
}
switch (capType)
{
case CustomLineCapType.Default:
return new CustomLineCap(cap);
case CustomLineCapType.AdjustableArrowCap:
return new AdjustableArrowCap(cap);
}
SafeNativeMethods.Gdip.GdipDeleteCustomLineCap(new HandleRef(null, cap));
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.NotImplemented);
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.SetStrokeCaps"]/*' />
/// <devdoc>
/// Sets the caps used to start and end lines.
/// </devdoc>
public void SetStrokeCaps(LineCap startCap, LineCap endCap)
{
int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapStrokeCaps(new HandleRef(this, nativeCap), startCap, endCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.GetStrokeCaps"]/*' />
/// <devdoc>
/// Gets the caps used to start and end lines.
/// </devdoc>
public void GetStrokeCaps(out LineCap startCap, out LineCap endCap)
{
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapStrokeCaps(new HandleRef(this, nativeCap), out startCap, out endCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private void _SetStrokeJoin(LineJoin lineJoin)
{
int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapStrokeJoin(new HandleRef(this, nativeCap), lineJoin);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private LineJoin _GetStrokeJoin()
{
LineJoin lineJoin;
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapStrokeJoin(new HandleRef(this, nativeCap), out lineJoin);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return lineJoin;
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.StrokeJoin"]/*' />
/// <devdoc>
/// Gets or sets the <see cref='System.Drawing.Drawing2D.LineJoin'/> used by this custom cap.
/// </devdoc>
public LineJoin StrokeJoin
{
get { return _GetStrokeJoin(); }
set { _SetStrokeJoin(value); }
}
private void _SetBaseCap(LineCap baseCap)
{
int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapBaseCap(new HandleRef(this, nativeCap), baseCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private LineCap _GetBaseCap()
{
LineCap baseCap;
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapBaseCap(new HandleRef(this, nativeCap), out baseCap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return baseCap;
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.BaseCap"]/*' />
/// <devdoc>
/// Gets or sets the <see cref='System.Drawing.Drawing2D.LineCap'/> on which this <see cref='System.Drawing.Drawing2D.CustomLineCap'/> is based.
/// </devdoc>
public LineCap BaseCap
{
get { return _GetBaseCap(); }
set { _SetBaseCap(value); }
}
private void _SetBaseInset(float inset)
{
int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapBaseInset(new HandleRef(this, nativeCap), inset);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private float _GetBaseInset()
{
float inset;
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapBaseInset(new HandleRef(this, nativeCap), out inset);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return inset;
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.BaseInset"]/*' />
/// <devdoc>
/// Gets or sets the distance between the cap
/// and the line.
/// </devdoc>
public float BaseInset
{
get { return _GetBaseInset(); }
set { _SetBaseInset(value); }
}
private void _SetWidthScale(float widthScale)
{
int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapWidthScale(new HandleRef(this, nativeCap), widthScale);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
private float _GetWidthScale()
{
float widthScale;
int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapWidthScale(new HandleRef(this, nativeCap), out widthScale);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return widthScale;
}
/// <include file='doc\CustomLineCap.uex' path='docs/doc[@for="CustomLineCap.WidthScale"]/*' />
/// <devdoc>
/// Gets or sets the amount by which to scale
/// the width of the cap.
/// </devdoc>
public float WidthScale
{
get { return _GetWidthScale(); }
set { _SetWidthScale(value); }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanInt32()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareGreaterThanInt32 testClass)
{
var result = Sse2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareGreaterThanInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__CompareGreaterThanInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareGreaterThan(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareGreaterThan(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareGreaterThanInt32();
var result = Sse2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareGreaterThanInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] > right[0]) ? unchecked((int)(-1)) : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] > right[i]) ? unchecked((int)(-1)) : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThan)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
/*
* $Id: InfTree.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
namespace Org.BouncyCastle.Utilities.Zlib
{
internal sealed class InflateTree
{
private const int MANY = 1440;
private const int fixed_bl = 9;
private const int fixed_bd = 5;
static readonly int[] fixed_tl = {
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,192,
80,7,10, 0,8,96, 0,8,32, 0,9,160,
0,8,0, 0,8,128, 0,8,64, 0,9,224,
80,7,6, 0,8,88, 0,8,24, 0,9,144,
83,7,59, 0,8,120, 0,8,56, 0,9,208,
81,7,17, 0,8,104, 0,8,40, 0,9,176,
0,8,8, 0,8,136, 0,8,72, 0,9,240,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,200,
81,7,13, 0,8,100, 0,8,36, 0,9,168,
0,8,4, 0,8,132, 0,8,68, 0,9,232,
80,7,8, 0,8,92, 0,8,28, 0,9,152,
84,7,83, 0,8,124, 0,8,60, 0,9,216,
82,7,23, 0,8,108, 0,8,44, 0,9,184,
0,8,12, 0,8,140, 0,8,76, 0,9,248,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,196,
81,7,11, 0,8,98, 0,8,34, 0,9,164,
0,8,2, 0,8,130, 0,8,66, 0,9,228,
80,7,7, 0,8,90, 0,8,26, 0,9,148,
84,7,67, 0,8,122, 0,8,58, 0,9,212,
82,7,19, 0,8,106, 0,8,42, 0,9,180,
0,8,10, 0,8,138, 0,8,74, 0,9,244,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,204,
81,7,15, 0,8,102, 0,8,38, 0,9,172,
0,8,6, 0,8,134, 0,8,70, 0,9,236,
80,7,9, 0,8,94, 0,8,30, 0,9,156,
84,7,99, 0,8,126, 0,8,62, 0,9,220,
82,7,27, 0,8,110, 0,8,46, 0,9,188,
0,8,14, 0,8,142, 0,8,78, 0,9,252,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,194,
80,7,10, 0,8,97, 0,8,33, 0,9,162,
0,8,1, 0,8,129, 0,8,65, 0,9,226,
80,7,6, 0,8,89, 0,8,25, 0,9,146,
83,7,59, 0,8,121, 0,8,57, 0,9,210,
81,7,17, 0,8,105, 0,8,41, 0,9,178,
0,8,9, 0,8,137, 0,8,73, 0,9,242,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,202,
81,7,13, 0,8,101, 0,8,37, 0,9,170,
0,8,5, 0,8,133, 0,8,69, 0,9,234,
80,7,8, 0,8,93, 0,8,29, 0,9,154,
84,7,83, 0,8,125, 0,8,61, 0,9,218,
82,7,23, 0,8,109, 0,8,45, 0,9,186,
0,8,13, 0,8,141, 0,8,77, 0,9,250,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,198,
81,7,11, 0,8,99, 0,8,35, 0,9,166,
0,8,3, 0,8,131, 0,8,67, 0,9,230,
80,7,7, 0,8,91, 0,8,27, 0,9,150,
84,7,67, 0,8,123, 0,8,59, 0,9,214,
82,7,19, 0,8,107, 0,8,43, 0,9,182,
0,8,11, 0,8,139, 0,8,75, 0,9,246,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,206,
81,7,15, 0,8,103, 0,8,39, 0,9,174,
0,8,7, 0,8,135, 0,8,71, 0,9,238,
80,7,9, 0,8,95, 0,8,31, 0,9,158,
84,7,99, 0,8,127, 0,8,63, 0,9,222,
82,7,27, 0,8,111, 0,8,47, 0,9,190,
0,8,15, 0,8,143, 0,8,79, 0,9,254,
96,7,256, 0,8,80, 0,8,16, 84,8,115,
82,7,31, 0,8,112, 0,8,48, 0,9,193,
80,7,10, 0,8,96, 0,8,32, 0,9,161,
0,8,0, 0,8,128, 0,8,64, 0,9,225,
80,7,6, 0,8,88, 0,8,24, 0,9,145,
83,7,59, 0,8,120, 0,8,56, 0,9,209,
81,7,17, 0,8,104, 0,8,40, 0,9,177,
0,8,8, 0,8,136, 0,8,72, 0,9,241,
80,7,4, 0,8,84, 0,8,20, 85,8,227,
83,7,43, 0,8,116, 0,8,52, 0,9,201,
81,7,13, 0,8,100, 0,8,36, 0,9,169,
0,8,4, 0,8,132, 0,8,68, 0,9,233,
80,7,8, 0,8,92, 0,8,28, 0,9,153,
84,7,83, 0,8,124, 0,8,60, 0,9,217,
82,7,23, 0,8,108, 0,8,44, 0,9,185,
0,8,12, 0,8,140, 0,8,76, 0,9,249,
80,7,3, 0,8,82, 0,8,18, 85,8,163,
83,7,35, 0,8,114, 0,8,50, 0,9,197,
81,7,11, 0,8,98, 0,8,34, 0,9,165,
0,8,2, 0,8,130, 0,8,66, 0,9,229,
80,7,7, 0,8,90, 0,8,26, 0,9,149,
84,7,67, 0,8,122, 0,8,58, 0,9,213,
82,7,19, 0,8,106, 0,8,42, 0,9,181,
0,8,10, 0,8,138, 0,8,74, 0,9,245,
80,7,5, 0,8,86, 0,8,22, 192,8,0,
83,7,51, 0,8,118, 0,8,54, 0,9,205,
81,7,15, 0,8,102, 0,8,38, 0,9,173,
0,8,6, 0,8,134, 0,8,70, 0,9,237,
80,7,9, 0,8,94, 0,8,30, 0,9,157,
84,7,99, 0,8,126, 0,8,62, 0,9,221,
82,7,27, 0,8,110, 0,8,46, 0,9,189,
0,8,14, 0,8,142, 0,8,78, 0,9,253,
96,7,256, 0,8,81, 0,8,17, 85,8,131,
82,7,31, 0,8,113, 0,8,49, 0,9,195,
80,7,10, 0,8,97, 0,8,33, 0,9,163,
0,8,1, 0,8,129, 0,8,65, 0,9,227,
80,7,6, 0,8,89, 0,8,25, 0,9,147,
83,7,59, 0,8,121, 0,8,57, 0,9,211,
81,7,17, 0,8,105, 0,8,41, 0,9,179,
0,8,9, 0,8,137, 0,8,73, 0,9,243,
80,7,4, 0,8,85, 0,8,21, 80,8,258,
83,7,43, 0,8,117, 0,8,53, 0,9,203,
81,7,13, 0,8,101, 0,8,37, 0,9,171,
0,8,5, 0,8,133, 0,8,69, 0,9,235,
80,7,8, 0,8,93, 0,8,29, 0,9,155,
84,7,83, 0,8,125, 0,8,61, 0,9,219,
82,7,23, 0,8,109, 0,8,45, 0,9,187,
0,8,13, 0,8,141, 0,8,77, 0,9,251,
80,7,3, 0,8,83, 0,8,19, 85,8,195,
83,7,35, 0,8,115, 0,8,51, 0,9,199,
81,7,11, 0,8,99, 0,8,35, 0,9,167,
0,8,3, 0,8,131, 0,8,67, 0,9,231,
80,7,7, 0,8,91, 0,8,27, 0,9,151,
84,7,67, 0,8,123, 0,8,59, 0,9,215,
82,7,19, 0,8,107, 0,8,43, 0,9,183,
0,8,11, 0,8,139, 0,8,75, 0,9,247,
80,7,5, 0,8,87, 0,8,23, 192,8,0,
83,7,51, 0,8,119, 0,8,55, 0,9,207,
81,7,15, 0,8,103, 0,8,39, 0,9,175,
0,8,7, 0,8,135, 0,8,71, 0,9,239,
80,7,9, 0,8,95, 0,8,31, 0,9,159,
84,7,99, 0,8,127, 0,8,63, 0,9,223,
82,7,27, 0,8,111, 0,8,47, 0,9,191,
0,8,15, 0,8,143, 0,8,79, 0,9,255
};
static readonly int[] fixed_td = {
80,5,1, 87,5,257, 83,5,17, 91,5,4097,
81,5,5, 89,5,1025, 85,5,65, 93,5,16385,
80,5,3, 88,5,513, 84,5,33, 92,5,8193,
82,5,9, 90,5,2049, 86,5,129, 192,5,24577,
80,5,2, 87,5,385, 83,5,25, 91,5,6145,
81,5,7, 89,5,1537, 85,5,97, 93,5,24577,
80,5,4, 88,5,769, 84,5,49, 92,5,12289,
82,5,13, 90,5,3073, 86,5,193, 192,5,24577
};
// Tables for deflate from PKZIP's appnote.txt.
static readonly int[] cplens = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
// see note #13 above about 258
static readonly int[] cplext = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112 // 112==invalid
};
static readonly int[] cpdist = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577
};
static readonly int[] cpdext = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
const int BMAX = 15; // maximum bit length of any code
int[] hn = null; // hufts used in space
int[] v = null; // work area for huft_build
int[] c = null; // bit length count table
int[] r = null; // table entry for structure assignment
int[] u = null; // table stack
int[] x = null; // bit offsets, then code stack
private ZLibStatus HuftBuild(int[] b, // code lengths in bits (all assumed <= BMAX)
int bindex,
int n, // number of codes (assumed <= 288)
int s, // number of simple-valued codes (0..s-1)
int[] d, // list of base values for non-simple codes
int[] e, // list of extra bits for non-simple codes
int[] t, // result: starting table
int[] m, // maximum lookup bits, returns actual
int[] hp,// space for trees
int[] hn,// hufts used in space
int[] v // working area: values in order of bit length
)
{
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in this
// case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
// lengths), or Z_MEM_ERROR if not enough memory.
int a; // counter for codes of length k
int f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
int i; // counter, current code
int j; // counter
int k; // number of bits in current code
int l; // bits per table (returned in m)
int mask; // (1 << w) - 1, to avoid cc -O bug on HP
int p; // pointer into c[], b[], or v[]
int q; // points to current table
int w; // bits before this table == (l * h)
int xp; // pointer into x
int y; // number of dummy codes added
int z; // number of entries in current table
// Generate counts for each bit length
p = 0; i = n;
do
{
c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX
} while (i != 0);
if (c[0] == n)
{ // null input--all zero length codes
t[0] = -1;
m[0] = 0;
return ZLibStatus.Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = m[0];
for (j = 1; j <= BMAX; j++)
if (c[j] != 0) break;
k = j; // minimum code length
if (l < j)
{
l = j;
}
for (i = BMAX; i != 0; i--)
{
if (c[i] != 0) break;
}
g = i; // maximum code length
if (l > i)
{
l = i;
}
m[0] = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1)
{
if ((y -= c[j]) < 0)
{
return ZLibStatus.Z_DATA_ERROR;
}
}
if ((y -= c[i]) < 0)
{
return ZLibStatus.Z_DATA_ERROR;
}
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = 1; xp = 2;
while (--i != 0)
{ // note that i == g from above
x[xp] = (j += c[p]);
xp++;
p++;
}
// Make a table of values in order of bit lengths
i = 0; p = 0;
do
{
if ((j = b[bindex + p]) != 0)
{
v[x[j]++] = i;
}
p++;
}
while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = 0; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = 0; // just to keep compilers happy
q = 0; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++)
{
a = c[k];
while (a-- != 0)
{
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l)
{
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = (z > l) ? l : z; // table size upper limit
if ((f = 1 << (j = k - w)) > a + 1)
{ // try a k-w bit table
// too few codes for k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = k;
if (j < z)
{
while (++j < z)
{ // try smaller tables up to z bits
if ((f <<= 1) <= c[++xp])
break; // enough codes to use up j bits
f -= c[xp]; // else deduct codes from patterns
}
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (hn[0] + z > MANY)
{ // (note: doesn't matter for fixed)
return ZLibStatus.Z_DATA_ERROR; // overflow of MANY
}
u[h] = q = /*hp+*/ hn[0]; // DEBUG
hn[0] += z;
// connect to last table, if there is one
if (h != 0)
{
x[h] = i; // save pattern for backing up
r[0] = (byte)j; // bits in this table
r[1] = (byte)l; // bits to dump before this table
j = i >> (w - l);
r[2] = (int)(q - u[h - 1] - j); // offset to this table
System.Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table
}
else
{
t[0] = q; // first table is returned result
}
}
// set up table entry in r
r[1] = (byte)(k - w);
if (p >= n)
{
r[0] = 128 + 64; // out of values--invalid code
}
else if (v[p] < s)
{
r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is end-of-block
r[2] = v[p++]; // simple code is just the value
}
else
{
r[0] = (byte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists
r[2] = d[v[p++] - s];
}
// fill code-like entries with r
f = 1 << (k - w);
for (j = i >> w; j < z; j += f)
{
System.Array.Copy(r, 0, hp, (q + j) * 3, 3);
}
// backwards increment the k-bit code i
for (j = 1 << (k - 1); (i & j) != 0; j >>= 1)
{
i ^= j;
}
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h])
{
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? ZLibStatus.Z_BUF_ERROR : ZLibStatus.Z_OK;
}
internal ZLibStatus InflateTreesBits(int[] c, // 19 code lengths
int[] bb, // bits tree desired/actual depth
int[] tb, // bits tree result
int[] hp, // space for trees
ICompressor z // for messages
)
{
ZLibStatus result;
InitWorkArea(19);
hn[0] = 0;
result = HuftBuild(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
if (result == ZLibStatus.Z_DATA_ERROR)
{
z.msg = "oversubscribed dynamic bit lengths tree";
}
else if (result == ZLibStatus.Z_BUF_ERROR || bb[0] == 0)
{
z.msg = "incomplete dynamic bit lengths tree";
result = ZLibStatus.Z_DATA_ERROR;
}
return result;
}
internal ZLibStatus InflateTreesDynamic(int nl, // number of literal/length codes
int nd, // number of distance codes
int[] c, // that many (total) code lengths
int[] bl, // literal desired/actual bit depth
int[] bd, // distance desired/actual bit depth
int[] tl, // literal/length tree result
int[] td, // distance tree result
int[] hp, // space for trees
ICompressor z // for messages
)
{
ZLibStatus result;
// build literal/length tree
InitWorkArea(288);
hn[0] = 0;
result = HuftBuild(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
if (result != ZLibStatus.Z_OK || bl[0] == 0)
{
if (result == ZLibStatus.Z_DATA_ERROR)
{
z.msg = "oversubscribed literal/length tree";
}
else if (result != ZLibStatus.Z_MEM_ERROR)
{
z.msg = "incomplete literal/length tree";
result = ZLibStatus.Z_DATA_ERROR;
}
return result;
}
// build distance tree
InitWorkArea(288);
result = HuftBuild(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
if (result != ZLibStatus.Z_OK || (bd[0] == 0 && nl > 257))
{
if (result == ZLibStatus.Z_DATA_ERROR)
{
z.msg = "oversubscribed distance tree";
}
else if (result == ZLibStatus.Z_BUF_ERROR)
{
z.msg = "incomplete distance tree";
result = ZLibStatus.Z_DATA_ERROR;
}
else if (result != ZLibStatus.Z_MEM_ERROR)
{
z.msg = "empty distance tree with lengths";
result = ZLibStatus.Z_DATA_ERROR;
}
return result;
}
return ZLibStatus.Z_OK;
}
internal static ZLibStatus InflateTreesFixed(int[] bl, //literal desired/actual bit depth
int[] bd, //distance desired/actual bit depth
int[][] tl,//literal/length tree result
int[][] td,//distance tree result
ICompressor z //for memory allocation
)
{
bl[0] = fixed_bl;
bd[0] = fixed_bd;
tl[0] = fixed_tl;
td[0] = fixed_td;
return ZLibStatus.Z_OK;
}
private void InitWorkArea(int vsize)
{
if (hn == null)
{
hn = new int[1];
v = new int[vsize];
c = new int[BMAX + 1];
r = new int[3];
u = new int[BMAX];
x = new int[BMAX + 1];
}
if (v.Length < vsize) { v = new int[vsize]; }
for (int i = 0; i < vsize; i++) { v[i] = 0; }
for (int i = 0; i < BMAX + 1; i++) { c[i] = 0; }
for (int i = 0; i < 3; i++) { r[i] = 0; }
// for(int i=0; i<BMAX; i++){u[i]=0;}
System.Array.Copy(c, 0, u, 0, BMAX);
// for(int i=0; i<BMAX+1; i++){x[i]=0;}
System.Array.Copy(c, 0, x, 0, BMAX + 1);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using CoreTweet.Core;
namespace CoreTweet
{
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for sending a request to Twitter and some other web services.
/// </summary>
internal static partial class Request
{
private static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> prm)
{
return prm.Select(x => UrlEncode(x.Key) + "=" + UrlEncode(x.Value)).JoinToString("&");
}
internal static string CreateQueryString(IEnumerable<KeyValuePair<string, object>> prm)
{
return CreateQueryString(prm.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())));
}
#if !WIN_RT
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm)
{
const int bufferSize = 81920;
foreach(var x in prm)
{
var valueStream = x.Value as Stream;
var valueArraySegment = x.Value as ArraySegment<byte>?;
var valueBytes = x.Value as IEnumerable<byte>;
#if !PCL
var valueFile = x.Value as FileInfo;
#endif
var valueString = x.Value.ToString();
#if WP
var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream;
if(valueInputStream != null) valueStream = valueInputStream.AsStreamForRead();
#endif
stream.WriteString("--" + boundary + "\r\n");
if(valueStream != null || valueBytes != null || valueArraySegment != null
#if !PCL
|| valueFile != null
#endif
)
{
stream.WriteString("Content-Type: application/octet-stream\r\n");
}
stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key));
#if !PCL
if(valueFile != null)
stream.WriteString(string.Format(@"; filename=""{0}""",
valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22")));
else
#endif
if(valueStream != null || valueBytes != null || valueArraySegment != null)
stream.WriteString(@"; filename=""file""");
stream.WriteString("\r\n\r\n");
#if !PCL
if(valueFile != null)
valueStream = valueFile.OpenRead();
#endif
if(valueStream != null)
{
var buffer = new byte[bufferSize];
int count;
while((count = valueStream.Read(buffer, 0, bufferSize)) > 0)
stream.Write(buffer, 0, count);
}
else if(valueArraySegment != null)
{
stream.Write(valueArraySegment.Value.Array, valueArraySegment.Value.Offset, valueArraySegment.Value.Count);
}
else if(valueBytes != null)
{
var buffer = valueBytes as byte[];
if(buffer != null)
stream.Write(buffer, 0, buffer.Length);
else
{
buffer = new byte[bufferSize];
var i = 0;
foreach(var b in valueBytes)
{
buffer[i++] = b;
if(i == bufferSize)
{
stream.Write(buffer, 0, bufferSize);
i = 0;
}
}
if(i > 0)
stream.Write(buffer, 0, i);
}
}
else
stream.WriteString(valueString);
#if !PCL
if(valueFile != null)
valueStream.Close();
#endif
stream.WriteString("\r\n");
}
stream.WriteString("--" + boundary + "--");
}
#endif
#if !WP
private const DecompressionMethods CompressionType = DecompressionMethods.GZip | DecompressionMethods.Deflate;
#endif
#if !ASYNC_ONLY
internal static HttpWebResponse HttpGet(Uri url, string authorizationHeader, ConnectionOptions options)
{
if(options == null) options = new ConnectionOptions();
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
return (HttpWebResponse)req.GetResponse();
}
internal static HttpWebResponse HttpPost(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(prm == null) prm = new Dictionary<string,object>();
if(options == null) options = new ConnectionOptions();
var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
using(var reqstr = req.GetRequestStream())
reqstr.Write(data, 0, data.Length);
return (HttpWebResponse)req.GetResponse();
}
internal static HttpWebResponse HttpPostWithMultipartFormData(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(options == null) options = new ConnectionOptions();
var boundary = Guid.NewGuid().ToString();
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.ContentType = "multipart/form-data;boundary=" + boundary;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
req.SendChunked = true;
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
using(var reqstr = req.GetRequestStream())
WriteMultipartFormData(reqstr, boundary, prm);
return (HttpWebResponse)req.GetResponse();
}
#endif
/// <summary>
/// Generates the signature.
/// </summary>
/// <param name="t">The tokens.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="url">The URL.</param>
/// <param name="prm">The parameters.</param>
/// <returns>The signature.</returns>
internal static string GenerateSignature(Tokens t, MethodType httpMethod, Uri url, IEnumerable<KeyValuePair<string, string>> prm)
{
var key = Encoding.UTF8.GetBytes(
string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret),
UrlEncode(t.AccessTokenSecret)));
var prmstr = prm.Select(x => new KeyValuePair<string, string>(UrlEncode(x.Key), UrlEncode(x.Value)))
.Concat(
url.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var s = x.Split('=');
return new KeyValuePair<string, string>(s[0], s[1]);
})
)
.OrderBy(x => x.Key).ThenBy(x => x.Value)
.Select(x => x.Key + "=" + x.Value)
.JoinToString("&");
var msg = Encoding.UTF8.GetBytes(
string.Format("{0}&{1}&{2}",
httpMethod.ToString().ToUpperInvariant(),
UrlEncode(url.GetComponents(UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped)),
UrlEncode(prmstr)
));
return Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg));
}
/// <summary>
/// Generates the parameters.
/// </summary>
/// <param name="consumerKey">The consumer key.</param>
/// <param name="token">The token.</param>
/// <returns>The parameters.</returns>
internal static Dictionary<string, string> GenerateParameters(string consumerKey, string token)
{
var ret = new Dictionary<string, string>() {
{"oauth_consumer_key", consumerKey},
{"oauth_signature_method", "HMAC-SHA1"},
{"oauth_timestamp", ((DateTimeOffset.UtcNow - InternalUtils.unixEpoch).Ticks / 10000000L).ToString("D")},
{"oauth_nonce", new Random().Next(int.MinValue, int.MaxValue).ToString("X")},
{"oauth_version", "1.0"}
};
if(!string.IsNullOrEmpty(token))
ret.Add("oauth_token", token);
return ret;
}
/// <summary>
/// Encodes the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The encoded text.</returns>
internal static string UrlEncode(string text)
{
if(string.IsNullOrEmpty(text))
return "";
return Encoding.UTF8.GetBytes(text)
.Select(x => x < 0x80 && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
.Contains(((char)x).ToString()) ? ((char)x).ToString() : ('%' + x.ToString("X2")))
.JoinToString();
}
}
}
| |
// 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.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using ProtocolFamily = System.Net.Internals.ProtocolFamily;
namespace System.Net
{
internal static partial class NameResolutionPal
{
//
// used by GetHostName() to preallocate a buffer for the call to gethostname.
//
private const int HostNameBufferLength = 256;
private static bool s_initialized;
private static readonly object s_initializedLock = new object();
private static readonly unsafe Interop.Winsock.LPLOOKUPSERVICE_COMPLETION_ROUTINE s_getAddrInfoExCallback = GetAddressInfoExCallback;
private static bool s_getAddrInfoExSupported;
public static bool SupportsGetAddrInfoAsync
{
get
{
EnsureSocketsAreInitialized();
return s_getAddrInfoExSupported;
}
}
/*++
Routine Description:
Takes a native pointer (expressed as an int) to a hostent structure,
and converts the information in their to an IPHostEntry class. This
involves walking through an array of native pointers, and a temporary
ArrayList object is used in doing this.
Arguments:
nativePointer - Native pointer to hostent structure.
Return Value:
An IPHostEntry structure.
--*/
private static IPHostEntry NativeToHostEntry(IntPtr nativePointer)
{
//
// marshal pointer to struct
//
hostent Host = Marshal.PtrToStructure<hostent>(nativePointer);
IPHostEntry HostEntry = new IPHostEntry();
if (Host.h_name != IntPtr.Zero)
{
HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"HostEntry.HostName: {HostEntry.HostName}");
}
// decode h_addr_list to ArrayList of IP addresses.
// The h_addr_list field is really a pointer to an array of pointers
// to IP addresses. Loop through the array, and while the pointer
// isn't NULL read the IP address, convert it to an IPAddress class,
// and add it to the list.
var TempIPAddressList = new List<IPAddress>();
int IPAddressToAdd;
string AliasToAdd;
IntPtr currentArrayElement;
//
// get the first pointer in the array
//
currentArrayElement = Host.h_addr_list;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero)
{
//
// if it's not null it points to an IPAddress,
// read it...
//
IPAddressToAdd = Marshal.ReadInt32(nativePointer);
#if BIGENDIAN
// IP addresses from native code are always a byte array
// converted to int. We need to convert the address into
// a uniform integer value.
IPAddressToAdd = (int)(((uint)IPAddressToAdd << 24) |
(((uint)IPAddressToAdd & 0x0000FF00) << 8) |
(((uint)IPAddressToAdd >> 8) & 0x0000FF00) |
((uint)IPAddressToAdd >> 24));
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer} IPAddressToAdd:{IPAddressToAdd}");
//
// ...and add it to the list
//
TempIPAddressList.Add(new IPAddress((long)IPAddressToAdd & 0x0FFFFFFFF));
//
// now get the next pointer in the array and start over
//
currentArrayElement = currentArrayElement + IntPtr.Size;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.AddressList = TempIPAddressList.ToArray();
//
// Now do the same thing for the aliases.
//
var TempAliasList = new List<string>();
currentArrayElement = Host.h_aliases;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"currentArrayElement:{currentArrayElement} nativePointer:{nativePointer}");
//
// if it's not null it points to an Alias,
// read it...
//
AliasToAdd = Marshal.PtrToStringAnsi(nativePointer);
//
// ...and add it to the list
//
TempAliasList.Add(AliasToAdd);
//
// now get the next pointer in the array and start over
//
currentArrayElement = currentArrayElement + IntPtr.Size;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.Aliases = TempAliasList.ToArray();
return HostEntry;
} // NativeToHostEntry
public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
{
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
SafeFreeAddrInfo root = null;
var addresses = new List<IPAddress>();
string canonicalname = null;
AddressInfo hints = new AddressInfo();
hints.ai_flags = AddressInfoHints.AI_CANONNAME;
hints.ai_family = AddressFamily.Unspecified; // gets all address families
nativeErrorCode = 0;
//
// Use try / finally so we always get a shot at freeaddrinfo
//
try
{
SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root);
if (errorCode != SocketError.Success)
{ // Should not throw, return mostly blank hostentry
hostinfo = NameResolutionUtilities.GetUnresolvedAnswer(name);
return errorCode;
}
AddressInfo* pAddressInfo = (AddressInfo*)root.DangerousGetHandle();
//
// Process the results
//
while (pAddressInfo != null)
{
//
// Retrieve the canonical name for the host - only appears in the first AddressInfo
// entry in the returned array.
//
if (canonicalname == null && pAddressInfo->ai_canonname != null)
{
canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname);
}
//
// Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll
// ever get any other address families, but better to be safe than sorry.
// We also filter based on whether IPv6 is supported on the current
// platform / machine.
//
var socketAddress = new ReadOnlySpan<byte>(pAddressInfo->ai_addr, pAddressInfo->ai_addrlen);
if (pAddressInfo->ai_family == AddressFamily.InterNetwork)
{
if (socketAddress.Length == SocketAddressPal.IPv4AddressSize)
addresses.Add(CreateIPv4Address(socketAddress));
}
else if (pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && SocketProtocolSupportPal.OSSupportsIPv6)
{
if (socketAddress.Length == SocketAddressPal.IPv6AddressSize)
addresses.Add(CreateIPv6Address(socketAddress));
}
//
// Next addressinfo entry
//
pAddressInfo = pAddressInfo->ai_next;
}
}
finally
{
if (root != null)
{
root.Dispose();
}
}
//
// Finally, put together the IPHostEntry
//
hostinfo = new IPHostEntry();
hostinfo.HostName = canonicalname != null ? canonicalname : name;
hostinfo.Aliases = Array.Empty<string>();
hostinfo.AddressList = addresses.ToArray();
return SocketError.Success;
}
public static string TryGetNameInfo(IPAddress addr, out SocketError errorCode, out int nativeErrorCode)
{
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
SocketAddress address = (new IPEndPoint(addr, 0)).Serialize();
StringBuilder hostname = new StringBuilder(1025); // NI_MAXHOST
int flags = (int)Interop.Winsock.NameInfoFlags.NI_NAMEREQD;
nativeErrorCode = 0;
byte[] addressBuffer = new byte[address.Size];
for (int i = 0; i < address.Size; i++)
{
addressBuffer[i] = address[i];
}
errorCode =
Interop.Winsock.GetNameInfoW(
addressBuffer,
address.Size,
hostname,
hostname.Capacity,
null, // We don't want a service name
0, // so no need for buffer or length
flags);
if (errorCode != SocketError.Success)
{
return null;
}
return hostname.ToString();
}
public static unsafe string GetHostName()
{
//
// note that we could cache the result ourselves since you
// wouldn't expect the hostname of the machine to change during
// execution, but this might still happen and we would want to
// react to that change.
//
byte* buffer = stackalloc byte[HostNameBufferLength];
if (Interop.Winsock.gethostname(buffer, HostNameBufferLength) != SocketError.Success)
{
throw new SocketException();
}
return new string((sbyte*)buffer);
}
public static void EnsureSocketsAreInitialized()
{
if (!Volatile.Read(ref s_initialized))
{
lock (s_initializedLock)
{
if (!s_initialized)
{
Interop.Winsock.WSAData wsaData = new Interop.Winsock.WSAData();
SocketError errorCode =
Interop.Winsock.WSAStartup(
(short)0x0202, // we need 2.2
out wsaData);
if (errorCode != SocketError.Success)
{
//
// failed to initialize, throw
//
// WSAStartup does not set LastWin32Error
throw new SocketException((int)errorCode);
}
s_getAddrInfoExSupported = GetAddrInfoExSupportsOverlapped();
Volatile.Write(ref s_initialized, true);
}
}
}
}
public static unsafe void GetAddrInfoAsync(DnsResolveAsyncResult asyncResult)
{
GetAddrInfoExContext* context = GetAddrInfoExContext.AllocateContext();
try
{
var state = new GetAddrInfoExState(asyncResult);
context->QueryStateHandle = state.CreateHandle();
}
catch
{
GetAddrInfoExContext.FreeContext(context);
throw;
}
AddressInfoEx hints = new AddressInfoEx();
hints.ai_flags = AddressInfoHints.AI_CANONNAME;
hints.ai_family = AddressFamily.Unspecified; // Gets all address families
SocketError errorCode =
(SocketError)Interop.Winsock.GetAddrInfoExW(asyncResult.HostName, null, 0 /* NS_ALL*/, IntPtr.Zero, ref hints, out context->Result, IntPtr.Zero, ref context->Overlapped, s_getAddrInfoExCallback, out context->CancelHandle);
if (errorCode != SocketError.IOPending)
ProcessResult(errorCode, context);
}
private static unsafe void GetAddressInfoExCallback([In] int error, [In] int bytes, [In] NativeOverlapped* overlapped)
{
// Can be casted directly to GetAddrInfoExContext* because the overlapped is its first field
GetAddrInfoExContext* context = (GetAddrInfoExContext*)overlapped;
ProcessResult((SocketError)error, context);
}
private static unsafe void ProcessResult(SocketError errorCode, GetAddrInfoExContext* context)
{
try
{
GetAddrInfoExState state = GetAddrInfoExState.FromHandleAndFree(context->QueryStateHandle);
if (errorCode != SocketError.Success)
{
state.CompleteAsyncResult(new SocketException((int)errorCode));
return;
}
AddressInfoEx* result = context->Result;
string canonicalName = null;
List<IPAddress> addresses = new List<IPAddress>();
while (result != null)
{
if (canonicalName == null && result->ai_canonname != IntPtr.Zero)
canonicalName = Marshal.PtrToStringUni(result->ai_canonname);
var socketAddress = new ReadOnlySpan<byte>(result->ai_addr, result->ai_addrlen);
if (result->ai_family == AddressFamily.InterNetwork)
{
if (socketAddress.Length == SocketAddressPal.IPv4AddressSize)
addresses.Add(CreateIPv4Address(socketAddress));
}
else if (SocketProtocolSupportPal.OSSupportsIPv6 && result->ai_family == AddressFamily.InterNetworkV6)
{
if (socketAddress.Length == SocketAddressPal.IPv6AddressSize)
addresses.Add(CreateIPv6Address(socketAddress));
}
result = result->ai_next;
}
if (canonicalName == null)
canonicalName = state.HostName;
state.CompleteAsyncResult(new IPHostEntry
{
HostName = canonicalName,
Aliases = Array.Empty<string>(),
AddressList = addresses.ToArray()
});
}
finally
{
GetAddrInfoExContext.FreeContext(context);
}
}
private static unsafe IPAddress CreateIPv4Address(ReadOnlySpan<byte> socketAddress)
{
long address = (long)SocketAddressPal.GetIPv4Address(socketAddress) & 0x0FFFFFFFF;
return new IPAddress(address);
}
private static unsafe IPAddress CreateIPv6Address(ReadOnlySpan<byte> socketAddress)
{
Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
SocketAddressPal.GetIPv6Address(socketAddress, address, out scope);
return new IPAddress(address, (long)scope);
}
#region GetAddrInfoAsync Helper Classes
//
// Warning: If this ever ported to NETFX, AppDomain unloads needs to be handled
// to protect against AppDomainUnloadException if there are pending operations.
//
private sealed class GetAddrInfoExState
{
private DnsResolveAsyncResult _asyncResult;
private object _result;
public string HostName => _asyncResult.HostName;
public GetAddrInfoExState(DnsResolveAsyncResult asyncResult)
{
_asyncResult = asyncResult;
}
public void CompleteAsyncResult(object o)
{
// We don't want to expose the GetAddrInfoEx callback thread to user code.
// The callback occurs in a native windows thread pool.
_result = o;
Task.Factory.StartNew(s =>
{
var self = (GetAddrInfoExState)s;
self._asyncResult.InvokeCallback(self._result);
}, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public IntPtr CreateHandle()
{
GCHandle handle = GCHandle.Alloc(this, GCHandleType.Normal);
return GCHandle.ToIntPtr(handle);
}
public static GetAddrInfoExState FromHandleAndFree(IntPtr handle)
{
GCHandle gcHandle = GCHandle.FromIntPtr(handle);
var state = (GetAddrInfoExState)gcHandle.Target;
gcHandle.Free();
return state;
}
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct GetAddrInfoExContext
{
public NativeOverlapped Overlapped;
public AddressInfoEx* Result;
public IntPtr CancelHandle;
public IntPtr QueryStateHandle;
public static GetAddrInfoExContext* AllocateContext()
{
var context = (GetAddrInfoExContext*)Marshal.AllocHGlobal(sizeof(GetAddrInfoExContext));
*context = default;
return context;
}
public static void FreeContext(GetAddrInfoExContext* context)
{
if (context->Result != null)
Interop.Winsock.FreeAddrInfoExW(context->Result);
Marshal.FreeHGlobal((IntPtr)context);
}
}
#endregion
}
}
| |
using JoinRpg.DataModel;
using JoinRpg.DataModel.Mocks;
using JoinRpg.Domain;
using JoinRpg.Web.Models;
using Shouldly;
using Xunit;
namespace JoinRpg.Web.Test
{
public class CustomFieldsViewModelTest
{
private static MockedProject Mock { get; } = new MockedProject();
[Fact]
public void HideMasterOnlyFieldOnAddClaimTest()
{
var vm = new CustomFieldsViewModel(Mock.Player.UserId, Mock.Group);
(vm.FieldById(Mock.MasterOnlyField.ProjectFieldId)?.CanView ?? false).ShouldBeFalse();
}
[Fact]
public void HideUnApprovedFieldOnAddClaimTest()
{
var vm = new CustomFieldsViewModel(Mock.Player.UserId, Mock.Group);
(vm.FieldById(Mock.HideForUnApprovedClaim.ProjectFieldId)?.CanView ?? false).ShouldBeFalse();
}
[Fact]
public void ShowPublicFieldToAnon()
{
MockedProject.AssignFieldValues(Mock.Character,
new FieldWithValue(Mock.PublicField, "1"));
var vm = new CustomFieldsViewModel(currentUserId: null, character: Mock.Character);
var publicField = vm.FieldById(Mock.PublicField.ProjectFieldId);
_ = publicField.ShouldNotBeNull();
publicField.CanView.ShouldBeTrue();
_ = publicField.Value.ShouldNotBeNull();
}
[Fact]
public void ShowPublicFieldToAnonEvenIfEditDisabled()
{
MockedProject.AssignFieldValues(Mock.Character, new FieldWithValue(Mock.PublicField, "1"));
var vm = new CustomFieldsViewModel(currentUserId: null, character: Mock.Character, disableEdit: true);
var publicField = vm.FieldById(Mock.PublicField.ProjectFieldId);
_ = publicField.ShouldNotBeNull();
publicField.CanView.ShouldBeTrue();
}
[Fact]
public void AllowCharactersFieldOnAddClaimTest()
{
var vm = new CustomFieldsViewModel(Mock.Player.UserId, (IClaimSource)Mock.Character);
var characterField = vm.FieldById(Mock.CharacterField.ProjectFieldId);
_ = characterField.ShouldNotBeNull();
characterField.CanView.ShouldBeFalse();
characterField.Value.ShouldBeNull();
characterField.CanEdit.ShouldBeTrue();
}
[Fact]
public void AllowShadowCharacterFieldsTest()
{
var mock = new MockedProject();
var claim = mock.CreateClaim(mock.Character, mock.Player);
MockedProject.AssignFieldValues(claim, new FieldWithValue(mock.CharacterField, "test"));
var vm = new CustomFieldsViewModel(mock.Player.UserId, claim);
var characterField = vm.FieldById(mock.CharacterField.ProjectFieldId);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.Value.ShouldBe("test");
characterField.ShouldBeEditable();
}
[Fact]
public void DoNotDiscloseOriginalFieldValuesTest()
{
var mock = new MockedProject();
var claim = mock.CreateClaim(mock.Character, mock.Player);
var vm = new CustomFieldsViewModel(mock.Player.UserId, claim);
var characterField = vm.Field(mock.CharacterField);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.ShouldNotHaveValue();
characterField.ShouldBeEditable();
}
[Fact]
public void DoNotDiscloseOriginalFieldValuesOnAddTest()
{
var mock = new MockedProject();
var vm = new CustomFieldsViewModel(mock.Player.UserId, (IClaimSource)mock.Character);
var characterField = vm.Field(mock.CharacterField);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.ShouldNotHaveValue();
characterField.ShouldBeEditable();
}
[Fact]
public void AllowCharactersFieldOnAddClaimForCharacterTest()
{
var vm = new CustomFieldsViewModel(Mock.Player.UserId, (IClaimSource)Mock.Character);
var characterField = vm.Field(Mock.CharacterField);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.ShouldNotHaveValue();
characterField.ShouldBeEditable();
}
[Fact]
public void ProperlyHideConditionalHeader()
{
var conditionalHeader = Mock.CreateConditionalHeader();
var claim = Mock.CreateApprovedClaim(Mock.CharacterWithoutGroup, Mock.Player);
var vm = new CustomFieldsViewModel(Mock.Player.UserId, claim);
var characterField = vm.FieldById(conditionalHeader.ProjectFieldId);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.ShouldNotHaveValue();
characterField.ShouldBeReadonly();
}
[Fact]
public void ProperlyShowConditionalHeaderTest()
{
var conditionalHeader = Mock.CreateConditionalHeader();
var claim = Mock.CreateApprovedClaim(Mock.Character, Mock.Player);
var vm = new CustomFieldsViewModel(Mock.Player.UserId, claim);
var characterField = vm.FieldById(conditionalHeader.ProjectFieldId);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeVisible();
characterField.ShouldNotHaveValue();
characterField.ShouldBeEditable();
}
[Fact]
public void AllowCharactersFieldOnAddClaimForGroupTest()
{
var vm = new CustomFieldsViewModel(Mock.Player.UserId, Mock.Group);
var characterField = vm.FieldById(Mock.CharacterField.ProjectFieldId);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeHidden();
characterField.ShouldNotHaveValue();
characterField.ShouldBeEditable();
}
[Fact]
public void ShowPublicCharactersFieldValueOnAddClaim()
{
var field = Mock.CreateField(new ProjectField() { IsPublic = true, CanPlayerEdit = false });
var value = new FieldWithValue(field, "xxx");
Mock.Character.JsonData = new[] { value }.SerializeFields();
var vm = new CustomFieldsViewModel(Mock.Player.UserId, (IClaimSource)Mock.Character);
var characterField = vm.Field(field);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeVisible();
characterField.Value.ShouldBe("xxx");
characterField.ShouldBeReadonly();
}
[Fact]
public void PublicCharactersFieldValueOnAddClaimAreReadonlyIfNotShowForUnApprovedClaims()
{
var field = Mock.CreateField(new ProjectField() { IsPublic = true, CanPlayerEdit = true, ShowOnUnApprovedClaims = false });
var value = new FieldWithValue(field, "xxx");
Mock.Character.JsonData = new[] { value }.SerializeFields();
var vm = new CustomFieldsViewModel(Mock.Player.UserId, (IClaimSource)Mock.Character);
var characterField = vm.Field(field);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeVisible();
characterField.Value.ShouldBe("xxx");
characterField.ShouldBeReadonly();
}
[Fact]
public void PublicCharactersFieldValueOnAddClaimShouldBeEditableIfNotShowForUnApprovedClaims()
{
var field = Mock.CreateField(new ProjectField()
{
IsPublic = true,
CanPlayerEdit = true,
ShowOnUnApprovedClaims = true,
});
var value = new FieldWithValue(field, "xxx");
Mock.Character.JsonData = new[] { value }.SerializeFields();
var vm = new CustomFieldsViewModel(Mock.Player.UserId, (IClaimSource)Mock.Character);
var characterField = vm.Field(field);
_ = characterField.ShouldNotBeNull();
characterField.ShouldBeVisible();
characterField.Value.ShouldBe("xxx");
characterField.ShouldBeEditable();
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Threading;
using dnlib.DotNet.MD;
using dnlib.Threading;
#if THREAD_SAFE
using ThreadSafe = dnlib.Threading.Collections;
#else
using ThreadSafe = System.Collections.Generic;
#endif
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the Property table
/// </summary>
public abstract class PropertyDef : IHasConstant, IHasCustomAttribute, IHasSemantic, IFullName, IMemberDef {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
#if THREAD_SAFE
readonly Lock theLock = Lock.Create();
#endif
/// <inheritdoc/>
public MDToken MDToken {
get { return new MDToken(Table.Property, rid); }
}
/// <inheritdoc/>
public uint Rid {
get { return rid; }
set { rid = value; }
}
/// <inheritdoc/>
public int HasConstantTag {
get { return 2; }
}
/// <inheritdoc/>
public int HasCustomAttributeTag {
get { return 9; }
}
/// <inheritdoc/>
public int HasSemanticTag {
get { return 1; }
}
/// <summary>
/// From column Property.PropFlags
/// </summary>
public PropertyAttributes Attributes {
get { return (PropertyAttributes)attributes; }
set { attributes = (int)value; }
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column Property.Name
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column Property.Type
/// </summary>
public CallingConventionSig Type {
get { return type; }
set { type = value; }
}
/// <summary/>
protected CallingConventionSig type;
/// <inheritdoc/>
public Constant Constant {
get {
if (!constant_isInitialized)
InitializeConstant();
return constant;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
constant = value;
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected Constant constant;
/// <summary/>
protected bool constant_isInitialized;
void InitializeConstant() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (constant_isInitialized)
return;
constant = GetConstant_NoLock();
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="constant"/></summary>
protected virtual Constant GetConstant_NoLock() {
return null;
}
/// <summary>Reset <see cref="Constant"/></summary>
protected void ResetConstant() {
constant_isInitialized = false;
}
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes == null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() {
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
}
/// <summary>
/// Gets/sets the first getter method. Writing <c>null</c> will clear all get methods.
/// </summary>
public MethodDef GetMethod {
get {
if (otherMethods == null)
InitializePropertyMethods();
return getMethods.Get(0, null);
}
set {
if (otherMethods == null)
InitializePropertyMethods();
if (value == null)
getMethods.Clear();
else if (getMethods.Count == 0)
getMethods.Add(value);
else
getMethods.Set(0, value);
}
}
/// <summary>
/// Gets/sets the first setter method. Writing <c>null</c> will clear all set methods.
/// </summary>
public MethodDef SetMethod {
get {
if (otherMethods == null)
InitializePropertyMethods();
return setMethods.Get(0, null);
}
set {
if (otherMethods == null)
InitializePropertyMethods();
if (value == null)
setMethods.Clear();
else if (setMethods.Count == 0)
setMethods.Add(value);
else
setMethods.Set(0, value);
}
}
/// <summary>
/// Gets all getter methods
/// </summary>
public ThreadSafe.IList<MethodDef> GetMethods {
get {
if (otherMethods == null)
InitializePropertyMethods();
return getMethods;
}
}
/// <summary>
/// Gets all setter methods
/// </summary>
public ThreadSafe.IList<MethodDef> SetMethods {
get {
if (otherMethods == null)
InitializePropertyMethods();
return setMethods;
}
}
/// <summary>
/// Gets the other methods
/// </summary>
public ThreadSafe.IList<MethodDef> OtherMethods {
get {
if (otherMethods == null)
InitializePropertyMethods();
return otherMethods;
}
}
void InitializePropertyMethods() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (otherMethods == null)
InitializePropertyMethods_NoLock();
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>
/// Initializes <see cref="otherMethods"/>, <see cref="getMethods"/>,
/// and <see cref="setMethods"/>.
/// </summary>
protected virtual void InitializePropertyMethods_NoLock() {
getMethods = ThreadSafeListCreator.Create<MethodDef>();
setMethods = ThreadSafeListCreator.Create<MethodDef>();
otherMethods = ThreadSafeListCreator.Create<MethodDef>();
}
/// <summary/>
protected ThreadSafe.IList<MethodDef> getMethods;
/// <summary/>
protected ThreadSafe.IList<MethodDef> setMethods;
/// <summary/>
protected ThreadSafe.IList<MethodDef> otherMethods;
/// <summary>Reset <see cref="GetMethods"/>, <see cref="SetMethods"/>, <see cref="OtherMethods"/></summary>
protected void ResetMethods() {
otherMethods = null;
}
/// <summary>
/// <c>true</c> if there are no methods attached to this property
/// </summary>
public bool IsEmpty {
get {
// The first property access initializes the other fields we access here
return GetMethods.Count == 0 &&
setMethods.Count == 0 &&
otherMethods.Count == 0;
}
}
/// <inheritdoc/>
public bool HasCustomAttributes {
get { return CustomAttributes.Count > 0; }
}
/// <summary>
/// <c>true</c> if <see cref="OtherMethods"/> is not empty
/// </summary>
public bool HasOtherMethods {
get { return OtherMethods.Count > 0; }
}
/// <summary>
/// <c>true</c> if <see cref="Constant"/> is not <c>null</c>
/// </summary>
public bool HasConstant {
get { return Constant != null; }
}
/// <summary>
/// Gets the constant element type or <see cref="dnlib.DotNet.ElementType.End"/> if there's no constant
/// </summary>
public ElementType ElementType {
get {
var c = Constant;
return c == null ? ElementType.End : c.Type;
}
}
/// <summary>
/// Gets/sets the property sig
/// </summary>
public PropertySig PropertySig {
get { return type as PropertySig; }
set { type = value; }
}
/// <summary>
/// Gets/sets the declaring type (owner type)
/// </summary>
public TypeDef DeclaringType {
get { return declaringType2; }
set {
var currentDeclaringType = DeclaringType2;
if (currentDeclaringType == value)
return;
if (currentDeclaringType != null)
currentDeclaringType.Properties.Remove(this); // Will set DeclaringType2 = null
if (value != null)
value.Properties.Add(this); // Will set DeclaringType2 = value
}
}
/// <inheritdoc/>
ITypeDefOrRef IMemberRef.DeclaringType {
get { return declaringType2; }
}
/// <summary>
/// Called by <see cref="DeclaringType"/> and should normally not be called by any user
/// code. Use <see cref="DeclaringType"/> instead. Only call this if you must set the
/// declaring type without inserting it in the declaring type's method list.
/// </summary>
public TypeDef DeclaringType2 {
get { return declaringType2; }
set { declaringType2 = value; }
}
/// <summary/>
protected TypeDef declaringType2;
/// <inheritdoc/>
public ModuleDef Module {
get {
var dt = declaringType2;
return dt == null ? null : dt.Module;
}
}
/// <summary>
/// Gets the full name of the property
/// </summary>
public string FullName {
get {
var dt = declaringType2;
return FullNameCreator.PropertyFullName(dt == null ? null : dt.FullName, name, type);
}
}
bool IIsTypeOrMethod.IsType {
get { return false; }
}
bool IIsTypeOrMethod.IsMethod {
get { return false; }
}
bool IMemberRef.IsField {
get { return false; }
}
bool IMemberRef.IsTypeSpec {
get { return false; }
}
bool IMemberRef.IsTypeRef {
get { return false; }
}
bool IMemberRef.IsTypeDef {
get { return false; }
}
bool IMemberRef.IsMethodSpec {
get { return false; }
}
bool IMemberRef.IsMethodDef {
get { return false; }
}
bool IMemberRef.IsMemberRef {
get { return false; }
}
bool IMemberRef.IsFieldDef {
get { return false; }
}
bool IMemberRef.IsPropertyDef {
get { return true; }
}
bool IMemberRef.IsEventDef {
get { return false; }
}
bool IMemberRef.IsGenericParam {
get { return false; }
}
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, PropertyAttributes flags) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
if (set)
newVal = origVal | (int)flags;
else
newVal = origVal & ~(int)flags;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
#endif
}
/// <summary>
/// Gets/sets the <see cref="PropertyAttributes.SpecialName"/> bit
/// </summary>
public bool IsSpecialName {
get { return ((PropertyAttributes)attributes & PropertyAttributes.SpecialName) != 0; }
set { ModifyAttributes(value, PropertyAttributes.SpecialName); }
}
/// <summary>
/// Gets/sets the <see cref="PropertyAttributes.RTSpecialName"/> bit
/// </summary>
public bool IsRuntimeSpecialName {
get { return ((PropertyAttributes)attributes & PropertyAttributes.RTSpecialName) != 0; }
set { ModifyAttributes(value, PropertyAttributes.RTSpecialName); }
}
/// <summary>
/// Gets/sets the <see cref="PropertyAttributes.HasDefault"/> bit
/// </summary>
public bool HasDefault {
get { return ((PropertyAttributes)attributes & PropertyAttributes.HasDefault) != 0; }
set { ModifyAttributes(value, PropertyAttributes.HasDefault); }
}
/// <inheritdoc/>
public override string ToString() {
return FullName;
}
}
/// <summary>
/// A Property row created by the user and not present in the original .NET file
/// </summary>
public class PropertyDefUser : PropertyDef {
/// <summary>
/// Default constructor
/// </summary>
public PropertyDefUser() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
public PropertyDefUser(UTF8String name)
: this(name, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="sig">Property signature</param>
public PropertyDefUser(UTF8String name, PropertySig sig)
: this(name, sig, 0) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="sig">Property signature</param>
/// <param name="flags">Flags</param>
public PropertyDefUser(UTF8String name, PropertySig sig, PropertyAttributes flags) {
this.name = name;
this.type = sig;
this.attributes = (int)flags;
}
}
/// <summary>
/// Created from a row in the Property table
/// </summary>
sealed class PropertyDefMD : PropertyDef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
/// <inheritdoc/>
public uint OrigRid {
get { return origRid; }
}
/// <inheritdoc/>
protected override Constant GetConstant_NoLock() {
return readerModule.ResolveConstant(readerModule.MetaData.GetConstantRid(Table.Property, origRid));
}
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.MetaData.GetCustomAttributeRidList(Table.Property, origRid);
var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>Property</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public PropertyDefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule == null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.PropertyTable.IsInvalidRID(rid))
throw new BadImageFormatException(string.Format("Property rid {0} does not exist", rid));
#endif
this.origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
uint name;
uint type = readerModule.TablesStream.ReadPropertyRow(origRid, out this.attributes, out name);
this.name = readerModule.StringsStream.ReadNoNull(name);
this.declaringType2 = readerModule.GetOwnerType(this);
this.type = readerModule.ReadSignature(type, new GenericParamContext(declaringType2));
}
internal PropertyDefMD InitializeAll() {
MemberMDInitializer.Initialize(Attributes);
MemberMDInitializer.Initialize(Name);
MemberMDInitializer.Initialize(Type);
MemberMDInitializer.Initialize(Constant);
MemberMDInitializer.Initialize(CustomAttributes);
MemberMDInitializer.Initialize(GetMethod);
MemberMDInitializer.Initialize(SetMethod);
MemberMDInitializer.Initialize(OtherMethods);
MemberMDInitializer.Initialize(DeclaringType);
return this;
}
/// <inheritdoc/>
protected override void InitializePropertyMethods_NoLock() {
if (otherMethods != null)
return;
ThreadSafe.IList<MethodDef> newOtherMethods;
ThreadSafe.IList<MethodDef> newGetMethods, newSetMethods;
var dt = declaringType2 as TypeDefMD;
if (dt == null) {
newGetMethods = ThreadSafeListCreator.Create<MethodDef>();
newSetMethods = ThreadSafeListCreator.Create<MethodDef>();
newOtherMethods = ThreadSafeListCreator.Create<MethodDef>();
}
else
dt.InitializeProperty(this, out newGetMethods, out newSetMethods, out newOtherMethods);
getMethods = newGetMethods;
setMethods = newSetMethods;
// Must be initialized last
otherMethods = newOtherMethods;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc.Utility;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpedyc
{
#region Basic Types
/// <summary>
/// Header bitmask fields
/// </summary>
public class Header
{
private const byte cmdBitmask = 0xF0;
private const byte spBitmask = 0x0C;
private const byte cbChIdBitmask = 0x03;
/// <summary>
/// Indicates the PDU type and MUST be set to one of the
/// following values.
/// 0x01, 0x02, 0x03, 0x04, 0x05
/// </summary>
public Cmd_Values Cmd { get; set; }
/// <summary>
/// The value and meaning depend on the Cmd field.
/// </summary>
public int Sp { get; set; }
/// <summary>
/// Indicates the length of the ChannelId field.
/// </summary>
public cbChId_Values CbChannelId { get; set; }
/// <summary>
/// Raw data of the header fields.
/// </summary>
public byte RawData
{
get
{
// Always re-caculate the latest result.
return (byte)(((int)Cmd << 4) | (Sp << 2) | (int)CbChannelId);
}
}
/// <summary>
/// Unmarshal constructor.
/// </summary>
/// <param name="data">raw data to be unmarshaled.</param>
public Header(byte data)
{
Cmd = (Cmd_Values)((data & cmdBitmask) >> 4);
Sp = (int)((data & spBitmask) >> 2);
CbChannelId = (cbChId_Values)(data & cbChIdBitmask);
}
/// <summary>
/// Marshal constructor
/// </summary>
/// <param name="cmd">Cmd field</param>
/// <param name="sp">SP field</param>
/// <param name="cbChId">cbChId field</param>
public Header(Cmd_Values cmd, int sp, cbChId_Values cbChId)
{
this.Cmd = cmd;
this.Sp = sp;
this.CbChannelId = cbChId;
}
}
public enum Version_Values : ushort
{
/// <summary>
/// Version level one is supported.
/// </summary>
V1 = 0x0001,
/// <summary>
/// Version level two is supported.
/// </summary>
V2 = 0x0002,
}
public enum Cmd_Values : int {
/// <summary>
/// The message contained in the optionalFields field is
/// a Create Request PDU or a Create Response PDU.
/// </summary>
Create = 0x01,
/// <summary>
/// The message contained in the optionalFields field is
/// a Data First PDU.
/// </summary>
FirstData = 0x02,
/// <summary>
/// The message contained in the optionalFields field is
/// a Data PDU.
/// </summary>
Data = 0x03,
/// <summary>
/// The message contained in the optionalFields field is
/// a Close Request PDU or a Close Response PDU.
/// </summary>
Close = 0x04,
/// <summary>
/// The message contained in the optionalFields field is
/// a Capability Request PDU or a Capabilities Response
/// PDU.
/// </summary>
Capability = 0x05,
/// <summary>
/// Not supported by the protocol. Only apply to marshalinhg
/// runtines.
/// </summary>
Unknown = 0x0F
}
public enum cbChId_Values : int
{
/// <summary>
/// The ChannelId is 1 byte wide.
/// </summary>
OneByte = 0x00,
/// <summary>
/// The ChannelId is 2 bytes wide.
/// </summary>
TwoBytes = 0x01,
/// <summary>
/// The ChannelId is 4 bytes wide.
/// </summary>
FourBytes = 0x02,
/// <summary>
/// The ChannelId is 4 bytes wide.
/// </summary>
Invalid = 0x03
}
public enum Len_Values : int
{
/// <summary>
/// Length field length is 1 byte.
/// </summary>
OneByte = 0x0,
/// <summary>
/// Length field length is 2 bytes.
/// </summary>
TwoBytes = 0x1,
/// <summary>
/// Length field length is 4 bytes.
/// </summary>
FourBytes = 0x2,
/// <summary>
/// The ChannelId is 4 bytes wide.
/// </summary>
Invalid = 0x3,
}
public enum DynamicVC_TransportType : uint
{
/// <summary>
/// use static virtual channel
/// </summary>
RDP_TCP = 0x0,
/// <summary>
/// use reliable UDP transport
/// </summary>
RDP_UDP_Reliable = 0x1,
/// <summary>
/// use lossy UDP transport
/// </summary>
RDP_UDP_Lossy = 0x2,
}
/// <summary>
/// DYNVC_CAPS version
/// </summary>
public enum DYNVC_CAPS_Version : ushort
{
VERSION1 = 0x0001,
VERSION2 = 0x0002,
VERSION3 = 0x0003,
}
#endregion
#region MS-RDPEDYC PDUs
public abstract class DynamicVCPDU : BasePDU
{
public virtual Header HeaderBits { get; set; }
public byte[] RawData { get; protected set; }
public virtual uint ChannelId { get; set; }
protected abstract Cmd_Values Cmd { get; }
public DynamicVCPDU()
{
// Unknown PDU doesn't support header.
if (Cmd != Cmd_Values.Unknown)
{
HeaderBits = new Header(Cmd, 0, 0);
}
}
#region Encoding Members
public override void Encode(PduMarshaler marshaler)
{
if (Cmd != Cmd_Values.Unknown)
{
marshaler.WriteByte(HeaderBits.RawData);
}
DoMarshal(marshaler);
SetRawData(true, marshaler);
}
public override bool Decode(PduMarshaler marshaler)
{
HeaderBits = new Header(marshaler.ReadByte());
Cmd_Values c = HeaderBits.Cmd;
// TODO: Check this logic
// Check in the special case that the Cmd bit field just
// equals to Cmd_Values.Unknown
if (c == Cmd_Values.Unknown)
{
return false;
}
try
{
if (c == Cmd)
{
DoUnmarshal(marshaler);
SetRawData(false, marshaler);
return true;
}
}
catch (OverflowException)
{
marshaler.Reset();
}
return false;
}
protected abstract void DoUnmarshal(PduMarshaler marshaler);
protected abstract void DoMarshal(PduMarshaler marshaler);
#endregion
#region Private and Protected Methods
protected void ReadChannelId(PduMarshaler marshaler)
{
uint res = 0;
switch (HeaderBits.CbChannelId)
{
case cbChId_Values.OneByte:
res = Convert.ToUInt32(marshaler.ReadByte());
break;
case cbChId_Values.TwoBytes:
res = Convert.ToUInt32(marshaler.ReadUInt16());
break;
case cbChId_Values.FourBytes:
res = Convert.ToUInt32(marshaler.ReadUInt32());
break;
case cbChId_Values.Invalid:
default:
//TODO: handle errors.
break;
}
//TODO: handle errors.
ChannelId = res;
}
protected void WriteChannelId(PduMarshaler marshaler)
{
//TODO: Refine this method
switch (HeaderBits.CbChannelId)
{
case cbChId_Values.OneByte:
marshaler.WriteByte(Convert.ToByte(ChannelId));
break;
case cbChId_Values.TwoBytes:
marshaler.WriteUInt16(Convert.ToUInt16(ChannelId));
break;
case cbChId_Values.FourBytes:
marshaler.WriteUInt32(Convert.ToUInt32(ChannelId));
break;
case cbChId_Values.Invalid:
default:
DynamicVCException.Throw("chChId is invalid.");
break;
}
}
protected void UpdateCbChannelId()
{
// TODO: check this logic
if (ChannelId <= Byte.MaxValue)
{
HeaderBits.CbChannelId = cbChId_Values.OneByte;
}
else if (ChannelId <= UInt16.MaxValue)
{
HeaderBits.CbChannelId = cbChId_Values.TwoBytes;
}
else if (ChannelId <= UInt32.MaxValue)
{
HeaderBits.CbChannelId = cbChId_Values.FourBytes;
}
}
protected uint ReadLength(PduMarshaler marshaler)
{
uint res = 0;
switch ((Len_Values)HeaderBits.Sp)
{
case Len_Values.OneByte:
res = Convert.ToUInt32(marshaler.ReadByte());
break;
case Len_Values.TwoBytes:
res = Convert.ToUInt32(marshaler.ReadUInt16());
break;
case Len_Values.FourBytes:
res = Convert.ToUInt32(marshaler.ReadUInt32());
break;
case Len_Values.Invalid:
default:
//TODO: handle errors.
break;
}
//TODO: handle errors.
return res;
}
protected void WriteLength(PduMarshaler marshaler, uint Length)
{
//TODO: Refine this method
switch ((Len_Values)HeaderBits.Sp)
{
case Len_Values.OneByte:
marshaler.WriteByte(Convert.ToByte(Length));
break;
case Len_Values.TwoBytes:
marshaler.WriteUInt16(Convert.ToUInt16(Length));
break;
case Len_Values.FourBytes:
marshaler.WriteUInt32(Convert.ToUInt32(Length));
break;
case Len_Values.Invalid:
default:
DynamicVCException.Throw("Len is invalid.");
break;
}
}
protected void UpdateLengthOfLength(uint length)
{
// TODO: check this logic
if (length <= Byte.MaxValue)
{
HeaderBits.Sp = (int)Len_Values.OneByte;
}
else if (length <= UInt16.MaxValue)
{
HeaderBits.Sp = (int)Len_Values.TwoBytes;
}
else if (length <= UInt32.MaxValue)
{
HeaderBits.Sp = (int)Len_Values.FourBytes;
}
}
private void SetRawData(bool marshaling, PduMarshaler marshaler)
{
byte[] data = marshaler.RawData;
if ((null == data) || (data.Length <= 0))
{
if (marshaling)
{
DynamicVCException.Throw("The PDU object was not marshaled successfully.");
}
else
{
DynamicVCException.Throw("The PDU object was not unmarshaled successfully.");
}
}
RawData = data;
}
#endregion
}
public class UnknownDynamicVCPDU : DynamicVCPDU
{
public override Header HeaderBits
{
get
{
DynamicVCException.Throw("UnknownDynamicVCPDU doesn't support valid header fields.");
return null;
}
set
{
DynamicVCException.Throw("UnknownDynamicVCPDU doesn't support valid header fields.");
}
}
public override uint ChannelId
{
get
{
DynamicVCException.Throw("UnknownDynamicVCPDU doesn't support channel ID.");
return 0;
}
set
{
DynamicVCException.Throw("UnknownDynamicVCPDU doesn't support channel ID.");
}
}
public UnknownDynamicVCPDU()
{
}
public UnknownDynamicVCPDU(byte[] data)
{
RawData = data;
}
protected override Cmd_Values Cmd
{
get
{
return Cmd_Values.Unknown;
}
}
protected override void DoMarshal(PduMarshaler marshaler)
{
marshaler.WriteBytes(RawData);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
}
}
public abstract class RequestDvcPDU : DynamicVCPDU
{
}
public abstract class ResponseDvcPDU : DynamicVCPDU
{
}
#region Initializing Dynamic Virtual Channels
public class CapsVer1ReqDvcPdu : RequestDvcPDU
{
public byte Pad;
public ushort Version;
public override uint ChannelId
{
get
{
DynamicVCException.Throw("CapsVer1ReqDvcPdu doesn't support channel ID.");
return 0;
}
set
{
DynamicVCException.Throw("CapsVer1ReqDvcPdu doesn't support channel ID.");
}
}
public CapsVer1ReqDvcPdu()
{
Pad = 0x00;
Version = 0x0001;
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Capability; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
marshaler.WriteByte(Pad);
marshaler.WriteUInt16(Version);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
Pad = marshaler.ReadByte();
Version = marshaler.ReadUInt16();
}
}
public class CapsVer2ReqDvcPdu : RequestDvcPDU
{
public byte Pad;
public ushort Version;
public ushort PriorityCharge0;
public ushort PriorityCharge1;
public ushort PriorityCharge2;
public ushort PriorityCharge3;
public override uint ChannelId
{
get
{
DynamicVCException.Throw("CapsVer2ReqDvcPdu doesn't support channel ID.");
return 0;
}
set
{
DynamicVCException.Throw("CapsVer2ReqDvcPdu doesn't support channel ID.");
}
}
public CapsVer2ReqDvcPdu()
{
}
public CapsVer2ReqDvcPdu(
ushort priorityCharge0,
ushort priorityCharge1,
ushort priorityCharge2,
ushort priorityCharge3
)
{
Pad = 0x00;
Version = 0x0002;
this.PriorityCharge0 = priorityCharge0;
this.PriorityCharge1 = priorityCharge1;
this.PriorityCharge2 = priorityCharge2;
this.PriorityCharge3 = priorityCharge3;
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Capability; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
marshaler.WriteByte(Pad);
marshaler.WriteUInt16(Version);
marshaler.WriteUInt16(PriorityCharge0);
marshaler.WriteUInt16(PriorityCharge1);
marshaler.WriteUInt16(PriorityCharge2);
marshaler.WriteUInt16(PriorityCharge3);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
Pad = marshaler.ReadByte();
Version = marshaler.ReadUInt16();
PriorityCharge0 = marshaler.ReadUInt16();
PriorityCharge1 = marshaler.ReadUInt16();
PriorityCharge2 = marshaler.ReadUInt16();
PriorityCharge3 = marshaler.ReadUInt16();
}
}
public class CapsVer3ReqDvcPdu : RequestDvcPDU
{
public byte Pad;
public ushort Version;
public ushort PriorityCharge0;
public ushort PriorityCharge1;
public ushort PriorityCharge2;
public ushort PriorityCharge3;
public override uint ChannelId
{
get
{
DynamicVCException.Throw("CapsVer2ReqDvcPdu doesn't support channel ID.");
return 0;
}
set
{
DynamicVCException.Throw("CapsVer2ReqDvcPdu doesn't support channel ID.");
}
}
public CapsVer3ReqDvcPdu()
{
}
public CapsVer3ReqDvcPdu(
ushort priorityCharge0,
ushort priorityCharge1,
ushort priorityCharge2,
ushort priorityCharge3
)
{
Pad = 0x00;
Version = 0x0003;
this.PriorityCharge0 = priorityCharge0;
this.PriorityCharge1 = priorityCharge1;
this.PriorityCharge2 = priorityCharge2;
this.PriorityCharge3 = priorityCharge3;
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Capability; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
marshaler.WriteByte(Pad);
marshaler.WriteUInt16(Version);
marshaler.WriteUInt16(PriorityCharge0);
marshaler.WriteUInt16(PriorityCharge1);
marshaler.WriteUInt16(PriorityCharge2);
marshaler.WriteUInt16(PriorityCharge3);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
Pad = marshaler.ReadByte();
Version = marshaler.ReadUInt16();
PriorityCharge0 = marshaler.ReadUInt16();
PriorityCharge1 = marshaler.ReadUInt16();
PriorityCharge2 = marshaler.ReadUInt16();
PriorityCharge3 = marshaler.ReadUInt16();
}
}
public class CapsRespDvcPdu : ResponseDvcPDU
{
public byte Pad;
public ushort Version;
public override uint ChannelId
{
get
{
DynamicVCException.Throw("CapsRespDvcPdu doesn't support channel ID.");
return 0;
}
set
{
DynamicVCException.Throw("CapsRespDvcPdu doesn't support channel ID.");
}
}
public CapsRespDvcPdu()
{
}
public CapsRespDvcPdu(ushort version)
{
this.Version = version;
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Capability; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
marshaler.WriteByte(Pad);
marshaler.WriteUInt16(Version);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
Pad = marshaler.ReadByte();
Version = marshaler.ReadUInt16();
}
}
#endregion
#region Opening Dynamic Virtual Channel PDUs
public class CreateReqDvcPdu : RequestDvcPDU
{
public string ChannelName;
public CreateReqDvcPdu()
{
}
public CreateReqDvcPdu(int priority, uint channelId, string channelName)
{
HeaderBits = new Header(Cmd, priority, cbChId_Values.Invalid);
this.ChannelId = channelId;
this.ChannelName = channelName;
UpdateCbChannelId();
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Create; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
WriteChannelId(marshaler);
marshaler.WriteASCIIString(ChannelName);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
ReadChannelId(marshaler);
ChannelName = marshaler.ReadASCIIString();
}
}
public class CreateRespDvcPdu : ResponseDvcPDU
{
// A 32-bit, signed integer that specifies the NTSTATUS code that indicates success or
// failure of the client dynamic virtual channel creation. NTSTATUS codes are specified
// in [MS-ERREF] section 2.3. A zero or positive value indicates success; a negative value
// indicates failure.
public int CreationStatus { set; get; }
public CreateRespDvcPdu()
{
}
public CreateRespDvcPdu(uint channelId, int creationStatus)
{
HeaderBits = new Header(Cmd, 0, cbChId_Values.Invalid);
this.ChannelId = channelId;
this.CreationStatus = creationStatus;
UpdateCbChannelId();
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Create; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
WriteChannelId(marshaler);
marshaler.WriteInt32(CreationStatus);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
ReadChannelId(marshaler);
CreationStatus = marshaler.ReadInt32();
}
}
#endregion
#region Sending and Receiving Data PDUs
public abstract class DataDvcBasePdu : DynamicVCPDU
{
public byte[] Data { get; set; }
}
public class DataFirstDvcPdu : DataDvcBasePdu
{
public uint Length { get; set; }
public DataFirstDvcPdu()
{
}
public DataFirstDvcPdu(uint channelId, uint length, byte[] data)
{
this.ChannelId = channelId;
this.Length = length;
this.Data = data;
UpdateCbChannelId();
UpdateLengthOfLength(length);
}
public int GetNonDataSize()
{
int channelIdSize = 0;
int lengthSize = 0;
const int headerSize = 1;
// TODO: refine
switch (this.HeaderBits.CbChannelId)
{
case cbChId_Values.OneByte:
channelIdSize = 1;
break;
case cbChId_Values.TwoBytes:
channelIdSize = 2;
break;
case cbChId_Values.FourBytes:
channelIdSize = 4;
break;
case cbChId_Values.Invalid:
default:
DynamicVCException.Throw("channelIdSize is invalid.");
break;
}
switch ((Len_Values)this.HeaderBits.Sp)
{
case Len_Values.OneByte:
lengthSize = 1;
break;
case Len_Values.TwoBytes:
lengthSize = 2;
break;
case Len_Values.FourBytes:
lengthSize = 4;
break;
case Len_Values.Invalid:
default:
DynamicVCException.Throw("lengthSize is invalid.");
break;
}
return (headerSize + channelIdSize + lengthSize);
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.FirstData; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
WriteChannelId(marshaler);
WriteLength(marshaler, this.Length);
marshaler.WriteBytes(this.Data);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
ReadChannelId(marshaler);
Length = ReadLength(marshaler);
Data = marshaler.ReadToEnd();
}
}
public class DataDvcPdu : DataDvcBasePdu
{
public DataDvcPdu()
{
}
public DataDvcPdu(uint channelId, byte[] data)
{
this.ChannelId = channelId;
this.Data = data;
UpdateCbChannelId();
}
public int GetNonDataSize()
{
int channelIdSize = 0;
const int headerSize = 1;
// TODO: refine
switch (this.HeaderBits.CbChannelId)
{
case cbChId_Values.OneByte:
channelIdSize = 1;
break;
case cbChId_Values.TwoBytes:
channelIdSize = 2;
break;
case cbChId_Values.FourBytes:
channelIdSize = 4;
break;
case cbChId_Values.Invalid:
default:
DynamicVCException.Throw("channelIdSize is invalid.");
break;
}
return (headerSize + channelIdSize);
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Data; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
WriteChannelId(marshaler);
marshaler.WriteBytes(Data);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
ReadChannelId(marshaler);
this.Data = marshaler.ReadToEnd();
}
}
#endregion
#region Closing Dynamic Virtual Channel PDUs
public class CloseDvcPdu : DynamicVCPDU
{
public CloseDvcPdu()
{
}
public CloseDvcPdu(uint channelId)
{
this.ChannelId = channelId;
}
protected override Cmd_Values Cmd
{
get { return Cmd_Values.Close; }
}
protected override void DoMarshal(PduMarshaler marshaler)
{
WriteChannelId(marshaler);
}
protected override void DoUnmarshal(PduMarshaler marshaler)
{
ReadChannelId(marshaler);
}
}
#endregion
#endregion
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("2D Toolkit/Camera/tk2dCamera")]
[ExecuteInEditMode]
/// <summary>
/// Maintains a screen resolution camera.
/// Whole number increments seen through this camera represent one pixel.
/// For example, setting an object to 300, 300 will position it at exactly that pixel position.
/// </summary>
public class tk2dCamera : MonoBehaviour
{
static int CURRENT_VERSION = 1;
public int version = 0;
[SerializeField] private tk2dCameraSettings cameraSettings = new tk2dCameraSettings();
/// <summary>
/// The unity camera settings.
/// Use this instead of camera.XXX to change parameters.
/// </summary>
public tk2dCameraSettings CameraSettings {
get {
return cameraSettings;
}
}
/// <summary>
/// Resolution overrides, if necessary. See <see cref="tk2dCameraResolutionOverride"/>
/// </summary>
public tk2dCameraResolutionOverride[] resolutionOverride = new tk2dCameraResolutionOverride[1] {
tk2dCameraResolutionOverride.DefaultOverride
};
/// <summary>
/// The currently used override
/// </summary>
public tk2dCameraResolutionOverride CurrentResolutionOverride {
get {
tk2dCamera settings = SettingsRoot;
Camera cam = ScreenCamera;
float pixelWidth = cam.pixelWidth;
float pixelHeight = cam.pixelHeight;
#if UNITY_EDITOR
if (settings.useGameWindowResolutionInEditor) {
pixelWidth = settings.gameWindowResolution.x;
pixelHeight = settings.gameWindowResolution.y;
}
else if (settings.forceResolutionInEditor)
{
pixelWidth = settings.forceResolution.x;
pixelHeight = settings.forceResolution.y;
}
#endif
tk2dCameraResolutionOverride currentResolutionOverride = null;
if ((currentResolutionOverride == null ||
(currentResolutionOverride != null && (currentResolutionOverride.width != pixelWidth || currentResolutionOverride.height != pixelHeight))
))
{
currentResolutionOverride = null;
// find one if it matches the current resolution
if (settings.resolutionOverride != null)
{
foreach (var ovr in settings.resolutionOverride)
{
if (ovr.Match((int)pixelWidth, (int)pixelHeight))
{
currentResolutionOverride = ovr;
break;
}
}
}
}
return currentResolutionOverride;
}
}
/// <summary>
/// A tk2dCamera to inherit configuration from.
/// All resolution and override settings will be pulled from the root inherited camera.
/// This allows you to create a tk2dCamera prefab in your project or a master camera
/// in the scene and guarantee that multiple instances of tk2dCameras referencing this
/// will use exactly the same paramaters.
/// </summary>
public tk2dCamera InheritConfig {
get { return inheritSettings; }
set {
if (inheritSettings != value) {
inheritSettings = value;
_settingsRoot = null;
}
}
}
[SerializeField]
private tk2dCamera inheritSettings = null;
/// <summary>
/// Native resolution width of the camera. Override this in the inspector.
/// Don't change this at runtime unless you understand the implications.
/// </summary>
public int nativeResolutionWidth = 960;
/// <summary>
/// Native resolution height of the camera. Override this in the inspector.
/// Don't change this at runtime unless you understand the implications.
/// </summary>
public int nativeResolutionHeight = 640;
[SerializeField]
private Camera _unityCamera;
private Camera UnityCamera {
get {
if (_unityCamera == null) {
_unityCamera = camera;
if (_unityCamera == null) {
Debug.LogError("A unity camera must be attached to the tk2dCamera script");
}
}
return _unityCamera;
}
}
static tk2dCamera inst;
/// <summary>
/// Global instance, used by sprite and textmesh class to quickly find the tk2dCamera instance.
/// </summary>
public static tk2dCamera Instance {
get {
return inst;
}
}
// Global instance of active tk2dCameras, used to quickly find cameras matching a particular layer.
private static List<tk2dCamera> allCameras = new List<tk2dCamera>();
/// <summary>
/// Returns the first camera in the list that can "see" this layer, or null if none can be found
/// </summary>
public static tk2dCamera CameraForLayer( int layer ) {
int layerMask = 1 << layer;
int cameraCount = allCameras.Count;
for (int i = 0; i < cameraCount; ++i) {
tk2dCamera cam = allCameras[i];
if ((cam.UnityCamera.cullingMask & layerMask) == layerMask) {
return cam;
}
}
return null;
}
/// <summary>
/// Returns screen extents - top, bottom, left and right will be the extent of the physical screen
/// Regardless of resolution or override
/// </summary>
public Rect ScreenExtents { get { return _screenExtents; } }
/// <summary>
/// Returns screen extents - top, bottom, left and right will be the extent of the native screen
/// before it gets scaled and processed by overrides
/// </summary>
public Rect NativeScreenExtents { get { return _nativeScreenExtents; } }
/// <summary>
/// Enable/disable viewport clipping.
/// ScreenCamera must be valid for it to be actually enabled when rendering.
/// </summary>
public bool viewportClippingEnabled = false;
/// <summary>
/// Viewport clipping region.
/// </summary>
public Vector4 viewportRegion = new Vector4(0, 0, 100, 100);
/// <summary>
/// Target resolution
/// The target resolution currently being used.
/// If displaying on a 960x640 display, this will be the number returned here, regardless of scale, etc.
/// If the editor resolution is forced, the returned value will be the forced resolution.
/// </summary>
public Vector2 TargetResolution { get { return _targetResolution; } }
Vector2 _targetResolution = Vector2.zero;
/// <summary>
/// Native resolution
/// The native resolution of this camera.
/// This is the native resolution of the camera before any scaling is performed.
/// The resolution the game is set up to run at initially.
/// </summary>
public Vector2 NativeResolution { get { return new Vector2(nativeResolutionWidth, nativeResolutionHeight); } }
// Some obselete functions, use ScreenExtents instead
[System.Obsolete] public Vector2 ScreenOffset { get { return new Vector2(ScreenExtents.xMin - NativeScreenExtents.xMin, ScreenExtents.yMin - NativeScreenExtents.yMin); } }
[System.Obsolete] public Vector2 resolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } }
[System.Obsolete] public Vector2 ScreenResolution { get { return new Vector2( ScreenExtents.xMax, ScreenExtents.yMax ); } }
[System.Obsolete] public Vector2 ScaledResolution { get { return new Vector2( ScreenExtents.width, ScreenExtents.height ); } }
/// <summary>
/// Zooms the current display
/// A zoom factor of 2 will zoom in 2x, i.e. the object on screen will be twice as large
/// Anchors will still be anchored, but will be scaled with the zoomScale.
/// It is recommended to use a second camera for HUDs if necessary to avoid this behaviour.
/// </summary>
public float ZoomFactor {
get { return zoomFactor; }
set { zoomFactor = Mathf.Max(0.01f, value); }
}
/// <summary>
/// Obselete - use <see cref="ZoomFactor"/> instead.
/// </summary>
[System.Obsolete]
public float zoomScale {
get { return 1.0f / Mathf.Max(0.001f, zoomFactor); }
set { ZoomFactor = 1.0f / Mathf.Max(0.001f, value); }
}
[SerializeField] float zoomFactor = 1.0f;
[HideInInspector]
/// <summary>
/// Forces the resolution in the editor. This option is only used when tk2dCamera can't detect the game window resolution.
/// </summary>
public bool forceResolutionInEditor = false;
[HideInInspector]
/// <summary>
/// The resolution to force the game window to when <see cref="forceResolutionInEditor"/> is enabled.
/// </summary>
public Vector2 forceResolution = new Vector2(960, 640);
#if UNITY_EDITOR
// When true, overrides the "forceResolutionInEditor" flag above
bool useGameWindowResolutionInEditor = false;
// Usred when useGameWindowResolutionInEditor == true
Vector2 gameWindowResolution = new Vector2(960, 640);
#endif
/// <summary>
/// The camera that sees the screen - i.e. if viewport clipping is enabled, its the camera that sees the entire screen
/// </summary>
public Camera ScreenCamera {
get {
bool viewportClippingEnabled = this.viewportClippingEnabled && this.inheritSettings != null && this.inheritSettings.UnityCamera.rect == unitRect;
return viewportClippingEnabled ? this.inheritSettings.UnityCamera : UnityCamera;
}
}
// Use this for initialization
void Awake () {
Upgrade();
if (allCameras.IndexOf(this) == -1) {
allCameras.Add(this);
}
tk2dCamera settings = SettingsRoot;
tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings;
if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) {
UnityCamera.transparencySortMode = inheritedCameraSettings.transparencySortMode;
}
}
void OnEnable() {
if (UnityCamera != null) {
UpdateCameraMatrix();
}
else {
this.camera.enabled = false;
}
if (!viewportClippingEnabled) // the main camera can't display rect
inst = this;
if (allCameras.IndexOf(this) == -1) {
allCameras.Add(this);
}
}
void OnDestroy() {
int idx = allCameras.IndexOf(this);
if (idx != -1) {
allCameras.RemoveAt( idx );
}
}
void OnPreCull() {
// Commit all pending changes - this more or less guarantees
// everything is committed before drawing this camera.
tk2dUpdateManager.FlushQueues();
UpdateCameraMatrix();
}
#if UNITY_EDITOR
void LateUpdate() {
if (!Application.isPlaying) {
UpdateCameraMatrix();
}
}
#endif
Rect _screenExtents;
Rect _nativeScreenExtents;
Rect unitRect = new Rect(0, 0, 1, 1);
// Gives you the size of one pixel in world units at the native resolution
// For perspective cameras, it is dependent on the distance to the camera.
public float GetSizeAtDistance(float distance) {
tk2dCameraSettings cameraSettings = SettingsRoot.CameraSettings;
switch (cameraSettings.projection) {
case tk2dCameraSettings.ProjectionType.Orthographic:
if (cameraSettings.orthographicType == tk2dCameraSettings.OrthographicType.PixelsPerMeter) {
return 1.0f / cameraSettings.orthographicPixelsPerMeter;
}
else {
return 2.0f * cameraSettings.orthographicSize / SettingsRoot.nativeResolutionHeight;
}
case tk2dCameraSettings.ProjectionType.Perspective:
return Mathf.Tan(CameraSettings.fieldOfView * Mathf.Deg2Rad * 0.5f) * distance * 2.0f / SettingsRoot.nativeResolutionHeight;
}
return 1;
}
// This returns the tk2dCamera object which has the settings stored on it
// Trace back to the source, however far up the hierarchy that may be
// You can't change this at runtime
tk2dCamera _settingsRoot;
public tk2dCamera SettingsRoot {
get {
if (_settingsRoot == null) {
_settingsRoot = (inheritSettings == null || inheritSettings == this) ? this : inheritSettings.SettingsRoot;
}
return _settingsRoot;
}
}
#if UNITY_EDITOR
public static tk2dCamera Editor__Inst {
get {
if (inst != null) {
return inst;
}
return GameObject.FindObjectOfType(typeof(tk2dCamera)) as tk2dCamera;
}
}
#endif
#if UNITY_EDITOR
static bool Editor__getGameViewSizeError = false;
public static bool Editor__gameViewReflectionError = false;
// Try and get game view size
// Will return true if it is able to work this out
// If width / height == 0, it means the user has selected an aspect ratio "Resolution"
public static bool Editor__GetGameViewSize(out float width, out float height, out float aspect) {
try {
Editor__gameViewReflectionError = false;
System.Type gameViewType = System.Type.GetType("UnityEditor.GameView,UnityEditor");
System.Reflection.MethodInfo GetMainGameView = gameViewType.GetMethod("GetMainGameView", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
object mainGameViewInst = GetMainGameView.Invoke(null, null);
if (mainGameViewInst == null) {
width = height = aspect = 0;
return false;
}
System.Reflection.FieldInfo s_viewModeResolutions = gameViewType.GetField("s_viewModeResolutions", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
if (s_viewModeResolutions == null) {
System.Reflection.PropertyInfo currentGameViewSize = gameViewType.GetProperty("currentGameViewSize", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
object gameViewSize = currentGameViewSize.GetValue(mainGameViewInst, null);
System.Type gameViewSizeType = gameViewSize.GetType();
int gvWidth = (int)gameViewSizeType.GetProperty("width").GetValue(gameViewSize, null);
int gvHeight = (int)gameViewSizeType.GetProperty("height").GetValue(gameViewSize, null);
int gvSizeType = (int)gameViewSizeType.GetProperty("sizeType").GetValue(gameViewSize, null);
if (gvWidth == 0 || gvHeight == 0) {
width = height = aspect = 0;
return false;
}
else if (gvSizeType == 0) {
width = height = 0;
aspect = (float)gvWidth / (float)gvHeight;
return true;
}
else {
width = gvWidth; height = gvHeight;
aspect = (float)gvWidth / (float)gvHeight;
return true;
}
}
else {
Vector2[] viewModeResolutions = (Vector2[])s_viewModeResolutions.GetValue(null);
float[] viewModeAspects = (float[])gameViewType.GetField("s_viewModeAspects", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null);
string[] viewModeStrings = (string[])gameViewType.GetField("s_viewModeAspectStrings", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(null);
if (mainGameViewInst != null
&& viewModeStrings != null
&& viewModeResolutions != null && viewModeAspects != null) {
int aspectRatio = (int)gameViewType.GetField("m_AspectRatio", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).GetValue(mainGameViewInst);
string thisViewModeString = viewModeStrings[aspectRatio];
if (thisViewModeString.Contains("Standalone")) {
width = UnityEditor.PlayerSettings.defaultScreenWidth; height = UnityEditor.PlayerSettings.defaultScreenHeight;
aspect = width / height;
}
else if (thisViewModeString.Contains("Web")) {
width = UnityEditor.PlayerSettings.defaultWebScreenWidth; height = UnityEditor.PlayerSettings.defaultWebScreenHeight;
aspect = width / height;
}
else {
width = viewModeResolutions[ aspectRatio ].x; height = viewModeResolutions[ aspectRatio ].y;
aspect = viewModeAspects[ aspectRatio ];
// this is an error state
if (width == 0 && height == 0 && aspect == 0) {
return false;
}
}
return true;
}
}
}
catch (System.Exception e) {
if (Editor__getGameViewSizeError == false) {
Debug.LogError("tk2dCamera.GetGameViewSize - has a Unity update broken this?\nThis is not a fatal error, but a warning that you've probably not got the latest 2D Toolkit update.\n\n" + e.ToString());
Editor__getGameViewSizeError = true;
}
Editor__gameViewReflectionError = true;
}
width = height = aspect = 0;
return false;
}
#endif
public Matrix4x4 OrthoOffCenter(Vector2 scale, float left, float right, float bottom, float top, float near, float far) {
// Additional half texel offset
// Takes care of texture unit offset, if necessary.
float x = (2.0f) / (right - left) * scale.x;
float y = (2.0f) / (top - bottom) * scale.y;
float z = -2.0f / (far - near);
float a = -(right + left) / (right - left);
float b = -(bottom + top) / (top - bottom);
float c = -(far + near) / (far - near);
Matrix4x4 m = new Matrix4x4();
m[0,0] = x; m[0,1] = 0; m[0,2] = 0; m[0,3] = a;
m[1,0] = 0; m[1,1] = y; m[1,2] = 0; m[1,3] = b;
m[2,0] = 0; m[2,1] = 0; m[2,2] = z; m[2,3] = c;
m[3,0] = 0; m[3,1] = 0; m[3,2] = 0; m[3,3] = 1;
return m;
}
Vector2 GetScaleForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float width, float height) {
Vector2 scale = Vector2.one;
float s = 1.0f;
if (currentOverride == null) {
return scale;
}
switch (currentOverride.autoScaleMode)
{
case tk2dCameraResolutionOverride.AutoScaleMode.PixelPerfect:
s = 1;
scale.Set(s, s);
break;
case tk2dCameraResolutionOverride.AutoScaleMode.FitHeight:
s = height / settings.nativeResolutionHeight;
scale.Set(s, s);
break;
case tk2dCameraResolutionOverride.AutoScaleMode.FitWidth:
s = width / settings.nativeResolutionWidth;
scale.Set(s, s);
break;
case tk2dCameraResolutionOverride.AutoScaleMode.FitVisible:
case tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo:
float nativeAspect = (float)settings.nativeResolutionWidth / settings.nativeResolutionHeight;
float currentAspect = width / height;
if (currentAspect < nativeAspect)
s = width / settings.nativeResolutionWidth;
else
s = height / settings.nativeResolutionHeight;
if (currentOverride.autoScaleMode == tk2dCameraResolutionOverride.AutoScaleMode.ClosestMultipleOfTwo)
{
if (s > 1.0f)
s = Mathf.Floor(s); // round number
else
s = Mathf.Pow(2, Mathf.Floor(Mathf.Log(s, 2))); // minimise only as power of two
}
scale.Set(s, s);
break;
case tk2dCameraResolutionOverride.AutoScaleMode.StretchToFit:
scale.Set(width / settings.nativeResolutionWidth, height / settings.nativeResolutionHeight);
break;
case tk2dCameraResolutionOverride.AutoScaleMode.Fill:
s = Mathf.Max(width / settings.nativeResolutionWidth,height / settings.nativeResolutionHeight);
scale.Set(s, s);
break;
default:
case tk2dCameraResolutionOverride.AutoScaleMode.None:
s = currentOverride.scale;
scale.Set(s, s);
break;
}
return scale;
}
Vector2 GetOffsetForOverride(tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, Vector2 scale, float width, float height) {
Vector2 offset = Vector2.zero;
if (currentOverride == null) {
return offset;
}
switch (currentOverride.fitMode) {
case tk2dCameraResolutionOverride.FitMode.Center:
if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.BottomLeft) {
offset = new Vector2(Mathf.Round((settings.nativeResolutionWidth * scale.x - width ) / 2.0f),
Mathf.Round((settings.nativeResolutionHeight * scale.y - height) / 2.0f));
}
break;
default:
case tk2dCameraResolutionOverride.FitMode.Constant:
offset = -currentOverride.offsetPixels;
break;
}
return offset;
}
#if UNITY_EDITOR
private Matrix4x4 Editor__GetPerspectiveMatrix() {
float aspect = (float)nativeResolutionWidth / (float)nativeResolutionHeight;
return Matrix4x4.Perspective(SettingsRoot.CameraSettings.fieldOfView, aspect, UnityCamera.nearClipPlane, UnityCamera.farClipPlane);
}
public Matrix4x4 Editor__GetNativeProjectionMatrix( ) {
tk2dCamera settings = SettingsRoot;
if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) {
return Editor__GetPerspectiveMatrix();
}
Rect rect1 = new Rect(0, 0, 1, 1);
Rect rect2 = new Rect(0, 0, 1, 1);
return GetProjectionMatrixForOverride( settings, null, nativeResolutionWidth, nativeResolutionHeight, false, out rect1, out rect2 );
}
public Matrix4x4 Editor__GetFinalProjectionMatrix( ) {
tk2dCamera settings = SettingsRoot;
if (settings.CameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) {
return Editor__GetPerspectiveMatrix();
}
Vector2 resolution = GetScreenPixelDimensions(settings);
Rect rect1 = new Rect(0, 0, 1, 1);
Rect rect2 = new Rect(0, 0, 1, 1);
return GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, resolution.x, resolution.y, false, out rect1, out rect2 );
}
#endif
Matrix4x4 GetProjectionMatrixForOverride( tk2dCamera settings, tk2dCameraResolutionOverride currentOverride, float pixelWidth, float pixelHeight, bool halfTexelOffset, out Rect screenExtents, out Rect unscaledScreenExtents ) {
Vector2 scale = GetScaleForOverride( settings, currentOverride, pixelWidth, pixelHeight );
Vector2 offset = GetOffsetForOverride( settings, currentOverride, scale, pixelWidth, pixelHeight);
float left = offset.x, bottom = offset.y;
float right = pixelWidth + offset.x, top = pixelHeight + offset.y;
Vector2 nativeResolutionOffset = Vector2.zero;
// Correct for viewport clipping rendering
// Coordinates in subrect are "native" pixels, but origin is from the extrema of screen
if (this.viewportClippingEnabled && this.InheritConfig != null) {
float vw = (right - left) / scale.x;
float vh = (top - bottom) / scale.y;
Vector4 sr = new Vector4((int)this.viewportRegion.x, (int)this.viewportRegion.y,
(int)this.viewportRegion.z, (int)this.viewportRegion.w);
float viewportLeft = -offset.x / pixelWidth + sr.x / vw;
float viewportBottom = -offset.y / pixelHeight + sr.y / vh;
float viewportWidth = sr.z / vw;
float viewportHeight = sr.w / vh;
if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) {
viewportLeft += (pixelWidth - settings.nativeResolutionWidth * scale.x) / pixelWidth / 2.0f;
viewportBottom += (pixelHeight - settings.nativeResolutionHeight * scale.y) / pixelHeight / 2.0f;
}
Rect r = new Rect( viewportLeft, viewportBottom, viewportWidth, viewportHeight );
if (UnityCamera.rect.x != viewportLeft ||
UnityCamera.rect.y != viewportBottom ||
UnityCamera.rect.width != viewportWidth ||
UnityCamera.rect.height != viewportHeight) {
UnityCamera.rect = r;
}
float maxWidth = Mathf.Min( 1.0f - r.x, r.width );
float maxHeight = Mathf.Min( 1.0f - r.y, r.height );
float rectOffsetX = sr.x * scale.x - offset.x;
float rectOffsetY = sr.y * scale.y - offset.y;
if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) {
rectOffsetX -= settings.nativeResolutionWidth * 0.5f * scale.x;
rectOffsetY -= settings.nativeResolutionHeight * 0.5f * scale.y;
}
if (r.x < 0.0f) {
rectOffsetX += -r.x * pixelWidth;
maxWidth = (r.x + r.width);
}
if (r.y < 0.0f) {
rectOffsetY += -r.y * pixelHeight;
maxHeight = (r.y + r.height);
}
left += rectOffsetX;
bottom += rectOffsetY;
right = pixelWidth * maxWidth + offset.x + rectOffsetX;
top = pixelHeight * maxHeight + offset.y + rectOffsetY;
}
else {
if (UnityCamera.rect != CameraSettings.rect) {
UnityCamera.rect = CameraSettings.rect;
}
// By default the camera is orthographic, bottom left, 1 pixel per meter
if (settings.cameraSettings.orthographicOrigin == tk2dCameraSettings.OrthographicOrigin.Center) {
float w = (right - left) * 0.5f;
left -= w; right -= w;
float h = (top - bottom) * 0.5f;
top -= h; bottom -= h;
nativeResolutionOffset.Set(-nativeResolutionWidth / 2.0f, -nativeResolutionHeight / 2.0f);
}
}
float zoomScale = 1.0f / ZoomFactor;
// Only need the half texel offset on PC/D3D
bool needHalfTexelOffset = (Application.platform == RuntimePlatform.WindowsPlayer ||
Application.platform == RuntimePlatform.WindowsWebPlayer ||
Application.platform == RuntimePlatform.WindowsEditor);
float halfTexel = (halfTexelOffset && needHalfTexelOffset) ? 0.5f : 0.0f;
float orthoSize = settings.cameraSettings.orthographicSize;
switch (settings.cameraSettings.orthographicType) {
case tk2dCameraSettings.OrthographicType.OrthographicSize:
orthoSize = 2.0f * settings.cameraSettings.orthographicSize / settings.nativeResolutionHeight;
break;
case tk2dCameraSettings.OrthographicType.PixelsPerMeter:
orthoSize = 1.0f / settings.cameraSettings.orthographicPixelsPerMeter;
break;
}
float s = orthoSize * zoomScale;
screenExtents = new Rect(left * s / scale.x, bottom * s / scale.y,
(right - left) * s / scale.x, (top - bottom) * s / scale.y);
unscaledScreenExtents = new Rect(nativeResolutionOffset.x * s, nativeResolutionOffset.y * s,
nativeResolutionWidth * s, nativeResolutionHeight * s);
// Near and far clip planes are tweakable per camera, so we pull from current camera instance regardless of inherited values
return OrthoOffCenter(scale, orthoSize * (left + halfTexel) * zoomScale, orthoSize * (right + halfTexel) * zoomScale,
orthoSize * (bottom - halfTexel) * zoomScale, orthoSize * (top - halfTexel) * zoomScale,
UnityCamera.nearClipPlane, UnityCamera.farClipPlane);
}
Vector2 GetScreenPixelDimensions(tk2dCamera settings) {
Vector2 dimensions = new Vector2(ScreenCamera.pixelWidth, ScreenCamera.pixelHeight);
#if UNITY_EDITOR
// This bit here allocates memory, but only runs in the editor
float gameViewPixelWidth = 0, gameViewPixelHeight = 0;
float gameViewAspect = 0;
settings.useGameWindowResolutionInEditor = false;
if (Editor__GetGameViewSize( out gameViewPixelWidth, out gameViewPixelHeight, out gameViewAspect)) {
if (gameViewPixelWidth != 0 && gameViewPixelHeight != 0) {
if (!settings.useGameWindowResolutionInEditor ||
settings.gameWindowResolution.x != gameViewPixelWidth ||
settings.gameWindowResolution.y != gameViewPixelHeight) {
settings.useGameWindowResolutionInEditor = true;
settings.gameWindowResolution.x = gameViewPixelWidth;
settings.gameWindowResolution.y = gameViewPixelHeight;
}
dimensions.x = settings.gameWindowResolution.x;
dimensions.y = settings.gameWindowResolution.y;
}
}
if (!settings.useGameWindowResolutionInEditor && settings.forceResolutionInEditor)
{
dimensions.x = settings.forceResolution.x;
dimensions.y = settings.forceResolution.y;
}
#endif
return dimensions;
}
private void Upgrade() {
if (version != CURRENT_VERSION) {
if (version == 0) {
// Backwards compatibility
cameraSettings.orthographicPixelsPerMeter = 1;
cameraSettings.orthographicType = tk2dCameraSettings.OrthographicType.PixelsPerMeter;
cameraSettings.orthographicOrigin = tk2dCameraSettings.OrthographicOrigin.BottomLeft;
cameraSettings.projection = tk2dCameraSettings.ProjectionType.Orthographic;
foreach (tk2dCameraResolutionOverride ovr in resolutionOverride) {
ovr.Upgrade( version );
}
// Mirror camera settings
Camera unityCamera = camera;
if (unityCamera != null) {
cameraSettings.rect = unityCamera.rect;
if (!unityCamera.isOrthoGraphic) {
cameraSettings.projection = tk2dCameraSettings.ProjectionType.Perspective;
cameraSettings.fieldOfView = unityCamera.fieldOfView * ZoomFactor;
}
unityCamera.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
}
}
Debug.Log("tk2dCamera '" + this.name + "' - Upgraded from version " + version.ToString());
version = CURRENT_VERSION;
}
}
/// <summary>
/// Updates the camera matrix to ensure 1:1 pixel mapping
/// Or however the override is set up.
/// </summary>
public void UpdateCameraMatrix()
{
Upgrade();
if (!this.viewportClippingEnabled)
inst = this;
Camera unityCamera = UnityCamera;
tk2dCamera settings = SettingsRoot;
tk2dCameraSettings inheritedCameraSettings = settings.CameraSettings;
if (unityCamera.rect != cameraSettings.rect) unityCamera.rect = cameraSettings.rect;
// Projection type is inherited from base camera
_targetResolution = GetScreenPixelDimensions(settings);
if (inheritedCameraSettings.projection == tk2dCameraSettings.ProjectionType.Perspective) {
if (unityCamera.orthographic == true) unityCamera.orthographic = false;
float fov = Mathf.Min(179.9f, inheritedCameraSettings.fieldOfView / Mathf.Max(0.001f, ZoomFactor));
if (unityCamera.fieldOfView != fov) unityCamera.fieldOfView = fov;
_screenExtents.Set( -unityCamera.aspect, -1, unityCamera.aspect * 2, 2 );
_nativeScreenExtents = _screenExtents;
unityCamera.ResetProjectionMatrix();
}
else {
if (unityCamera.orthographic == false) unityCamera.orthographic = true;
// Find an override if necessary
Matrix4x4 m = GetProjectionMatrixForOverride( settings, settings.CurrentResolutionOverride, _targetResolution.x, _targetResolution.y, true, out _screenExtents, out _nativeScreenExtents );
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_1)
// Windows phone?
if (Application.platform == RuntimePlatform.WP8Player &&
(Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)) {
float angle = (Screen.orientation == ScreenOrientation.LandscapeRight) ? 90.0f : -90.0f;
Matrix4x4 m2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one);
m = m2 * m;
}
#endif
if (unityCamera.projectionMatrix != m) {
unityCamera.projectionMatrix = m;
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.IO;
using System.Text;
using System.Threading;
using log4net.Util;
using log4net.Layout;
using log4net.Core;
namespace log4net.Appender
{
#if !NETCF
/// <summary>
/// Appends logging events to a file.
/// </summary>
/// <remarks>
/// <para>
/// Logging events are sent to the file specified by
/// the <see cref="File"/> property.
/// </para>
/// <para>
/// The file can be opened in either append or overwrite mode
/// by specifying the <see cref="AppendToFile"/> property.
/// If the file path is relative it is taken as relative from
/// the application base directory. The file encoding can be
/// specified by setting the <see cref="Encoding"/> property.
/// </para>
/// <para>
/// The layout's <see cref="ILayout.Header"/> and <see cref="ILayout.Footer"/>
/// values will be written each time the file is opened and closed
/// respectively. If the <see cref="AppendToFile"/> property is <see langword="true"/>
/// then the file may contain multiple copies of the header and footer.
/// </para>
/// <para>
/// This appender will first try to open the file for writing when <see cref="ActivateOptions"/>
/// is called. This will typically be during configuration.
/// If the file cannot be opened for writing the appender will attempt
/// to open the file again each time a message is logged to the appender.
/// If the file cannot be opened for writing when a message is logged then
/// the message will be discarded by this appender.
/// </para>
/// <para>
/// The <see cref="FileAppender"/> supports pluggable file locking models via
/// the <see cref="LockingModel"/> property.
/// The default behavior, implemented by <see cref="FileAppender.ExclusiveLock"/>
/// is to obtain an exclusive write lock on the file until this appender is closed.
/// The alternative models only hold a
/// write lock while the appender is writing a logging event (<see cref="FileAppender.MinimalLock"/>)
/// or synchronize by using a named system wide Mutex (<see cref="FileAppender.InterProcessLock"/>).
/// </para>
/// <para>
/// All locking strategies have issues and you should seriously consider using a different strategy that
/// avoids having multiple processes logging to the same file.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Rodrigo B. de Oliveira</author>
/// <author>Douglas de la Torre</author>
/// <author>Niall Daley</author>
#else
/// <summary>
/// Appends logging events to a file.
/// </summary>
/// <remarks>
/// <para>
/// Logging events are sent to the file specified by
/// the <see cref="File"/> property.
/// </para>
/// <para>
/// The file can be opened in either append or overwrite mode
/// by specifying the <see cref="AppendToFile"/> property.
/// If the file path is relative it is taken as relative from
/// the application base directory. The file encoding can be
/// specified by setting the <see cref="Encoding"/> property.
/// </para>
/// <para>
/// The layout's <see cref="ILayout.Header"/> and <see cref="ILayout.Footer"/>
/// values will be written each time the file is opened and closed
/// respectively. If the <see cref="AppendToFile"/> property is <see langword="true"/>
/// then the file may contain multiple copies of the header and footer.
/// </para>
/// <para>
/// This appender will first try to open the file for writing when <see cref="ActivateOptions"/>
/// is called. This will typically be during configuration.
/// If the file cannot be opened for writing the appender will attempt
/// to open the file again each time a message is logged to the appender.
/// If the file cannot be opened for writing when a message is logged then
/// the message will be discarded by this appender.
/// </para>
/// <para>
/// The <see cref="FileAppender"/> supports pluggable file locking models via
/// the <see cref="LockingModel"/> property.
/// The default behavior, implemented by <see cref="FileAppender.ExclusiveLock"/>
/// is to obtain an exclusive write lock on the file until this appender is closed.
/// The alternative model only holds a
/// write lock while the appender is writing a logging event (<see cref="FileAppender.MinimalLock"/>).
/// </para>
/// <para>
/// All locking strategies have issues and you should seriously consider using a different strategy that
/// avoids having multiple processes logging to the same file.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Rodrigo B. de Oliveira</author>
/// <author>Douglas de la Torre</author>
/// <author>Niall Daley</author>
#endif
public class FileAppender : TextWriterAppender
{
#region LockingStream Inner Class
/// <summary>
/// Write only <see cref="Stream"/> that uses the <see cref="LockingModelBase"/>
/// to manage access to an underlying resource.
/// </summary>
private sealed class LockingStream : Stream, IDisposable
{
public sealed class LockStateException : LogException
{
public LockStateException(string message): base(message)
{
}
}
private Stream m_realStream=null;
private LockingModelBase m_lockingModel=null;
private int m_readTotal=-1;
private int m_lockLevel=0;
public LockingStream(LockingModelBase locking) : base()
{
if (locking==null)
{
throw new ArgumentException("Locking model may not be null","locking");
}
m_lockingModel=locking;
}
#region Override Implementation of Stream
// Methods
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
AssertLocked();
IAsyncResult ret=m_realStream.BeginRead(buffer,offset,count,callback,state);
m_readTotal=EndRead(ret);
return ret;
}
/// <summary>
/// True asynchronous writes are not supported, the implementation forces a synchronous write.
/// </summary>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
AssertLocked();
IAsyncResult ret=m_realStream.BeginWrite(buffer,offset,count,callback,state);
EndWrite(ret);
return ret;
}
public override void Close()
{
m_lockingModel.CloseFile();
}
public override int EndRead(IAsyncResult asyncResult)
{
AssertLocked();
return m_readTotal;
}
public override void EndWrite(IAsyncResult asyncResult)
{
//No-op, it has already been handled
}
public override void Flush()
{
AssertLocked();
m_realStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return m_realStream.Read(buffer,offset,count);
}
public override int ReadByte()
{
return m_realStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
AssertLocked();
return m_realStream.Seek(offset,origin);
}
public override void SetLength(long value)
{
AssertLocked();
m_realStream.SetLength(value);
}
void IDisposable.Dispose()
{
Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
AssertLocked();
m_realStream.Write(buffer,offset,count);
}
public override void WriteByte(byte value)
{
AssertLocked();
m_realStream.WriteByte(value);
}
// Properties
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get
{
AssertLocked();
return m_realStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
AssertLocked();
return m_realStream.CanWrite;
}
}
public override long Length
{
get
{
AssertLocked();
return m_realStream.Length;
}
}
public override long Position
{
get
{
AssertLocked();
return m_realStream.Position;
}
set
{
AssertLocked();
m_realStream.Position=value;
}
}
#endregion Override Implementation of Stream
#region Locking Methods
private void AssertLocked()
{
if (m_realStream == null)
{
throw new LockStateException("The file is not currently locked");
}
}
public bool AcquireLock()
{
bool ret=false;
lock(this)
{
if (m_lockLevel==0)
{
// If lock is already acquired, nop
m_realStream=m_lockingModel.AcquireLock();
}
if (m_realStream!=null)
{
m_lockLevel++;
ret=true;
}
}
return ret;
}
public void ReleaseLock()
{
lock(this)
{
m_lockLevel--;
if (m_lockLevel==0)
{
// If already unlocked, nop
m_lockingModel.ReleaseLock();
m_realStream=null;
}
}
}
#endregion Locking Methods
}
#endregion LockingStream Inner Class
#region Locking Models
/// <summary>
/// Locking model base class
/// </summary>
/// <remarks>
/// <para>
/// Base class for the locking models available to the <see cref="FileAppender"/> derived loggers.
/// </para>
/// </remarks>
public abstract class LockingModelBase
{
private FileAppender m_appender=null;
/// <summary>
/// Open the output file
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="append">Whether to append to the file, or overwrite</param>
/// <param name="encoding">The encoding to use</param>
/// <remarks>
/// <para>
/// Open the file specified and prepare for logging.
/// No writes will be made until <see cref="AcquireLock"/> is called.
/// Must be called before any calls to <see cref="AcquireLock"/>,
/// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>.
/// </para>
/// </remarks>
public abstract void OpenFile(string filename, bool append,Encoding encoding);
/// <summary>
/// Close the file
/// </summary>
/// <remarks>
/// <para>
/// Close the file. No further writes will be made.
/// </para>
/// </remarks>
public abstract void CloseFile();
/// <summary>
/// Acquire the lock on the file
/// </summary>
/// <returns>A stream that is ready to be written to.</returns>
/// <remarks>
/// <para>
/// Acquire the lock on the file in preparation for writing to it.
/// Return a stream pointing to the file. <see cref="ReleaseLock"/>
/// must be called to release the lock on the output file.
/// </para>
/// </remarks>
public abstract Stream AcquireLock();
/// <summary>
/// Release the lock on the file
/// </summary>
/// <remarks>
/// <para>
/// Release the lock on the file. No further writes will be made to the
/// stream until <see cref="AcquireLock"/> is called again.
/// </para>
/// </remarks>
public abstract void ReleaseLock();
/// <summary>
/// Gets or sets the <see cref="FileAppender"/> for this LockingModel
/// </summary>
/// <value>
/// The <see cref="FileAppender"/> for this LockingModel
/// </value>
/// <remarks>
/// <para>
/// The file appender this locking model is attached to and working on
/// behalf of.
/// </para>
/// <para>
/// The file appender is used to locate the security context and the error handler to use.
/// </para>
/// <para>
/// The value of this property will be set before <see cref="OpenFile"/> is
/// called.
/// </para>
/// </remarks>
public FileAppender CurrentAppender
{
get { return m_appender; }
set { m_appender = value; }
}
/// <summary>
/// Helper method that creates a FileStream under CurrentAppender's SecurityContext.
/// </summary>
/// <remarks>
/// <para>
/// Typically called during OpenFile or AcquireLock.
/// </para>
/// <para>
/// If the directory portion of the <paramref name="filename"/> does not exist, it is created
/// via Directory.CreateDirecctory.
/// </para>
/// </remarks>
/// <param name="filename"></param>
/// <param name="append"></param>
/// <param name="fileShare"></param>
/// <returns></returns>
protected Stream CreateStream(string filename, bool append, FileShare fileShare)
{
using (CurrentAppender.SecurityContext.Impersonate(this))
{
// Ensure that the directory structure exists
string directoryFullName = Path.GetDirectoryName(filename);
// Only create the directory if it does not exist
// doing this check here resolves some permissions failures
if (!Directory.Exists(directoryFullName))
{
Directory.CreateDirectory(directoryFullName);
}
FileMode fileOpenMode = append ? FileMode.Append : FileMode.Create;
return new FileStream(filename, fileOpenMode, FileAccess.Write, fileShare);
}
}
/// <summary>
/// Helper method to close <paramref name="stream"/> under CurrentAppender's SecurityContext.
/// </summary>
/// <remarks>
/// Does not set <paramref name="stream"/> to null.
/// </remarks>
/// <param name="stream"></param>
protected void CloseStream(Stream stream)
{
using (CurrentAppender.SecurityContext.Impersonate(this))
{
stream.Close();
}
}
}
/// <summary>
/// Hold an exclusive lock on the output file
/// </summary>
/// <remarks>
/// <para>
/// Open the file once for writing and hold it open until <see cref="CloseFile"/> is called.
/// Maintains an exclusive lock on the file during this time.
/// </para>
/// </remarks>
public class ExclusiveLock : LockingModelBase
{
private Stream m_stream = null;
/// <summary>
/// Open the file specified and prepare for logging.
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="append">Whether to append to the file, or overwrite</param>
/// <param name="encoding">The encoding to use</param>
/// <remarks>
/// <para>
/// Open the file specified and prepare for logging.
/// No writes will be made until <see cref="AcquireLock"/> is called.
/// Must be called before any calls to <see cref="AcquireLock"/>,
/// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>.
/// </para>
/// </remarks>
public override void OpenFile(string filename, bool append,Encoding encoding)
{
try
{
m_stream = CreateStream(filename, append, FileShare.Read);
}
catch (Exception e1)
{
CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+filename+". "+e1.Message);
}
}
/// <summary>
/// Close the file
/// </summary>
/// <remarks>
/// <para>
/// Close the file. No further writes will be made.
/// </para>
/// </remarks>
public override void CloseFile()
{
CloseStream(m_stream);
m_stream = null;
}
/// <summary>
/// Acquire the lock on the file
/// </summary>
/// <returns>A stream that is ready to be written to.</returns>
/// <remarks>
/// <para>
/// Does nothing. The lock is already taken
/// </para>
/// </remarks>
public override Stream AcquireLock()
{
return m_stream;
}
/// <summary>
/// Release the lock on the file
/// </summary>
/// <remarks>
/// <para>
/// Does nothing. The lock will be released when the file is closed.
/// </para>
/// </remarks>
public override void ReleaseLock()
{
//NOP
}
}
/// <summary>
/// Acquires the file lock for each write
/// </summary>
/// <remarks>
/// <para>
/// Opens the file once for each <see cref="AcquireLock"/>/<see cref="ReleaseLock"/> cycle,
/// thus holding the lock for the minimal amount of time. This method of locking
/// is considerably slower than <see cref="FileAppender.ExclusiveLock"/> but allows
/// other processes to move/delete the log file whilst logging continues.
/// </para>
/// </remarks>
public class MinimalLock : LockingModelBase
{
private string m_filename;
private bool m_append;
private Stream m_stream=null;
/// <summary>
/// Prepares to open the file when the first message is logged.
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="append">Whether to append to the file, or overwrite</param>
/// <param name="encoding">The encoding to use</param>
/// <remarks>
/// <para>
/// Open the file specified and prepare for logging.
/// No writes will be made until <see cref="AcquireLock"/> is called.
/// Must be called before any calls to <see cref="AcquireLock"/>,
/// <see cref="ReleaseLock"/> and <see cref="CloseFile"/>.
/// </para>
/// </remarks>
public override void OpenFile(string filename, bool append, Encoding encoding)
{
m_filename=filename;
m_append=append;
}
/// <summary>
/// Close the file
/// </summary>
/// <remarks>
/// <para>
/// Close the file. No further writes will be made.
/// </para>
/// </remarks>
public override void CloseFile()
{
// NOP
}
/// <summary>
/// Acquire the lock on the file
/// </summary>
/// <returns>A stream that is ready to be written to.</returns>
/// <remarks>
/// <para>
/// Acquire the lock on the file in preparation for writing to it.
/// Return a stream pointing to the file. <see cref="ReleaseLock"/>
/// must be called to release the lock on the output file.
/// </para>
/// </remarks>
public override Stream AcquireLock()
{
if (m_stream==null)
{
try
{
m_stream = CreateStream(m_filename, m_append, FileShare.Read);
m_append = true;
}
catch (Exception e1)
{
CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file "+m_filename+". "+e1.Message);
}
}
return m_stream;
}
/// <summary>
/// Release the lock on the file
/// </summary>
/// <remarks>
/// <para>
/// Release the lock on the file. No further writes will be made to the
/// stream until <see cref="AcquireLock"/> is called again.
/// </para>
/// </remarks>
public override void ReleaseLock()
{
CloseStream(m_stream);
m_stream = null;
}
}
#if !NETCF
/// <summary>
/// Provides cross-process file locking.
/// </summary>
/// <author>Ron Grabowski</author>
/// <author>Steve Wranovsky</author>
public class InterProcessLock : LockingModelBase
{
private Mutex m_mutex = null;
private bool m_mutexClosed = false;
private Stream m_stream = null;
/// <summary>
/// Open the file specified and prepare for logging.
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="append">Whether to append to the file, or overwrite</param>
/// <param name="encoding">The encoding to use</param>
/// <remarks>
/// <para>
/// Open the file specified and prepare for logging.
/// No writes will be made until <see cref="AcquireLock"/> is called.
/// Must be called before any calls to <see cref="AcquireLock"/>,
/// -<see cref="ReleaseLock"/> and <see cref="CloseFile"/>.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
public override void OpenFile(string filename, bool append, Encoding encoding)
{
try
{
m_stream = CreateStream(filename, append, FileShare.ReadWrite);
string mutextFriendlyFilename = filename
.Replace("\\", "_")
.Replace(":", "_")
.Replace("/", "_");
m_mutex = new Mutex(false, mutextFriendlyFilename);
}
catch (Exception e1)
{
CurrentAppender.ErrorHandler.Error("Unable to acquire lock on file " + filename + ". " + e1.Message);
}
}
/// <summary>
/// Close the file
/// </summary>
/// <remarks>
/// <para>
/// Close the file. No further writes will be made.
/// </para>
/// </remarks>
public override void CloseFile()
{
try {
CloseStream(m_stream);
m_stream = null;
}
finally {
m_mutex.ReleaseMutex();
m_mutex.Close();
m_mutexClosed = true;
}
}
/// <summary>
/// Acquire the lock on the file
/// </summary>
/// <returns>A stream that is ready to be written to.</returns>
/// <remarks>
/// <para>
/// Does nothing. The lock is already taken
/// </para>
/// </remarks>
public override Stream AcquireLock()
{
if (m_mutex != null) {
// TODO: add timeout?
m_mutex.WaitOne();
// should always be true (and fast) for FileStream
if (m_stream.CanSeek) {
m_stream.Seek(0, SeekOrigin.End);
}
}
return m_stream;
}
/// <summary>
///
/// </summary>
public override void ReleaseLock()
{
if (m_mutexClosed == false && m_mutex != null)
{
m_mutex.ReleaseMutex();
}
}
}
#endif
#endregion Locking Models
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public FileAppender()
{
}
/// <summary>
/// Construct a new appender using the layout, file and append mode.
/// </summary>
/// <param name="layout">the layout to use with this appender</param>
/// <param name="filename">the full path to the file to write to</param>
/// <param name="append">flag to indicate if the file should be appended to</param>
/// <remarks>
/// <para>
/// Obsolete constructor.
/// </para>
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout, File & AppendToFile properties")]
public FileAppender(ILayout layout, string filename, bool append)
{
Layout = layout;
File = filename;
AppendToFile = append;
ActivateOptions();
}
/// <summary>
/// Construct a new appender using the layout and file specified.
/// The file will be appended to.
/// </summary>
/// <param name="layout">the layout to use with this appender</param>
/// <param name="filename">the full path to the file to write to</param>
/// <remarks>
/// <para>
/// Obsolete constructor.
/// </para>
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout & File properties")]
public FileAppender(ILayout layout, string filename) : this(layout, filename, true)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the path to the file that logging will be written to.
/// </summary>
/// <value>
/// The path to the file that logging will be written to.
/// </value>
/// <remarks>
/// <para>
/// If the path is relative it is taken as relative from
/// the application base directory.
/// </para>
/// </remarks>
virtual public string File
{
get { return m_fileName; }
set { m_fileName = value; }
}
/// <summary>
/// Gets or sets a flag that indicates whether the file should be
/// appended to or overwritten.
/// </summary>
/// <value>
/// Indicates whether the file should be appended to or overwritten.
/// </value>
/// <remarks>
/// <para>
/// If the value is set to false then the file will be overwritten, if
/// it is set to true then the file will be appended to.
/// </para>
/// The default value is true.
/// </remarks>
public bool AppendToFile
{
get { return m_appendToFile; }
set { m_appendToFile = value; }
}
/// <summary>
/// Gets or sets <see cref="Encoding"/> used to write to the file.
/// </summary>
/// <value>
/// The <see cref="Encoding"/> used to write to the file.
/// </value>
/// <remarks>
/// <para>
/// The default encoding set is <see cref="System.Text.Encoding.Default"/>
/// which is the encoding for the system's current ANSI code page.
/// </para>
/// </remarks>
public Encoding Encoding
{
get { return m_encoding; }
set { m_encoding = value; }
}
/// <summary>
/// Gets or sets the <see cref="SecurityContext"/> used to write to the file.
/// </summary>
/// <value>
/// The <see cref="SecurityContext"/> used to write to the file.
/// </value>
/// <remarks>
/// <para>
/// Unless a <see cref="SecurityContext"/> specified here for this appender
/// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the
/// security context to use. The default behavior is to use the security context
/// of the current thread.
/// </para>
/// </remarks>
public SecurityContext SecurityContext
{
get { return m_securityContext; }
set { m_securityContext = value; }
}
#if NETCF
/// <summary>
/// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file.
/// </summary>
/// <value>
/// The <see cref="FileAppender.LockingModel"/> used to lock the file.
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file.
/// </para>
/// <para>
/// There are two built in locking models, <see cref="FileAppender.ExclusiveLock"/> and <see cref="FileAppender.MinimalLock"/>.
/// The first locks the file from the start of logging to the end, the
/// second locks only for the minimal amount of time when logging each message
/// and the last synchronizes processes using a named system wide Mutex.
/// </para>
/// <para>
/// The default locking model is the <see cref="FileAppender.ExclusiveLock"/>.
/// </para>
/// </remarks>
#else
/// <summary>
/// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file.
/// </summary>
/// <value>
/// The <see cref="FileAppender.LockingModel"/> used to lock the file.
/// </value>
/// <remarks>
/// <para>
/// Gets or sets the <see cref="FileAppender.LockingModel"/> used to handle locking of the file.
/// </para>
/// <para>
/// There are three built in locking models, <see cref="FileAppender.ExclusiveLock"/>, <see cref="FileAppender.MinimalLock"/> and <see cref="FileAppender.InterProcessLock"/> .
/// The first locks the file from the start of logging to the end, the
/// second locks only for the minimal amount of time when logging each message
/// and the last synchronizes processes using a named system wide Mutex.
/// </para>
/// <para>
/// The default locking model is the <see cref="FileAppender.ExclusiveLock"/>.
/// </para>
/// </remarks>
#endif
public FileAppender.LockingModelBase LockingModel
{
get { return m_lockingModel; }
set { m_lockingModel = value; }
}
#endregion Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// Activate the options on the file appender.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// This will cause the file to be opened.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
base.ActivateOptions();
if (m_securityContext == null)
{
m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
}
if (m_lockingModel == null)
{
m_lockingModel = new FileAppender.ExclusiveLock();
}
m_lockingModel.CurrentAppender=this;
using(SecurityContext.Impersonate(this))
{
m_fileName = ConvertToFullPath(m_fileName.Trim());
}
if (m_fileName != null)
{
SafeOpenFile(m_fileName, m_appendToFile);
}
else
{
LogLog.Warn(declaringType, "FileAppender: File option not set for appender ["+Name+"].");
LogLog.Warn(declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?");
}
}
#endregion Override implementation of AppenderSkeleton
#region Override implementation of TextWriterAppender
/// <summary>
/// Closes any previously opened file and calls the parent's <see cref="TextWriterAppender.Reset"/>.
/// </summary>
/// <remarks>
/// <para>
/// Resets the filename and the file stream.
/// </para>
/// </remarks>
override protected void Reset()
{
base.Reset();
m_fileName = null;
}
/// <summary>
/// Called to initialize the file writer
/// </summary>
/// <remarks>
/// <para>
/// Will be called for each logged message until the file is
/// successfully opened.
/// </para>
/// </remarks>
override protected void PrepareWriter()
{
SafeOpenFile(m_fileName, m_appendToFile);
}
/// <summary>
/// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/>
/// method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes a log statement to the output stream if the output stream exists
/// and is writable.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
if (m_stream.AcquireLock())
{
try
{
base.Append(loggingEvent);
}
finally
{
m_stream.ReleaseLock();
}
}
}
/// <summary>
/// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent[])"/>
/// method.
/// </summary>
/// <param name="loggingEvents">The array of events to log.</param>
/// <remarks>
/// <para>
/// Acquires the output file locks once before writing all the events to
/// the stream.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent[] loggingEvents)
{
if (m_stream.AcquireLock())
{
try
{
base.Append(loggingEvents);
}
finally
{
m_stream.ReleaseLock();
}
}
}
/// <summary>
/// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property.
/// </summary>
/// <remarks>
/// <para>
/// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property.
/// </para>
/// </remarks>
protected override void WriteFooter()
{
if (m_stream!=null)
{
//WriteFooter can be called even before a file is opened
m_stream.AcquireLock();
try
{
base.WriteFooter();
}
finally
{
m_stream.ReleaseLock();
}
}
}
/// <summary>
/// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property.
/// </summary>
/// <remarks>
/// <para>
/// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property.
/// </para>
/// </remarks>
protected override void WriteHeader()
{
if (m_stream!=null)
{
if (m_stream.AcquireLock())
{
try
{
base.WriteHeader();
}
finally
{
m_stream.ReleaseLock();
}
}
}
}
/// <summary>
/// Closes the underlying <see cref="TextWriter"/>.
/// </summary>
/// <remarks>
/// <para>
/// Closes the underlying <see cref="TextWriter"/>.
/// </para>
/// </remarks>
protected override void CloseWriter()
{
if (m_stream!=null)
{
m_stream.AcquireLock();
try
{
base.CloseWriter();
}
finally
{
m_stream.ReleaseLock();
}
}
}
#endregion Override implementation of TextWriterAppender
#region Public Instance Methods
/// <summary>
/// Closes the previously opened file.
/// </summary>
/// <remarks>
/// <para>
/// Writes the <see cref="ILayout.Footer"/> to the file and then
/// closes the file.
/// </para>
/// </remarks>
protected void CloseFile()
{
WriteFooterAndCloseWriter();
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Sets and <i>opens</i> the file where the log output will go. The specified file must be writable.
/// </summary>
/// <param name="fileName">The path to the log file. Must be a fully qualified path.</param>
/// <param name="append">If true will append to fileName. Otherwise will truncate fileName</param>
/// <remarks>
/// <para>
/// Calls <see cref="OpenFile"/> but guarantees not to throw an exception.
/// Errors are passed to the <see cref="TextWriterAppender.ErrorHandler"/>.
/// </para>
/// </remarks>
virtual protected void SafeOpenFile(string fileName, bool append)
{
try
{
OpenFile(fileName, append);
}
catch(Exception e)
{
ErrorHandler.Error("OpenFile("+fileName+","+append+") call failed.", e, ErrorCode.FileOpenFailure);
}
}
/// <summary>
/// Sets and <i>opens</i> the file where the log output will go. The specified file must be writable.
/// </summary>
/// <param name="fileName">The path to the log file. Must be a fully qualified path.</param>
/// <param name="append">If true will append to fileName. Otherwise will truncate fileName</param>
/// <remarks>
/// <para>
/// If there was already an opened file, then the previous file
/// is closed first.
/// </para>
/// <para>
/// This method will ensure that the directory structure
/// for the <paramref name="fileName"/> specified exists.
/// </para>
/// </remarks>
virtual protected void OpenFile(string fileName, bool append)
{
if (LogLog.IsErrorEnabled)
{
// Internal check that the fileName passed in is a rooted path
bool isPathRooted = false;
using(SecurityContext.Impersonate(this))
{
isPathRooted = Path.IsPathRooted(fileName);
}
if (!isPathRooted)
{
LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile("+fileName+"): File name is not fully qualified.");
}
}
lock(this)
{
Reset();
LogLog.Debug(declaringType, "Opening file for writing ["+fileName+"] append ["+append+"]");
// Save these for later, allowing retries if file open fails
m_fileName = fileName;
m_appendToFile = append;
LockingModel.CurrentAppender=this;
LockingModel.OpenFile(fileName,append,m_encoding);
m_stream=new LockingStream(LockingModel);
if (m_stream != null)
{
m_stream.AcquireLock();
try
{
SetQWForFiles(new StreamWriter(m_stream, m_encoding));
}
finally
{
m_stream.ReleaseLock();
}
}
WriteHeader();
}
}
/// <summary>
/// Sets the quiet writer used for file output
/// </summary>
/// <param name="fileStream">the file stream that has been opened for writing</param>
/// <remarks>
/// <para>
/// This implementation of <see cref="SetQWForFiles(Stream)"/> creates a <see cref="StreamWriter"/>
/// over the <paramref name="fileStream"/> and passes it to the
/// <see cref="SetQWForFiles(TextWriter)"/> method.
/// </para>
/// <para>
/// This method can be overridden by sub classes that want to wrap the
/// <see cref="Stream"/> in some way, for example to encrypt the output
/// data using a <c>System.Security.Cryptography.CryptoStream</c>.
/// </para>
/// </remarks>
virtual protected void SetQWForFiles(Stream fileStream)
{
SetQWForFiles(new StreamWriter(fileStream, m_encoding));
}
/// <summary>
/// Sets the quiet writer being used.
/// </summary>
/// <param name="writer">the writer over the file stream that has been opened for writing</param>
/// <remarks>
/// <para>
/// This method can be overridden by sub classes that want to
/// wrap the <see cref="TextWriter"/> in some way.
/// </para>
/// </remarks>
virtual protected void SetQWForFiles(TextWriter writer)
{
QuietWriter = new QuietTextWriter(writer, ErrorHandler);
}
#endregion Protected Instance Methods
#region Protected Static Methods
/// <summary>
/// Convert a path into a fully qualified path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// </remarks>
protected static string ConvertToFullPath(string path)
{
return SystemInfo.ConvertToFullPath(path);
}
#endregion Protected Static Methods
#region Private Instance Fields
/// <summary>
/// Flag to indicate if we should append to the file
/// or overwrite the file. The default is to append.
/// </summary>
private bool m_appendToFile = true;
/// <summary>
/// The name of the log file.
/// </summary>
private string m_fileName = null;
/// <summary>
/// The encoding to use for the file stream.
/// </summary>
private Encoding m_encoding = Encoding.Default;
/// <summary>
/// The security context to use for privileged calls
/// </summary>
private SecurityContext m_securityContext;
/// <summary>
/// The stream to log to. Has added locking semantics
/// </summary>
private FileAppender.LockingStream m_stream = null;
/// <summary>
/// The locking model to use
/// </summary>
private FileAppender.LockingModelBase m_lockingModel = new FileAppender.ExclusiveLock();
#endregion Private Instance Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the FileAppender class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(FileAppender);
#endregion Private Static Fields
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public abstract class HttpContent : IDisposable
{
private HttpContentHeaders _headers;
private MemoryStream _bufferedContent;
private object _contentReadStream; // Stream or Task<Stream>
private bool _disposed;
private bool _canCalculateLength;
internal const int MaxBufferSize = int.MaxValue;
internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8;
private const int UTF8CodePage = 65001;
private const int UTF8PreambleLength = 3;
private const byte UTF8PreambleByte0 = 0xEF;
private const byte UTF8PreambleByte1 = 0xBB;
private const byte UTF8PreambleByte2 = 0xBF;
private const int UTF8PreambleFirst2Bytes = 0xEFBB;
#if !uap
// UTF32 not supported on Phone
private const int UTF32CodePage = 12000;
private const int UTF32PreambleLength = 4;
private const byte UTF32PreambleByte0 = 0xFF;
private const byte UTF32PreambleByte1 = 0xFE;
private const byte UTF32PreambleByte2 = 0x00;
private const byte UTF32PreambleByte3 = 0x00;
#endif
private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE;
private const int UnicodeCodePage = 1200;
private const int UnicodePreambleLength = 2;
private const byte UnicodePreambleByte0 = 0xFF;
private const byte UnicodePreambleByte1 = 0xFE;
private const int BigEndianUnicodeCodePage = 1201;
private const int BigEndianUnicodePreambleLength = 2;
private const byte BigEndianUnicodePreambleByte0 = 0xFE;
private const byte BigEndianUnicodePreambleByte1 = 0xFF;
private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF;
#if DEBUG
static HttpContent()
{
// Ensure the encoding constants used in this class match the actual data from the Encoding class
AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes,
UTF8PreambleByte0,
UTF8PreambleByte1,
UTF8PreambleByte2);
#if !uap
// UTF32 not supported on Phone
AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UTF32PreambleByte0,
UTF32PreambleByte1,
UTF32PreambleByte2,
UTF32PreambleByte3);
#endif
AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes,
UnicodePreambleByte0,
UnicodePreambleByte1);
AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes,
BigEndianUnicodePreambleByte0,
BigEndianUnicodePreambleByte1);
}
private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble)
{
Debug.Assert(encoding != null);
Debug.Assert(preamble != null);
Debug.Assert(codePage == encoding.CodePage,
"Encoding code page mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage);
byte[] actualPreamble = encoding.GetPreamble();
Debug.Assert(preambleLength == actualPreamble.Length,
"Encoding preamble length mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length);
Debug.Assert(actualPreamble.Length >= 2);
int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1];
Debug.Assert(first2Bytes == actualFirst2Bytes,
"Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes);
Debug.Assert(preamble.Length == actualPreamble.Length,
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
for (int i = 0; i < preamble.Length; i++)
{
Debug.Assert(preamble[i] == actualPreamble[i],
"Encoding preamble mismatch for encoding: " + encoding.EncodingName,
"Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}",
BitConverter.ToString(preamble),
BitConverter.ToString(actualPreamble));
}
}
#endif
public HttpContentHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpContentHeaders(this);
}
return _headers;
}
}
private bool IsBuffered
{
get { return _bufferedContent != null; }
}
internal void SetBuffer(byte[] buffer, int offset, int count)
{
_bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true);
}
internal bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (_bufferedContent != null)
{
return _bufferedContent.TryGetBuffer(out buffer);
}
buffer = default;
return false;
}
protected HttpContent()
{
// Log to get an ID for the current content. This ID is used when the content gets associated to a message.
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// We start with the assumption that we can calculate the content length.
_canCalculateLength = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
public Task<string> ReadAsStringAsync()
{
CheckDisposed();
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString());
}
private string ReadBufferedContentAsString()
{
Debug.Assert(IsBuffered);
if (_bufferedContent.Length == 0)
{
return string.Empty;
}
ArraySegment<byte> buffer;
if (!TryGetBuffer(out buffer))
{
buffer = new ArraySegment<byte>(_bufferedContent.ToArray());
}
return ReadBufferAsString(buffer, Headers);
}
internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers)
{
// We don't validate the Content-Encoding header: If the content was encoded, it's the caller's
// responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the
// Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a
// decoded response stream.
Encoding encoding = null;
int bomLength = -1;
// If we do have encoding information in the 'Content-Type' header, use that information to convert
// the content to a string.
if ((headers.ContentType != null) && (headers.ContentType.CharSet != null))
{
try
{
encoding = Encoding.GetEncoding(headers.ContentType.CharSet);
// Byte-order-mark (BOM) characters may be present even if a charset was specified.
bomLength = GetPreambleLength(buffer, encoding);
}
catch (ArgumentException e)
{
throw new InvalidOperationException(SR.net_http_content_invalid_charset, e);
}
}
// If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present,
// then check for a BOM in the data to figure out the encoding.
if (encoding == null)
{
if (!TryDetectEncoding(buffer, out encoding, out bomLength))
{
// Use the default encoding (UTF8) if we couldn't detect one.
encoding = DefaultStringEncoding;
// We already checked to see if the data had a UTF8 BOM in TryDetectEncoding
// and DefaultStringEncoding is UTF8, so the bomLength is 0.
bomLength = 0;
}
}
// Drop the BOM when decoding the data.
return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength);
}
public Task<byte[]> ReadAsByteArrayAsync()
{
CheckDisposed();
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray());
}
internal byte[] ReadBufferedContentAsByteArray()
{
// The returned array is exposed out of the library, so use ToArray rather
// than TryGetBuffer in order to make a copy.
return _bufferedContent.ToArray();
}
public Task<Stream> ReadAsStreamAsync()
{
CheckDisposed();
// _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously
// initialized in TryReadAsStream), or a Task<Stream> (it was previously initialized here
// in ReadAsStreamAsync).
if (_contentReadStream == null) // don't yet have a Stream
{
Task<Stream> t = TryGetBuffer(out ArraySegment<byte> buffer) ?
Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)) :
CreateContentReadStreamAsync();
_contentReadStream = t;
return t;
}
else if (_contentReadStream is Task<Stream> t) // have a Task<Stream>
{
return t;
}
else
{
Debug.Assert(_contentReadStream is Stream, $"Expected a Stream, got ${_contentReadStream}");
Task<Stream> ts = Task.FromResult((Stream)_contentReadStream);
_contentReadStream = ts;
return ts;
}
}
internal Stream TryReadAsStream()
{
CheckDisposed();
// _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously
// initialized here in TryReadAsStream), or a Task<Stream> (it was previously initialized
// in ReadAsStreamAsync).
if (_contentReadStream == null) // don't yet have a Stream
{
Stream s = TryGetBuffer(out ArraySegment<byte> buffer) ?
new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false) :
TryCreateContentReadStream();
_contentReadStream = s;
return s;
}
else if (_contentReadStream is Stream s) // have a Stream
{
return s;
}
else // have a Task<Stream>
{
Debug.Assert(_contentReadStream is Task<Stream>, $"Expected a Task<Stream>, got ${_contentReadStream}");
Task<Stream> t = (Task<Stream>)_contentReadStream;
return t.Status == TaskStatus.RanToCompletion ? t.Result : null;
}
}
protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context);
// TODO #9071: Expose this publicly. Until it's public, only sealed or internal types should override it, and then change
// their SerializeToStreamAsync implementation to delegate to this one. They need to be sealed as otherwise an external
// type could derive from it and override SerializeToStreamAsync(stream, context) further, at which point when
// HttpClient calls SerializeToStreamAsync(stream, context, cancellationToken), their custom override will be skipped.
internal virtual Task SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken) =>
SerializeToStreamAsync(stream, context);
public Task CopyToAsync(Stream stream, TransportContext context) =>
CopyToAsync(stream, context, CancellationToken.None);
// TODO #9071: Expose this publicly.
internal Task CopyToAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
{
CheckDisposed();
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
try
{
ArraySegment<byte> buffer;
if (TryGetBuffer(out buffer))
{
return CopyToAsyncCore(stream.WriteAsync(new ReadOnlyMemory<byte>(buffer.Array, buffer.Offset, buffer.Count), cancellationToken));
}
else
{
Task task = SerializeToStreamAsync(stream, context, cancellationToken);
CheckTaskNotNull(task);
return CopyToAsyncCore(new ValueTask(task));
}
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
return Task.FromException(GetStreamCopyException(e));
}
}
private static async Task CopyToAsyncCore(ValueTask copyTask)
{
try
{
await copyTask.ConfigureAwait(false);
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
throw GetStreamCopyException(e);
}
}
public Task CopyToAsync(Stream stream)
{
return CopyToAsync(stream, null);
}
public Task LoadIntoBufferAsync()
{
return LoadIntoBufferAsync(MaxBufferSize);
}
// No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting
// in an exception being thrown while we're buffering.
// If buffering is used without a connection, it is supposed to be fast, thus no cancellation required.
public Task LoadIntoBufferAsync(long maxBufferSize) =>
LoadIntoBufferAsync(maxBufferSize, CancellationToken.None);
internal Task LoadIntoBufferAsync(long maxBufferSize, CancellationToken cancellationToken)
{
CheckDisposed();
if (maxBufferSize > HttpContent.MaxBufferSize)
{
// This should only be hit when called directly; HttpClient/HttpClientHandler
// will not exceed this limit.
throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
if (IsBuffered)
{
// If we already buffered the content, just return a completed task.
return Task.CompletedTask;
}
Exception error = null;
MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error);
if (tempBuffer == null)
{
// We don't throw in LoadIntoBufferAsync(): return a faulted task.
return Task.FromException(error);
}
try
{
Task task = SerializeToStreamAsync(tempBuffer, null, cancellationToken);
CheckTaskNotNull(task);
return LoadIntoBufferAsyncCore(task, tempBuffer);
}
catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e))
{
return Task.FromException(GetStreamCopyException(e));
}
// other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate
}
private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
{
try
{
await serializeToStreamTask.ConfigureAwait(false);
}
catch (Exception e)
{
tempBuffer.Dispose(); // Cleanup partially filled stream.
Exception we = GetStreamCopyException(e);
if (we != e) throw we;
throw;
}
try
{
tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data.
_bufferedContent = tempBuffer;
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
throw;
}
}
protected virtual Task<Stream> CreateContentReadStreamAsync()
{
// By default just buffer the content to a memory stream. Derived classes can override this behavior
// if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient
// way, like wrapping a read-only MemoryStream around the bytes/string)
return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent);
}
// As an optimization for internal consumers of HttpContent (e.g. HttpClient.GetStreamAsync), and for
// HttpContent-derived implementations that override CreateContentReadStreamAsync in a way that always
// or frequently returns synchronously-completed tasks, we can avoid the task allocation by enabling
// callers to try to get the Stream first synchronously.
internal virtual Stream TryCreateContentReadStream() => null;
// Derived types return true if they're able to compute the length. It's OK if derived types return false to
// indicate that they're not able to compute the length. The transport channel needs to decide what to do in
// that case (send chunked, buffer first, etc.).
protected internal abstract bool TryComputeLength(out long length);
internal long? GetComputedOrBufferLength()
{
CheckDisposed();
if (IsBuffered)
{
return _bufferedContent.Length;
}
// If we already tried to calculate the length, but the derived class returned 'false', then don't try
// again; just return null.
if (_canCalculateLength)
{
long length = 0;
if (TryComputeLength(out length))
{
return length;
}
// Set flag to make sure next time we don't try to compute the length, since we know that we're unable
// to do so.
_canCalculateLength = false;
}
return null;
}
private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
{
Contract.Ensures((Contract.Result<MemoryStream>() != null) ||
(Contract.ValueAtReturn<Exception>(out error) != null));
error = null;
// If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
// content length exceeds the max. buffer size.
long? contentLength = Headers.ContentLength;
if (contentLength != null)
{
Debug.Assert(contentLength >= 0);
if (contentLength > maxBufferSize)
{
error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
return null;
}
// We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize.
return new LimitMemoryStream((int)maxBufferSize, (int)contentLength);
}
// We couldn't determine the length of the buffer. Create a memory stream with an empty buffer.
return new LimitMemoryStream((int)maxBufferSize, 0);
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
if (_contentReadStream != null)
{
Stream s = _contentReadStream as Stream ??
(_contentReadStream is Task<Stream> t && t.Status == TaskStatus.RanToCompletion ? t.Result : null);
s?.Dispose();
_contentReadStream = null;
}
if (IsBuffered)
{
_bufferedContent.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Helpers
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private void CheckTaskNotNull(Task task)
{
if (task == null)
{
var e = new InvalidOperationException(SR.net_http_content_no_task_returned);
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
throw e;
}
}
private static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException;
private static Exception GetStreamCopyException(Exception originalException)
{
// HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
// provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
// types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
// exceptions (depending on the underlying transport), but just HttpRequestExceptions
// Custom stream should throw either IOException or HttpRequestException.
// We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
// don't want to hide such "usage error" exceptions in HttpRequestException.
// ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
// the response stream being closed.
return StreamCopyExceptionNeedsWrapping(originalException) ?
new HttpRequestException(SR.net_http_content_stream_copy_error, originalException) :
originalException;
}
private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding)
{
byte[] data = buffer.Array;
int offset = buffer.Offset;
int dataLength = buffer.Count;
Debug.Assert(data != null);
Debug.Assert(encoding != null);
switch (encoding.CodePage)
{
case UTF8CodePage:
return (dataLength >= UTF8PreambleLength
&& data[offset + 0] == UTF8PreambleByte0
&& data[offset + 1] == UTF8PreambleByte1
&& data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0;
#if !uap
// UTF32 not supported on Phone
case UTF32CodePage:
return (dataLength >= UTF32PreambleLength
&& data[offset + 0] == UTF32PreambleByte0
&& data[offset + 1] == UTF32PreambleByte1
&& data[offset + 2] == UTF32PreambleByte2
&& data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0;
#endif
case UnicodeCodePage:
return (dataLength >= UnicodePreambleLength
&& data[offset + 0] == UnicodePreambleByte0
&& data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0;
case BigEndianUnicodeCodePage:
return (dataLength >= BigEndianUnicodePreambleLength
&& data[offset + 0] == BigEndianUnicodePreambleByte0
&& data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0;
default:
byte[] preamble = encoding.GetPreamble();
return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0;
}
}
private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength)
{
byte[] data = buffer.Array;
int offset = buffer.Offset;
int dataLength = buffer.Count;
Debug.Assert(data != null);
if (dataLength >= 2)
{
int first2Bytes = data[offset + 0] << 8 | data[offset + 1];
switch (first2Bytes)
{
case UTF8PreambleFirst2Bytes:
if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2)
{
encoding = Encoding.UTF8;
preambleLength = UTF8PreambleLength;
return true;
}
break;
case UTF32OrUnicodePreambleFirst2Bytes:
#if !uap
// UTF32 not supported on Phone
if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3)
{
encoding = Encoding.UTF32;
preambleLength = UTF32PreambleLength;
}
else
#endif
{
encoding = Encoding.Unicode;
preambleLength = UnicodePreambleLength;
}
return true;
case BigEndianUnicodePreambleFirst2Bytes:
encoding = Encoding.BigEndianUnicode;
preambleLength = BigEndianUnicodePreambleLength;
return true;
}
}
encoding = null;
preambleLength = 0;
return false;
}
private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix)
{
byte[] byteArray = buffer.Array;
if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0)
return false;
for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++)
{
if (prefix[i] != byteArray[j])
return false;
}
return true;
}
#endregion Helpers
private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc)
{
await waitTask.ConfigureAwait(false);
return returnFunc(state);
}
private static Exception CreateOverCapacityException(int maxBufferSize)
{
return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize));
}
internal sealed class LimitMemoryStream : MemoryStream
{
private readonly int _maxSize;
public LimitMemoryStream(int maxSize, int capacity)
: base(capacity)
{
Debug.Assert(capacity <= maxSize);
_maxSize = maxSize;
}
public byte[] GetSizedBuffer()
{
ArraySegment<byte> buffer;
return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ?
buffer.Array :
ToArray();
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckSize(count);
base.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
CheckSize(1);
base.WriteByte(value);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckSize(count);
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
CheckSize(buffer.Length);
return base.WriteAsync(buffer, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
CheckSize(count);
return base.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
base.EndWrite(asyncResult);
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
ArraySegment<byte> buffer;
if (TryGetBuffer(out buffer))
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
long pos = Position;
long length = Length;
Position = length;
long bytesToWrite = length - pos;
return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken);
}
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
private void CheckSize(int countToAdd)
{
if (_maxSize - Length < countToAdd)
{
throw CreateOverCapacityException(_maxSize);
}
}
}
internal sealed class LimitArrayPoolWriteStream : Stream
{
private const int MaxByteArrayLength = 0x7FFFFFC7;
private const int InitialLength = 256;
private readonly int _maxBufferSize;
private byte[] _buffer;
private int _length;
public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { }
public LimitArrayPoolWriteStream(int maxBufferSize, long capacity)
{
if (capacity < InitialLength)
{
capacity = InitialLength;
}
else if (capacity > maxBufferSize)
{
throw CreateOverCapacityException(maxBufferSize);
}
_maxBufferSize = maxBufferSize;
_buffer = ArrayPool<byte>.Shared.Rent((int)capacity);
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_buffer != null);
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = null;
base.Dispose(disposing);
}
public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length);
public byte[] ToArray()
{
var arr = new byte[_length];
Buffer.BlockCopy(_buffer, 0, arr, 0, _length);
return arr;
}
private void EnsureCapacity(int value)
{
if ((uint)value > (uint)_maxBufferSize) // value cast handles overflow to negative as well
{
throw CreateOverCapacityException(_maxBufferSize);
}
else if (value > _buffer.Length)
{
Grow(value);
}
}
private void Grow(int value)
{
Debug.Assert(value > _buffer.Length);
// Extract the current buffer to be replaced.
byte[] currentBuffer = _buffer;
_buffer = null;
// Determine the capacity to request for the new buffer. It should be
// at least twice as long as the current one, if not more if the requested
// value is more than that. If the new value would put it longer than the max
// allowed byte array, than shrink to that (and if the required length is actually
// longer than that, we'll let the runtime throw).
uint twiceLength = 2 * (uint)currentBuffer.Length;
int newCapacity = twiceLength > MaxByteArrayLength ?
(value > MaxByteArrayLength ? value : MaxByteArrayLength) :
Math.Max(value, (int)twiceLength);
// Get a new buffer, copy the current one to it, return the current one, and
// set the new buffer as current.
byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity);
Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length);
ArrayPool<byte>.Shared.Return(currentBuffer);
_buffer = newBuffer;
}
public override void Write(byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
EnsureCapacity(_length + count);
Buffer.BlockCopy(buffer, offset, _buffer, _length, count);
_length += count;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
EnsureCapacity(_length + buffer.Length);
buffer.CopyTo(new Span<byte>(_buffer, _length, buffer.Length));
_length += buffer.Length;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
Write(buffer.Span);
return default;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
public override void WriteByte(byte value)
{
int newLength = _length + 1;
EnsureCapacity(newLength);
_buffer[_length] = value;
_length = newLength;
}
public override void Flush() { }
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override long Length => _length;
public override bool CanWrite => true;
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
}
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit
{
using System;
using BusConfigurators;
using EndpointConfigurators;
using Magnum.Reflection;
using Newtonsoft.Json;
using Serialization;
public static class SerializerConfigurationExtensions
{
public static T UseJsonSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SetDefaultSerializer<JsonMessageSerializer>();
return configurator;
}
public static T ConfigureJsonSerializer<T>(this T configurator,
Func<JsonSerializerSettings, JsonSerializerSettings> configure)
{
JsonMessageSerializer.SerializerSettings = configure(JsonMessageSerializer.SerializerSettings);
return configurator;
}
public static T ConfigureJsonDeserializer<T>(this T configurator,
Func<JsonSerializerSettings, JsonSerializerSettings> configure)
{
JsonMessageSerializer.DeserializerSettings = configure(JsonMessageSerializer.DeserializerSettings);
return configurator;
}
public static T UseBsonSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SetDefaultSerializer<BsonMessageSerializer>();
return configurator;
}
public static T UseXmlSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SetDefaultSerializer<XmlMessageSerializer>();
return configurator;
}
public static T UseVersionOneXmlSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SetDefaultSerializer<VersionOneXmlMessageSerializer>();
return configurator;
}
public static T UseBinarySerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SetDefaultSerializer<BinaryMessageSerializer>();
return configurator;
}
/// <summary>
/// Support the receipt of messages serialized by the JsonMessageSerializer
/// </summary>
public static T SupportJsonSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SupportMessageSerializer<JsonMessageSerializer>();
return configurator;
}
public static T SupportBsonSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SupportMessageSerializer<BsonMessageSerializer>();
return configurator;
}
public static T SupportXmlSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SupportMessageSerializer<XmlMessageSerializer>();
return configurator;
}
public static T SupportVersionOneXmlSerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SupportMessageSerializer<VersionOneXmlMessageSerializer>();
return configurator;
}
public static T SupportBinarySerializer<T>(this T configurator)
where T : EndpointFactoryConfigurator
{
configurator.SupportMessageSerializer<BinaryMessageSerializer>();
return configurator;
}
public static ServiceBusConfigurator SupportMessageSerializer<TSerializer>(
this ServiceBusConfigurator configurator)
where TSerializer : IMessageSerializer, new()
{
return SupportMessageSerializer(configurator, () => new TSerializer());
}
public static EndpointFactoryConfigurator SupportMessageSerializer<TSerializer>(
this EndpointFactoryConfigurator configurator)
where TSerializer : IMessageSerializer, new()
{
return SupportMessageSerializer(configurator, () => new TSerializer());
}
static T SetDefaultSerializer<T>(this T configurator, Func<IMessageSerializer> serializerFactory)
where T : EndpointFactoryConfigurator
{
var serializerConfigurator = new DefaultSerializerEndpointFactoryConfigurator(serializerFactory);
configurator.AddEndpointFactoryConfigurator(serializerConfigurator);
return configurator;
}
static T SupportMessageSerializer<T>(this T configurator, Func<IMessageSerializer> serializerFactory)
where T : EndpointFactoryConfigurator
{
var serializerConfigurator = new AddSerializerEndpointFactoryConfigurator(serializerFactory);
configurator.AddEndpointFactoryConfigurator(serializerConfigurator);
return configurator;
}
/// <summary>
/// Sets the default message serializer for endpoints
/// </summary>
/// <typeparam name="TSerializer"></typeparam>
/// <param name="configurator"></param>
/// <returns></returns>
public static EndpointFactoryConfigurator SetDefaultSerializer<TSerializer>(
this EndpointFactoryConfigurator configurator)
where TSerializer : IMessageSerializer, new()
{
return SetDefaultSerializer(configurator, () => new TSerializer());
}
/// <summary>
/// Sets the default message serializer for endpoints
/// </summary>
/// <typeparam name="TSerializer"></typeparam>
/// <param name="configurator"></param>
/// <returns></returns>
public static ServiceBusConfigurator SetDefaultSerializer<TSerializer>(this ServiceBusConfigurator configurator)
where TSerializer : IMessageSerializer, new()
{
return SetDefaultSerializer(configurator, () => new TSerializer());
}
/// <summary>
/// Sets the default message serializer for endpoints
/// </summary>
/// <param name="configurator"></param>
/// <param name="serializerType"></param>
/// <returns></returns>
public static T SetDefaultSerializer<T>(this T configurator,
Type serializerType)
where T : EndpointFactoryConfigurator
{
return SetDefaultSerializer(configurator, () => (IMessageSerializer)FastActivator.Create(serializerType));
}
/// <summary>
/// Sets the default message serializer for endpoints
/// </summary>
/// <param name="configurator"></param>
/// <param name="serializer"></param>
/// <returns></returns>
public static T SetDefaultSerializer<T>(this T configurator,
IMessageSerializer serializer)
where T : EndpointFactoryConfigurator
{
return SetDefaultSerializer(configurator, () => serializer);
}
// -----------------------------------------------------------------------
public static ServiceBusConfigurator SetSupportedMessageSerializers<T>(
this ServiceBusConfigurator configurator)
where T : ISupportedMessageSerializers, new()
{
return SetSupportedMessageSerializers(configurator, () => new T());
}
public static EndpointFactoryConfigurator SetSupportedMessageSerializers<T>(
this EndpointFactoryConfigurator configurator)
where T : ISupportedMessageSerializers, new()
{
return SetSupportedMessageSerializers(configurator, () => new T());
}
/// <summary>
/// Sets the default message serializer for endpoints
/// </summary>
/// <param name="configurator"></param>
/// <param name="supportedSerializer"></param>
/// <returns></returns>
public static T SetSupportedMessageSerializers<T>(this T configurator,
ISupportedMessageSerializers supportedSerializer)
where T : EndpointFactoryConfigurator
{
return SetSupportedMessageSerializers(configurator, () => supportedSerializer);
}
static T SetSupportedMessageSerializers<T>(this T configurator, Func<ISupportedMessageSerializers> supportedSerializers)
where T : EndpointFactoryConfigurator
{
var serializerConfigurator = new SetSupportedMessageSerializersEndpointFactoryConfigurator(supportedSerializers);
configurator.AddEndpointFactoryConfigurator(serializerConfigurator);
return configurator;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
using Pathfinding.Voxels;
namespace Pathfinding.Voxels {
/** Voxelizer for recast graphs.
*
* In comments: units wu are World Units, vx are Voxels
*
* \astarpro
*/
public partial class Voxelize {
public List<ExtraMesh> inputExtraMeshes;
protected Vector3[] inputVertices;
protected int[] inputTriangles;
/* Minimum floor to 'ceiling' height that will still allow the floor area to
* be considered walkable. [Limit: > 0] [Units: wu] */
//public float walkableHeight = 0.8F;
/* Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: wu] */
//public float walkableClimb = 0.8F;
/** Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: vx] */
public readonly int voxelWalkableClimb;
/** Minimum floor to 'ceiling' height that will still allow the floor area to
* be considered walkable. [Limit: >= 3] [Units: vx] */
public readonly uint voxelWalkableHeight;
/** The xz-plane cell size to use for fields. [Limit: > 0] [Units: wu] */
public readonly float cellSize = 0.2F;
/** The y-axis cell size to use for fields. [Limit: > 0] [Units: wu] */
public readonly float cellHeight = 0.1F;
public int minRegionSize = 100;
/** The size of the non-navigable border around the heightfield. [Limit: >=0] [Units: vx] */
public int borderSize = 0;
/** The maximum allowed length for contour edges along the border of the mesh. [Limit: >= 0] [Units: vx] */
public float maxEdgeLength = 20;
/** The maximum slope that is considered walkable. [Limits: 0 <= value < 90] [Units: Degrees] */
public float maxSlope = 30;
public RecastGraph.RelevantGraphSurfaceMode relevantGraphSurfaceMode;
/** The world AABB to rasterize */
public Bounds forcedBounds;
public VoxelArea voxelArea;
public VoxelContourSet countourSet;
/** Width in voxels.
* Must match the #forcedBounds
*/
public int width;
/** Depth in voxels.
* Must match the #forcedBounds
*/
public int depth;
#region Debug
public Vector3 voxelOffset;
public Vector3 CompactSpanToVector (int x, int z, int i) {
return voxelOffset+new Vector3((x+0.5f)*cellSize, voxelArea.compactSpans[i].y*cellHeight, (z+0.5f)*cellSize);
}
public void VectorToIndex (Vector3 p, out int x, out int z) {
p -= voxelOffset;
x = Mathf.RoundToInt((p.x / cellSize) - 0.5f);
z = Mathf.RoundToInt((p.z / cellSize) - 0.5f);
}
#endregion
#region Constants /** @name Constants @{ */
public const uint NotConnected = 0x3f;
/** Unmotivated variable, but let's clamp the layers at 65535 */
public const int MaxLayers = 65535;
/** \todo : Check up on this variable */
public const int MaxRegions = 500;
public const int UnwalkableArea = 0;
/** If heightfield region ID has the following bit set, the region is on border area
* and excluded from many calculations. */
public const ushort BorderReg = 0x8000;
/** If contour region ID has the following bit set, the vertex will be later
* removed in order to match the segments and vertices at tile boundaries. */
public const int RC_BORDER_VERTEX = 0x10000;
public const int RC_AREA_BORDER = 0x20000;
public const int VERTEX_BUCKET_COUNT = 1<<12;
public const int RC_CONTOUR_TESS_WALL_EDGES = 0x01; // Tessellate wall edges
public const int RC_CONTOUR_TESS_AREA_EDGES = 0x02; // Tessellate edges between areas.
/** Mask used with contours to extract region id. */
public const int ContourRegMask = 0xffff;
#endregion /** @} */
public string debugString = "";
public void OnGUI () {
GUI.Label(new Rect(5, 5, 200, Screen.height), debugString);
}
public readonly Vector3 cellScale;
public readonly Vector3 cellScaleDivision;
public Voxelize (float ch, float cs, float wc, float wh, float ms) {
cellSize = cs;
cellHeight = ch;
float walkableHeight = wh;
float walkableClimb = wc;
maxSlope = ms;
cellScale = new Vector3(cellSize, cellHeight, cellSize);
cellScaleDivision = new Vector3(1F/cellSize, 1F/cellHeight, 1F/cellSize);
voxelWalkableHeight = (uint)(walkableHeight/cellHeight);
voxelWalkableClimb = Mathf.RoundToInt(walkableClimb/cellHeight);
}
public void CollectMeshes () {
CollectMeshes(inputExtraMeshes, forcedBounds, out inputVertices, out inputTriangles);
}
public static void CollectMeshes (List<ExtraMesh> extraMeshes, Bounds bounds, out Vector3[] verts, out int[] tris) {
verts = null;
tris = null;
}
public void Init () {
//Initialize the voxel area
if (voxelArea == null || voxelArea.width != width || voxelArea.depth != depth)
voxelArea = new VoxelArea(width, depth);
else voxelArea.Reset();
}
public void VoxelizeInput () {
AstarProfiler.StartProfile("Build Navigation Mesh");
AstarProfiler.StartProfile("Voxelizing - Step 1");
Vector3 min = forcedBounds.min;
voxelOffset = min;
// Scale factor from world space to voxel space
float ics = 1F/cellSize;
float ich = 1F/cellHeight;
AstarProfiler.EndProfile("Voxelizing - Step 1");
AstarProfiler.StartProfile("Voxelizing - Step 2 - Init");
float slopeLimit = Mathf.Cos(Mathf.Atan(Mathf.Tan(maxSlope*Mathf.Deg2Rad)*(ich*cellSize)));
// Temporary arrays used for rasterization
float[] vTris = new float[3*3];
float[] vOut = new float[7*3];
float[] vRow = new float[7*3];
float[] vCellOut = new float[7*3];
float[] vCell = new float[7*3];
if (inputExtraMeshes == null) throw new System.NullReferenceException("inputExtraMeshes not set");
//Find the largest lengths of vertex arrays and check for meshes which can be skipped
int maxVerts = 0;
for (int m = 0; m < inputExtraMeshes.Count; m++) {
if (!inputExtraMeshes[m].bounds.Intersects(forcedBounds)) continue;
maxVerts = System.Math.Max(inputExtraMeshes[m].vertices.Length, maxVerts);
}
//Create buffer, here vertices will be stored multiplied with the local-to-voxel-space matrix
Vector3[] verts = new Vector3[maxVerts];
// First subtract min, then scale to voxel space (one unit equals one voxel along the x and z axes)
// then subtract half a voxel to fix rounding
Matrix4x4 voxelMatrix = Matrix4x4.TRS(-new Vector3(0.5f, 0, 0.5f), Quaternion.identity, Vector3.one) * Matrix4x4.Scale(new Vector3(ics, ich, ics)) * Matrix4x4.TRS(-min, Quaternion.identity, Vector3.one);
AstarProfiler.EndProfile("Voxelizing - Step 2 - Init");
AstarProfiler.StartProfile("Voxelizing - Step 2");
for (int m = 0; m < inputExtraMeshes.Count; m++) {
ExtraMesh mesh = inputExtraMeshes[m];
if (!mesh.bounds.Intersects(forcedBounds)) continue;
Matrix4x4 matrix = mesh.matrix;
matrix = voxelMatrix * matrix;
// Flip the orientation of all faces if the mesh is scaled in such a way
// that the face orientations would change
// This happens for example if a mesh has a negative scale along an odd number of axes
// e.g it happens for the scale (-1, 1, 1) but not for (-1, -1, 1) or (1,1,1)
var flipOrientation = VectorMath.ReversesFaceOrientations(matrix);
Vector3[] vs = mesh.vertices;
int[] tris = mesh.triangles;
int trisLength = tris.Length;
for (int i = 0; i < vs.Length; i++) verts[i] = matrix.MultiplyPoint3x4(vs[i]);
//AstarProfiler.StartFastProfile(0);
int mesharea = mesh.area;
for (int i = 0; i < trisLength; i += 3) {
Vector3 p1;
Vector3 p2;
Vector3 p3;
int minX;
int minZ;
int maxX;
int maxZ;
p1 = verts[tris[i]];
p2 = verts[tris[i+1]];
p3 = verts[tris[i+2]];
if (flipOrientation) {
var tmp = p1;
p1 = p3;
p3 = tmp;
}
minX = (int)(Utility.Min(p1.x, p2.x, p3.x));
minZ = (int)(Utility.Min(p1.z, p2.z, p3.z));
maxX = (int)System.Math.Ceiling(Utility.Max(p1.x, p2.x, p3.x));
maxZ = (int)System.Math.Ceiling(Utility.Max(p1.z, p2.z, p3.z));
minX = Mathf.Clamp(minX, 0, voxelArea.width-1);
maxX = Mathf.Clamp(maxX, 0, voxelArea.width-1);
minZ = Mathf.Clamp(minZ, 0, voxelArea.depth-1);
maxZ = Mathf.Clamp(maxZ, 0, voxelArea.depth-1);
if (minX >= voxelArea.width || minZ >= voxelArea.depth || maxX <= 0 || maxZ <= 0) continue;
// Debug code
//Debug.DrawLine (p1*cellSize+min+Vector3.up*0.2F,p2*cellSize+voxelOffset+Vector3.up*0.1F,Color.red);
//Debug.DrawLine (p1*cellSize+min,p2*cellSize+voxelOffset,Color.red, 1);
//Debug.DrawLine (p2*cellSize+min,p3*cellSize+voxelOffset,Color.red, 1);
//Debug.DrawLine (p3*cellSize+min,p1*cellSize+voxelOffset,Color.red, 1);
Vector3 normal;
int area;
//AstarProfiler.StartProfile ("Rasterize...");
normal = Vector3.Cross(p2-p1, p3-p1);
float dot = Vector3.Dot(normal.normalized, Vector3.up);
if (dot < slopeLimit) {
area = UnwalkableArea;
} else {
area = 1 + mesharea;
}
Utility.CopyVector(vTris, 0, p1);
Utility.CopyVector(vTris, 3, p2);
Utility.CopyVector(vTris, 6, p3);
for (int x = minX; x <= maxX; x++) {
int nrow = Utility.ClipPolygon(vTris, 3, vOut, 1F, -x+0.5F, 0);
if (nrow < 3) {
continue;
}
nrow = Utility.ClipPolygon(vOut, nrow, vRow, -1F, x+0.5F, 0);
if (nrow < 3) {
continue;
}
float clampZ1 = vRow[2];
float clampZ2 = vRow[2];
for (int q = 1; q < nrow; q++) {
float val = vRow[q*3+2];
clampZ1 = System.Math.Min(clampZ1, val);
clampZ2 = System.Math.Max(clampZ2, val);
}
int clampZ1I = Mathf.Clamp((int)System.Math.Round(clampZ1), 0, voxelArea.depth-1);
int clampZ2I = Mathf.Clamp((int)System.Math.Round(clampZ2), 0, voxelArea.depth-1);
for (int z = clampZ1I; z <= clampZ2I; z++) {
//AstarProfiler.StartFastProfile(1);
int ncell = Utility.ClipPolygon(vRow, nrow, vCellOut, 1F, -z+0.5F, 2);
if (ncell < 3) {
//AstarProfiler.EndFastProfile(1);
continue;
}
ncell = Utility.ClipPolygonY(vCellOut, ncell, vCell, -1F, z+0.5F, 2);
if (ncell < 3) {
//AstarProfiler.EndFastProfile(1);
continue;
}
//AstarProfiler.EndFastProfile(1);
//AstarProfiler.StartFastProfile(2);
float sMin = vCell[1];
float sMax = vCell[1];
for (int q = 1; q < ncell; q++) {
float val = vCell[q*3+1];
sMin = System.Math.Min(sMin, val);
sMax = System.Math.Max(sMax, val);
}
//AstarProfiler.EndFastProfile(2);
int maxi = (int)System.Math.Ceiling(sMax);
// Skip span if below the bounding box
if (maxi >= 0) {
// Make sure mini >= 0
int mini = System.Math.Max(0, (int)sMin);
// Make sure the span is at least 1 voxel high
maxi = System.Math.Max(mini+1, maxi);
voxelArea.AddLinkedSpan(z*voxelArea.width+x, (uint)mini, (uint)maxi, area, voxelWalkableClimb);
}
}
}
}
//AstarProfiler.EndFastProfile(0);
//AstarProfiler.EndProfile ("Rasterize...");
}
AstarProfiler.EndProfile("Voxelizing - Step 2");
}
public void DebugDrawSpans () {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
int wd = voxelArea.width*voxelArea.depth;
var min = forcedBounds.min;
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) {
for (int x = 0; x < voxelArea.width; x++) {
for (int s = z+x; s != -1 && spans[s].bottom != VoxelArea.InvalidSpanValue; s = spans[s].next) {
uint bottom = spans[s].top;
uint top = spans[s].next != -1 ? spans[spans[s].next].bottom : VoxelArea.MaxHeight;
if (bottom > top) {
Debug.Log(bottom + " " + top);
Debug.DrawLine(new Vector3(x*cellSize, bottom*cellHeight, pz*cellSize)+min, new Vector3(x*cellSize, top*cellHeight, pz*cellSize)+min, Color.yellow, 1);
}
//Debug.DrawRay (p,voxelArea.VectorDirection[d]*cellSize*0.5F,Color.red);
if (top - bottom < voxelWalkableHeight) {
//spans[s].area = UnwalkableArea;
}
}
}
}
#else
Debug.LogError("This debug method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
}
public void DebugDrawCompactSpans () {
int sCount = voxelArea.compactSpans.Length;
Vector3[] debugPointsTop = new Vector3[sCount];
Vector3[] debugPointsBottom = new Vector3[sCount];
Color[] debugColors = new Color[sCount];
int debugPointsCount = 0;
int wd = voxelArea.width*voxelArea.depth;
var min = forcedBounds.min;
for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) {
for (int x = 0; x < voxelArea.width; x++) {
Vector3 p = new Vector3(x, 0, pz)*cellSize+min;
//CompactVoxelCell c = voxelArea.compactCells[x+z];
CompactVoxelCell c = voxelArea.compactCells[x+z];
//if (c.count == 0) {
// Debug.DrawRay (p,Vector3.up,Color.red);
//}
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
p.y = ((float)(s.y+0.1F))*cellHeight+min.y;
debugPointsTop[debugPointsCount] = p;
p.y = ((float)s.y)*cellHeight+min.y;
debugPointsBottom[debugPointsCount] = p;
Color col = Color.black;
switch (s.reg) {
case 0:
col = Color.red;
break;
case 1:
col = Color.green;
break;
case 2:
col = Color.yellow;
break;
case 3:
col = Color.magenta;
break;
}
debugColors[debugPointsCount] = col;//Color.Lerp (Color.black, Color.white , (float)dst[i] / (float)voxelArea.maxDistance);//(float)(Mathf.Abs(dst[i]-src[i])) / (float)5);//s.area == 1 ? Color.green : (s.area == 2 ? Color.yellow : Color.red);
debugPointsCount++;
//Debug.DrawRay (p,Vector3.up*0.5F,Color.green);
}
}
}
DebugUtility.DrawCubes(debugPointsTop, debugPointsBottom, debugColors, cellSize);
}
public void BuildCompactField () {
AstarProfiler.StartProfile("Build Compact Voxel Field");
//Build compact representation
int spanCount = voxelArea.GetSpanCount();
voxelArea.compactSpanCount = spanCount;
if (voxelArea.compactSpans == null || voxelArea.compactSpans.Length < spanCount) {
voxelArea.compactSpans = new CompactVoxelSpan[spanCount];
voxelArea.areaTypes = new int[spanCount];
}
uint idx = 0;
int w = voxelArea.width;
int d = voxelArea.depth;
int wd = w*d;
if (this.voxelWalkableHeight >= 0xFFFF) {
Debug.LogWarning("Too high walkable height to guarantee correctness. Increase voxel height or lower walkable height.");
}
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
#endif
//Parallel.For (0, voxelArea.depth, delegate (int pz) {
for (int z = 0, pz = 0; z < wd; z += w, pz++) {
for (int x = 0; x < w; x++) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
int spanIndex = x+z;
if (spans[spanIndex].bottom == VoxelArea.InvalidSpanValue) {
voxelArea.compactCells[x+z] = new CompactVoxelCell(0, 0);
continue;
}
uint index = idx;
uint count = 0;
//Vector3 p = new Vector3(x,0,pz)*cellSize+voxelOffset;
while (spanIndex != -1) {
if (spans[spanIndex].area != UnwalkableArea) {
int bottom = (int)spans[spanIndex].top;
int next = spans[spanIndex].next;
int top = next != -1 ? (int)spans[next].bottom : VoxelArea.MaxHeightInt;
voxelArea.compactSpans[idx] = new CompactVoxelSpan((ushort)(bottom > 0xFFFF ? 0xFFFF : bottom), (uint)(top-bottom > 0xFFFF ? 0xFFFF : top-bottom));
voxelArea.areaTypes[idx] = spans[spanIndex].area;
idx++;
count++;
}
spanIndex = spans[spanIndex].next;
}
voxelArea.compactCells[x+z] = new CompactVoxelCell(index, count);
#else
VoxelSpan s = voxelArea.cells[x+z].firstSpan;
if (s == null) {
voxelArea.compactCells[x+z] = new CompactVoxelCell(0, 0);
continue;
}
uint index = idx;
uint count = 0;
//Vector3 p = new Vector3(x,0,pz)*cellSize+voxelOffset;
while (s != null) {
if (s.area != UnwalkableArea) {
int bottom = (int)s.top;
int top = s.next != null ? (int)s.next.bottom : VoxelArea.MaxHeightInt;
voxelArea.compactSpans[idx] = new CompactVoxelSpan((ushort)AstarMath.Clamp(bottom, 0, 0xffff), (uint)AstarMath.Clamp(top-bottom, 0, 0xffff));
voxelArea.areaTypes[idx] = s.area;
idx++;
count++;
}
s = s.next;
}
voxelArea.compactCells[x+z] = new CompactVoxelCell(index, count);
#endif
}
}
AstarProfiler.EndProfile("Build Compact Voxel Field");
}
public void BuildVoxelConnections () {
AstarProfiler.StartProfile("Build Voxel Connections");
int wd = voxelArea.width*voxelArea.depth;
CompactVoxelSpan[] spans = voxelArea.compactSpans;
CompactVoxelCell[] cells = voxelArea.compactCells;
//Build voxel connections
for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) {
//System.Threading.ManualResetEvent[] handles = new System.Threading.ManualResetEvent[voxelArea.depth];
//This will run the loop in multiple threads (speedup by ? 40%)
//Parallel.For (0, voxelArea.depth, delegate (int pz) {
//System.Threading.WaitCallback del = delegate (System.Object _pz) {
//int pz = (int)_pz;
//int z = pz*voxelArea.width;
for (int x = 0; x < voxelArea.width; x++) {
CompactVoxelCell c = cells[x+z];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) {
CompactVoxelSpan s = spans[i];
spans[i].con = 0xFFFFFFFF;
for (int d = 0; d < 4; d++) {
int nx = x+voxelArea.DirectionX[d];
int nz = z+voxelArea.DirectionZ[d];
if (nx < 0 || nz < 0 || nz >= wd || nx >= voxelArea.width) {
continue;
}
CompactVoxelCell nc = cells[nx+nz];
for (int k = (int)nc.index, nk = (int)(nc.index+nc.count); k < nk; k++) {
CompactVoxelSpan ns = spans[k];
int bottom = System.Math.Max(s.y, ns.y);
int top = System.Math.Min((int)s.y+(int)s.h, (int)ns.y+(int)ns.h);
if ((top-bottom) >= voxelWalkableHeight && System.Math.Abs((int)ns.y - (int)s.y) <= voxelWalkableClimb) {
uint connIdx = (uint)k - nc.index;
if (connIdx > MaxLayers) {
Debug.LogError("Too many layers");
continue;
}
spans[i].SetConnection(d, connIdx);
break;
}
}
}
}
}
//handles[pz].Set ();
//};
//});
}
/*for (int z=0, pz = 0;z < wd;z += voxelArea.width, pz++) {
* handles[pz] = new System.Threading.ManualResetEvent(false);
* System.Threading.ThreadPool.QueueUserWorkItem (del, pz);
* }
*
* System.Threading.WaitHandle.WaitAll (handles);*/
AstarProfiler.EndProfile("Build Voxel Connections");
}
void DrawLine (int a, int b, int[] indices, int[] verts, Color col) {
int p1 = (indices[a] & 0x0fffffff) * 4;
int p2 = (indices[b] & 0x0fffffff) * 4;
Debug.DrawLine(ConvertPosCorrZ(verts[p1+0], verts[p1+1], verts[p1+2]), ConvertPosCorrZ(verts[p2+0], verts[p2+1], verts[p2+2]), col);
}
Vector3 ConvertPos (int x, int y, int z) {
Vector3 p = Vector3.Scale(
new Vector3(
x+0.5F,
y,
(z/(float)voxelArea.width)+0.5F
)
, cellScale)
+voxelOffset;
return p;
}
Vector3 ConvertPosCorrZ (int x, int y, int z) {
Vector3 p = Vector3.Scale(
new Vector3(
x,
y,
z
)
, cellScale)
+voxelOffset;
return p;
}
Vector3 ConvertPosWithoutOffset (int x, int y, int z) {
Vector3 p = Vector3.Scale(
new Vector3(
x,
y,
(z/(float)voxelArea.width)
)
, cellScale)
+voxelOffset;
return p;
}
Vector3 ConvertPosition (int x, int z, int i) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
return new Vector3(x*cellSize, s.y*cellHeight, (z/(float)voxelArea.width)*cellSize)+voxelOffset;
}
public void ErodeWalkableArea (int radius) {
AstarProfiler.StartProfile("Erode Walkable Area");
ushort[] src = voxelArea.tmpUShortArr;
if (src == null || src.Length < voxelArea.compactSpanCount) {
src = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
}
Pathfinding.Util.Memory.MemSet<ushort>(src, 0xffff, sizeof(ushort));
//for (int i=0;i<src.Length;i++) {
// src[i] = 0xffff;
//}
CalculateDistanceField(src);
for (int i = 0; i < src.Length; i++) {
//Note multiplied with 2 because the distance field increments distance by 2 for each voxel (and 3 for diagonal)
if (src[i] < radius*2) {
voxelArea.areaTypes[i] = UnwalkableArea;
}
}
AstarProfiler.EndProfile("Erode Walkable Area");
}
public void BuildDistanceField () {
AstarProfiler.StartProfile("Build Distance Field");
ushort[] src = voxelArea.tmpUShortArr;
if (src == null || src.Length < voxelArea.compactSpanCount) {
src = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
}
Pathfinding.Util.Memory.MemSet<ushort>(src, 0xffff, sizeof(ushort));
//for (int i=0;i<src.Length;i++) {
// src[i] = 0xffff;
//}
voxelArea.maxDistance = CalculateDistanceField(src);
ushort[] dst = voxelArea.dist;
if (dst == null || dst.Length < voxelArea.compactSpanCount) {
dst = new ushort[voxelArea.compactSpanCount];
}
dst = BoxBlur(src, dst);
voxelArea.dist = dst;
AstarProfiler.EndProfile("Build Distance Field");
}
/** \todo Complete the ErodeVoxels function translation */
[System.Obsolete("This function is not complete and should not be used")]
public void ErodeVoxels (int radius) {
if (radius > 255) {
Debug.LogError("Max Erode Radius is 255");
radius = 255;
}
int wd = voxelArea.width*voxelArea.depth;
int[] dist = new int[voxelArea.compactSpanCount];
for (int i = 0; i < dist.Length; i++) {
dist[i] = 0xFF;
}
for (int z = 0; z < wd; z += voxelArea.width) {
for (int x = 0; x < voxelArea.width; x++) {
CompactVoxelCell c = voxelArea.compactCells[x+z];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; i++) {
if (voxelArea.areaTypes[i] != UnwalkableArea) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
int nc = 0;
for (int dir = 0; dir < 4; dir++) {
if (s.GetConnection(dir) != NotConnected)
nc++;
}
//At least one missing neighbour
if (nc != 4) {
dist[i] = 0;
}
}
}
}
}
//int nd = 0;
//Pass 1
/*for (int z=0;z < wd;z += voxelArea.width) {
* for (int x=0;x < voxelArea.width;x++) {
*
* CompactVoxelCell c = voxelArea.compactCells[x+z];
*
* for (int i= (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) {
* CompactVoxelSpan s = voxelArea.compactSpans[i];
*
* if (s.GetConnection (0) != NotConnected) {
* // (-1,0)
* int nx = x+voxelArea.DirectionX[0];
* int nz = z+voxelArea.DirectionZ[0];
*
* int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection (0));
* CompactVoxelSpan ns = voxelArea.compactSpans[ni];
*
* if (dist[ni]+2 < dist[i]) {
* dist[i] = (ushort)(dist[ni]+2);
* }
*
* if (ns.GetConnection (3) != NotConnected) {
* // (-1,0) + (0,-1) = (-1,-1)
* int nnx = nx+voxelArea.DirectionX[3];
* int nnz = nz+voxelArea.DirectionZ[3];
*
* int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection (3));
*
* if (src[nni]+3 < src[i]) {
* src[i] = (ushort)(src[nni]+3);
* }
* }
* }
*
* if (s.GetConnection (3) != NotConnected) {
* // (0,-1)
* int nx = x+voxelArea.DirectionX[3];
* int nz = z+voxelArea.DirectionZ[3];
*
* int ni = (int)(voxelArea.compactCells[nx+nz].index+s.GetConnection (3));
*
* if (src[ni]+2 < src[i]) {
* src[i] = (ushort)(src[ni]+2);
* }
*
* CompactVoxelSpan ns = voxelArea.compactSpans[ni];
*
* if (ns.GetConnection (2) != NotConnected) {
*
* // (0,-1) + (1,0) = (1,-1)
* int nnx = nx+voxelArea.DirectionX[2];
* int nnz = nz+voxelArea.DirectionZ[2];
*
* int nni = (int)(voxelArea.compactCells[nnx+nnz].index+ns.GetConnection (2));
*
* if (src[nni]+3 < src[i]) {
* src[i] = (ushort)(src[nni]+3);
* }
* }
* }
* }
* }
* }*/
}
public void FilterLowHeightSpans (uint voxelWalkableHeight, float cs, float ch, Vector3 min) {
int wd = voxelArea.width*voxelArea.depth;
//Filter all ledges
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) {
for (int x = 0; x < voxelArea.width; x++) {
for (int s = z+x; s != -1 && spans[s].bottom != VoxelArea.InvalidSpanValue; s = spans[s].next) {
uint bottom = spans[s].top;
uint top = spans[s].next != -1 ? spans[spans[s].next].bottom : VoxelArea.MaxHeight;
if (top - bottom < voxelWalkableHeight) {
spans[s].area = UnwalkableArea;
}
}
}
}
#else
for (int z = 0, pz = 0; z < wd; z += voxelArea.width, pz++) {
for (int x = 0; x < voxelArea.width; x++) {
for (VoxelSpan s = voxelArea.cells[z+x].firstSpan; s != null; s = s.next) {
uint bottom = s.top;
uint top = s.next != null ? s.next.bottom : VoxelArea.MaxHeight;
if (top - bottom < voxelWalkableHeight) {
s.area = UnwalkableArea;
}
}
}
}
#endif
}
//Code almost completely ripped from Recast
public void FilterLedges (uint voxelWalkableHeight, int voxelWalkableClimb, float cs, float ch, Vector3 min) {
int wd = voxelArea.width*voxelArea.depth;
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
LinkedVoxelSpan[] spans = voxelArea.linkedSpans;
int[] DirectionX = voxelArea.DirectionX;
int[] DirectionZ = voxelArea.DirectionZ;
#endif
int width = voxelArea.width;
//Filter all ledges
for (int z = 0, pz = 0; z < wd; z += width, pz++) {
for (int x = 0; x < width; x++) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
if (spans[x+z].bottom == VoxelArea.InvalidSpanValue) continue;
for (int s = x+z; s != -1; s = spans[s].next) {
//Skip non-walkable spans
if (spans[s].area == UnwalkableArea) {
continue;
}
int bottom = (int)spans[s].top;
int top = spans[s].next != -1 ? (int)spans[spans[s].next].bottom : VoxelArea.MaxHeightInt;
int minHeight = VoxelArea.MaxHeightInt;
int aMinHeight = (int)spans[s].top;
int aMaxHeight = aMinHeight;
for (int d = 0; d < 4; d++) {
int nx = x+DirectionX[d];
int nz = z+DirectionZ[d];
//Skip out-of-bounds points
if (nx < 0 || nz < 0 || nz >= wd || nx >= width) {
spans[s].area = UnwalkableArea;
break;
}
int nsx = nx+nz;
int nbottom = -voxelWalkableClimb;
int ntop = spans[nsx].bottom != VoxelArea.InvalidSpanValue ? (int)spans[nsx].bottom : VoxelArea.MaxHeightInt;
if (System.Math.Min(top, ntop) - System.Math.Max(bottom, nbottom) > voxelWalkableHeight) {
minHeight = System.Math.Min(minHeight, nbottom - bottom);
}
//Loop through spans
if (spans[nsx].bottom != VoxelArea.InvalidSpanValue) {
for (int ns = nsx; ns != -1; ns = spans[ns].next) {
nbottom = (int)spans[ns].top;
ntop = spans[ns].next != -1 ? (int)spans[spans[ns].next].bottom : VoxelArea.MaxHeightInt;
if (System.Math.Min(top, ntop) - System.Math.Max(bottom, nbottom) > voxelWalkableHeight) {
minHeight = System.Math.Min(minHeight, nbottom - bottom);
if (System.Math.Abs(nbottom - bottom) <= voxelWalkableClimb) {
if (nbottom < aMinHeight) { aMinHeight = nbottom; }
if (nbottom > aMaxHeight) { aMaxHeight = nbottom; }
}
}
}
}
}
if (minHeight < -voxelWalkableClimb || (aMaxHeight - aMinHeight) > voxelWalkableClimb) {
spans[s].area = UnwalkableArea;
}
}
#else
for (VoxelSpan s = voxelArea.cells[z+x].firstSpan; s != null; s = s.next) {
//Skip non-walkable spans
if (s.area == UnwalkableArea) {
continue;
}
int bottom = (int)s.top;
int top = s.next != null ? (int)s.next.bottom : VoxelArea.MaxHeightInt;
int minHeight = VoxelArea.MaxHeightInt;
int aMinHeight = (int)s.top;
int aMaxHeight = (int)s.top;
for (int d = 0; d < 4; d++) {
int nx = x+voxelArea.DirectionX[d];
int nz = z+voxelArea.DirectionZ[d];
//Skip out-of-bounds points
if (nx < 0 || nz < 0 || nz >= wd || nx >= voxelArea.width) {
s.area = UnwalkableArea;
break;
}
VoxelSpan nsx = voxelArea.cells[nx+nz].firstSpan;
int nbottom = -voxelWalkableClimb;
int ntop = nsx != null ? (int)nsx.bottom : VoxelArea.MaxHeightInt;
if (AstarMath.Min(top, ntop) - AstarMath.Max(bottom, nbottom) > voxelWalkableHeight) {
minHeight = AstarMath.Min(minHeight, nbottom - bottom);
}
//Loop through spans
for (VoxelSpan ns = nsx; ns != null; ns = ns.next) {
nbottom = (int)ns.top;
ntop = ns.next != null ? (int)ns.next.bottom : VoxelArea.MaxHeightInt;
if (AstarMath.Min(top, ntop) - AstarMath.Max(bottom, nbottom) > voxelWalkableHeight) {
minHeight = AstarMath.Min(minHeight, nbottom - bottom);
if (AstarMath.Abs(nbottom - bottom) <= voxelWalkableClimb) {
if (nbottom < aMinHeight) { aMinHeight = nbottom; }
if (nbottom > aMaxHeight) { aMaxHeight = nbottom; }
}
}
}
}
if (minHeight < -voxelWalkableClimb || (aMaxHeight - aMinHeight) > voxelWalkableClimb) {
s.area = UnwalkableArea;
}
}
#endif
}
}
}
}
}
| |
//
// AppDomainCas.cs - CAS unit tests for System.AppDomain
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
namespace MonoCasTests.System {
[TestFixture]
[Category ("CAS")]
public class AppDomainCas {
private AppDomain ad;
[TestFixtureSetUp]
public void FixtureSetUp ()
{
// it's safe to create the AppDomain here
string temp = Path.GetTempPath ();
AppDomainSetup setup = new AppDomainSetup ();
setup.ApplicationName = "CAS";
setup.PrivateBinPath = temp;
setup.DynamicBase = temp;
ad = AppDomain.CreateDomain ("CAS", null, setup);
}
[SetUp]
public void SetUp ()
{
if (!SecurityManager.SecurityEnabled)
Assert.Ignore ("SecurityManager.SecurityEnabled is OFF");
}
// Partial Trust Tests
[Test]
[PermissionSet (SecurityAction.Deny, Unrestricted = true)]
public void PartialTrust_Deny_Unrestricted ()
{
// static
Assert.IsNotNull (AppDomain.CurrentDomain, "CurrentDomain");
// instance
Assert.IsNotNull (ad.FriendlyName, "FriendlyName");
Assert.IsNotNull (ad.SetupInformation, "SetupInformation");
Assert.IsFalse (ad.ShadowCopyFiles, "ShadowCopyFiles");
}
// see http://bugzilla.ximian.com/show_bug.cgi?id=74411
[Category ("NotWorking")]
[Test]
[FileIOPermission (SecurityAction.Deny, Unrestricted = true)]
[ExpectedException (typeof (SecurityException))]
public void BaseDirectory_Deny_FileIOPermission ()
{
Assert.IsNotNull (ad.BaseDirectory, "BaseDirectory");
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void CreateDomain1_Deny_ControlAppDomain ()
{
AppDomain.CreateDomain (null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void CreateDomain2_Deny_ControlAppDomain ()
{
AppDomain.CreateDomain (null, null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void CreateDomain3_Deny_ControlAppDomain ()
{
AppDomain.CreateDomain (null, null, null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void CreateDomain5_Deny_ControlAppDomain ()
{
AppDomain.CreateDomain (null, null, null, null, false);
}
#if NET_2_0
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void CreateDomain7_Deny_ControlAppDomain ()
{
AppDomain.CreateDomain (null, null, null, null, false, null, null);
}
#endif
// see http://bugzilla.ximian.com/show_bug.cgi?id=74411
[Category ("NotWorking")]
[Test]
[FileIOPermission (SecurityAction.Deny, Unrestricted = true)]
[ExpectedException (typeof (SecurityException))]
public void DynamicDirectory_Deny_FileIOPermission ()
{
Assert.IsNotNull (ad.DynamicDirectory, "DynamicDirectory");
}
[Category ("NotWorking")] // check not yet implemented
[Test]
[SecurityPermission (SecurityAction.Deny, ControlEvidence = true)]
[ExpectedException (typeof (SecurityException))]
public void Evidence_Deny_ControlEvidence ()
{
Assert.IsNotNull (ad.Evidence, "Evidence");
}
// see http://bugzilla.ximian.com/show_bug.cgi?id=74411
[Category ("NotWorking")]
[Test]
[FileIOPermission (SecurityAction.Deny, Unrestricted = true)]
[ExpectedException (typeof (SecurityException))]
public void RelativeSearchPath_Deny_FileIOPermission ()
{
Assert.IsNotNull (ad.RelativeSearchPath, "RelativeSearchPath");
}
// see http://bugzilla.ximian.com/show_bug.cgi?id=74411
[Category ("NotWorking")]
[Test]
[SecurityPermission (SecurityAction.Deny, ControlPrincipal = true)]
[ExpectedException (typeof (SecurityException))]
public void SetPrincipalPolicy_Deny_ControlPrincipal ()
{
ad.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
}
// see http://bugzilla.ximian.com/show_bug.cgi?id=74411
[Category ("NotWorking")]
[Test]
[SecurityPermission (SecurityAction.Deny, ControlPrincipal = true)]
[ExpectedException (typeof (SecurityException))]
public void SetThreadPrincipal_Deny_ControlPrincipal ()
{
ad.SetThreadPrincipal (new GenericPrincipal (new GenericIdentity ("me"), null));
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void Unload_Deny_ControlAppDomain ()
{
AppDomain.Unload (null);
}
[Test]
[FileIOPermission (SecurityAction.PermitOnly, Unrestricted = true)]
public void PermitOnly_FileIOPermission ()
{
Assert.IsNotNull (ad.BaseDirectory, "BaseDirectory");
Assert.IsNotNull (ad.DynamicDirectory, "DynamicDirectory");
Assert.IsNotNull (ad.RelativeSearchPath, "RelativeSearchPath");
}
[Test]
[SecurityPermission (SecurityAction.PermitOnly, ControlEvidence = true)]
public void PermitOnly_ControlEvidence ()
{
// other permissions required to get evidence from another domain
Assert.IsNotNull (AppDomain.CurrentDomain.Evidence, "Evidence");
}
[Test]
[SecurityPermission (SecurityAction.PermitOnly, ControlPrincipal = true)]
public void PermitOnly_ControlPrincipal ()
{
ad.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
ad.SetThreadPrincipal (new GenericPrincipal (new GenericIdentity ("me"), null));
}
// we use reflection to call AppDomain as some methods and events are protected
// by LinkDemand (which will be converted into full demand, i.e. a stack walk)
// when reflection is used (i.e. it gets testable).
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AppendPrivatePath ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("AppendPrivatePath");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { String.Empty });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void ClearPrivatePath ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("ClearPrivatePath");
mi.Invoke (AppDomain.CurrentDomain, null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void ClearShadowCopyPath ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("ClearShadowCopyPath");
mi.Invoke (AppDomain.CurrentDomain, null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void SetCachePath ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("SetCachePath");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { String.Empty });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void SetData ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("SetData");
mi.Invoke (AppDomain.CurrentDomain, new object [2] { String.Empty, null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void SetShadowCopyFiles ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("SetShadowCopyFiles");
mi.Invoke (AppDomain.CurrentDomain, null);
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void SetDynamicBase ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("SetDynamicBase");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { String.Empty });
}
// events
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddDomainUnload ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_DomainUnload");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveDomainUnload ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_DomainUnload");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddAssemblyLoad ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_AssemblyLoad");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveAssemblyLoad ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_AssemblyLoad");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddProcessExit ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_ProcessExit");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveProcessExit ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_ProcessExit");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddTypeResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_TypeResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveTypeResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_TypeResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddResourceResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_ResourceResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveResourceResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_ResourceResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddAssemblyResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_AssemblyResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveAssemblyResolve ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_AssemblyResolve");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void AddUnhandledException ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("add_UnhandledException");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
[Test]
[SecurityPermission (SecurityAction.Deny, ControlAppDomain = true)]
[ExpectedException (typeof (SecurityException))]
public void RemoveUnhandledException ()
{
MethodInfo mi = typeof (AppDomain).GetMethod ("remove_UnhandledException");
mi.Invoke (AppDomain.CurrentDomain, new object [1] { null });
}
}
}
| |
//
// Mono.Data.Sqlite.SQLiteCommandBuilder.cs
//
// Author(s):
// Robert Simpson (robert@blackcastlesoft.com)
//
// Adapted and modified for the Mono Project by
// Marek Habersack (grendello@gmail.com)
//
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2007 Marek Habersack
//
// 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.
//
/********************************************************
* ADO.NET 2.0 Data Provider for Sqlite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
#if NET_2_0
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.ComponentModel;
/// <summary>
/// Sqlite implementation of DbCommandBuilder.
/// </summary>
public sealed class SqliteCommandBuilder : DbCommandBuilder
{
private EventHandler<RowUpdatingEventArgs> _handler;
/// <summary>
/// Default constructor
/// </summary>
public SqliteCommandBuilder() : this(null)
{
}
/// <summary>
/// Initializes the command builder and associates it with the specified data adapter.
/// </summary>
/// <param name="adp"></param>
public SqliteCommandBuilder(SqliteDataAdapter adp)
{
QuotePrefix = "[";
QuoteSuffix = "]";
DataAdapter = adp;
}
/// <summary>
/// Minimal amount of parameter processing. Primarily sets the DbType for the parameter equal to the provider type in the schema
/// </summary>
/// <param name="parameter">The parameter to use in applying custom behaviors to a row</param>
/// <param name="row">The row to apply the parameter to</param>
/// <param name="statementType">The type of statement</param>
/// <param name="whereClause">Whether the application of the parameter is part of a WHERE clause</param>
protected override void ApplyParameterInfo(DbParameter parameter, DataRow row, StatementType statementType, bool whereClause)
{
SqliteParameter param = (SqliteParameter)parameter;
param.DbType = (DbType)row[SchemaTableColumn.ProviderType];
}
/// <summary>
/// Returns a valid named parameter
/// </summary>
/// <param name="parameterName">The name of the parameter</param>
/// <returns>Error</returns>
protected override string GetParameterName(string parameterName)
{
return String.Format(CultureInfo.InvariantCulture, "@{0}", parameterName);
}
/// <summary>
/// Returns a named parameter for the given ordinal
/// </summary>
/// <param name="parameterOrdinal">The i of the parameter</param>
/// <returns>Error</returns>
protected override string GetParameterName(int parameterOrdinal)
{
return String.Format(CultureInfo.InvariantCulture, "@param{0}", parameterOrdinal);
}
/// <summary>
/// Returns a placeholder character for the specified parameter i.
/// </summary>
/// <param name="parameterOrdinal">The index of the parameter to provide a placeholder for</param>
/// <returns>Returns a named parameter</returns>
protected override string GetParameterPlaceholder(int parameterOrdinal)
{
return GetParameterName(parameterOrdinal);
}
/// <summary>
/// Sets the handler for receiving row updating events. Used by the DbCommandBuilder to autogenerate SQL
/// statements that may not have previously been generated.
/// </summary>
/// <param name="adapter">A data adapter to receive events on.</param>
protected override void SetRowUpdatingHandler(DbDataAdapter adapter)
{
SqliteDataAdapter adp = (SqliteDataAdapter)adapter;
_handler = new EventHandler<RowUpdatingEventArgs>(RowUpdatingEventHandler);
adp.RowUpdating += _handler;
}
private void RowUpdatingEventHandler(object sender, RowUpdatingEventArgs e)
{
base.RowUpdatingHandler(e);
}
/// <summary>
/// Gets/sets the DataAdapter for this CommandBuilder
/// </summary>
public new SqliteDataAdapter DataAdapter
{
get { return (SqliteDataAdapter)base.DataAdapter; }
set { base.DataAdapter = value; }
}
/// <summary>
/// Returns the automatically-generated Sqlite command to delete rows from the database
/// </summary>
/// <returns></returns>
public new SqliteCommand GetDeleteCommand()
{
return (SqliteCommand)base.GetDeleteCommand();
}
/// <summary>
/// Returns the automatically-generated Sqlite command to delete rows from the database
/// </summary>
/// <param name="useColumnsForParameterNames"></param>
/// <returns></returns>
public new SqliteCommand GetDeleteCommand(bool useColumnsForParameterNames)
{
return (SqliteCommand)base.GetDeleteCommand(useColumnsForParameterNames);
}
/// <summary>
/// Returns the automatically-generated Sqlite command to update rows in the database
/// </summary>
/// <returns></returns>
public new SqliteCommand GetUpdateCommand()
{
return (SqliteCommand)base.GetUpdateCommand();
}
/// <summary>
/// Returns the automatically-generated Sqlite command to update rows in the database
/// </summary>
/// <param name="useColumnsForParameterNames"></param>
/// <returns></returns>
public new SqliteCommand GetUpdateCommand(bool useColumnsForParameterNames)
{
return (SqliteCommand)base.GetUpdateCommand(useColumnsForParameterNames);
}
/// <summary>
/// Returns the automatically-generated Sqlite command to insert rows into the database
/// </summary>
/// <returns></returns>
public new SqliteCommand GetInsertCommand()
{
return (SqliteCommand)base.GetInsertCommand();
}
/// <summary>
/// Returns the automatically-generated Sqlite command to insert rows into the database
/// </summary>
/// <param name="useColumnsForParameterNames"></param>
/// <returns></returns>
public new SqliteCommand GetInsertCommand(bool useColumnsForParameterNames)
{
return (SqliteCommand)base.GetInsertCommand(useColumnsForParameterNames);
}
/// <summary>
/// Overridden to hide its property from the designer
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false)]
#endif
public override CatalogLocation CatalogLocation
{
get
{
return base.CatalogLocation;
}
set
{
base.CatalogLocation = value;
}
}
/// <summary>
/// Overridden to hide its property from the designer
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false)]
#endif
public override string CatalogSeparator
{
get
{
return base.CatalogSeparator;
}
set
{
base.CatalogSeparator = value;
}
}
/// <summary>
/// Overridden to hide its property from the designer
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false)]
#endif
[DefaultValue("[")]
public override string QuotePrefix
{
get
{
return base.QuotePrefix;
}
set
{
base.QuotePrefix = value;
}
}
/// <summary>
/// Overridden to hide its property from the designer
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false)]
#endif
public override string QuoteSuffix
{
get
{
return base.QuoteSuffix;
}
set
{
base.QuoteSuffix = value;
}
}
/// <summary>
/// Places brackets around an identifier
/// </summary>
/// <param name="unquotedIdentifier">The identifier to quote</param>
/// <returns>The bracketed identifier</returns>
public override string QuoteIdentifier(string unquotedIdentifier)
{
if (String.IsNullOrEmpty(QuotePrefix)
|| String.IsNullOrEmpty(QuoteSuffix)
|| String.IsNullOrEmpty(unquotedIdentifier))
return unquotedIdentifier;
return QuotePrefix + unquotedIdentifier.Replace(QuoteSuffix, QuoteSuffix + QuoteSuffix) + QuoteSuffix;
}
/// <summary>
/// Removes brackets around an identifier
/// </summary>
/// <param name="quotedIdentifier">The quoted (bracketed) identifier</param>
/// <returns>The undecorated identifier</returns>
public override string UnquoteIdentifier(string quotedIdentifier)
{
if (String.IsNullOrEmpty(QuotePrefix)
|| String.IsNullOrEmpty(QuoteSuffix)
|| String.IsNullOrEmpty(quotedIdentifier))
return quotedIdentifier;
if (quotedIdentifier.StartsWith(QuotePrefix, StringComparison.InvariantCultureIgnoreCase) == false
|| quotedIdentifier.EndsWith(QuoteSuffix, StringComparison.InvariantCultureIgnoreCase) == false)
return quotedIdentifier;
return quotedIdentifier.Substring(QuotePrefix.Length, quotedIdentifier.Length - (QuotePrefix.Length + QuoteSuffix.Length)).Replace(QuoteSuffix + QuoteSuffix, QuoteSuffix);
}
/// <summary>
/// Overridden to hide its property from the designer
/// </summary>
#if !PLATFORM_COMPACTFRAMEWORK
[Browsable(false)]
#endif
public override string SchemaSeparator
{
get
{
return base.SchemaSeparator;
}
set
{
base.SchemaSeparator = value;
}
}
/// <summary>
/// Override helper, which can help the base command builder choose the right keys for the given query
/// </summary>
/// <param name="sourceCommand"></param>
/// <returns></returns>
protected override DataTable GetSchemaTable(DbCommand sourceCommand)
{
using (IDataReader reader = sourceCommand.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
DataTable schema = reader.GetSchemaTable();
// If the query contains a primary key, turn off the IsUnique property
// for all the non-key columns
if (HasSchemaPrimaryKey(schema))
ResetIsUniqueSchemaColumn(schema);
// if table has no primary key we use unique columns as a fall back
return schema;
}
}
private bool HasSchemaPrimaryKey(DataTable schema)
{
DataColumn IsKeyColumn = schema.Columns[SchemaTableColumn.IsKey];
foreach (DataRow schemaRow in schema.Rows)
{
if ((bool)schemaRow[IsKeyColumn] == true)
return true;
}
return false;
}
private void ResetIsUniqueSchemaColumn(DataTable schema)
{
DataColumn IsUniqueColumn = schema.Columns[SchemaTableColumn.IsUnique];
DataColumn IsKeyColumn = schema.Columns[SchemaTableColumn.IsKey];
foreach (DataRow schemaRow in schema.Rows)
{
if ((bool)schemaRow[IsKeyColumn] == false)
schemaRow[IsUniqueColumn] = false;
}
schema.AcceptChanges();
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
/// <summary>Per-thread cached StringBuilder for building of strings to send on the connection.</summary>
[ThreadStatic]
private static StringBuilder t_cachedStringBuilder;
/// <summary>Default encoding for HTTP requests. Latin alphabeta no 1, ISO/IEC 8859-1.</summary>
private static readonly Encoding s_defaultHttpEncoding = Encoding.GetEncoding(28591);
/// <summary>Size of the receive buffer to use.</summary>
private const int DefaultReceiveBufferSize = 0x1000;
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
private WebSocketState _state = WebSocketState.Connecting;
private WebSocket _webSocket;
public static WebSocketHandle Create() => new WebSocketHandle();
public static bool IsValid(WebSocketHandle handle) => handle != null;
public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus;
public string CloseStatusDescription => _webSocket?.CloseStatusDescription;
public WebSocketState State => _webSocket?.State ?? _state;
public string SubProtocol => _webSocket?.SubProtocol;
public static void CheckPlatformSupport() { /* nop */ }
public void Dispose()
{
_state = WebSocketState.Closed;
_webSocket?.Dispose();
}
public void Abort()
{
_abortSource.Cancel();
_webSocket?.Abort();
}
public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
// TODO #14480 : Not currently implemented, or explicitly ignored:
// - ClientWebSocketOptions.UseDefaultCredentials
// - ClientWebSocketOptions.Credentials
// - ClientWebSocketOptions.Proxy
// - ClientWebSocketOptions._sendBufferSize
// Establish connection to the server
CancellationTokenRegistration registration = cancellationToken.Register(s => ((WebSocketHandle)s).Abort(), this);
try
{
// Connect to the remote server
Socket connectedSocket = await ConnectSocketAsync(uri.Host, uri.Port, cancellationToken).ConfigureAwait(false);
Stream stream = new NetworkStream(connectedSocket, ownsSocket:true);
// Upgrade to SSL if needed
if (uri.Scheme == UriScheme.Wss)
{
var sslStream = new SslStream(stream);
await sslStream.AuthenticateAsClientAsync(
uri.Host,
options.ClientCertificates,
SecurityProtocol.AllowedSecurityProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
stream = sslStream;
}
// Create the security key and expected response, then build all of the request headers
KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
byte[] requestHeader = BuildRequestHeader(uri, options, secKeyAndSecWebSocketAccept.Key);
// Write out the header to the connection
await stream.WriteAsync(requestHeader, 0, requestHeader.Length, cancellationToken).ConfigureAwait(false);
// Parse the response and store our state for the remainder of the connection
string subprotocol = await ParseAndValidateConnectResponseAsync(stream, options, secKeyAndSecWebSocketAccept.Value, cancellationToken).ConfigureAwait(false);
_webSocket = WebSocket.CreateClientWebSocket(
stream, subprotocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, false, options.Buffer.GetValueOrDefault());
// If a concurrent Abort or Dispose came in before we set _webSocket, make sure to update it appropriately
if (_state == WebSocketState.Aborted)
{
_webSocket.Abort();
}
else if (_state == WebSocketState.Closed)
{
_webSocket.Dispose();
}
}
catch (Exception exc)
{
if (_state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
Abort();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
finally
{
registration.Dispose();
}
}
/// <summary>Connects a socket to the specified host and port, subject to cancellation and aborting.</summary>
/// <param name="host">The host to which to connect.</param>
/// <param name="port">The port to which to connect on the host.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The connected Socket.</returns>
private async Task<Socket> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken)
{
IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in addresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
using (cancellationToken.Register(s => ((Socket)s).Dispose(), socket))
using (_abortSource.Token.Register(s => ((Socket)s).Dispose(), socket))
{
try
{
await socket.ConnectAsync(address, port).ConfigureAwait(false);
}
catch (ObjectDisposedException ode)
{
// If the socket was disposed because cancellation was requested, translate the exception
// into a new OperationCanceledException. Otherwise, let the original ObjectDisposedexception propagate.
CancellationToken token = cancellationToken.IsCancellationRequested ? cancellationToken : _abortSource.Token;
if (token.IsCancellationRequested)
{
throw new OperationCanceledException(new OperationCanceledException().Message, ode, token);
}
}
}
cancellationToken.ThrowIfCancellationRequested(); // in case of a race and socket was disposed after the await
_abortSource.Token.ThrowIfCancellationRequested();
return socket;
}
catch (Exception exc)
{
socket.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}
lastException?.Throw();
Debug.Fail("We should never get here. We should have already returned or an exception should have been thrown.");
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
/// <summary>Creates a byte[] containing the headers to send to the server.</summary>
/// <param name="uri">The Uri of the server.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
/// <returns>The byte[] containing the encoded headers ready to send to the network.</returns>
private static byte[] BuildRequestHeader(Uri uri, ClientWebSocketOptions options, string secKey)
{
StringBuilder builder = t_cachedStringBuilder ?? (t_cachedStringBuilder = new StringBuilder());
Debug.Assert(builder.Length == 0, $"Expected builder to be empty, got one of length {builder.Length}");
try
{
builder.Append("GET ").Append(uri.PathAndQuery).Append(" HTTP/1.1\r\n");
// Add all of the required headers, honoring Host header if set.
string hostHeader = options.RequestHeaders[HttpKnownHeaderNames.Host];
builder.Append("Host: ");
if (string.IsNullOrEmpty(hostHeader))
{
builder.Append(uri.IdnHost).Append(':').Append(uri.Port).Append("\r\n");
}
else
{
builder.Append(hostHeader).Append("\r\n");
}
builder.Append("Connection: Upgrade\r\n");
builder.Append("Upgrade: websocket\r\n");
builder.Append("Sec-WebSocket-Version: 13\r\n");
builder.Append("Sec-WebSocket-Key: ").Append(secKey).Append("\r\n");
// Add all of the additionally requested headers
foreach (string key in options.RequestHeaders.AllKeys)
{
if (string.Equals(key, HttpKnownHeaderNames.Host, StringComparison.OrdinalIgnoreCase))
{
// Host header handled above
continue;
}
builder.Append(key).Append(": ").Append(options.RequestHeaders[key]).Append("\r\n");
}
// Add the optional subprotocols header
if (options.RequestedSubProtocols.Count > 0)
{
builder.Append(HttpKnownHeaderNames.SecWebSocketProtocol).Append(": ");
builder.Append(options.RequestedSubProtocols[0]);
for (int i = 1; i < options.RequestedSubProtocols.Count; i++)
{
builder.Append(", ").Append(options.RequestedSubProtocols[i]);
}
builder.Append("\r\n");
}
// Add an optional cookies header
if (options.Cookies != null)
{
string header = options.Cookies.GetCookieHeader(uri);
if (!string.IsNullOrWhiteSpace(header))
{
builder.Append(HttpKnownHeaderNames.Cookie).Append(": ").Append(header).Append("\r\n");
}
}
// End the headers
builder.Append("\r\n");
// Return the bytes for the built up header
return s_defaultHttpEncoding.GetBytes(builder.ToString());
}
finally
{
// Make sure we clear the builder
builder.Clear();
}
}
/// <summary>
/// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and
/// the associated response we expect to receive as the Sec-WebSocket-Accept header value.
/// </summary>
/// <returns>A key-value pair of the request header security key and expected response header value.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "Required by RFC6455")]
private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept()
{
string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
using (SHA1 sha = SHA1.Create())
{
return new KeyValuePair<string, string>(
secKey,
Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid))));
}
}
/// <summary>Read and validate the connect response headers from the server.</summary>
/// <param name="stream">The stream from which to read the response headers.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="expectedSecWebSocketAccept">The expected value of the Sec-WebSocket-Accept header.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The agreed upon subprotocol with the server, or null if there was none.</returns>
private async Task<string> ParseAndValidateConnectResponseAsync(
Stream stream, ClientWebSocketOptions options, string expectedSecWebSocketAccept, CancellationToken cancellationToken)
{
// Read the first line of the response
string statusLine = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false);
// Depending on the underlying sockets implementation and timing, connecting to a server that then
// immediately closes the connection may either result in an exception getting thrown from the connect
// earlier, or it may result in getting to here but reading 0 bytes. If we read 0 bytes and thus have
// an empty status line, treat it as a connect failure.
if (string.IsNullOrEmpty(statusLine))
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
const string ExpectedStatusStart = "HTTP/1.1 ";
const string ExpectedStatusStatWithCode = "HTTP/1.1 101"; // 101 == SwitchingProtocols
// If the status line doesn't begin with "HTTP/1.1" or isn't long enough to contain a status code, fail.
if (!statusLine.StartsWith(ExpectedStatusStart, StringComparison.Ordinal) || statusLine.Length < ExpectedStatusStatWithCode.Length)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
// If the status line doesn't contain a status code 101, or if it's long enough to have a status description
// but doesn't contain whitespace after the 101, fail.
if (!statusLine.StartsWith(ExpectedStatusStatWithCode, StringComparison.Ordinal) ||
(statusLine.Length > ExpectedStatusStatWithCode.Length && !char.IsWhiteSpace(statusLine[ExpectedStatusStatWithCode.Length])))
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
// Read each response header. Be liberal in parsing the response header, treating
// everything to the left of the colon as the key and everything to the right as the value, trimming both.
// For each header, validate that we got the expected value.
bool foundUpgrade = false, foundConnection = false, foundSecWebSocketAccept = false;
string subprotocol = null;
string line;
while (!string.IsNullOrEmpty(line = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false)))
{
int colonIndex = line.IndexOf(':');
if (colonIndex == -1)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
string headerName = line.SubstringTrim(0, colonIndex);
string headerValue = line.SubstringTrim(colonIndex + 1);
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
ValidateAndTrackHeader(HttpKnownHeaderNames.Connection, "Upgrade", headerName, headerValue, ref foundConnection);
ValidateAndTrackHeader(HttpKnownHeaderNames.Upgrade, "websocket", headerName, headerValue, ref foundUpgrade);
ValidateAndTrackHeader(HttpKnownHeaderNames.SecWebSocketAccept, expectedSecWebSocketAccept, headerName, headerValue, ref foundSecWebSocketAccept);
// The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
// and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
// already got one in a previous header), fail. Otherwise, track which one we got.
if (string.Equals(HttpKnownHeaderNames.SecWebSocketProtocol, headerName, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(headerValue))
{
string newSubprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, headerValue, StringComparison.OrdinalIgnoreCase));
if (newSubprotocol == null || subprotocol != null)
{
throw new WebSocketException(
WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol));
}
subprotocol = newSubprotocol;
}
}
if (!foundUpgrade || !foundConnection || !foundSecWebSocketAccept)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
return subprotocol;
}
/// <summary>Validates a received header against expected values and tracks that we've received it.</summary>
/// <param name="targetHeaderName">The header name against which we're comparing.</param>
/// <param name="targetHeaderValue">The header value against which we're comparing.</param>
/// <param name="foundHeaderName">The actual header name received.</param>
/// <param name="foundHeaderValue">The actual header value received.</param>
/// <param name="foundHeader">A bool tracking whether this header has been seen.</param>
private static void ValidateAndTrackHeader(
string targetHeaderName, string targetHeaderValue,
string foundHeaderName, string foundHeaderValue,
ref bool foundHeader)
{
bool isTargetHeader = string.Equals(targetHeaderName, foundHeaderName, StringComparison.OrdinalIgnoreCase);
if (!foundHeader)
{
if (isTargetHeader)
{
if (!string.Equals(targetHeaderValue, foundHeaderValue, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, targetHeaderName, foundHeaderValue));
}
foundHeader = true;
}
}
else
{
if (isTargetHeader)
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
}
}
/// <summary>Reads a line from the stream.</summary>
/// <param name="stream">The stream from which to read.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
/// <returns>The read line, or null if none could be read.</returns>
private static async Task<string> ReadResponseHeaderLineAsync(Stream stream, CancellationToken cancellationToken)
{
StringBuilder sb = t_cachedStringBuilder;
if (sb != null)
{
t_cachedStringBuilder = null;
Debug.Assert(sb.Length == 0, $"Expected empty StringBuilder");
}
else
{
sb = new StringBuilder();
}
var arr = new byte[1];
char prevChar = '\0';
try
{
// TODO: Reading one byte is extremely inefficient. The problem, however,
// is that if we read multiple bytes, we could end up reading bytes post-headers
// that are part of messages meant to be read by the managed websocket after
// the connection. The likely solution here is to wrap the stream in a BufferedStream,
// though a) that comes at the expense of an extra set of virtual calls, b)
// it adds a buffer when the managed websocket will already be using a buffer, and
// c) it's not exposed on the version of the System.IO contract we're currently using.
while (await stream.ReadAsync(arr, 0, 1, cancellationToken).ConfigureAwait(false) == 1)
{
// Process the next char
char curChar = (char)arr[0];
if (prevChar == '\r' && curChar == '\n')
{
break;
}
sb.Append(curChar);
prevChar = curChar;
}
if (sb.Length > 0 && sb[sb.Length - 1] == '\r')
{
sb.Length = sb.Length - 1;
}
return sb.ToString();
}
finally
{
sb.Clear();
t_cachedStringBuilder = sb;
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Elders.Cronus.DomainModeling;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Parsing;
namespace Elders.Cronus.Projections.ElasticSearch.Linq
{
public class SubLuceneIndexExpression
{
public SubLuceneIndexExpression()
{
ExpressionBuilder = new StringBuilder();
}
public QueryIndex Index { get; private set; }
public StringBuilder ExpressionBuilder { get; private set; }
public void AttachIndex(string index)
{
Index = new QueryIndex(index);
}
public void Append(string expressionPart)
{
ExpressionBuilder.Append(expressionPart);
}
public string FormatExpression()
{
return "+(" + ExpressionBuilder.ToString() + ")";
}
}
public class SubQueryMemoryExpressionTreeVisitor : ThrowingExpressionTreeVisitor
{
public static LuceneIndexExpression GetLuceneExpression(Expression linqExpression)
{
var visitor = new SubQueryMemoryExpressionTreeVisitor();
visitor.VisitExpression(linqExpression);
return visitor.GetLuceneExpression();
}
private readonly LuceneIndexExpression luceneExpression;
private SubQueryMemoryExpressionTreeVisitor()
{
luceneExpression = new LuceneIndexExpression();
}
private LuceneIndexExpression GetLuceneExpression()
{
return luceneExpression;
}
protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression)
{
luceneExpression.AttachIndex(expression.ReferencedQuerySource.ItemType.GetContractId());
luceneExpression.Append(expression.ReferencedQuerySource.ItemName);
return expression;
}
protected override Expression VisitBinaryExpression(BinaryExpression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Equal: // left:right
VisitExpression(expression.Left);
luceneExpression.Append(":");
VisitExpression(expression.Right);
break;
case ExpressionType.NotEqual: // -(left:right)
luceneExpression.Append("-");
luceneExpression.Append("(");
VisitExpression(expression.Left);
luceneExpression.Append(":");
VisitExpression(expression.Right);
luceneExpression.Append(")");
break;
case ExpressionType.AndAlso:
case ExpressionType.And: // +(left)+(right)
luceneExpression.Append("+");
luceneExpression.Append("(");
VisitExpression(expression.Left);
luceneExpression.Append(")");
luceneExpression.Append("+");
luceneExpression.Append("(");
VisitExpression(expression.Right);
luceneExpression.Append(")");
break;
case ExpressionType.OrElse: // (left)|(right)
case ExpressionType.Or:
luceneExpression.Append("(");
VisitExpression(expression.Left);
luceneExpression.Append(")");
luceneExpression.Append("|");
luceneExpression.Append("(");
VisitExpression(expression.Right);
luceneExpression.Append(")");
break;
case ExpressionType.Not: // -(left)
luceneExpression.Append("-");
luceneExpression.Append("(");
VisitExpression(expression.Left);
luceneExpression.Append(")");
break;
default:
base.VisitBinaryExpression(expression);
break;
}
return expression;
}
private Expression VisitMemberExpressionInternal(MemberExpression expression)
{
if (expression.Expression is MemberExpression)
{
VisitMemberExpressionInternal(expression.Expression as MemberExpression);
}
else
{
VisitExpression(expression.Expression);
}
var contractOrder = expression.Member.CustomAttributes
.Where(attr => typeof(DataMemberAttribute).IsAssignableFrom(attr.AttributeType))
.SingleOrDefault();
if (contractOrder == null)
{
string internalFieldName = expression.Member.Name + "Internal";
var internalField = expression.Member.DeclaringType.GetMember(internalFieldName, BindingFlags.NonPublic | BindingFlags.Instance).SingleOrDefault();
contractOrder = internalField.CustomAttributes
.Where(attr => typeof(DataMemberAttribute).IsAssignableFrom(attr.AttributeType))
.SingleOrDefault();
}
var memberName = contractOrder == null
? expression.Member.Name
: contractOrder.NamedArguments.Where(arg => arg.MemberName == "Order").Select(x => x.TypedValue.Value).Single();
var propertyInfo = expression.Member as PropertyInfo;
luceneExpression.Append("." + memberName);
if (propertyInfo != null && typeof(byte[]).IsAssignableFrom(propertyInfo.PropertyType))//Simple type
luceneExpression.Append(".$value");
return expression;
}
bool reduced = false;
protected override Expression VisitMemberExpression(MemberExpression expression)
{
var aggregateIdProperty = expression.Member as PropertyInfo;
var canReduce = aggregateIdProperty != null && reduced == false &&
typeof(IBlobId).IsAssignableFrom(aggregateIdProperty.PropertyType) && aggregateIdProperty.PropertyType.IsInterface == false;
reduced = true;
if (canReduce)
return VisitExpression(new ArExpression(expression, aggregateIdProperty.PropertyType));
else
return VisitMemberExpressionInternal(expression);
}
private Expression VisitArExpression(ArExpression expression)
{
var exp = base.VisitExpression(expression.Expression);
var rawIdIndex = expression.ArTyoe
.GetAllMembers().Where(x => x.Name == "RawId")
.Single().GetAttrubuteValue<DataMemberAttribute, int>(attr => attr.Order)
.ToString();
luceneExpression.Append(string.Format(".{0}.$value", rawIdIndex));
return expression;
}
public class ArExpression : Expression
{
public Expression Expression { get; private set; }
public Type ArTyoe { get; private set; }
public ArExpression(Expression ex, Type arType)
{
Expression = ex;
ArTyoe = arType;
}
public override Type Type { get { return Expression.Type; } }
public override ExpressionType NodeType { get { return Expression.NodeType; } }
public override bool CanReduce { get { return Expression.CanReduce; } }
public override Expression Reduce() { return Expression.Reduce(); }
}
protected override MemberBinding VisitMemberAssignment(MemberAssignment memberAssigment)
{
return base.VisitMemberAssignment(memberAssigment);
}
protected override Expression VisitConditionalExpression(ConditionalExpression expression)
{
return base.VisitConditionalExpression(expression);
}
protected override ElementInit VisitElementInit(ElementInit elementInit)
{
return base.VisitElementInit(elementInit);
}
protected override Expression VisitMemberInitExpression(MemberInitExpression expression)
{
return base.VisitMemberInitExpression(expression);
}
protected override MemberBinding VisitMemberBinding(MemberBinding memberBinding)
{
return base.VisitMemberBinding(memberBinding);
}
public override ReadOnlyCollection<T> VisitAndConvert<T>(ReadOnlyCollection<T> expressions, string callerName)
{
return base.VisitAndConvert<T>(expressions, callerName);
}
public override T VisitAndConvert<T>(T expression, string methodName)
{
return base.VisitAndConvert<T>(expression, methodName);
}
protected override ReadOnlyCollection<ElementInit> VisitElementInitList(ReadOnlyCollection<ElementInit> expressions)
{
return base.VisitElementInitList(expressions);
}
public override Expression VisitExpression(Expression expression)
{
if (expression is ArExpression)
return VisitArExpression(expression as ArExpression);
else
return base.VisitExpression(expression);
}
protected override Expression VisitExtensionExpression(ExtensionExpression expression)
{
return base.VisitExtensionExpression(expression);
}
protected override Expression VisitInvocationExpression(InvocationExpression expression)
{
return VisitExpression(expression.Expression);
}
protected override Expression VisitConstantExpression(ConstantExpression expression)
{
if (typeof(IBlobId).IsAssignableFrom(expression.Type))
{
var aggregateId = expression.Value as IBlobId;
var aggregateIdAsBase64String = System.Convert.ToBase64String(aggregateId.RawId);
luceneExpression.Append(string.Format("(\"{0}\")", aggregateIdAsBase64String));
}
else if (typeof(byte[]).IsAssignableFrom(expression.Type))
{
var valueAsBase64String = System.Convert.ToBase64String(expression.Value as byte[]);
luceneExpression.Append(string.Format("(\"{0}\")", valueAsBase64String));
}
else
{
luceneExpression.Append(string.Format("(\"{0}\")", expression.Value));
}
return expression;
}
protected override Expression VisitLambdaExpression(LambdaExpression expression)
{
return base.VisitLambdaExpression(expression);
}
protected override Expression VisitListInitExpression(ListInitExpression expression)
{
return base.VisitListInitExpression(expression);
}
protected override ReadOnlyCollection<MemberBinding> VisitMemberBindingList(ReadOnlyCollection<MemberBinding> expressions)
{
return base.VisitMemberBindingList(expressions);
}
protected override MemberBinding VisitMemberListBinding(MemberListBinding listBinding)
{
return base.VisitMemberListBinding(listBinding);
}
protected override MemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
return base.VisitMemberMemberBinding(binding);
}
protected override Expression VisitNewArrayExpression(NewArrayExpression expression)
{
return base.VisitNewArrayExpression(expression);
}
protected override Expression VisitNewExpression(NewExpression expression)
{
return base.VisitNewExpression(expression);
}
protected override Expression VisitParameterExpression(ParameterExpression expression)
{
return base.VisitParameterExpression(expression);
}
protected override Expression VisitSubQueryExpression(SubQueryExpression expression)
{
//var asd = ProjectionQueryModelVisitor.GenerateElasticSearchRequest(expression.QueryModel);
//return expression;
return base.VisitSubQueryExpression(expression);
}
protected override Expression VisitTypeBinaryExpression(TypeBinaryExpression expression)
{
return base.VisitTypeBinaryExpression(expression);
}
protected override Expression VisitUnaryExpression(UnaryExpression expression)
{
switch (expression.NodeType)
{
case ExpressionType.Not: // -(left)
luceneExpression.Append("-");
luceneExpression.Append("(");
VisitExpression(expression.Operand);
luceneExpression.Append(")");
break;
case ExpressionType.TypeAs:
case ExpressionType.Convert:
var memberExp = expression.Operand as MemberExpression;
if (memberExp != null && reduced == false)
{
if (typeof(IBlobId).IsAssignableFrom(expression.Type))
VisitExpression(new ArExpression(expression.Operand, expression.Type));
return expression;
}
else
base.VisitExpression(expression.Operand);
break;
default:
base.VisitUnaryExpression(expression);
break;
}
return expression;
}
protected override TResult VisitUnhandledItem<TItem, TResult>(TItem unhandledItem, string visitMethod, Func<TItem, TResult> baseBehavior)
{
return base.VisitUnhandledItem<TItem, TResult>(unhandledItem, visitMethod, baseBehavior);
}
protected override Expression VisitUnknownNonExtensionExpression(Expression expression)
{
return base.VisitUnknownNonExtensionExpression(expression);
}
protected override Expression VisitMethodCallExpression(MethodCallExpression expression)
{
// In production code, handle this via method lookup tables.
var supportedMethod = typeof(string).GetMethod("Contains");
if (expression.Method.Equals(supportedMethod))
{
luceneExpression.Append("(");
VisitExpression(expression.Object);
luceneExpression.Append(" like '%'+");
VisitExpression(expression.Arguments[0]);
luceneExpression.Append("+'%')");
return expression;
}
else
{
return base.VisitMethodCallExpression(expression); // throws
}
}
// Called when a LINQ expression type is not handled above.
protected override Exception CreateUnhandledItemException<T>(T unhandledItem, string visitMethod)
{
string itemText = FormatUnhandledItem(unhandledItem);
var message = string.Format("The expression '{0}' (type: {1}) is not supported by this LINQ provider.", itemText, typeof(T));
return new NotSupportedException(message);
}
private string FormatUnhandledItem<T>(T unhandledItem)
{
var itemAsExpression = unhandledItem as Expression;
return itemAsExpression != null ? FormattingExpressionTreeVisitor.Format(itemAsExpression) : unhandledItem.ToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.ComponentModel;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation
{
/// <summary>
/// Serves as the arguments for events triggered by exceptions in the SetValue method of <see cref="PSObjectPropertyDescriptor"/>
/// </summary>
/// <remarks>
/// The sender of this event is an object of type <see cref="PSObjectPropertyDescriptor"/>.
/// It is permitted to subclass <see cref="SettingValueExceptionEventArgs"/>
/// but there is no established scenario for doing this, nor has it been tested.
/// </remarks>
public class SettingValueExceptionEventArgs : EventArgs
{
/// <summary>
/// Gets and sets a <see cref="System.Boolean"/> indicating if the SetValue method of <see cref="PSObjectPropertyDescriptor"/>
/// should throw the exception associated with this event.
/// </summary>
/// <remarks>
/// The default value is true, indicating that the Exception associated with this event will be thrown.
/// </remarks>
public bool ShouldThrow { get; set; }
/// <summary>
/// Gets the exception that triggered the associated event.
/// </summary>
public Exception Exception { get; }
/// <summary>
/// Initializes a new instance of <see cref="SettingValueExceptionEventArgs"/> setting the value of the exception that triggered the associated event.
/// </summary>
/// <param name="exception">Exception that triggered the associated event.</param>
internal SettingValueExceptionEventArgs(Exception exception)
{
Exception = exception;
ShouldThrow = true;
}
}
/// <summary>
/// Serves as the arguments for events triggered by exceptions in the GetValue
/// method of <see cref="PSObjectPropertyDescriptor"/>
/// </summary>
/// <remarks>
/// The sender of this event is an object of type <see cref="PSObjectPropertyDescriptor"/>.
/// It is permitted to subclass <see cref="GettingValueExceptionEventArgs"/>
/// but there is no established scenario for doing this, nor has it been tested.
/// </remarks>
public class GettingValueExceptionEventArgs : EventArgs
{
/// <summary>
/// Gets and sets a <see cref="System.Boolean"/> indicating if the GetValue method of <see cref="PSObjectPropertyDescriptor"/>
/// should throw the exception associated with this event.
/// </summary>
public bool ShouldThrow { get; set; }
/// <summary>
/// Gets the Exception that triggered the associated event.
/// </summary>
public Exception Exception { get; }
/// <summary>
/// Initializes a new instance of <see cref="GettingValueExceptionEventArgs"/> setting the value of the exception that triggered the associated event.
/// </summary>
/// <param name="exception">Exception that triggered the associated event.</param>
internal GettingValueExceptionEventArgs(Exception exception)
{
Exception = exception;
ValueReplacement = null;
ShouldThrow = true;
}
/// <summary>
/// Gets and sets the value that will serve as a replacement to the return of the GetValue
/// method of <see cref="PSObjectPropertyDescriptor"/>. If this property is not set
/// to a value other than null then the exception associated with this event is thrown.
/// </summary>
public object ValueReplacement { get; set; }
}
/// <summary>
/// Serves as the property information generated by the GetProperties method of <see cref="PSObjectTypeDescriptor"/>.
/// </summary>
/// <remarks>
/// It is permitted to subclass <see cref="SettingValueExceptionEventArgs"/>
/// but there is no established scenario for doing this, nor has it been tested.
/// </remarks>
public class PSObjectPropertyDescriptor : PropertyDescriptor
{
internal event EventHandler<SettingValueExceptionEventArgs> SettingValueException;
internal event EventHandler<GettingValueExceptionEventArgs> GettingValueException;
internal PSObjectPropertyDescriptor(string propertyName, Type propertyType, bool isReadOnly, AttributeCollection propertyAttributes)
: base(propertyName, Array.Empty<Attribute>())
{
IsReadOnly = isReadOnly;
Attributes = propertyAttributes;
PropertyType = propertyType;
}
/// <summary>
/// Gets the collection of attributes for this member.
/// </summary>
public override AttributeCollection Attributes { get; }
/// <summary>
/// Gets a value indicating whether this property is read-only.
/// </summary>
public override bool IsReadOnly { get; }
/// <summary>
/// This method has no effect for <see cref="PSObjectPropertyDescriptor"/>.
/// CanResetValue returns false.
/// </summary>
/// <param name="component">This parameter is ignored for <see cref="PSObjectPropertyDescriptor"/></param>
public override void ResetValue(object component) { }
/// <summary>
/// Returns false to indicate that ResetValue has no effect.
/// </summary>
/// <param name="component">The component to test for reset capability.</param>
/// <returns>False.</returns>
public override bool CanResetValue(object component) { return false; }
/// <summary>
/// Returns true to indicate that the value of this property needs to be persisted.
/// </summary>
/// <param name="component">The component with the property to be examined for persistence.</param>
/// <returns>True.</returns>
public override bool ShouldSerializeValue(object component)
{
return true;
}
/// <summary>
/// Gets the type of the component this property is bound to.
/// </summary>
/// <remarks>This property returns the <see cref="PSObject"/> type.</remarks>
public override Type ComponentType
{
get { return typeof(PSObject); }
}
/// <summary>
/// Gets the type of the property value.
/// </summary>
public override Type PropertyType { get; }
/// <summary>
/// Gets the current value of the property on a component.
/// </summary>
/// <param name="component">The component with the property for which to retrieve the value.</param>
/// <returns>The value of a property for a given component.</returns>
/// <exception cref="ExtendedTypeSystemException">
/// If the property has not been found in the component or an exception has
/// been thrown when getting the value of the property.
/// This Exception will only be thrown if there is no event handler for the GettingValueException
/// event of the <see cref="PSObjectTypeDescriptor"/> that created this <see cref="PSObjectPropertyDescriptor"/>.
/// If there is an event handler, it can prevent this exception from being thrown, by changing
/// the ShouldThrow property of <see cref="GettingValueExceptionEventArgs"/> from its default
/// value of true to false.
/// </exception>
/// <exception cref="PSArgumentNullException">If <paramref name="component"/> is null.</exception>
/// <exception cref="PSArgumentException">If <paramref name="component"/> is not
/// an <see cref="PSObject"/> or an <see cref="PSObjectTypeDescriptor"/>.</exception>
public override object GetValue(object component)
{
if (component == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(component));
}
PSObject mshObj = GetComponentPSObject(component);
PSPropertyInfo property;
try
{
property = mshObj.Properties[this.Name] as PSPropertyInfo;
if (property == null)
{
PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", this.Name);
ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue",
null,
ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name);
bool shouldThrow;
object returnValue = DealWithGetValueException(e, out shouldThrow);
if (shouldThrow)
{
throw e;
}
return returnValue;
}
return property.Value;
}
catch (ExtendedTypeSystemException e)
{
PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception getting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message);
bool shouldThrow;
object returnValue = DealWithGetValueException(e, out shouldThrow);
if (shouldThrow)
{
throw;
}
return returnValue;
}
}
private static PSObject GetComponentPSObject(object component)
{
// If you use the PSObjectTypeDescriptor directly as your object, it will be the component
// if you use a provider, the PSObject will be the component.
PSObject mshObj = component as PSObject;
if (mshObj == null)
{
if (!(component is PSObjectTypeDescriptor descriptor))
{
throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent,
"component",
nameof(PSObject),
nameof(PSObjectTypeDescriptor));
}
mshObj = descriptor.Instance;
}
return mshObj;
}
private object DealWithGetValueException(ExtendedTypeSystemException e, out bool shouldThrow)
{
GettingValueExceptionEventArgs eventArgs = new GettingValueExceptionEventArgs(e);
if (GettingValueException != null)
{
GettingValueException.SafeInvoke(this, eventArgs);
PSObjectTypeDescriptor.typeDescriptor.WriteLine(
"GettingValueException event has been triggered resulting in ValueReplacement:\"{0}\".",
eventArgs.ValueReplacement);
}
shouldThrow = eventArgs.ShouldThrow;
return eventArgs.ValueReplacement;
}
/// <summary>
/// Sets the value of the component to a different value.
/// </summary>
/// <param name="component">The component with the property value that is to be set.</param>
/// <param name="value">The new value.</param>
/// <exception cref="ExtendedTypeSystemException">
/// If the property has not been found in the component or an exception has
/// been thrown when setting the value of the property.
/// This Exception will only be thrown if there is no event handler for the SettingValueException
/// event of the <see cref="PSObjectTypeDescriptor"/> that created this <see cref="PSObjectPropertyDescriptor"/>.
/// If there is an event handler, it can prevent this exception from being thrown, by changing
/// the ShouldThrow property of <see cref="SettingValueExceptionEventArgs"/>
/// from its default value of true to false.
/// </exception>
/// <exception cref="PSArgumentNullException">If <paramref name="component"/> is null.</exception>
/// <exception cref="PSArgumentException">If <paramref name="component"/> is not an
/// <see cref="PSObject"/> or an <see cref="PSObjectTypeDescriptor"/>.
/// </exception>
public override void SetValue(object component, object value)
{
if (component == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(component));
}
PSObject mshObj = GetComponentPSObject(component);
try
{
PSPropertyInfo property = mshObj.Properties[this.Name] as PSPropertyInfo;
if (property == null)
{
PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name);
ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue",
null,
ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name);
bool shouldThrow;
DealWithSetValueException(e, out shouldThrow);
if (shouldThrow)
{
throw e;
}
return;
}
property.Value = value;
}
catch (ExtendedTypeSystemException e)
{
PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception setting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message);
bool shouldThrow;
DealWithSetValueException(e, out shouldThrow);
if (shouldThrow)
{
throw;
}
}
OnValueChanged(component, EventArgs.Empty);
}
private void DealWithSetValueException(ExtendedTypeSystemException e, out bool shouldThrow)
{
SettingValueExceptionEventArgs eventArgs = new SettingValueExceptionEventArgs(e);
if (SettingValueException != null)
{
SettingValueException.SafeInvoke(this, eventArgs);
PSObjectTypeDescriptor.typeDescriptor.WriteLine(
"SettingValueException event has been triggered resulting in ShouldThrow:\"{0}\".",
eventArgs.ShouldThrow);
}
shouldThrow = eventArgs.ShouldThrow;
return;
}
}
/// <summary>
/// Provides information about the properties for an object of the type <see cref="PSObject"/>.
/// </summary>
public class PSObjectTypeDescriptor : CustomTypeDescriptor
{
internal static readonly PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false);
/// <summary>
/// Occurs when there was an exception setting the value of a property.
/// </summary>
/// <remarks>
/// The ShouldThrow property of the <see cref="SettingValueExceptionEventArgs"/> allows
/// subscribers to prevent the exception from being thrown.
/// </remarks>
public event EventHandler<SettingValueExceptionEventArgs> SettingValueException;
/// <summary>
/// Occurs when there was an exception getting the value of a property.
/// </summary>
/// <remarks>
/// The ShouldThrow property of the <see cref="GettingValueExceptionEventArgs"/> allows
/// subscribers to prevent the exception from being thrown.
/// </remarks>
public event EventHandler<GettingValueExceptionEventArgs> GettingValueException;
/// <summary>
/// Initializes a new instance of the <see cref="PSObjectTypeDescriptor"/> that provides
/// property information about <paramref name="instance"/>.
/// </summary>
/// <param name="instance">The <see cref="PSObject"/> this class retrieves property information from.</param>
public PSObjectTypeDescriptor(PSObject instance)
{
Instance = instance;
}
/// <summary>
/// Gets the <see cref="PSObject"/> this class retrieves property information from.
/// </summary>
public PSObject Instance { get; }
private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue)
{
using (typeDescriptor.TraceScope("Checking property \"{0}\".", propertyInfo.Name))
{
// WriteOnly properties are not returned in TypeDescriptor.GetProperties, so we do the same.
if (!propertyInfo.IsGettable)
{
typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", propertyInfo.Name);
return;
}
AttributeCollection propertyAttributes = null;
Type propertyType = typeof(object);
if (attributes != null && attributes.Length != 0)
{
PSProperty property = propertyInfo as PSProperty;
if (property != null)
{
DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry;
if (propertyEntry == null)
{
typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name);
}
else if (property.isDeserialized)
{
// At the moment we are not serializing attributes, so we can skip
// the attribute check if the property is deserialized.
typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", property.Name);
}
else
{
propertyType = propertyEntry.propertyType;
propertyAttributes = propertyEntry.Attributes;
foreach (Attribute attribute in attributes)
{
if (!propertyAttributes.Contains(attribute))
{
typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", property.Name, attribute);
return;
}
}
}
}
}
if (propertyAttributes == null)
{
propertyAttributes = new AttributeCollection();
}
typeDescriptor.WriteLine("Adding property \"{0}\".", propertyInfo.Name);
PSObjectPropertyDescriptor propertyDescriptor =
new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes);
propertyDescriptor.SettingValueException += this.SettingValueException;
propertyDescriptor.GettingValueException += this.GettingValueException;
returnValue.Add(propertyDescriptor);
}
}
/// <summary>
/// Returns a collection of property descriptors for the <see cref="PSObject"/> represented by this type descriptor.
/// </summary>
/// <returns>A PropertyDescriptorCollection containing the property descriptions for the <see cref="PSObject"/> represented by this type descriptor.</returns>
public override PropertyDescriptorCollection GetProperties()
{
return GetProperties(null);
}
/// <summary>
/// Returns a filtered collection of property descriptors for the <see cref="PSObject"/> represented by this type descriptor.
/// </summary>
/// <param name="attributes">An array of attributes to use as a filter. This can be a null reference (Nothing in Visual Basic).</param>
/// <returns>A PropertyDescriptorCollection containing the property descriptions for the <see cref="PSObject"/> represented by this type descriptor.</returns>
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
using (typeDescriptor.TraceScope("Getting properties."))
{
PropertyDescriptorCollection returnValue = new PropertyDescriptorCollection(null);
if (Instance == null)
{
return returnValue;
}
foreach (PSPropertyInfo property in Instance.Properties)
{
CheckAndAddProperty(property, attributes, ref returnValue);
}
return returnValue;
}
}
/// <summary>
/// Determines whether the Instance property of <paramref name="obj"/> is equal to the current Instance.
/// </summary>
/// <param name="obj">The Object to compare with the current Object.</param>
/// <returns>True if the Instance property of <paramref name="obj"/> is equal to the current Instance; otherwise, false.</returns>
public override bool Equals(object obj)
{
if (!(obj is PSObjectTypeDescriptor other))
{
return false;
}
if (this.Instance == null || other.Instance == null)
{
return ReferenceEquals(this, other);
}
return other.Instance.Equals(this.Instance);
}
/// <summary>
/// Provides a value for hashing algorithms.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
if (this.Instance == null)
{
return base.GetHashCode();
}
return this.Instance.GetHashCode();
}
/// <summary>
/// Returns the default property for this object.
/// </summary>
/// <returns>An <see cref="PSObjectPropertyDescriptor"/> that represents the default property for this object, or a null reference (Nothing in Visual Basic) if this object does not have properties.</returns>
public override PropertyDescriptor GetDefaultProperty()
{
if (this.Instance == null)
{
return null;
}
string defaultProperty = null;
PSMemberSet standardMembers = this.Instance.PSStandardMembers;
if (standardMembers != null)
{
PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty;
if (note != null)
{
defaultProperty = note.Value as string;
}
}
if (defaultProperty == null)
{
object[] defaultPropertyAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true);
if (defaultPropertyAttributes.Length == 1)
{
DefaultPropertyAttribute defaultPropertyAttribute = defaultPropertyAttributes[0] as DefaultPropertyAttribute;
if (defaultPropertyAttribute != null)
{
defaultProperty = defaultPropertyAttribute.Name;
}
}
}
PropertyDescriptorCollection properties = this.GetProperties();
if (defaultProperty != null)
{
// There is a defaultProperty, but let's check if it is actually one of the properties we are
// returning in GetProperties
foreach (PropertyDescriptor descriptor in properties)
{
if (string.Equals(descriptor.Name, defaultProperty, StringComparison.OrdinalIgnoreCase))
{
return descriptor;
}
}
}
return null;
}
/// <summary>
/// Returns a type converter for this object.
/// </summary>
/// <returns>A <see cref="TypeConverter"/> that is the converter for this object, or a null reference (Nothing in Visual Basic) if there is no <see cref="TypeConverter"/> for this object.</returns>
public override TypeConverter GetConverter()
{
if (this.Instance == null)
{
// If we return null, some controls will have an exception saying that this
// GetConverter returned an illegal value
return new TypeConverter();
}
object baseObject = this.Instance.BaseObject;
TypeConverter retValue = LanguagePrimitives.GetConverter(baseObject.GetType(), null) as TypeConverter ??
TypeDescriptor.GetConverter(baseObject);
return retValue;
}
/// <summary>
/// Returns the object that this value is a member of.
/// </summary>
/// <param name="pd">A <see cref="PropertyDescriptor"/> that represents the property whose owner is to be found.</param>
/// <returns>An object that represents the owner of the specified property.</returns>
public override object GetPropertyOwner(PropertyDescriptor pd)
{
return this.Instance;
}
#region Overrides Forwarded To BaseObject
#region ReadMe
// This region contains methods implemented like:
// TypeDescriptor.OverrideName(this.Instance.BaseObject)
// They serve the purpose of exposing Attributes and other information from the BaseObject
// of an PSObject, since the PSObject itself does not have the concept of class (or member)
// attributes.
// The calls are not recursive because the BaseObject was implemented so it is never
// another PSObject. ImmediateBaseObject or PSObject.Base could cause the call to be
// recursive in the case of an object like "new PSObject(new PSObject())".
// Even if we used ImmediateBaseObject, the recursion would be finite since we would
// keep getting an ImmediatebaseObject until it ceased to be an PSObject.
#endregion ReadMe
/// <summary>
/// Returns the default event for this object.
/// </summary>
/// <returns>An <see cref="EventDescriptor"/> that represents the default event for this object, or a null reference (Nothing in Visual Basic) if this object does not have events.</returns>
public override EventDescriptor GetDefaultEvent()
{
if (this.Instance == null)
{
return null;
}
return TypeDescriptor.GetDefaultEvent(this.Instance.BaseObject);
}
/// <summary>
/// Returns the events for this instance of a component.
/// </summary>
/// <returns>An <see cref="EventDescriptorCollection"/> that represents the events for this component instance.</returns>
public override EventDescriptorCollection GetEvents()
{
if (this.Instance == null)
{
return new EventDescriptorCollection(null);
}
return TypeDescriptor.GetEvents(this.Instance.BaseObject);
}
/// <summary>
/// Returns the events for this instance of a component using the attribute array as a filter.
/// </summary>
/// <param name="attributes">An array of type <see cref="Attribute"/> that is used as a filter.</param>
/// <returns>An <see cref="EventDescriptorCollection"/> that represents the events for this component instance that match the given set of attributes.</returns>
public override EventDescriptorCollection GetEvents(Attribute[] attributes)
{
if (this.Instance == null)
{
return null;
}
return TypeDescriptor.GetEvents(this.Instance.BaseObject, attributes);
}
/// <summary>
/// Returns a collection of type <see cref="Attribute"/> for this object.
/// </summary>
/// <returns>An <see cref="AttributeCollection"/> with the attributes for this object.</returns>
public override AttributeCollection GetAttributes()
{
if (this.Instance == null)
{
return new AttributeCollection();
}
return TypeDescriptor.GetAttributes(this.Instance.BaseObject);
}
/// <summary>
/// Returns the class name of this object.
/// </summary>
/// <returns>The class name of the object, or a null reference (Nothing in Visual Basic) if the class does not have a name.</returns>
public override string GetClassName()
{
if (this.Instance == null)
{
return null;
}
return TypeDescriptor.GetClassName(this.Instance.BaseObject);
}
/// <summary>
/// Returns the name of this object.
/// </summary>
/// <returns>The name of the object, or a null reference (Nothing in Visual Basic) if object does not have a name.</returns>
public override string GetComponentName()
{
if (this.Instance == null)
{
return null;
}
return TypeDescriptor.GetComponentName(this.Instance.BaseObject);
}
/// <summary>
/// Returns an editor of the specified type for this object.
/// </summary>
/// <param name="editorBaseType">A <see cref="Type"/> that represents the editor for this object.</param>
/// <returns>An object of the specified type that is the editor for this object, or a null reference (Nothing in Visual Basic) if the editor cannot be found.</returns>
public override object GetEditor(Type editorBaseType)
{
if (this.Instance == null)
{
return null;
}
return TypeDescriptor.GetEditor(this.Instance.BaseObject, editorBaseType);
}
#endregion Forwarded To BaseObject
}
/// <summary>
/// Retrieves a <see cref="PSObjectTypeDescriptor"/> to provides information about the properties for an object of the type <see cref="PSObject"/>.
/// </summary>
public class PSObjectTypeDescriptionProvider : TypeDescriptionProvider
{
/// <summary>
/// Occurs when there was an exception setting the value of a property.
/// </summary>
/// <remarks>
/// The ShouldThrow property of the <see cref="SettingValueExceptionEventArgs"/> allows
/// subscribers to prevent the exception from being thrown.
/// </remarks>
public event EventHandler<SettingValueExceptionEventArgs> SettingValueException;
/// <summary>
/// Occurs when there was an exception getting the value of a property.
/// </summary>
/// <remarks>
/// The ShouldThrow property of the <see cref="GettingValueExceptionEventArgs"/> allows
/// subscribers to prevent the exception from being thrown.
/// </remarks>
public event EventHandler<GettingValueExceptionEventArgs> GettingValueException;
/// <summary>
/// Initializes a new instance of <see cref="PSObjectTypeDescriptionProvider"/>
/// </summary>
public PSObjectTypeDescriptionProvider()
{
}
/// <summary>
/// Retrieves a <see cref="PSObjectTypeDescriptor"/> to provide information about the properties for an object of the type <see cref="PSObject"/>.
/// </summary>
/// <param name="objectType">The type of object for which to retrieve the type descriptor. If this parameter is not noll and is not the <see cref="PSObject"/>, the return of this method will be null.</param>
/// <param name="instance">An instance of the type. If instance is null or has a type other than <see cref="PSObject"/>, this method returns null.</param>
/// <returns>An <see cref="ICustomTypeDescriptor"/> that can provide property information for the
/// type <see cref="PSObject"/>, or null if <paramref name="objectType"/> is not null,
/// but has a type other than <see cref="PSObject"/>.</returns>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
PSObject mshObj = instance as PSObject;
#region ReadMe
// Instance can be null, in a couple of circumstances:
// 1) In one of the many calls to this method caused by setting the SelectedObject
// property of a PropertyGrid.
// 2) If, by mistake, an object[] or Collection<PSObject> is used instead of an ArrayList
// to set the DataSource property of a DataGrid or DatagridView.
//
// It would be nice to throw an exception for the case 2) instructing the user to use
// an ArrayList, but since we have case 1) and maybe others we haven't found we return
// an PSObjectTypeDescriptor(null). PSObjectTypeDescriptor's GetProperties
// checks for null instance and returns an empty property collection.
// All other overrides also check for null and return some default result.
// Case 1), which is using a PropertyGrid seems to be unaffected by these results returned
// by PSObjectTypeDescriptor overrides when the Instance is null, so we must conclude
// that the TypeDescriptor returned by that call where instance is null is not used
// for anything meaningful. That null instance PSObjectTypeDescriptor is only one
// of the many PSObjectTypeDescriptor's returned by this method in a PropertyGrid use.
// Some of the other calls to this method are passing a valid instance and the objects
// returned by these calls seem to be the ones used for meaningful calls in the PropertyGrid.
//
// It might sound strange that we are not verifying the type of objectType or of instance
// to be PSObject, but in this PropertyGrid use that passes a null instance (case 1), if
// we return null we have an exception flagging the return as invalid. Since we cannot
// return null and MSDN has a note saying that we should return null instead of throwing
// exceptions, the safest behavior seems to be creating this PSObjectTypeDescriptor with
// null instance.
#endregion ReadMe
PSObjectTypeDescriptor typeDescriptor = new PSObjectTypeDescriptor(mshObj);
typeDescriptor.SettingValueException += this.SettingValueException;
typeDescriptor.GettingValueException += this.GettingValueException;
return typeDescriptor;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Rest.Generator.Azure.Python.Properties;
using Microsoft.Rest.Generator.Azure.Python.Templates;
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.Python;
using Microsoft.Rest.Generator.Python.Templates;
using Microsoft.Rest.Generator.Python.TemplateModels;
using Microsoft.Rest.Generator.Utilities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Rest.Generator.Azure.Python
{
public class AzurePythonCodeGenerator : PythonCodeGenerator
{
private const string ClientRuntimePackage = "msrestazure version 0.3.0";
// page extensions class dictionary.
private IList<PageTemplateModel> pageModels;
public AzurePythonCodeGenerator(Settings settings)
: base(settings)
{
pageModels = new List<PageTemplateModel>();
Namer = new AzurePythonCodeNamer();
}
public override string Name
{
get { return "Azure.Python"; }
}
public override string Description
{
// TODO resource string.
get { return "Azure specific Python code generator."; }
}
public override string UsageInstructions
{
get
{
return string.Format(CultureInfo.InvariantCulture,
Resources.UsageInformation, ClientRuntimePackage);
}
}
/// <summary>
/// Normalizes client model by updating names and types to be language specific.
/// </summary>
/// <param name="serviceClient"></param>
public override void NormalizeClientModel(ServiceClient serviceClient)
{
// Don't add pagable/longrunning method since we already handle ourself.
Settings.AddCredentials = true;
AzureExtensions.UpdateHeadMethods(serviceClient);
AzureExtensions.ParseODataExtension(serviceClient);
Extensions.FlattenModels(serviceClient);
Extensions.AddParameterGroups(serviceClient);
AzureExtensions.AddAzureProperties(serviceClient);
AzureExtensions.SetDefaultResponses(serviceClient);
CorrectFilterParameters(serviceClient);
base.NormalizeClientModel(serviceClient);
NormalizeApiVersion(serviceClient);
NormalizePaginatedMethods(serviceClient);
}
private static void NormalizeApiVersion(ServiceClient serviceClient)
{
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.ApiVersion, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.AcceptLanguage, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
}
private string GetPagingSetting(Dictionary<string, object> extensions, string valueTypeName)
{
var ext = extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer;
string nextLinkName = (string)ext["nextLinkName"] ?? "nextLink";
string itemName = (string)ext["itemName"] ?? "value";
string className = (string)ext["className"];
if (string.IsNullOrEmpty(className))
{
className = valueTypeName + "Paged";
ext["className"] = className;
}
var pageModel = new PageTemplateModel(className, nextLinkName, itemName, valueTypeName);
if (!pageModels.Contains(pageModel))
{
pageModels.Add(pageModel);
}
return className;
}
/// <summary>
/// Changes paginated method signatures to return Page type.
/// </summary>
/// <param name="serviceClient"></param>
private void NormalizePaginatedMethods(ServiceClient serviceClient)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
var convertedTypes = new Dictionary<IType, Response>();
foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension)))
{
foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key))
{
var compositType = (CompositeType)method.Responses[responseStatus].Body;
var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType;
// if the type is a wrapper over page-able response
if (sequenceType != null)
{
string pagableTypeName = GetPagingSetting(method.Extensions, sequenceType.ElementType.Name);
CompositeType pagedResult = new CompositeType
{
Name = pagableTypeName
};
convertedTypes[compositType] = new Response(pagedResult, null);
method.Responses[responseStatus] = convertedTypes[compositType];
break;
}
}
if (convertedTypes.ContainsKey(method.ReturnType.Body))
{
method.ReturnType = convertedTypes[method.ReturnType.Body];
}
}
Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name)));
}
/// <summary>
/// Corrects type of the filter parameter. Currently typization of filters isn't
/// supported and therefore we provide to user an opportunity to pass it in form
/// of raw string.
/// </summary>
/// <param name="serviceClient">The service client.</param>
public static void CorrectFilterParameters(ServiceClient serviceClient)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.ODataExtension)))
{
var filterParameter = method.Parameters.FirstOrDefault(p =>
p.SerializedName.Equals("$filter", StringComparison.OrdinalIgnoreCase) &&
p.Location == ParameterLocation.Query &&
p.Type is CompositeType);
if (filterParameter != null)
{
filterParameter.Type = new PrimaryType(KnownPrimaryType.String);
}
}
}
/// <summary>
/// Generate Python client code for given ServiceClient.
/// </summary>
/// <param name="serviceClient"></param>
/// <returns></returns>
public override async Task Generate(ServiceClient serviceClient)
{
var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient);
if (!string.IsNullOrWhiteSpace(Version))
{
serviceClientTemplateModel.Version = Version;
}
// Service client
var setupTemplate = new SetupTemplate
{
Model = serviceClientTemplateModel
};
await Write(setupTemplate, "setup.py");
var serviceClientInitTemplate = new ServiceClientInitTemplate
{
Model = serviceClientTemplateModel
};
await Write(serviceClientInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "__init__.py"));
var serviceClientTemplate = new AzureServiceClientTemplate
{
Model = serviceClientTemplateModel,
};
await Write(serviceClientTemplate, Path.Combine(serviceClientTemplateModel.PackageName, serviceClientTemplateModel.Name.ToPythonCase() + ".py"));
var versionTemplate = new VersionTemplate
{
Model = serviceClientTemplateModel,
};
await Write(versionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "version.py"));
var exceptionTemplate = new ExceptionTemplate
{
Model = serviceClientTemplateModel,
};
await Write(exceptionTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "exceptions.py"));
var credentialTemplate = new CredentialTemplate
{
Model = serviceClientTemplateModel,
};
await Write(credentialTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "credentials.py"));
//Models
if (serviceClientTemplateModel.ModelTemplateModels.Any())
{
var modelInitTemplate = new AzureModelInitTemplate
{
Model = new AzureModelInitTemplateModel(serviceClient, pageModels.Select(t => t.TypeDefinitionName))
};
await Write(modelInitTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", "__init__.py"));
foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels)
{
var modelTemplate = new ModelTemplate
{
Model = modelType
};
await Write(modelTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", modelType.Name.ToPythonCase() + ".py"));
}
}
//MethodGroups
if (serviceClientTemplateModel.MethodGroupModels.Any())
{
var methodGroupIndexTemplate = new MethodGroupInitTemplate
{
Model = serviceClientTemplateModel
};
await Write(methodGroupIndexTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", "__init__.py"));
foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels)
{
var methodGroupTemplate = new AzureMethodGroupTemplate
{
Model = methodGroupModel as AzureMethodGroupTemplateModel
};
await Write(methodGroupTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "operations", methodGroupModel.MethodGroupType.ToPythonCase() + ".py"));
}
}
// Enums
if (serviceClient.EnumTypes.Any())
{
var enumTemplate = new EnumTemplate
{
Model = new EnumTemplateModel(serviceClient.EnumTypes),
};
await Write(enumTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", serviceClientTemplateModel.Name.ToPythonCase() + "_enums.py"));
}
// Page class
foreach (var pageModel in pageModels)
{
var pageTemplate = new PageTemplate
{
Model = pageModel
};
await Write(pageTemplate, Path.Combine(serviceClientTemplateModel.PackageName, "models", pageModel.TypeDefinitionName.ToPythonCase() + ".py"));
}
}
}
}
| |
namespace OctoTorrent.Client
{
using System;
using System.Collections.Generic;
using Common;
using Messages;
using Messages.FastPeer;
using Messages.Standard;
internal class ChokeUnchokeManager : IUnchoker
{
#region Private Fields
private readonly PeerList _candidatePeers = new PeerList(PeerListType.CandidatePeers);
//Peers that are candidates for unchoking based on past performance
private readonly int _minimumTimeBetweenReviews = 30;
//seconds. Minimum time that needs to pass before we execute a review
private readonly PeerList _nascentPeers = new PeerList(PeerListType.NascentPeers);
//Peers that have yet to be unchoked and downloading for a full review period
private readonly PeerList _optimisticUnchokeCandidates =
new PeerList(PeerListType.OptimisticUnchokeCandidatePeers);
//Peers that are candidates for unchoking in case they perform well
private readonly TorrentManager _owningTorrent; //The torrent to which this manager belongs
private readonly int _percentOfMaxRateToSkipReview = 90;
//If the latest download/upload rate is >= to this percentage of the maximum rate we should skip the review
private bool _firstCall = true; //Indicates the first call to the TimePassed method
private bool _isDownloading = true; //Allows us to identify change in state from downloading to seeding
private PeerId _optimisticUnchokePeer; //This is the peer we have optimistically unchoked, or null
//Lists of peers held by the choke/unchoke manager
private DateTime _timeOfLastReview; //When we last reviewed the choke/unchoke position
/// <summary>
/// Number of peer reviews that have been conducted
/// </summary>
internal int ReviewsExecuted { get; private set; }
#endregion Private Fields
#region Constructors
/// <summary>
/// Creates a new choke/unchoke manager for a torrent manager
/// </summary>
public ChokeUnchokeManager(TorrentManager torrentManager, int minimumTimeBetweenReviews,
int percentOfMaxRateToSkipReview)
{
_owningTorrent = torrentManager;
_minimumTimeBetweenReviews = minimumTimeBetweenReviews;
_percentOfMaxRateToSkipReview = percentOfMaxRateToSkipReview;
}
#endregion
#region Public Methods
/// <summary>
/// Executed each tick of the client engine
/// </summary>
public void TimePassed()
{
//Start by identifying:
// the choked and interested peers
// the number of unchoked peers
//Choke peers that have become disinterested at the same time
var chokedInterestedPeers = new List<PeerId>();
var interestedCount = 0;
var unchokedCount = 0;
var skipDownload = (_isDownloading &&
(_owningTorrent.Monitor.DownloadSpeed <
(_owningTorrent.Settings.MaxDownloadSpeed*_percentOfMaxRateToSkipReview/100.0)));
var skipUpload = (!_isDownloading &&
(_owningTorrent.Monitor.UploadSpeed <
(_owningTorrent.Settings.MaxUploadSpeed*_percentOfMaxRateToSkipReview/100.0)));
skipDownload = skipDownload && _owningTorrent.Settings.MaxDownloadSpeed > 0;
skipUpload = skipUpload && _owningTorrent.Settings.MaxUploadSpeed > 0;
foreach (var connectedPeer in _owningTorrent.Peers.ConnectedPeers)
{
if (connectedPeer.Connection == null)
continue;
//If the peer is a seeder and we are not currently interested in it, put that right
if (connectedPeer.Peer.IsSeeder && !connectedPeer.AmInterested)
{
// FIXME - Is this necessary anymore? I don't think so
//owningTorrent.Mode.SetAmInterestedStatus(connectedPeer, true);
//Send2Log("Forced AmInterested: " + connectedPeer.Peer.Location);
}
// If the peer is interesting try to queue up some piece requests off him
// If he is choking, we will only queue a piece if there is a FastPiece we can choose
if (connectedPeer.AmInterested)
_owningTorrent.PieceManager.AddPieceRequests(connectedPeer);
if (connectedPeer.Peer.IsSeeder)
continue;
if (!connectedPeer.IsInterested && !connectedPeer.AmChoking)
//This peer is disinterested and unchoked; choke it
Choke(connectedPeer);
else if (connectedPeer.IsInterested)
{
interestedCount++;
if (!connectedPeer.AmChoking) //This peer is interested and unchoked, count it
unchokedCount++;
else
chokedInterestedPeers.Add(connectedPeer);
//This peer is interested and choked, remember it and count it
}
}
if (_firstCall)
{
//This is the first time we've been called for this torrent; set current status and run an initial review
_isDownloading = !_owningTorrent.Complete; //If progress is less than 100% we must be downloading
_firstCall = false;
ExecuteReview();
}
else if (_isDownloading && _owningTorrent.Complete)
{
//The state has changed from downloading to seeding; set new status and run an initial review
_isDownloading = false;
ExecuteReview();
}
else if (interestedCount <= _owningTorrent.Settings.UploadSlots)
//Since we have enough slots to satisfy everyone that's interested, unchoke them all; no review needed
UnchokePeerList(chokedInterestedPeers);
else if (_minimumTimeBetweenReviews > 0 &&
(SecondsBetween(_timeOfLastReview, DateTime.Now) >= _minimumTimeBetweenReviews) &&
(skipDownload || skipUpload))
//Based on the time of the last review, a new review is due
//There are more interested peers than available upload slots
//If we're downloading, the download rate is insufficient to skip the review
//If we're seeding, the upload rate is insufficient to skip the review
//So, we need a review
ExecuteReview();
else
//We're not going to do a review this time
//Allocate any available slots based on the results of the last review
AllocateSlots(unchokedCount);
}
#endregion
#region Private Methods
public void Choke(PeerId peer)
{
//Choke the supplied peer
if (peer.AmChoking)
//We're already choking this peer, nothing to do
return;
peer.AmChoking = true;
_owningTorrent.UploadingTo--;
RejectPendingRequests(peer);
peer.EnqueueAt(new ChokeMessage(), 0);
Logger.Log(peer.Connection, "Choking");
// Send2Log("Choking: " + PeerToChoke.Location);
}
public void Unchoke(PeerId PeerToUnchoke)
{
//Unchoke the supplied peer
if (!PeerToUnchoke.AmChoking)
//We're already unchoking this peer, nothing to do
return;
PeerToUnchoke.AmChoking = false;
_owningTorrent.UploadingTo++;
PeerToUnchoke.EnqueueAt(new UnchokeMessage(), 0);
PeerToUnchoke.LastUnchoked = DateTime.Now;
PeerToUnchoke.FirstReviewPeriod = true;
Logger.Log(PeerToUnchoke.Connection, "Unchoking");
// Send2Log("Unchoking: " + PeerToUnchoke.Location);
}
private IEnumerable<PeerList> AllLists()
{
yield return _nascentPeers;
yield return _candidatePeers;
yield return _optimisticUnchokeCandidates;
}
private void AllocateSlots(int alreadyUnchoked)
{
PeerId peer;
//Allocate interested peers to slots based on the latest review results
//First determine how many slots are available to be allocated
var availableSlots = _owningTorrent.Settings.UploadSlots - alreadyUnchoked;
// If there are no slots, just return
if (availableSlots <= 0)
return;
// Check the peer lists (nascent, then candidate then optimistic unchoke)
// for an interested choked peer, if one is found, unchoke it.
foreach (var list in AllLists())
while ((peer = list.GetFirstInterestedChokedPeer()) != null && (availableSlots-- > 0))
Unchoke(peer);
// In the time that has passed since the last review we might have connected to more peers
// that don't appear in AllLists. It's also possible we have not yet run a review in
// which case AllLists will be empty. Fill remaining slots with unchoked, interested peers
// from the full list.
while (availableSlots-- > 0)
{
//No peers left, look for any interested choked peers
var peerFound = false;
foreach (var connectedPeer in _owningTorrent.Peers.ConnectedPeers)
{
if (connectedPeer.Connection == null)
continue;
if (connectedPeer.IsInterested && connectedPeer.AmChoking)
{
Unchoke(connectedPeer);
peerFound = true;
break;
}
}
if (!peerFound)
//No interested choked peers anywhere, we're done
break;
}
}
private void ExecuteReview()
{
//Review current choke/unchoke position and adjust as necessary
//Start by populating the lists of peers, then allocate available slots oberving the unchoke limit
//Clear the lists to start with
_nascentPeers.Clear();
_candidatePeers.Clear();
_optimisticUnchokeCandidates.Clear();
//No review needed or disabled by the torrent settings
/////???Remove when working
////Log peer status - temporary
//if (isLogging)
//{
// StringBuilder logEntry = new StringBuilder(1000);
// logEntry.Append(B2YN(owningTorrent.State == TorrentState.Seeding) + timeOfLastReview.ToString() + "," + DateTime.Now.ToString() + ";");
// foreach (PeerIdInternal connectedPeer in owningTorrent.Peers.ConnectedPeers)
// {
// if (connectedPeer.Connection != null)
// if (!connectedPeer.Peer.IsSeeder)
// {
// {
// logEntry.Append(
// B2YN(connectedPeer.Peer.IsSeeder) +
// B2YN(connectedPeer.AmChoking) +
// B2YN(connectedPeer.AmInterested) +
// B2YN(connectedPeer.IsInterested) +
// B2YN(connectedPeer.Peer.FirstReviewPeriod) +
// connectedPeer.Connection.Monitor.DataBytesDownloaded.ToString() + "," +
// connectedPeer.Peer.BytesDownloadedAtLastReview.ToString() + "," +
// connectedPeer.Connection.Monitor.DataBytesUploaded.ToString() + "," +
// connectedPeer.Peer.BytesUploadedAtLastReview.ToString() + "," +
// connectedPeer.Peer.Location);
// DateTime? lastUnchoked = connectedPeer.Peer.LastUnchoked;
// if (lastUnchoked.HasValue)
// logEntry.Append(
// "," +
// lastUnchoked.ToString() + "," +
// SecondsBetween(lastUnchoked.Value, DateTime.Now).ToString());
// logEntry.Append(";");
// }
// }
// }
// Send2Log(logEntry.ToString());
//}
//Scan the peers building the lists as we go and count number of unchoked peers
var unchokedPeers = 0;
foreach (var connectedPeer in _owningTorrent.Peers.ConnectedPeers)
{
if (connectedPeer.Connection != null)
{
if (!connectedPeer.Peer.IsSeeder)
{
//Determine common values for use in this routine
var timeSinceLastReview = SecondsBetween(_timeOfLastReview, DateTime.Now);
double timeUnchoked = 0;
if (!connectedPeer.AmChoking)
{
timeUnchoked = SecondsBetween(connectedPeer.LastUnchoked.Value, DateTime.Now);
unchokedPeers++;
}
long bytesTransferred = 0;
if (!_isDownloading)
//We are seeding the torrent; determine bytesTransferred as bytes uploaded
bytesTransferred = connectedPeer.Monitor.DataBytesUploaded -
connectedPeer.BytesUploadedAtLastReview;
else
//The peer is unchoked and we are downloading the torrent; determine bytesTransferred as bytes downloaded
bytesTransferred = connectedPeer.Monitor.DataBytesDownloaded -
connectedPeer.BytesDownloadedAtLastReview;
//Reset review up and download rates to zero; peers are therefore non-responders unless we determine otherwise
connectedPeer.LastReviewDownloadRate = 0;
connectedPeer.LastReviewUploadRate = 0;
if (!connectedPeer.AmChoking &&
(timeUnchoked < _minimumTimeBetweenReviews ||
(connectedPeer.FirstReviewPeriod && bytesTransferred > 0)))
//The peer is unchoked but either it has not been unchoked for the warm up interval,
// or it is the first full period and only just started transferring data
_nascentPeers.Add(connectedPeer);
else if ((timeUnchoked >= _minimumTimeBetweenReviews) && bytesTransferred > 0)
//The peer is unchoked, has been for the warm up period and has transferred data in the period
{
//Add to peers that are candidates for unchoking based on their performance
_candidatePeers.Add(connectedPeer);
//Calculate the latest up/downloadrate
connectedPeer.LastReviewUploadRate = (connectedPeer.Monitor.DataBytesUploaded -
connectedPeer.BytesUploadedAtLastReview)/
timeSinceLastReview;
connectedPeer.LastReviewDownloadRate = (connectedPeer.Monitor.DataBytesDownloaded -
connectedPeer.BytesDownloadedAtLastReview)/
timeSinceLastReview;
}
else if (_isDownloading && connectedPeer.IsInterested && connectedPeer.AmChoking &&
bytesTransferred > 0)
//A peer is optimistically unchoking us. Take the maximum of their current download rate and their download rate over the
// review period since they might have only just unchoked us and we don't want to miss out on a good opportunity. Upload
// rate is less important, so just take an average over the period.
{
//Add to peers that are candidates for unchoking based on their performance
_candidatePeers.Add(connectedPeer);
//Calculate the latest up/downloadrate
connectedPeer.LastReviewUploadRate = (connectedPeer.Monitor.DataBytesUploaded -
connectedPeer.BytesUploadedAtLastReview)/
timeSinceLastReview;
connectedPeer.LastReviewDownloadRate =
Math.Max(
(connectedPeer.Monitor.DataBytesDownloaded -
connectedPeer.BytesDownloadedAtLastReview)/timeSinceLastReview,
connectedPeer.Monitor.DownloadSpeed);
}
else if (connectedPeer.IsInterested)
//All other interested peers are candidates for optimistic unchoking
_optimisticUnchokeCandidates.Add(connectedPeer);
//Remember the number of bytes up and downloaded for the next review
connectedPeer.BytesUploadedAtLastReview = connectedPeer.Monitor.DataBytesUploaded;
connectedPeer.BytesDownloadedAtLastReview = connectedPeer.Monitor.DataBytesDownloaded;
//If the peer has been unchoked for longer than one review period, unset FirstReviewPeriod
if (timeUnchoked >= _minimumTimeBetweenReviews)
connectedPeer.FirstReviewPeriod = false;
}
}
}
// Send2Log(nascentPeers.Count.ToString() + "," + candidatePeers.Count.ToString() + "," + optimisticUnchokeCandidates.Count.ToString());
//Now sort the lists of peers so we are ready to reallocate them
_nascentPeers.Sort(_owningTorrent.State == TorrentState.Seeding);
_candidatePeers.Sort(_owningTorrent.State == TorrentState.Seeding);
_optimisticUnchokeCandidates.Sort(_owningTorrent.State == TorrentState.Seeding);
// if (isLogging)
// {
// string x = "";
// while (optimisticUnchokeCandidates.MorePeers)
// x += optimisticUnchokeCandidates.GetNextPeer().Location + ";";
// Send2Log(x);
// optimisticUnchokeCandidates.StartScan();
// }
//If there is an optimistic unchoke peer and it is nascent, we should reallocate all the available slots
//Otherwise, if all the slots are allocated to nascent peers, don't try an optimistic unchoke this time
if (_nascentPeers.Count >= _owningTorrent.Settings.UploadSlots || _nascentPeers.Includes(_optimisticUnchokePeer))
ReallocateSlots(_owningTorrent.Settings.UploadSlots, unchokedPeers);
else
{
//We should reallocate all the slots but one and allocate the last slot to the next optimistic unchoke peer
ReallocateSlots(_owningTorrent.Settings.UploadSlots - 1, unchokedPeers);
//In case we don't find a suitable peer, make the optimistic unchoke peer null
var oup = _optimisticUnchokeCandidates.GetOUPeer();
if (oup != null)
{
// Send2Log("OUP: " + oup.Location);
Unchoke(oup);
_optimisticUnchokePeer = oup;
}
}
//Finally, deallocate (any) remaining peers from the three lists
while (_nascentPeers.MorePeers)
{
var nextPeer = _nascentPeers.GetNextPeer();
if (!nextPeer.AmChoking)
Choke(nextPeer);
}
while (_candidatePeers.MorePeers)
{
var nextPeer = _candidatePeers.GetNextPeer();
if (!nextPeer.AmChoking)
Choke(nextPeer);
}
while (_optimisticUnchokeCandidates.MorePeers)
{
var nextPeer = _optimisticUnchokeCandidates.GetNextPeer();
if (!nextPeer.AmChoking)
//This peer is currently unchoked, choke it unless it is the optimistic unchoke peer
if (_optimisticUnchokePeer == null)
//There isn't an optimistic unchoke peer
Choke(nextPeer);
else if (!nextPeer.Equals(_optimisticUnchokePeer))
//This isn't the optimistic unchoke peer
Choke(nextPeer);
}
_timeOfLastReview = DateTime.Now;
ReviewsExecuted++;
}
/// <summary>
/// Review method for BitTyrant Choking/Unchoking Algorithm
/// </summary>
private void ExecuteTyrantReview()
{
// if we are seeding, don't deal with it - just send it to old method
if (!_isDownloading)
ExecuteReview();
var sortedPeers = new List<PeerId>();
foreach (var connectedPeer in _owningTorrent.Peers.ConnectedPeers)
{
if (connectedPeer.Connection != null)
{
// update tyrant stats
connectedPeer.UpdateTyrantStats();
sortedPeers.Add(connectedPeer);
}
}
// sort the list by BitTyrant ratio
sortedPeers.Sort(delegate(PeerId p1, PeerId p2) { return p2.Ratio.CompareTo(p1.Ratio); });
//TODO: Make sure that lan-local peers always get unchoked. Perhaps an implementation like AZInstanceManager
//(in com.aelitis.azureus.core.instancemanager)
// After this is complete, sort them and and unchoke until upload capcity is met
// TODO: Should we consider some extra measures, like nascent peers, candidatePeers, optimisticUnchokeCandidates ETC.
var uploadBandwidthUsed = 0;
foreach (var pid in sortedPeers)
{
// unchoke the top interested peers till we reach the max bandwidth allotted.
if (uploadBandwidthUsed < _owningTorrent.Settings.MaxUploadSpeed && pid.IsInterested)
{
Unchoke(pid);
uploadBandwidthUsed += pid.UploadRateForRecip;
}
else
{
Choke(pid);
}
}
_timeOfLastReview = DateTime.Now;
ReviewsExecuted++;
}
/// <summary>
/// Reallocates the specified number of upload slots
/// </summary>
/// <param name="NumberOfSlots"> </param>
/// The number of slots we should reallocate
private void ReallocateSlots(int NumberOfSlots, int NumberOfUnchokedPeers)
{
//First determine the maximum number of peers we can unchoke in this review = maximum of:
// half the number of upload slots; and
// slots not already unchoked
var maximumUnchokes = NumberOfSlots/2;
maximumUnchokes = Math.Max(maximumUnchokes, NumberOfSlots - NumberOfUnchokedPeers);
//Now work through the lists of peers in turn until we have allocated all the slots
while (NumberOfSlots > 0)
{
if (_nascentPeers.MorePeers)
ReallocateSlot(ref NumberOfSlots, ref maximumUnchokes, _nascentPeers.GetNextPeer());
else if (_candidatePeers.MorePeers)
ReallocateSlot(ref NumberOfSlots, ref maximumUnchokes, _candidatePeers.GetNextPeer());
else if (_optimisticUnchokeCandidates.MorePeers)
ReallocateSlot(ref NumberOfSlots, ref maximumUnchokes, _optimisticUnchokeCandidates.GetNextPeer());
else
//No more peers left, we're done
break;
}
}
/// <summary>
/// Reallocates the next slot with the specified peer if we can
/// </summary>
/// <param name="NumberOfSlots"> </param>
/// The number of slots left to reallocate
/// <param name="MaximumUnchokes"> </param>
/// The number of peers we can unchoke
/// <param name="Peer"> </param>
/// The peer to consider for reallocation
private void ReallocateSlot(ref int NumberOfSlots, ref int MaximumUnchokes, PeerId peer)
{
if (!peer.AmChoking)
{
//This peer is already unchoked, just decrement the number of slots
NumberOfSlots--;
// Send2Log("Leave: " + peer.Location);
}
else if (MaximumUnchokes > 0)
{
//This peer is choked and we've not yet reached the limit of unchokes, unchoke it
Unchoke(peer);
MaximumUnchokes--;
NumberOfSlots--;
}
}
/// <summary>
/// Checks the send queue of the peer to see if there are any outstanding pieces which they requested
/// and rejects them as necessary
/// </summary>
/// <param name="Peer"> </param>
private void RejectPendingRequests(PeerId Peer)
{
var length = Peer.QueueLength;
for (var i = 0; i < length; i++)
{
var message = Peer.Dequeue();
var pieceMessage = message as PieceMessage;
if (pieceMessage == null)
{
Peer.Enqueue(message);
continue;
}
// If the peer doesn't support fast peer, then we will never requeue the message
if (!(Peer.SupportsFastPeer && ClientEngine.SupportsFastPeer))
{
Peer.IsRequestingPiecesCount--;
continue;
}
// If the peer supports fast peer, queue the message if it is an AllowedFast piece
// Otherwise send a reject message for the piece
if (Peer.AmAllowedFastPieces.Contains(pieceMessage.PieceIndex))
Peer.Enqueue(pieceMessage);
else
{
Peer.IsRequestingPiecesCount--;
Peer.Enqueue(new RejectRequestMessage(pieceMessage));
}
}
}
private static double SecondsBetween(DateTime FirstTime, DateTime SecondTime)
{
//Calculate the number of seconds and fractions of a second that have elapsed between the first time and the second
var difference = SecondTime.Subtract(FirstTime);
return difference.TotalMilliseconds/1000;
}
private void UnchokePeerList(List<PeerId> PeerList)
{
//Unchoke all the peers in the supplied list
PeerList.ForEach(Unchoke);
}
#endregion
#region Temporary stuff for logging
//FileStream logStream;
//StreamWriter logStreamWriter;
//bool isLogging = true;
//private void Send2Log(string LogEntry)
//{
// if (isLogging)
// {
// if (logStream == null)
// {
// string logFileName = owningTorrent.Torrent.Name + ".ChokeUnchoke.Log";
// logStream = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),logFileName),FileMode.Append);
// logStreamWriter = new StreamWriter(logStream, System.Text.Encoding.ASCII);
// logStreamWriter.AutoFlush=true;
// }
// logStreamWriter.WriteLine(DateTime.Now.ToString() + ":" + LogEntry);
// }
//}
//private string B2YN(bool Boolean)
//{
// if (Boolean)
// return "Y,";
// else
// return "N,";
//}
#endregion
#region IUnchoker Members
public void UnchokeReview()
{
TimePassed();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Windows.Forms;
using Tao.OpenGl;
using Tao.Platform.Windows;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
/*
using Cauldron;
using xmljr.math;
using ButcherBlock.Interaction;
*/
namespace Pantry
{
/// <summary>
/// Summary description for OpenGLContext.
/// </summary>
public class OpenGLView : System.Windows.Forms.Control
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private IntPtr hDC; // Private GDI Device Context
private IntPtr hRC; // Permanent Rendering Context
// Camera System
/*
private Cameras.ICamera _MyCamera = null;
private Cameras.Fly _MyCameraFly = null;
private Group _MyScene;
private Interaction.Selection _MyInteract = null;
public Interaction.Selection MyInteract
{
get { return _MyInteract; }
set { _MyInteract = value; }
}
public Group Scene
{
get { return _MyScene; }
set
{
_MyScene = value;
_MyInteract = new Interaction.Selection(_MyScene, this);
}
}
public void SetSelectionMode(Interaction.Selection.RotationMode RM)
{
_MyInteract.RotateMode = RM;
}
public Cameras.ICamera MyCamera
{
get { return _MyCamera; }
set { _MyCamera = value; }
}
private MouseInteractContext _MyInteractContext;
private object Selection = null;
public bool IsSelected(object O)
{
return (O == Selection);
}
public void SetSelection(object O) { Selection = O; }
Rendering.Renderer _Renderer;
public void SetRenderer(Rendering.Renderer R)
{
_Renderer = R;
_SplashScreen.textMessage.Text = "Compiling Shaders";
R.compileshaders(_SplashScreen);
_SplashScreen.textMessage.Text = "Finished Shader Compilation";
_SplashScreen.Refresh();
System.Threading.Thread.Sleep(250);
_SplashScreen.textMessage.Text = "Building GeoMorph Transducer";
_SplashScreen.Refresh();
System.Threading.Thread.Sleep(250);
_SplashScreen.Close();
}
public Geometry Lock = null;
public void PointTrack(Geometry G, bool doLock)
{
double D = 25;
if(G.Maximum != null && G.Minimum != null)
D = (G.Maximum + -G.Minimum).Length3 * 2.5;
_MyCamera = new Cameras.SpherePointTrack(G.GlobalPose.GetPosition(), G.GlobalPose.GetUpVector(), G.GlobalPose.GetSideVector(), D);
Lock = null;
if(doLock)
Lock = G;
// 0,0,0,0,1,0,1,0,0,100.0);
}
void UpdateLock()
{
if(_MyCamera is Cameras.SpherePointTrack && Lock != null)
{
Cameras.SpherePointTrack SPT = _MyCamera as Cameras.SpherePointTrack;
SPT.Origin = Lock.GlobalPose.GetPosition();
SPT.Up = Lock.GlobalPose.GetUpVector();
SPT.Side = Lock.GlobalPose.GetSideVector();
}
}
public void Fly()
{
if(_MyCamera is Cameras.SpherePointTrack)
{
Cameras.SpherePointTrack SPT = _MyCamera as Cameras.SpherePointTrack;
_MyCameraFly.Position = -SPT.gEye();
Vector3 v3 = (SPT.Origin + - SPT.gEye());
v3.normalize3();
_MyCameraFly.Up = (SPT.Up + (- v3 * Vector3.dot3(SPT.Up, v3) ));
_MyCameraFly.Up.normalize3();
_MyCameraFly.Side = Vector3.cross(v3, _MyCameraFly.Up);
}
_MyCamera = _MyCameraFly;
}
public double [] Eye
{
get
{
if(_MyCamera is Cameras.SpherePointTrack)
{
Cameras.SpherePointTrack SPT = _MyCamera as Cameras.SpherePointTrack;
return new double[] { SPT.gEye().x, SPT.gEye().y, SPT.gEye().z };
}
if(_MyCamera is Cameras.Fly)
{
return new double[] { -_MyCameraFly.Position.x, -_MyCameraFly.Position.y, -_MyCameraFly.Position.z };
}
return null;
}
}
public Cameras.Fly GetFlier()
{
return _MyCameraFly;
}
public bool IsFlying()
{
return _MyCamera is Cameras.Fly;
}
SplashScreen _SplashScreen;
*/
// , MouseInteractContext MIC, SplashScreen SS
public OpenGLView()
{
this.Width = 100;
this.Height = 100;
CreateOpenGLView(100, 100);
}
public OpenGLView(int width, int height)
{
CreateOpenGLView(width, height);
}
public void CreateOpenGLView(int width, int height)
{
// _SplashScreen = SS;
// _MyInteractContext = MIC;
this.CreateParams.ClassStyle = this.CreateParams.ClassStyle | // Redraw On Size, And Own DC For Window.
User.CS_HREDRAW | User.CS_VREDRAW | User.CS_OWNDC;
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.Opaque, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
// SS.textMessage.Text = "Creating GL Window";
// SS.Refresh();
if (!CreateGLWindow(width, height, 16))
{
MessageBox.Show("Err");
}
// _MyCameraFly = new Cameras.Fly();
// _MyCamera = _MyCameraFly;
// _MyCamera = new Cameras.SpherePointTrack(0,0,0,0,1,0,1,0,0,100.0);
// Group G = new Group();
// SS.textMessage.Text = "Compiling Shaders";
// SS.Refresh();
this.Resize += new EventHandler(this.Control_Resize); // On Resize Event Call Form_Resize
}
public void Finish()
{
KillGLWindow();
}
public void Save(string fname)
{
// SaveWait SW = new SaveWait(fname, _MyScene);
// SW.Start();
// SW.ShowDialog(this);
}
public void Load(string fname)
{
// LoadWait LW = new LoadWait(fname);
// LW.Start();
// LW.ShowDialog(this);
// _MyScene = LW.Root;
// _MyInteract = new Interaction.Selection(_MyScene, this);
/*
StreamReader Sr = new StreamReader("scene.xml");
xmljr.XmlJrDom dom = xmljr.XmlJrDom.Read(Sr.ReadToEnd(), null);
_MyScene = Cauldron.Cauldron.BuildObjectTable(dom).LookUpObject(1) as Group;
Sr.Close();
*/
}
private bool CreateGLWindow(int width, int height, int bits)
{
int pixelFormat; // Holds The Results After Searching For A Match
GC.Collect(); // Request A Collection
// This Forces A Swap
Kernel.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
this.Width = width; // Set Window Width
this.Height = height; // Set Window Height
Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR(); // pfd Tells Windows How We Want Things To Be
pfd.nSize = (short)Marshal.SizeOf(pfd); // Size Of This Pixel Format Descriptor
pfd.nVersion = 1; // Version Number
pfd.dwFlags = Gdi.PFD_DRAW_TO_WINDOW | // Format Must Support Window
Gdi.PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
Gdi.PFD_DOUBLEBUFFER; // Format Must Support Double Buffering
pfd.iPixelType = (byte)Gdi.PFD_TYPE_RGBA; // Request An RGBA Format
pfd.cColorBits = (byte)bits; // Select Our Color Depth
pfd.cRedBits = 0; // Color Bits Ignored
pfd.cRedShift = 0;
pfd.cGreenBits = 0;
pfd.cGreenShift = 0;
pfd.cBlueBits = 0;
pfd.cBlueShift = 0;
pfd.cAlphaBits = 0; // No Alpha Buffer
pfd.cAlphaShift = 0; // Shift Bit Ignored
pfd.cAccumBits = 0; // No Accumulation Buffer
pfd.cAccumRedBits = 0; // Accumulation Bits Ignored
pfd.cAccumGreenBits = 0;
pfd.cAccumBlueBits = 0;
pfd.cAccumAlphaBits = 0;
pfd.cDepthBits = 16; // 16Bit Z-Buffer (Depth Buffer)
pfd.cStencilBits = 0; // No Stencil Buffer
pfd.cAuxBuffers = 0; // No Auxiliary Buffer
pfd.iLayerType = (byte)Gdi.PFD_MAIN_PLANE; // Main Drawing Layer
pfd.bReserved = 0; // Reserved
pfd.dwLayerMask = 0; // Layer Masks Ignored
pfd.dwVisibleMask = 0;
pfd.dwDamageMask = 0;
hDC = User.GetDC(this.Handle); // Attempt To Get A Device Context
if (hDC == IntPtr.Zero)
{ // Did We Get A Device Context?
KillGLWindow(); // Reset The Display
MessageBox.Show("Can't Create A GL Device Context.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
pixelFormat = Gdi.ChoosePixelFormat(hDC, ref pfd); // Attempt To Find An Appropriate Pixel Format
if (pixelFormat == 0)
{ // Did Windows Find A Matching Pixel Format?
KillGLWindow(); // Reset The Display
MessageBox.Show("Can't Find A Suitable PixelFormat.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
if (!Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd))
{ // Are We Able To Set The Pixel Format?
KillGLWindow(); // Reset The Display
MessageBox.Show("Can't Set The PixelFormat.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
hRC = Wgl.wglCreateContext(hDC); // Attempt To Get The Rendering Context
if (hRC == IntPtr.Zero)
{ // Are We Able To Get A Rendering Context?
KillGLWindow(); // Reset The Display
MessageBox.Show("Can't Create A GL Rendering Context.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
if (!Wgl.wglMakeCurrent(hDC, hRC))
{ // Try To Activate The Rendering Context
KillGLWindow(); // Reset The Display
MessageBox.Show("Can't Activate The GL Rendering Context.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// Tao.OpenGl.GlExtensionLoader.LoadAllExtensions(hRC);
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL())
{ // Initialize Our Newly Created GL Window
KillGLWindow(); // Reset The Display
MessageBox.Show("Initialization Failed.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true; // Success
}
private void KillGLWindow()
{
if (hRC != IntPtr.Zero)
{ // Do We Have A Rendering Context?
if (!Wgl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero))
{ // Are We Able To Release The DC and RC Contexts?
MessageBox.Show("Release Of DC And RC Failed.", "SHUTDOWN ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (!Wgl.wglDeleteContext(hRC))
{ // Are We Able To Delete The RC?
MessageBox.Show("Release Rendering Context Failed.", "SHUTDOWN ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
hRC = IntPtr.Zero; // Set RC To Null
}
if (hDC != IntPtr.Zero)
{ // Do We Have A Device Context?
if (!this.IsDisposed)
{ // Do We Have A Window?
if (this.Handle != IntPtr.Zero)
{ // Do We Have A Window Handle?
if (!User.ReleaseDC(this.Handle, hDC))
{ // Are We Able To Release The DC?
MessageBox.Show("Release Device Context Failed.", "SHUTDOWN ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
hDC = IntPtr.Zero; // Set DC To Null
}
// Glu.gluUnProject(
}
/*
public int [] ViewportVector = new int[4];
public double [] ProjectMatrix = new double[16];
public double [] ModelMatrix = new double[16];
public Matrix4x4 GetModelMatrix()
{
Matrix4x4 M = new Matrix4x4(ModelMatrix);
return M;
}
public Matrix4x4 GetInverseModelMatrix()
{
Matrix4x4 M = new Matrix4x4(ModelMatrix);
M.Invert();
return M;
}
public void Draw(Node N)
{
_Renderer.render(this, N);
}
*/
public void Redraw()
{
Draw(_RC, _AC);
}
Assets.RenderClosure _RC;
public Actions.ActionContext _AC;
public float _Time = 0;
public void Draw(Assets.RenderClosure RC, Actions.ActionContext AC)
{
_RC = RC;
_AC = AC;
_Time += 0.1f;
//Time
if (AC == null) return;
AC.CurrentGlView = this;
if (hRC == IntPtr.Zero) return;
if (hDC == IntPtr.Zero) return;
AC.Time = _Time;
/*
IntPtr _hDC = Wgl.wglGetCurrentDC();
IntPtr _hGLRC = Wgl.wglGetCurrentContext();
if (Wgl.wglMakeCurrent(hDC, hRC))
{
*/
Gl.glClearColor(1, 1, 1, 1);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
Gl.glLoadIdentity();
Glu.gluLookAt(0, AC.Zoom * Math.Sin(AC.Angle2), -AC.Zoom * Math.Cos(AC.Angle2), 0, 0, 0, 0, 1, 0);
//Gl.glTranslated(0, AC.Zoom * Math.Sin(AC.Angle2), -AC.Zoom * Math.Cos(AC.Angle2));
Gl.glRotated(AC.Angle, 0, 1, 0);
//Gl.glRotated(-AC.Angle2 * 180 / 3.14 , 0, 0, 1);
Gl.glClearDepth(1.0);
Gl.glEnable(Gl.GL_DEPTH_TEST);
Gl.glDisable(Gl.GL_LIGHTING);
Gl.glPushMatrix();
if (_AC.GridMode == 0)
{
Gl.glTranslated(-_AC.GridH / 2.0, 0, -_AC.GridH / 2.0);
}
Gl.glLineWidth(4);
Gl.glBegin(Gl.GL_LINES);
for (int h = 0; h < _AC.GridV; h++)
{
Gl.glColor3f(0.5f, 0.5f, 0.5f);
Gl.glVertex3f(0, h, 0);
Gl.glVertex3f(0, h, _AC.GridH);
Gl.glVertex3f(0, h, _AC.GridH);
Gl.glVertex3f( _AC.GridH, h, _AC.GridH);
Gl.glVertex3f( _AC.GridH, h, _AC.GridH);
Gl.glVertex3f( _AC.GridH, h, 0);
Gl.glVertex3f( _AC.GridH, h, 0);
Gl.glVertex3f( 0, h, 0);
}
Gl.glEnd();
Gl.glLineWidth(1);
Gl.glBegin(Gl.GL_LINES);
for (int h = 0; h < _AC.GridV; h++)
{
Gl.glColor3f(0.75f, 0.75f, 0.75f);
for (int x = 0; x < _AC.GridH; x++)
{
Gl.glVertex3f( x, h, 0);
Gl.glVertex3f( x, h, _AC.GridH);
Gl.glVertex3f( 0, h, x);
Gl.glVertex3f( _AC.GridH, h, x );
}
}
Gl.glEnd();
Gl.glPopMatrix();
Gl.glBegin(Gl.GL_LINES);
Gl.glColor3f(1,0,0);
Gl.glVertex3f(0, 0, 0);
Gl.glVertex3f(1000, 0, 0);
Gl.glColor3f(0,1,0);
Gl.glVertex3f(0, 0, 0);
Gl.glVertex3f(0,1000, 0);
Gl.glColor3f(0,0,1);
Gl.glVertex3f(0, 0, 0);
Gl.glVertex3f(0,0,1000);
Gl.glEnd();
Gl.glEnable(Gl.GL_CULL_FACE);
Gl.glCullFace(Gl.GL_BACK);
Pantry.Rendering.Render.Do(RC, AC);
_Time = _AC.Time;
/*
Wgl.wglMakeCurrent( _hDC, _hGLRC );
}
*/
/*
Gl.glEnable(Gl.GL_LIGHTING);
Gl.glEnable(Gl.GL_LIGHT0);
float [] modelcolor = new float[4];
modelcolor[0] = 1.0f;
modelcolor[1] = 1.0f;
modelcolor[2] = 1.0f;
modelcolor[3] = 1.0f;
Gl.glLightModelfv(Gl.GL_LIGHT_MODEL_AMBIENT, modelcolor);
Gl.glLoadIdentity();
// apply the camera tracking
if(_MyCamera!=null) _MyCamera.Upload();
Gl.glGetIntegerv(Gl.GL_VIEWPORT, ViewportVector);
Gl.glGetDoublev(Gl.GL_PROJECTION_MATRIX, ProjectMatrix);
Gl.glGetDoublev(Gl.GL_MODELVIEW_MATRIX, ModelMatrix);
*/
// if(_MyInteract is Interaction.Selection)
{
// Interaction.Selection Sel = (Interaction.Selection) _MyInteract;
/*
if(Sel.SrcLast != null)
{
Gl.glVertex3d(Sel.SrcLast.x,Sel.SrcLast.y,Sel.SrcLast.z);
Gl.glVertex3d(Sel.DestLast.x,Sel.DestLast.y,Sel.DestLast.z);
}
*/
}
//Draw(_MyScene);
Gdi.SwapBuffers(hDC);
}
#region bool InitGL()
/// <summary>
/// All setup for OpenGL goes here.
/// </summary>
/// <returns>
/// <c>true</c> on successful initialization, otherwise <c>false</c>.
/// </returns>
private static bool InitGL()
{
Gl.glShadeModel(Gl.GL_SMOOTH); // Enable Smooth Shading
Gl.glClearColor(1, 1, 1, 0.5f); // Black Background
Gl.glClearDepth(1); // Depth Buffer Setup
Gl.glEnable(Gl.GL_DEPTH_TEST); // Enables Depth Testing
Gl.glDepthFunc(Gl.GL_LEQUAL); // The Type Of Depth Testing To Do
Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST); // Really Nice Perspective Calculations
return true;
}
#endregion bool InitGL()
#region ReSizeGLScene(int width, int height)
/// <summary>
/// Resizes and initializes the GL window.
/// </summary>
/// <param name="width">
/// The new window width.
/// </param>
/// <param name="height">
/// The new window height.
/// </param>
private static void ReSizeGLScene(int width, int height)
{
if (height == 0)
{ // Prevent A Divide By Zero...
height = 1; // By Making Height Equal To One
}
Gl.glViewport(0, 0, width, height); // Reset The Current Viewport
Gl.glMatrixMode(Gl.GL_PROJECTION); // Select The Projection Matrix
Gl.glLoadIdentity(); // Reset The Projection Matrix
Glu.gluPerspective(45, width / (double)height, 0.1, 32000); // Calculate The Aspect Ratio Of The Window
Gl.glMatrixMode(Gl.GL_MODELVIEW); // Select The Modelview Matrix
Gl.glLoadIdentity(); // Reset The Modelview Matrix
}
#endregion ReSizeGLScene(int width, int height)
#region Control_Resize(object sender, EventArgs e)
/// <summary>
/// Handles the form's resize event.
/// </summary>
/// <param name="sender">
/// The event sender.
/// </param>
/// <param name="e">
/// The event arguments.
/// </param>
private void Control_Resize(object sender, EventArgs e)
{
ReSizeGLScene(this.Width, this.Height); // Resize The OpenGL Window
}
#endregion Form_Resize(object sender, EventArgs e)
#region AutoCode - Forms
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
}
#endregion
bool LeftDown = false;
bool RightDown = false;
int MouseX;
int MouseY;
protected override void OnMouseDown(MouseEventArgs e)
{
MouseX = e.X;
MouseY = e.Y;
if (e.Button == MouseButtons.Left)
{
LeftDown = true;
}
if (e.Button == MouseButtons.Right)
{
RightDown = true;
}
// Focus();
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseDown(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseDown(e);
}
protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
{
int dX = e.X - MouseX;
MouseX = e.X;
int dY = e.Y - MouseY;
MouseY = e.Y;
if (_AC != null)
{
if (LeftDown)
{
_AC.Angle += dX / 4.0;
_AC.Angle2 += dY / 60.0;
_AC.Angle2 = Math.Max(-Math.PI / 2.00001, Math.Min(Math.PI / 2.0001, _AC.Angle2 ));
}
if (RightDown)
{
_AC.Zoom *= 1 + Math.Max(-.999, dY / 25.0);
_AC.Zoom = Math.Min(1000, Math.Max(0.001, _AC.Zoom));
}
if (LeftDown || RightDown)
{
Redraw();
}
}
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseMove(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseMove(e);
// UpdateLock();
// this.Draw();
}
protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
LeftDown = false;
}
if (e.Button == MouseButtons.Right)
{
RightDown = false;
}
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseUp(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseUp(e);
// UpdateLock();
}
protected override void OnMouseEnter(System.EventArgs e)
{
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseEnter(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseEnter(e);
}
protected override void OnMouseHover(System.EventArgs e)
{
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseHover(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseHover(e);
}
protected override void OnMouseLeave(System.EventArgs e)
{
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseLeave(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseLeave(e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
// bool TrumpCamera = false;
// if(_MyInteract!=null){ _MyInteract.MouseWheel(e,_MyInteractContext); TrumpCamera = _MyInteract.TrumpCamera(); }
// if(_MyCamera!=null && !TrumpCamera ) _MyCamera.MouseWheel(e);
}
#region Bitmap LoadBMP(string fileName)
/// <summary>
/// Loads a bitmap image.
/// </summary>
/// <param name="fileName">
/// The filename to load.
/// </param>
/// <returns>
/// The bitmap if it exists, otherwise <c>null</c>.
/// </returns>
private static Bitmap LoadBMP(string fileName)
{
if (fileName == null || fileName == string.Empty)
{ // Make Sure A Filename Was Given
return null; // If Not Return Null
}
if (File.Exists(fileName))
{
return new Bitmap(fileName);
}
return null;
}
#endregion Bitmap LoadBMP(string fileName)
#region LoadGLTex()
/// <summary>
/// Load bitmaps and convert to textures.
/// </summary>
/// <returns>
/// <c>true</c> on success, otherwise <c>false</c>.
/// </returns>
private static uint LoadGLTex(string BitmapFile)
{
Bitmap textureImage = LoadBMP(BitmapFile);
if (textureImage != null)
{
uint texture;
Gl.glGenTextures(1, out texture); // Create Three Textures
// textureImage.RotateFlip(RotateFlipType.RotateNoneFlipY); // Flip The Bitmap Along The Y-Axis
Rectangle rectangle = new Rectangle(0, 0, textureImage.Width, textureImage.Height);
BitmapData bitmapData = textureImage.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
/*
// Create Nearest Filtered Texture
Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture[0]);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_NEAREST);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_NEAREST);
Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGB8, textureImage[0].Width, textureImage[0].Height, 0, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0);
// Create Linear Filtered Texture
Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture[1]);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_RGB8, textureImage[0].Width, textureImage[0].Height, 0, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0);
*/
// Create MipMapped Texture
Gl.glBindTexture(Gl.GL_TEXTURE_2D, texture);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_NEAREST);
Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGB8, textureImage.Width, textureImage.Height, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0);
if (textureImage != null)
{ // If Texture Exists
textureImage.UnlockBits(bitmapData); // Unlock The Pixel Data From Memory
textureImage.Dispose(); // Dispose The Bitmap
}
return texture;
}
throw new Exception("Error on LoadGLTex");
}
#endregion LoadGLTex()
SortedList TextureDatabase = new SortedList();
public uint LoadTexture(string filename)
{
if (TextureDatabase.Contains(filename))
return (uint)TextureDatabase[filename];
if (filename.Equals(null) || filename.Equals("")) return 0;
try
{
uint result = LoadGLTex(filename);
TextureDatabase.Add(filename, result);
return result;
}
catch (Exception ez)
{
return 0;
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
using Windows.Web.Http.Headers;
namespace WebAuthentication
{
public sealed partial class Scenario2_Twitter : Page
{
MainPage rootPage = MainPage.Current;
public Scenario2_Twitter()
{
this.InitializeComponent();
}
private async Task<String> SendDataAsync(String Url)
{
HttpClient httpClient = new HttpClient();
HttpGetStringResult result = await httpClient.TryGetStringAsync(new Uri(Url));
if (result.Succeeded)
{
return result.Value;
}
else
{
rootPage.NotifyUser("Error getting data from server." + result.ExtendedError.Message, NotifyType.StatusMessage);
return null;
}
}
private void OutputToken(String TokenUri)
{
TwitterReturnedToken.Text = TokenUri;
}
private async void Launch_Click(object sender, RoutedEventArgs e)
{
if (TwitterClientID.Text == "")
{
rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
}
else if (TwitterCallbackUrl.Text == "")
{
rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
}
else if (TwitterClientSecret.Text == "")
{
rootPage.NotifyUser("Please enter an Client Secret.", NotifyType.StatusMessage);
}
string oauth_token = await GetTwitterRequestTokenAsync(TwitterCallbackUrl.Text, TwitterClientID.Text);
if (String.IsNullOrEmpty(oauth_token))
{
rootPage.NotifyUser("Unable to obtain oauth token.", NotifyType.StatusMessage);
return;
}
string TwitterUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
System.Uri StartUri = new Uri(TwitterUrl);
System.Uri EndUri = new Uri(TwitterCallbackUrl.Text);
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
OutputToken(WebAuthenticationResult.ResponseData.ToString());
await GetTwitterUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
}
else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
}
else
{
OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
}
}
private async Task GetTwitterUserNameAsync(string webAuthResultResponseData)
{
// Acquiring a access_token first
string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token"));
string request_token = null;
string oauth_verifier = null;
String[] keyValPairs = responseData.Split('&');
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "oauth_token":
request_token = splits[1];
break;
case "oauth_verifier":
oauth_verifier = splits[1];
break;
}
}
String TwitterUrl = "https://api.twitter.com/oauth/access_token";
string timeStamp = GetTimeStamp();
string nonce = GetNonce();
String SigBaseStringParams = "oauth_consumer_key=" + TwitterClientID.Text;
SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
SigBaseStringParams += "&" + "oauth_token=" + request_token;
SigBaseStringParams += "&" + "oauth_version=1.0";
String SigBaseString = "POST&";
SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);
String Signature = GetSignature(SigBaseString, TwitterClientSecret.Text);
HttpStringContent httpContent = new HttpStringContent("oauth_verifier=" + oauth_verifier, Windows.Storage.Streams.UnicodeEncoding.Utf8);
httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
string authorizationHeaderParams = "oauth_consumer_key=\"" + TwitterClientID.Text + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(request_token) + "\", oauth_version=\"1.0\"";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams);
HttpRequestResult result = await httpClient.TryPostAsync(new Uri(TwitterUrl), httpContent);
if (result.Succeeded)
{
string response = await result.ResponseMessage.Content.ReadAsStringAsync();
String[] Tokens = response.Split('&');
string oauth_token_secret = null;
string access_token = null;
string screen_name = null;
for (int i = 0; i < Tokens.Length; i++)
{
String[] splits = Tokens[i].Split('=');
switch (splits[0])
{
case "screen_name":
screen_name = splits[1];
break;
case "oauth_token":
access_token = splits[1];
break;
case "oauth_token_secret":
oauth_token_secret = splits[1];
break;
}
}
if (access_token != null)
{
// Store access_token for futher use. See Scenario 5 (Account Management).
}
if (oauth_token_secret != null)
{
// Store oauth_token_secret for further use. See Scenario 5 (Account Management).
}
if (screen_name != null)
{
rootPage.NotifyUser(screen_name + " is connected!", NotifyType.StatusMessage);
}
}
}
private async Task<string> GetTwitterRequestTokenAsync(string twitterCallbackUrl, string consumerKey)
{
// Acquiring a request token
string TwitterUrl = "https://api.twitter.com/oauth/request_token";
string nonce = GetNonce();
string timeStamp = GetTimeStamp();
string SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(twitterCallbackUrl);
SigBaseStringParams += "&" + "oauth_consumer_key=" + consumerKey;
SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
SigBaseStringParams += "&" + "oauth_version=1.0";
string SigBaseString = "GET&";
SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);
string Signature = GetSignature(SigBaseString, TwitterClientSecret.Text);
TwitterUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature);
HttpClient httpClient = new HttpClient();
string request_token = null;
HttpGetStringResult result = await httpClient.TryGetStringAsync(new Uri(TwitterUrl));
if (result.Succeeded)
{
string oauth_token_secret = null;
string[] keyValPairs = result.Value.Split('&');
for (int i = 0; i < keyValPairs.Length; i++)
{
string[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "oauth_token":
request_token = splits[1];
break;
case "oauth_token_secret":
oauth_token_secret = splits[1];
break;
}
}
}
return request_token;
}
string GetNonce()
{
Random rand = new Random();
int nonce = rand.Next(1000000000);
return nonce.ToString();
}
string GetTimeStamp()
{
TimeSpan SinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
return Math.Round(SinceEpoch.TotalSeconds).ToString();
}
string GetSignature(string sigBaseString, string consumerSecretKey)
{
IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(consumerSecretKey + "&", BinaryStringEncoding.Utf8);
MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial);
IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(sigBaseString, BinaryStringEncoding.Utf8);
IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
string Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);
return Signature;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.XPath;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.Xslt
{
using TypeFactory = XmlQueryTypeFactory;
#if DEBUG && FEATURE_COMPILED_XSL
using XmlILTrace = System.Xml.Xsl.IlGen.XmlILTrace;
#endif
internal enum XslVersion
{
Version10 = 0,
ForwardsCompatible = 1,
Current = Version10,
}
// RootLevel is underdeveloped consept currently. I plane to move here more collections from Compiler.
// Compiler is like a stylesheet in some sense. it has a lot of properties of stylesheet. Instead of
// inhereting from Styleseet (or StylesheetLevel) I desided to agregate special subclass of StylesheetLevel.
// One more reason to for this design is to normolize apply-templates and apply-imports to one concept:
// apply-templates is apply-imports(compiler.Root).
// For now I don't create new files for these new classes to simplify integrations WebData <-> WebData_xsl
internal class RootLevel : StylesheetLevel
{
public RootLevel(Stylesheet principal)
{
base.Imports = new Stylesheet[] { principal };
}
}
internal class Compiler
{
public XsltSettings Settings;
public bool IsDebug;
public string ScriptAssemblyPath;
public int Version; // 0 - Auto; 1 - XSLT 1.0; 2 - XSLT 2.0
public string inputTypeAnnotations; // null - "unspecified"; "preserve"; "strip"
public CompilerErrorCollection CompilerErrorColl; // Results of the compilation
public int CurrentPrecedence = 0; // Decreases by 1 with each import
public XslNode StartApplyTemplates;
public RootLevel Root;
public Scripts Scripts;
public Output Output = new Output();
public List<VarPar> ExternalPars = new List<VarPar>();
public List<VarPar> GlobalVars = new List<VarPar>();
public List<WhitespaceRule> WhitespaceRules = new List<WhitespaceRule>();
public DecimalFormats DecimalFormats = new DecimalFormats();
public Keys Keys = new Keys();
public List<ProtoTemplate> AllTemplates = new List<ProtoTemplate>();
public Dictionary<QilName, VarPar> AllGlobalVarPars = new Dictionary<QilName, VarPar>();
public Dictionary<QilName, Template> NamedTemplates = new Dictionary<QilName, Template>();
public Dictionary<QilName, AttributeSet> AttributeSets = new Dictionary<QilName, AttributeSet>();
public Dictionary<string, NsAlias> NsAliases = new Dictionary<string, NsAlias>();
private Dictionary<string, int> _moduleOrder = new Dictionary<string, int>();
public Compiler(XsltSettings settings, bool debug, string scriptAssemblyPath)
{
Debug.Assert(CompilerErrorColl == null, "Compiler cannot be reused");
Settings = settings;
IsDebug = settings.IncludeDebugInformation | debug;
ScriptAssemblyPath = scriptAssemblyPath;
CompilerErrorColl = new CompilerErrorCollection();
Scripts = new Scripts(this);
}
public CompilerErrorCollection Compile(object stylesheet, XmlResolver xmlResolver, out QilExpression qil)
{
Debug.Assert(stylesheet != null);
Debug.Assert(Root == null, "Compiler cannot be reused");
new XsltLoader().Load(this, stylesheet, xmlResolver);
qil = QilGenerator.CompileStylesheet(this);
SortErrors();
return CompilerErrorColl;
}
public Stylesheet CreateStylesheet()
{
Stylesheet sheet = new Stylesheet(this, CurrentPrecedence);
if (CurrentPrecedence-- == 0)
{
Root = new RootLevel(sheet);
}
return sheet;
}
public void AddModule(string baseUri)
{
if (!_moduleOrder.ContainsKey(baseUri))
{
_moduleOrder[baseUri] = _moduleOrder.Count;
}
}
public void ApplyNsAliases(ref string prefix, ref string nsUri)
{
NsAlias alias;
if (NsAliases.TryGetValue(nsUri, out alias))
{
nsUri = alias.ResultNsUri;
prefix = alias.ResultPrefix;
}
}
// Returns true in case of redefinition
public bool SetNsAlias(string ssheetNsUri, string resultNsUri, string resultPrefix, int importPrecedence)
{
NsAlias oldNsAlias;
if (NsAliases.TryGetValue(ssheetNsUri, out oldNsAlias))
{
// Namespace alias for this stylesheet namespace URI has already been defined
Debug.Assert(importPrecedence <= oldNsAlias.ImportPrecedence, "Stylesheets must be processed in the order of decreasing import precedence");
if (importPrecedence < oldNsAlias.ImportPrecedence || resultNsUri == oldNsAlias.ResultNsUri)
{
// Either the identical definition or lower precedence - ignore it
return false;
}
// Recover by choosing the declaration that occurs later in the stylesheet
}
NsAliases[ssheetNsUri] = new NsAlias(resultNsUri, resultPrefix, importPrecedence);
return oldNsAlias != null;
}
private void MergeWhitespaceRules(Stylesheet sheet)
{
for (int idx = 0; idx <= 2; idx++)
{
sheet.WhitespaceRules[idx].Reverse();
this.WhitespaceRules.AddRange(sheet.WhitespaceRules[idx]);
}
sheet.WhitespaceRules = null;
}
private void MergeAttributeSets(Stylesheet sheet)
{
foreach (QilName attSetName in sheet.AttributeSets.Keys)
{
AttributeSet attSet;
if (!this.AttributeSets.TryGetValue(attSetName, out attSet))
{
this.AttributeSets[attSetName] = sheet.AttributeSets[attSetName];
}
else
{
// Lower import precedence - insert before all previous definitions
attSet.MergeContent(sheet.AttributeSets[attSetName]);
}
}
sheet.AttributeSets = null;
}
private void MergeGlobalVarPars(Stylesheet sheet)
{
foreach (VarPar var in sheet.GlobalVarPars)
{
Debug.Assert(var.NodeType == XslNodeType.Variable || var.NodeType == XslNodeType.Param);
if (!AllGlobalVarPars.ContainsKey(var.Name))
{
if (var.NodeType == XslNodeType.Variable)
{
GlobalVars.Add(var);
}
else
{
ExternalPars.Add(var);
}
AllGlobalVarPars[var.Name] = var;
}
}
sheet.GlobalVarPars = null;
}
public void MergeWithStylesheet(Stylesheet sheet)
{
MergeWhitespaceRules(sheet);
MergeAttributeSets(sheet);
MergeGlobalVarPars(sheet);
}
public static string ConstructQName(string prefix, string localName)
{
if (prefix.Length == 0)
{
return localName;
}
else
{
return prefix + ':' + localName;
}
}
public bool ParseQName(string qname, out string prefix, out string localName, IErrorHelper errorHelper)
{
Debug.Assert(qname != null);
try
{
ValidateNames.ParseQNameThrow(qname, out prefix, out localName);
return true;
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_042]*/e.Message, null);
prefix = PhantomNCName;
localName = PhantomNCName;
return false;
}
}
public bool ParseNameTest(string nameTest, out string prefix, out string localName, IErrorHelper errorHelper)
{
Debug.Assert(nameTest != null);
try
{
ValidateNames.ParseNameTestThrow(nameTest, out prefix, out localName);
return true;
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_043]*/e.Message, null);
prefix = PhantomNCName;
localName = PhantomNCName;
return false;
}
}
public void ValidatePiName(string name, IErrorHelper errorHelper)
{
Debug.Assert(name != null);
try
{
ValidateNames.ValidateNameThrow(
/*prefix:*/string.Empty, /*localName:*/name, /*ns:*/string.Empty,
XPathNodeType.ProcessingInstruction, ValidateNames.Flags.AllExceptPrefixMapping
);
}
catch (XmlException e)
{
errorHelper.ReportError(/*[XT_044]*/e.Message, null);
}
}
public readonly string PhantomNCName = "error";
private int _phantomNsCounter = 0;
public string CreatePhantomNamespace()
{
// Prepend invalid XmlChar to ensure this name would not clash with any namespace name in the stylesheet
return "\0namespace" + _phantomNsCounter++;
}
public bool IsPhantomNamespace(string namespaceName)
{
return namespaceName.Length > 0 && namespaceName[0] == '\0';
}
public bool IsPhantomName(QilName qname)
{
string nsUri = qname.NamespaceUri;
return nsUri.Length > 0 && nsUri[0] == '\0';
}
// -------------------------------- Error Handling --------------------------------
private int ErrorCount
{
get
{
return CompilerErrorColl.Count;
}
set
{
Debug.Assert(value <= ErrorCount);
for (int idx = ErrorCount - 1; idx >= value; idx--)
{
CompilerErrorColl.RemoveAt(idx);
}
}
}
private int _savedErrorCount = -1;
public void EnterForwardsCompatible()
{
Debug.Assert(_savedErrorCount == -1, "Nested EnterForwardsCompatible calls");
_savedErrorCount = ErrorCount;
}
// Returns true if no errors were suppressed
public bool ExitForwardsCompatible(bool fwdCompat)
{
Debug.Assert(_savedErrorCount != -1, "ExitForwardsCompatible without EnterForwardsCompatible");
if (fwdCompat && ErrorCount > _savedErrorCount)
{
ErrorCount = _savedErrorCount;
Debug.Assert((_savedErrorCount = -1) < 0);
return false;
}
Debug.Assert((_savedErrorCount = -1) < 0);
return true;
}
public CompilerError CreateError(ISourceLineInfo lineInfo, string res, params string[] args)
{
AddModule(lineInfo.Uri);
return new CompilerError(
lineInfo.Uri, lineInfo.Start.Line, lineInfo.Start.Pos, /*errorNumber:*/string.Empty,
/*errorText:*/XslTransformException.CreateMessage(res, args)
);
}
public void ReportError(ISourceLineInfo lineInfo, string res, params string[] args)
{
CompilerError error = CreateError(lineInfo, res, args);
CompilerErrorColl.Add(error);
}
public void ReportWarning(ISourceLineInfo lineInfo, string res, params string[] args)
{
int warningLevel = 1;
if (0 <= Settings.WarningLevel && Settings.WarningLevel < warningLevel)
{
// Ignore warning
return;
}
CompilerError error = CreateError(lineInfo, res, args);
if (Settings.TreatWarningsAsErrors)
{
error.ErrorText = XslTransformException.CreateMessage(SR.Xslt_WarningAsError, error.ErrorText);
CompilerErrorColl.Add(error);
}
else
{
error.IsWarning = true;
CompilerErrorColl.Add(error);
}
}
private void SortErrors()
{
CompilerErrorCollection errorColl = this.CompilerErrorColl;
if (errorColl.Count > 1)
{
CompilerError[] errors = new CompilerError[errorColl.Count];
errorColl.CopyTo(errors, 0);
Array.Sort<CompilerError>(errors, new CompilerErrorComparer(_moduleOrder));
errorColl.Clear();
errorColl.AddRange(errors);
}
}
private class CompilerErrorComparer : IComparer<CompilerError>
{
private Dictionary<string, int> _moduleOrder;
public CompilerErrorComparer(Dictionary<string, int> moduleOrder)
{
_moduleOrder = moduleOrder;
}
public int Compare(CompilerError x, CompilerError y)
{
if ((object)x == (object)y)
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
int result = _moduleOrder[x.FileName].CompareTo(_moduleOrder[y.FileName]);
if (result != 0)
return result;
result = x.Line.CompareTo(y.Line);
if (result != 0)
return result;
result = x.Column.CompareTo(y.Column);
if (result != 0)
return result;
result = x.IsWarning.CompareTo(y.IsWarning);
if (result != 0)
return result;
result = string.CompareOrdinal(x.ErrorNumber, y.ErrorNumber);
if (result != 0)
return result;
return string.CompareOrdinal(x.ErrorText, y.ErrorText);
}
}
}
internal class Output
{
public XmlWriterSettings Settings;
public string Version;
public string Encoding;
public XmlQualifiedName Method;
// All the xsl:output elements occurring in a stylesheet are merged into a single effective xsl:output element.
// We store the import precedence of each attribute value to catch redefinitions with the same import precedence.
public const int NeverDeclaredPrec = int.MinValue;
public int MethodPrec = NeverDeclaredPrec;
public int VersionPrec = NeverDeclaredPrec;
public int EncodingPrec = NeverDeclaredPrec;
public int OmitXmlDeclarationPrec = NeverDeclaredPrec;
public int StandalonePrec = NeverDeclaredPrec;
public int DocTypePublicPrec = NeverDeclaredPrec;
public int DocTypeSystemPrec = NeverDeclaredPrec;
public int IndentPrec = NeverDeclaredPrec;
public int MediaTypePrec = NeverDeclaredPrec;
public Output()
{
Settings = new XmlWriterSettings();
Settings.OutputMethod = XmlOutputMethod.AutoDetect;
Settings.AutoXmlDeclaration = true;
Settings.ConformanceLevel = ConformanceLevel.Auto;
Settings.MergeCDataSections = true;
}
}
internal class DecimalFormats : KeyedCollection<XmlQualifiedName, DecimalFormatDecl>
{
protected override XmlQualifiedName GetKeyForItem(DecimalFormatDecl format)
{
return format.Name;
}
}
internal class DecimalFormatDecl
{
public readonly XmlQualifiedName Name;
public readonly string InfinitySymbol;
public readonly string NanSymbol;
public readonly char[] Characters;
public static DecimalFormatDecl Default = new DecimalFormatDecl(new XmlQualifiedName(), "Infinity", "NaN", ".,%\u20300#;-");
public DecimalFormatDecl(XmlQualifiedName name, string infinitySymbol, string nanSymbol, string characters)
{
Debug.Assert(characters.Length == 8);
this.Name = name;
this.InfinitySymbol = infinitySymbol;
this.NanSymbol = nanSymbol;
this.Characters = characters.ToCharArray();
}
}
internal class NsAlias
{
public readonly string ResultNsUri;
public readonly string ResultPrefix;
public readonly int ImportPrecedence;
public NsAlias(string resultNsUri, string resultPrefix, int importPrecedence)
{
this.ResultNsUri = resultNsUri;
this.ResultPrefix = resultPrefix;
this.ImportPrecedence = importPrecedence;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedGlobalNetworkEndpointGroupsClientSnippets
{
/// <summary>Snippet for AttachNetworkEndpoints</summary>
public void AttachNetworkEndpointsRequestObject()
{
// Snippet: AttachNetworkEndpoints(AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest request = new AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest
{
GlobalNetworkEndpointGroupsAttachEndpointsRequestResource = new GlobalNetworkEndpointGroupsAttachEndpointsRequest(),
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.AttachNetworkEndpoints(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceAttachNetworkEndpoints(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AttachNetworkEndpointsAsync</summary>
public async Task AttachNetworkEndpointsRequestObjectAsync()
{
// Snippet: AttachNetworkEndpointsAsync(AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CallSettings)
// Additional: AttachNetworkEndpointsAsync(AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest request = new AttachNetworkEndpointsGlobalNetworkEndpointGroupRequest
{
GlobalNetworkEndpointGroupsAttachEndpointsRequestResource = new GlobalNetworkEndpointGroupsAttachEndpointsRequest(),
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.AttachNetworkEndpointsAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceAttachNetworkEndpointsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AttachNetworkEndpoints</summary>
public void AttachNetworkEndpoints()
{
// Snippet: AttachNetworkEndpoints(string, string, GlobalNetworkEndpointGroupsAttachEndpointsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
GlobalNetworkEndpointGroupsAttachEndpointsRequest globalNetworkEndpointGroupsAttachEndpointsRequestResource = new GlobalNetworkEndpointGroupsAttachEndpointsRequest();
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.AttachNetworkEndpoints(project, networkEndpointGroup, globalNetworkEndpointGroupsAttachEndpointsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceAttachNetworkEndpoints(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for AttachNetworkEndpointsAsync</summary>
public async Task AttachNetworkEndpointsAsync()
{
// Snippet: AttachNetworkEndpointsAsync(string, string, GlobalNetworkEndpointGroupsAttachEndpointsRequest, CallSettings)
// Additional: AttachNetworkEndpointsAsync(string, string, GlobalNetworkEndpointGroupsAttachEndpointsRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
GlobalNetworkEndpointGroupsAttachEndpointsRequest globalNetworkEndpointGroupsAttachEndpointsRequestResource = new GlobalNetworkEndpointGroupsAttachEndpointsRequest();
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.AttachNetworkEndpointsAsync(project, networkEndpointGroup, globalNetworkEndpointGroupsAttachEndpointsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceAttachNetworkEndpointsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteGlobalNetworkEndpointGroupRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
DeleteGlobalNetworkEndpointGroupRequest request = new DeleteGlobalNetworkEndpointGroupRequest
{
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteGlobalNetworkEndpointGroupRequest, CallSettings)
// Additional: DeleteAsync(DeleteGlobalNetworkEndpointGroupRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
DeleteGlobalNetworkEndpointGroupRequest request = new DeleteGlobalNetworkEndpointGroupRequest
{
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.Delete(project, networkEndpointGroup);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.DeleteAsync(project, networkEndpointGroup);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DetachNetworkEndpoints</summary>
public void DetachNetworkEndpointsRequestObject()
{
// Snippet: DetachNetworkEndpoints(DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest request = new DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest
{
GlobalNetworkEndpointGroupsDetachEndpointsRequestResource = new GlobalNetworkEndpointGroupsDetachEndpointsRequest(),
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.DetachNetworkEndpoints(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceDetachNetworkEndpoints(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DetachNetworkEndpointsAsync</summary>
public async Task DetachNetworkEndpointsRequestObjectAsync()
{
// Snippet: DetachNetworkEndpointsAsync(DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CallSettings)
// Additional: DetachNetworkEndpointsAsync(DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest request = new DetachNetworkEndpointsGlobalNetworkEndpointGroupRequest
{
GlobalNetworkEndpointGroupsDetachEndpointsRequestResource = new GlobalNetworkEndpointGroupsDetachEndpointsRequest(),
RequestId = "",
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.DetachNetworkEndpointsAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceDetachNetworkEndpointsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DetachNetworkEndpoints</summary>
public void DetachNetworkEndpoints()
{
// Snippet: DetachNetworkEndpoints(string, string, GlobalNetworkEndpointGroupsDetachEndpointsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
GlobalNetworkEndpointGroupsDetachEndpointsRequest globalNetworkEndpointGroupsDetachEndpointsRequestResource = new GlobalNetworkEndpointGroupsDetachEndpointsRequest();
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.DetachNetworkEndpoints(project, networkEndpointGroup, globalNetworkEndpointGroupsDetachEndpointsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceDetachNetworkEndpoints(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DetachNetworkEndpointsAsync</summary>
public async Task DetachNetworkEndpointsAsync()
{
// Snippet: DetachNetworkEndpointsAsync(string, string, GlobalNetworkEndpointGroupsDetachEndpointsRequest, CallSettings)
// Additional: DetachNetworkEndpointsAsync(string, string, GlobalNetworkEndpointGroupsDetachEndpointsRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
GlobalNetworkEndpointGroupsDetachEndpointsRequest globalNetworkEndpointGroupsDetachEndpointsRequestResource = new GlobalNetworkEndpointGroupsDetachEndpointsRequest();
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.DetachNetworkEndpointsAsync(project, networkEndpointGroup, globalNetworkEndpointGroupsDetachEndpointsRequestResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceDetachNetworkEndpointsAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetGlobalNetworkEndpointGroupRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
NetworkEndpointGroup response = globalNetworkEndpointGroupsClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetGlobalNetworkEndpointGroupRequest, CallSettings)
// Additional: GetAsync(GetGlobalNetworkEndpointGroupRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
GetGlobalNetworkEndpointGroupRequest request = new GetGlobalNetworkEndpointGroupRequest
{
Project = "",
NetworkEndpointGroup = "",
};
// Make the request
NetworkEndpointGroup response = await globalNetworkEndpointGroupsClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
NetworkEndpointGroup response = globalNetworkEndpointGroupsClient.Get(project, networkEndpointGroup);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
NetworkEndpointGroup response = await globalNetworkEndpointGroupsClient.GetAsync(project, networkEndpointGroup);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertGlobalNetworkEndpointGroupRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
InsertGlobalNetworkEndpointGroupRequest request = new InsertGlobalNetworkEndpointGroupRequest
{
RequestId = "",
Project = "",
NetworkEndpointGroupResource = new NetworkEndpointGroup(),
};
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertGlobalNetworkEndpointGroupRequest, CallSettings)
// Additional: InsertAsync(InsertGlobalNetworkEndpointGroupRequest, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
InsertGlobalNetworkEndpointGroupRequest request = new InsertGlobalNetworkEndpointGroupRequest
{
RequestId = "",
Project = "",
NetworkEndpointGroupResource = new NetworkEndpointGroup(),
};
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, NetworkEndpointGroup, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup();
// Make the request
lro::Operation<Operation, Operation> response = globalNetworkEndpointGroupsClient.Insert(project, networkEndpointGroupResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = globalNetworkEndpointGroupsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, NetworkEndpointGroup, CallSettings)
// Additional: InsertAsync(string, NetworkEndpointGroup, CancellationToken)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
NetworkEndpointGroup networkEndpointGroupResource = new NetworkEndpointGroup();
// Make the request
lro::Operation<Operation, Operation> response = await globalNetworkEndpointGroupsClient.InsertAsync(project, networkEndpointGroupResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation 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
lro::Operation<Operation, Operation> retrievedResponse = await globalNetworkEndpointGroupsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListGlobalNetworkEndpointGroupsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
ListGlobalNetworkEndpointGroupsRequest request = new ListGlobalNetworkEndpointGroupsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = globalNetworkEndpointGroupsClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (NetworkEndpointGroup 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 (NetworkEndpointGroupList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointGroup 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<NetworkEndpointGroup> 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 (NetworkEndpointGroup 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 ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListGlobalNetworkEndpointGroupsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
ListGlobalNetworkEndpointGroupsRequest request = new ListGlobalNetworkEndpointGroupsRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = globalNetworkEndpointGroupsClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((NetworkEndpointGroup 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((NetworkEndpointGroupList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointGroup 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<NetworkEndpointGroup> 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 (NetworkEndpointGroup 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 List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = globalNetworkEndpointGroupsClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (NetworkEndpointGroup 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 (NetworkEndpointGroupList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointGroup 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<NetworkEndpointGroup> 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 (NetworkEndpointGroup 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 ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<NetworkEndpointGroupList, NetworkEndpointGroup> response = globalNetworkEndpointGroupsClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((NetworkEndpointGroup 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((NetworkEndpointGroupList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointGroup 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<NetworkEndpointGroup> 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 (NetworkEndpointGroup 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 ListNetworkEndpoints</summary>
public void ListNetworkEndpointsRequestObject()
{
// Snippet: ListNetworkEndpoints(ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest request = new ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest
{
OrderBy = "",
Project = "",
Filter = "",
NetworkEndpointGroup = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<NetworkEndpointGroupsListNetworkEndpoints, NetworkEndpointWithHealthStatus> response = globalNetworkEndpointGroupsClient.ListNetworkEndpoints(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (NetworkEndpointWithHealthStatus 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 (NetworkEndpointGroupsListNetworkEndpoints page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointWithHealthStatus 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<NetworkEndpointWithHealthStatus> 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 (NetworkEndpointWithHealthStatus 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 ListNetworkEndpointsAsync</summary>
public async Task ListNetworkEndpointsRequestObjectAsync()
{
// Snippet: ListNetworkEndpointsAsync(ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest request = new ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest
{
OrderBy = "",
Project = "",
Filter = "",
NetworkEndpointGroup = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<NetworkEndpointGroupsListNetworkEndpoints, NetworkEndpointWithHealthStatus> response = globalNetworkEndpointGroupsClient.ListNetworkEndpointsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((NetworkEndpointWithHealthStatus 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((NetworkEndpointGroupsListNetworkEndpoints page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointWithHealthStatus 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<NetworkEndpointWithHealthStatus> 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 (NetworkEndpointWithHealthStatus 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 ListNetworkEndpoints</summary>
public void ListNetworkEndpoints()
{
// Snippet: ListNetworkEndpoints(string, string, string, int?, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = GlobalNetworkEndpointGroupsClient.Create();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
PagedEnumerable<NetworkEndpointGroupsListNetworkEndpoints, NetworkEndpointWithHealthStatus> response = globalNetworkEndpointGroupsClient.ListNetworkEndpoints(project, networkEndpointGroup);
// Iterate over all response items, lazily performing RPCs as required
foreach (NetworkEndpointWithHealthStatus 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 (NetworkEndpointGroupsListNetworkEndpoints page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointWithHealthStatus 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<NetworkEndpointWithHealthStatus> 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 (NetworkEndpointWithHealthStatus 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 ListNetworkEndpointsAsync</summary>
public async Task ListNetworkEndpointsAsync()
{
// Snippet: ListNetworkEndpointsAsync(string, string, string, int?, CallSettings)
// Create client
GlobalNetworkEndpointGroupsClient globalNetworkEndpointGroupsClient = await GlobalNetworkEndpointGroupsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string networkEndpointGroup = "";
// Make the request
PagedAsyncEnumerable<NetworkEndpointGroupsListNetworkEndpoints, NetworkEndpointWithHealthStatus> response = globalNetworkEndpointGroupsClient.ListNetworkEndpointsAsync(project, networkEndpointGroup);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((NetworkEndpointWithHealthStatus 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((NetworkEndpointGroupsListNetworkEndpoints page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (NetworkEndpointWithHealthStatus 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<NetworkEndpointWithHealthStatus> 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 (NetworkEndpointWithHealthStatus 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
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics.Contracts;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Runtime;
using System.Security.Authentication;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal class WindowsStreamSecurityUpgradeProvider : StreamSecurityUpgradeProvider
{
private bool _extractGroupsForWindowsAccounts;
private EndpointIdentity _identity;
private IdentityVerifier _identityVerifier;
private ProtectionLevel _protectionLevel;
private SecurityTokenManager _securityTokenManager;
private NetworkCredential _serverCredential;
private string _scheme;
private bool _isClient;
private Uri _listenUri;
public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
BindingContext context, bool isClient)
: base(context.Binding)
{
Contract.Assert(isClient, ".NET Core and .NET Native does not support server side");
_extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
_protectionLevel = bindingElement.ProtectionLevel;
_scheme = context.Binding.Scheme;
_isClient = isClient;
_listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
SecurityCredentialsManager credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>();
if (credentialProvider == null)
{
credentialProvider = ClientCredentials.CreateDefaultCredentials();
}
_securityTokenManager = credentialProvider.CreateSecurityTokenManager();
}
public string Scheme
{
get { return _scheme; }
}
internal bool ExtractGroupsForWindowsAccounts
{
get
{
return _extractGroupsForWindowsAccounts;
}
}
public override EndpointIdentity Identity
{
get
{
// If the server credential is null, then we have not been opened yet and have no identity to expose.
if (_serverCredential != null)
{
if (_identity == null)
{
lock (ThisLock)
{
if (_identity == null)
{
_identity = SecurityUtils.CreateWindowsIdentity(_serverCredential);
}
}
}
}
return _identity;
}
}
internal IdentityVerifier IdentityVerifier
{
get
{
return _identityVerifier;
}
}
public ProtectionLevel ProtectionLevel
{
get
{
return _protectionLevel;
}
}
private NetworkCredential ServerCredential
{
get
{
return _serverCredential;
}
}
public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via)
{
ThrowIfDisposedOrNotOpen();
return new WindowsStreamSecurityUpgradeInitiator(this, remoteAddress, via);
}
protected override void OnAbort()
{
}
protected override void OnClose(TimeSpan timeout)
{
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return TaskHelpers.CompletedTask();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnCloseAsync(timeout).ToApm(callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (!_isClient)
{
SecurityTokenRequirement sspiTokenRequirement = TransportSecurityHelpers.CreateSspiTokenRequirement(Scheme, _listenUri);
_serverCredential =
TransportSecurityHelpers.GetSspiCredential(_securityTokenManager, sspiTokenRequirement, timeout,
out _extractGroupsForWindowsAccounts);
}
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpened()
{
base.OnOpened();
if (_identityVerifier == null)
{
_identityVerifier = IdentityVerifier.CreateDefault();
}
if (_serverCredential == null)
{
_serverCredential = CredentialCache.DefaultNetworkCredentials;
}
}
private class WindowsStreamSecurityUpgradeInitiator : StreamSecurityUpgradeInitiatorBase
{
private WindowsStreamSecurityUpgradeProvider _parent;
private IdentityVerifier _identityVerifier;
private NetworkCredential _credential;
private TokenImpersonationLevel _impersonationLevel;
private SspiSecurityTokenProvider _clientTokenProvider;
private bool _allowNtlm;
public WindowsStreamSecurityUpgradeInitiator(
WindowsStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via)
: base(FramingUpgradeString.Negotiate, remoteAddress, via)
{
_parent = parent;
_clientTokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(
parent._securityTokenManager, remoteAddress, via, parent.Scheme, out _identityVerifier);
}
internal override async Task OpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.Open(timeoutHelper.RemainingTime());
OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>();
SecurityUtils.OpenTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime());
_credential = await TransportSecurityHelpers.GetSspiCredentialAsync(
_clientTokenProvider,
impersonationLevelWrapper,
allowNtlmWrapper,
timeoutHelper.GetCancellationToken());
_impersonationLevel = impersonationLevelWrapper.Value;
_allowNtlm = allowNtlmWrapper;
return;
}
internal override void Open(TimeSpan timeout)
{
OpenAsync(timeout).GetAwaiter();
}
internal override void Close(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.Close(timeoutHelper.RemainingTime());
SecurityUtils.CloseTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime());
}
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
private static SecurityMessageProperty CreateServerSecurity(NegotiateStream negotiateStream)
{
GenericIdentity remoteIdentity = (GenericIdentity)negotiateStream.RemoteIdentity;
string principalName = remoteIdentity.Name;
if ((principalName != null) && (principalName.Length > 0))
{
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(principalName);
SecurityMessageProperty result = new SecurityMessageProperty();
result.TransportToken = new SecurityTokenSpecification(null, authorizationPolicies);
result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies);
return result;
}
else
{
return null;
}
}
#endif // SUPPORTS_WINDOWSIDENTITY
protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity)
{
OutWrapper<SecurityMessageProperty> remoteSecurityOut = new OutWrapper<SecurityMessageProperty>();
var retVal = OnInitiateUpgradeAsync(stream, remoteSecurityOut).GetAwaiter().GetResult();
remoteSecurity = remoteSecurityOut.Value;
return retVal;
}
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity)
{
NegotiateStream negotiateStream;
string targetName;
EndpointIdentity identity;
if (WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgradeIsEnabled())
{
WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgrade();
}
// prepare
InitiateUpgradePrepare(stream, out negotiateStream, out targetName, out identity);
// authenticate
try
{
await negotiateStream.AuthenticateAsClientAsync(_credential, targetName, _parent.ProtectionLevel, _impersonationLevel);
}
catch (AuthenticationException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message,
exception));
}
catch (IOException ioException)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(
SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException));
}
remoteSecurity.Value = CreateServerSecurity(negotiateStream);
ValidateMutualAuth(identity, negotiateStream, remoteSecurity.Value, _allowNtlm);
return negotiateStream;
}
#else
protected override Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity)
{
throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported);
}
#endif // SUPPORTS_WINDOWSIDENTITY
#if SUPPORTS_WINDOWSIDENTITY // NegotiateStream
private void InitiateUpgradePrepare(
Stream stream,
out NegotiateStream negotiateStream,
out string targetName,
out EndpointIdentity identity)
{
negotiateStream = new NegotiateStream(stream);
targetName = string.Empty;
identity = null;
if (_parent.IdentityVerifier.TryGetIdentity(RemoteAddress, Via, out identity))
{
targetName = SecurityUtils.GetSpnFromIdentity(identity, RemoteAddress);
}
else
{
targetName = SecurityUtils.GetSpnFromTarget(RemoteAddress);
}
}
private void ValidateMutualAuth(EndpointIdentity expectedIdentity, NegotiateStream negotiateStream,
SecurityMessageProperty remoteSecurity, bool allowNtlm)
{
if (negotiateStream.IsMutuallyAuthenticated)
{
if (expectedIdentity != null)
{
if (!_parent.IdentityVerifier.CheckAccess(expectedIdentity,
remoteSecurity.ServiceSecurityContext.AuthorizationContext))
{
string primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(remoteSecurity.ServiceSecurityContext.AuthorizationContext);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(
SR.RemoteIdentityFailedVerification, primaryIdentity)));
}
}
}
else if (!allowNtlm)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.StreamMutualAuthNotSatisfied)));
}
}
#endif // SUPPORTS_WINDOWSIDENTITY
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Reflection.Tests
{
public class GetPropertiesTests
{
public static void TryGetProperties(string AssemblyQualifiedNameOfTypeToGet, string[] propertiesExpected)
{
TryGetProperties(AssemblyQualifiedNameOfTypeToGet, propertiesExpected, BindingFlags.Instance, false);
}
public static void TryGetProperties(string AssemblyQualifiedNameOfTypeToGet, string[] propertiesExpected, BindingFlags flags)
{
TryGetProperties(AssemblyQualifiedNameOfTypeToGet, propertiesExpected, flags, true);
}
public static void TryGetProperties(string AssemblyQualifiedNameOfTypeToGet, string[] propertiesExpected, BindingFlags flags, bool useFlags)
{
Type typeToCheck;
typeToCheck = Type.GetType(AssemblyQualifiedNameOfTypeToGet);
Assert.NotNull(typeToCheck);
PropertyInfo[] propertiesReturned;
if (useFlags)
{
propertiesReturned = typeToCheck.GetProperties(flags);
}
else
{
propertiesReturned = typeToCheck.GetProperties();
}
Assert.Equal(propertiesExpected.Length, propertiesReturned.Length);
int foundIndex;
Array.Sort(propertiesExpected);
for (int i = 0; i < propertiesReturned.Length; i++)
{
foundIndex = Array.BinarySearch(propertiesExpected, propertiesReturned[i].ToString());
Assert.False(foundIndex < 0, "An unexpected property " + propertiesReturned[i].ToString() + " was returned");
}
}
[Fact]
public void Test1()
{
TryGetProperties("System.Reflection.Tests.GenericClassWithVarArgMethod`1[System.String]", new string[] { "System.String publicField" });
}
[Fact]
public void Test2()
{
TryGetProperties("System.Reflection.Tests.Cat`1[System.Int32]", new string[] { "System.Object[] StuffConsumed" });
}
[Fact]
public void Test3()
{
TryGetProperties("System.Reflection.Tests.GenericClassWithVarArgMethod`1[System.Int32]", new string[] { "Int32 publicField" });
}
[Fact]
public void Test4()
{
TryGetProperties("System.Reflection.Tests.GenericClassWithVarArgMethod`1", new string[] { "T publicField" });
}
[Fact]
public void Test5()
{
TryGetProperties("System.Reflection.Tests.ClassWithVarArgMethod", new string[] { "Int32 publicField" });
}
[Fact]
public void Test6()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase);
}
[Fact]
public void Test7()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly);
}
[Fact]
public void Test8()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly);
}
[Fact]
public void Test9()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Instance);
}
[Fact]
public void Test10()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Instance);
}
[Fact]
public void Test11()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Instance);
}
[Fact]
public void Test12()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance);
}
[Fact]
public void Test13()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Static);
}
[Fact]
public void Test14()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Static);
}
[Fact]
public void Test15()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Static);
}
[Fact]
public void Test16()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Static);
}
[Fact]
public void Test17()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Instance | BindingFlags.Static);
}
[Fact]
public void Test18()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static);
}
[Fact]
public void Test19()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
}
[Fact]
public void Test20()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static);
}
[Fact]
public void Test21()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Public);
}
[Fact]
public void Test22()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Public);
}
[Fact]
public void Test23()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Public);
}
[Fact]
public void Test24()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Public);
}
[Fact]
public void Test25()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.Instance | BindingFlags.Public);
}
[Fact]
public void Test26()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
}
[Fact]
public void Test27()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
}
[Fact]
public void Test28()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
}
[Fact]
public void Test29()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test30()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test31()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test32()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test33()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test34()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test35()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test36()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
}
[Fact]
public void Test37()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.NonPublic);
}
[Fact]
public void Test38()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.NonPublic);
}
[Fact]
public void Test39()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.NonPublic);
}
[Fact]
public void Test40()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.NonPublic);
}
[Fact]
public void Test41()
{
TryGetProperties("System.String", new string[] { "Char FirstChar", }, BindingFlags.Instance | BindingFlags.NonPublic);
}
[Fact]
public void Test42()
{
TryGetProperties("System.String", new string[] { "Char FirstChar", }, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.NonPublic);
}
[Fact]
public void Test43()
{
TryGetProperties("System.String", new string[] { "Char FirstChar", }, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic);
}
[Fact]
public void Test44()
{
TryGetProperties("System.String", new string[] { "Char FirstChar", }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic);
}
[Fact]
public void Test45()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test46()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test47()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test48()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test49()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Char FirstChar", "Int32 Length", }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test50()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Char FirstChar", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test51()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Char FirstChar", "Int32 Length", }, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test52()
{
TryGetProperties("System.String", new string[] { "Char Chars [Int32]", "Char FirstChar", "Int32 Length", }, BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
[Fact]
public void Test53()
{
TryGetProperties("System.String", new string[] { }, BindingFlags.FlattenHierarchy);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.