context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.QrCode.Internal
{
/// <summary> <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
/// in one QR Code. This class decodes the bits back into text.</p>
///
/// <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
/// <author>Sean Owen</author>
/// </summary>
internal static class DecodedBitStreamParser
{
/// <summary>
/// See ISO 18004:2006, 6.4.4 Table 5
/// </summary>
private static readonly char[] ALPHANUMERIC_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".ToCharArray();
private const int GB2312_SUBSET = 1;
internal static DecoderResult decode(byte[] bytes,
Version version,
ErrorCorrectionLevel ecLevel,
IDictionary<DecodeHintType, object> hints)
{
var bits = new BitSource(bytes);
var result = new StringBuilder(50);
var byteSegments = new List<byte[]>(1);
var symbolSequence = -1;
var parityData = -1;
try
{
CharacterSetECI currentCharacterSetECI = null;
bool fc1InEffect = false;
Mode mode;
do
{
// While still another segment to read...
if (bits.available() < 4)
{
// OK, assume we're done. Really, a TERMINATOR mode should have been recorded here
mode = Mode.TERMINATOR;
}
else
{
try
{
mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
}
catch (ArgumentException)
{
return null;
}
}
if (mode != Mode.TERMINATOR)
{
if (mode == Mode.FNC1_FIRST_POSITION || mode == Mode.FNC1_SECOND_POSITION)
{
// We do little with FNC1 except alter the parsed result a bit according to the spec
fc1InEffect = true;
}
else if (mode == Mode.STRUCTURED_APPEND)
{
if (bits.available() < 16)
{
return null;
}
// not really supported; but sequence number and parity is added later to the result metadata
// Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
symbolSequence = bits.readBits(8);
parityData = bits.readBits(8);
}
else if (mode == Mode.ECI)
{
// Count doesn't apply to ECI
int value = parseECIValue(bits);
currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);
if (currentCharacterSetECI == null)
{
return null;
}
}
else
{
// First handle Hanzi mode which does not start with character count
if (mode == Mode.HANZI)
{
//chinese mode contains a sub set indicator right after mode indicator
int subset = bits.readBits(4);
int countHanzi = bits.readBits(mode.getCharacterCountBits(version));
if (subset == GB2312_SUBSET)
{
if (!decodeHanziSegment(bits, result, countHanzi))
return null;
}
}
else
{
// "Normal" QR code modes:
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode.getCharacterCountBits(version));
if (mode == Mode.NUMERIC)
{
if (!decodeNumericSegment(bits, result, count))
return null;
}
else if (mode == Mode.ALPHANUMERIC)
{
if (!decodeAlphanumericSegment(bits, result, count, fc1InEffect))
return null;
}
else if (mode == Mode.BYTE)
{
if (!decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints))
return null;
}
else if (mode == Mode.KANJI)
{
if (!decodeKanjiSegment(bits, result, count))
return null;
}
else
{
return null;
}
}
}
}
} while (mode != Mode.TERMINATOR);
}
catch (ArgumentException)
{
// from readBits() calls
return null;
}
#if WindowsCE
var resultString = result.ToString().Replace("\n", "\r\n");
#else
var resultString = result.ToString().Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
#endif
return new DecoderResult(bytes,
resultString,
byteSegments.Count == 0 ? null : byteSegments,
ecLevel == null ? null : ecLevel.ToString(),
symbolSequence, parityData);
}
/// <summary>
/// See specification GBT 18284-2000
/// </summary>
/// <param name="bits">The bits.</param>
/// <param name="result">The result.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
private static bool decodeHanziSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as GB2312 afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x060) << 8) | (twoBytes % 0x060);
if (assembledTwoBytes < 0x003BF)
{
// In the 0xA1A1 to 0xAAFE range
assembledTwoBytes += 0x0A1A1;
}
else
{
// In the 0xB0A1 to 0xFAFE range
assembledTwoBytes += 0x0A6A1;
}
buffer[offset] = (byte)((assembledTwoBytes >> 8) & 0xFF);
buffer[offset + 1] = (byte)(assembledTwoBytes & 0xFF);
offset += 2;
count--;
}
try
{
result.Append(Encoding.GetEncoding(StringUtils.GB2312).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeKanjiSegment(BitSource bits,
StringBuilder result,
int count)
{
// Don't crash trying to read more bits than we have available.
if (count * 13 > bits.available())
{
return false;
}
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0)
{
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00)
{
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
}
else
{
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (byte)(assembledTwoBytes >> 8);
buffer[offset + 1] = (byte)assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
try
{
result.Append(Encoding.GetEncoding(StringUtils.SHIFT_JIS).GetString(buffer, 0, buffer.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(buffer, 0, buffer.Length));
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
return true;
}
private static bool decodeByteSegment(BitSource bits,
StringBuilder result,
int count,
CharacterSetECI currentCharacterSetECI,
IList<byte[]> byteSegments,
IDictionary<DecodeHintType, object> hints)
{
// Don't crash trying to read more bits than we have available.
if (count << 3 > bits.available())
{
return false;
}
byte[] readBytes = new byte[count];
for (int i = 0; i < count; i++)
{
readBytes[i] = (byte)bits.readBits(8);
}
String encoding;
if (currentCharacterSetECI == null)
{
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
encoding = StringUtils.guessEncoding(readBytes, hints);
}
else
{
encoding = currentCharacterSetECI.EncodingName;
}
try
{
result.Append(Encoding.GetEncoding(encoding).GetString(readBytes, 0, readBytes.Length));
}
#if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || MONOANDROID || MONOTOUCH)
catch (ArgumentException)
{
try
{
// Silverlight only supports a limited number of character sets, trying fallback to UTF-8
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
catch (Exception)
{
return false;
}
}
#endif
#if WindowsCE
catch (PlatformNotSupportedException)
{
try
{
// WindowsCE doesn't support all encodings. But it is device depended.
// So we try here the some different ones
if (encoding == "ISO-8859-1")
{
result.Append(Encoding.GetEncoding(1252).GetString(readBytes, 0, readBytes.Length));
}
else
{
result.Append(Encoding.GetEncoding("UTF-8").GetString(readBytes, 0, readBytes.Length));
}
}
catch (Exception)
{
return false;
}
}
#endif
catch (Exception)
{
return false;
}
byteSegments.Add(readBytes);
return true;
}
private static char toAlphaNumericChar(int value)
{
if (value >= ALPHANUMERIC_CHARS.Length)
{
throw FormatException.Instance;
}
return ALPHANUMERIC_CHARS[value];
}
private static bool decodeAlphanumericSegment(BitSource bits,
StringBuilder result,
int count,
bool fc1InEffect)
{
// Read two characters at a time
int start = result.Length;
while (count > 1)
{
if (bits.available() < 11)
{
return false;
}
int nextTwoCharsBits = bits.readBits(11);
result.Append(toAlphaNumericChar(nextTwoCharsBits / 45));
result.Append(toAlphaNumericChar(nextTwoCharsBits % 45));
count -= 2;
}
if (count == 1)
{
// special case: one character left
if (bits.available() < 6)
{
return false;
}
result.Append(toAlphaNumericChar(bits.readBits(6)));
}
// See section 6.4.8.1, 6.4.8.2
if (fc1InEffect)
{
// We need to massage the result a bit if in an FNC1 mode:
for (int i = start; i < result.Length; i++)
{
if (result[i] == '%')
{
if (i < result.Length - 1 && result[i + 1] == '%')
{
// %% is rendered as %
result.Remove(i + 1, 1);
}
else
{
// In alpha mode, % should be converted to FNC1 separator 0x1D
result.Remove(i, 1);
result.Insert(i, new[] { (char)0x1D });
}
}
}
}
return true;
}
private static bool decodeNumericSegment(BitSource bits,
StringBuilder result,
int count)
{
// Read three digits at a time
while (count >= 3)
{
// Each 10 bits encodes three digits
if (bits.available() < 10)
{
return false;
}
int threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000)
{
return false;
}
result.Append(toAlphaNumericChar(threeDigitsBits / 100));
result.Append(toAlphaNumericChar((threeDigitsBits / 10) % 10));
result.Append(toAlphaNumericChar(threeDigitsBits % 10));
count -= 3;
}
if (count == 2)
{
// Two digits left over to read, encoded in 7 bits
if (bits.available() < 7)
{
return false;
}
int twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100)
{
return false;
}
result.Append(toAlphaNumericChar(twoDigitsBits / 10));
result.Append(toAlphaNumericChar(twoDigitsBits % 10));
}
else if (count == 1)
{
// One digit left over to read
if (bits.available() < 4)
{
return false;
}
int digitBits = bits.readBits(4);
if (digitBits >= 10)
{
return false;
}
result.Append(toAlphaNumericChar(digitBits));
}
return true;
}
private static int parseECIValue(BitSource bits)
{
int firstByte = bits.readBits(8);
if ((firstByte & 0x80) == 0)
{
// just one byte
return firstByte & 0x7F;
}
if ((firstByte & 0xC0) == 0x80)
{
// two bytes
int secondByte = bits.readBits(8);
return ((firstByte & 0x3F) << 8) | secondByte;
}
if ((firstByte & 0xE0) == 0xC0)
{
// three bytes
int secondThirdBytes = bits.readBits(16);
return ((firstByte & 0x1F) << 16) | secondThirdBytes;
}
throw new ArgumentException("Bad ECI bits starting with byte " + firstByte);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class GZipStreamTests
{
static String gzTestFile(String fileName) { return Path.Combine("GZTestData", fileName); }
[Fact]
public void BaseStream1()
{
var writeStream = new MemoryStream();
var zip = new GZipStream(writeStream, CompressionMode.Compress);
Assert.Same(zip.BaseStream, writeStream);
writeStream.Dispose();
}
[Fact]
public void BaseStream2()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.Same(zip.BaseStream, ms);
ms.Dispose();
}
[Fact]
public async Task ModifyBaseStream()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress);
int size = 1024;
Byte[] bytes = new Byte[size];
zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
}
[Fact]
public void DecompressCanRead()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.True(zip.CanRead, "GZipStream not CanRead in Decompress");
zip.Dispose();
Assert.False(zip.CanRead, "GZipStream CanRead after dispose in Decompress");
}
[Fact]
public void CompressCanWrite()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.True(zip.CanWrite, "GZipStream not CanWrite with CompressionMode.Compress");
zip.Dispose();
Assert.False(zip.CanWrite, "GZipStream CanWrite after dispose");
}
[Fact]
public void CanDisposeBaseStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
ms.Dispose(); // This would throw if this was invalid
}
[Fact]
public void CanDisposeGZipStream()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
zip.Dispose();
Assert.Null(zip.BaseStream);
zip.Dispose(); // Should be a no-op
}
[Fact]
public async Task CanReadBaseStreamAfterDispose()
{
var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
var zip = new GZipStream(ms, CompressionMode.Decompress, true);
var baseStream = zip.BaseStream;
zip.Dispose();
int size = 1024;
Byte[] bytes = new Byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
}
[Fact]
public async Task DecompressWorks()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDoc()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.doc.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithDocx()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.docx.gz"));
await DecompressAsync(compareStream, gzStream);
}
[Fact]
public async Task DecompressWorksWithPdf()
{
var compareStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf"));
var gzStream = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.pdf.gz"));
await DecompressAsync(compareStream, gzStream);
}
// Making this async since regular read/write are tested below
private static async Task DecompressAsync(MemoryStream compareStream, MemoryStream gzStream)
{
var ms = new MemoryStream();
var zip = new GZipStream(gzStream, CompressionMode.Decompress);
var GZipStream = new MemoryStream();
int _bufferSize = 1024;
var bytes = new Byte[_bufferSize];
bool finished = false;
int retCount;
while (!finished)
{
retCount = await zip.ReadAsync(bytes, 0, _bufferSize);
if (retCount != 0)
await GZipStream.WriteAsync(bytes, 0, retCount);
else
finished = true;
}
GZipStream.Position = 0;
compareStream.Position = 0;
byte[] compareArray = compareStream.ToArray();
byte[] writtenArray = GZipStream.ToArray();
Assert.Equal(compareArray.Length, writtenArray.Length);
for (int i = 0; i < compareArray.Length; i++)
{
Assert.Equal(compareArray[i], writtenArray[i]);
}
}
[Fact]
public void NullBaseStreamThrows()
{
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Decompress);
});
Assert.Throws<ArgumentNullException>(() =>
{
var deflate = new GZipStream(null, CompressionMode.Compress);
});
}
[Fact]
public void DisposedBaseStreamThrows()
{
var ms = new MemoryStream();
ms.Dispose();
Assert.Throws<ArgumentException>(() =>
{
var deflate = new GZipStream(ms, CompressionMode.Decompress);
});
Assert.Throws<ArgumentException>(() =>
{
var deflate = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void ReadOnlyStreamThrowsOnCompress()
{
var ms = new LocalMemoryStream();
ms.SetCanWrite(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new GZipStream(ms, CompressionMode.Compress);
});
}
[Fact]
public void WriteOnlyStreamThrowsOnDecompress()
{
var ms = new LocalMemoryStream();
ms.SetCanRead(false);
Assert.Throws<ArgumentException>(() =>
{
var gzip = new GZipStream(ms, CompressionMode.Decompress);
});
}
[Fact]
public void TestCtors()
{
CompressionLevel[] legalValues = new CompressionLevel[] { CompressionLevel.Optimal, CompressionLevel.Fastest, CompressionLevel.NoCompression };
foreach (CompressionLevel level in legalValues)
{
bool[] boolValues = new bool[] { true, false };
foreach (bool remainsOpen in boolValues)
{
TestCtor(level, remainsOpen);
}
}
}
[Fact]
public void TestLevelOptimial()
{
TestCtor(CompressionLevel.Optimal);
}
[Fact]
public void TestLevelNoCompression()
{
TestCtor(CompressionLevel.NoCompression);
}
[Fact]
public void TestLevelFastest()
{
TestCtor(CompressionLevel.Fastest);
}
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the GZipStream
int _bufferSize = 1024;
var bytes = new Byte[_bufferSize];
var baseStream = new MemoryStream(bytes, true);
GZipStream ds;
if (leaveOpen == null)
{
ds = new GZipStream(baseStream, level);
}
else
{
ds = new GZipStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
String strData = "Test Data";
var encoding = Encoding.UTF8;
Byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
Byte[] data2 = new Byte[_bufferSize];
baseStream = new MemoryStream(bytes, false);
ds = new GZipStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
[Fact]
public async Task Flush()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Flush();
await ds.FlushAsync();
// Just ensuring Flush doesn't throw
}
[Fact]
public void FlushFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
Assert.Throws<ObjectDisposedException>(() => { ds.Flush(); });
}
[Fact]
public async Task FlushAsyncFailsAfterDispose()
{
var ms = new MemoryStream();
var ds = new GZipStream(ms, CompressionMode.Compress);
ds.Dispose();
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
{
await ds.FlushAsync();
});
}
[Fact]
public void TestSeekMethodsDecompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Decompress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
[Fact]
public void TestSeekMethodsCompress()
{
var ms = new MemoryStream();
var zip = new GZipStream(ms, CompressionMode.Compress);
Assert.False(zip.CanSeek);
Assert.Throws<NotSupportedException>(delegate { long value = zip.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = zip.Position; });
Assert.Throws<NotSupportedException>(delegate { zip.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { zip.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { zip.Seek(100L, SeekOrigin.Begin); });
zip.Dispose();
Assert.False(zip.CanSeek);
}
}
}
| |
//
// AudioscrobblerService.cs
//
// Authors:
// Alexander Hixon <hixon.alexander@mediati.org>
// Chris Toshok <toshok@ximian.com>
// Ruben Vermeersch <ruben@savanne.be>
// Aaron Bockover <aaron@abock.org>
// Phil Trimble <philtrimble@gmail.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
// Copyright (C) 2013 Phil Trimble
//
// 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.Net;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Lastfm;
using Banshee.MediaEngine;
using Banshee.Base;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Gui;
using Banshee.Networking;
using Banshee.Sources;
using Banshee.Collection;
using Browser = Lastfm.Browser;
namespace Banshee.Lastfm.Audioscrobbler
{
public class AudioscrobblerService : IExtensionService, IDisposable
{
private AudioscrobblerConnection connection;
private ActionGroup actions;
private uint ui_manager_id;
private InterfaceActionService action_service;
private Queue queue;
private Account account;
private bool queued; /* if current_track has been queued */
private bool now_playing_sent = false; /* self-explanatory :) */
private int iterate_countdown = 4 * 4; /* number of times to wait for iterate event before sending now playing */
private DateTime song_start_time;
private TrackInfo last_track;
private readonly TimeSpan MINIMUM_TRACK_DURATION = TimeSpan.FromSeconds (30);
private readonly TimeSpan MINIMUM_TRACK_PLAYTIME = TimeSpan.FromSeconds (240);
private UserJob scrobble_job;
private int job_tracks_count;
private int job_tracks_total;
private string scrobbling_progress_message = Catalog.GetString ("Processed {0} of {1} tracks");
public AudioscrobblerService ()
{
}
void IExtensionService.Initialize ()
{
account = LastfmCore.Account;
if (account.UserName == null) {
account.UserName = LastfmSource.LastUserSchema.Get ();
account.SessionKey = LastfmSource.LastSessionKeySchema.Get ();
account.ScrobbleUrl = LastScrobbleUrlSchema.Get ();
}
if (LastfmCore.UserAgent == null) {
LastfmCore.UserAgent = Banshee.Web.Browser.UserAgent;
}
Browser.Open = Banshee.Web.Browser.Open;
queue = new Queue ();
LastfmCore.AudioscrobblerQueue = queue;
connection = LastfmCore.Audioscrobbler;
// Initialize with a reasonable value in case we miss the first StartOfStream event
song_start_time = DateTime.Now;
Network network = ServiceManager.Get<Network> ();
connection.UpdateNetworkState (network.Connected);
network.StateChanged += HandleNetworkStateChanged;
connection.SubmissionStart += OnSubmissionStart;
connection.SubmissionUpdate += OnSubmissionUpdate;
connection.SubmissionEnd += OnSubmissionEnd;
// Update the Visit action menu item if we update our account info
LastfmCore.Account.Updated += delegate (object o, EventArgs args) {
actions["AudioscrobblerVisitAction"].Sensitive = String.IsNullOrEmpty (LastfmCore.Account.UserName);
};
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent,
PlayerEvent.StartOfStream |
PlayerEvent.EndOfStream |
PlayerEvent.Seek |
PlayerEvent.Iterate);
if (DeviceEnabled) {
SubscribeForDeviceEvents ();
}
action_service = ServiceManager.Get<InterfaceActionService> ();
InterfaceInitialize ();
}
public void InterfaceInitialize ()
{
actions = new ActionGroup ("Audioscrobbler");
actions.Add (new ActionEntry [] {
new ActionEntry ("AudioscrobblerAction", null,
Catalog.GetString ("_Last.fm"), null,
Catalog.GetString ("Configure the Audioscrobbler plugin"), null),
new ActionEntry ("AudioscrobblerVisitAction", null,
Catalog.GetString ("Visit _User Profile Page"), null,
Catalog.GetString ("Visit Your Last.fm Profile Page"), OnVisitOwnProfile)
});
actions.Add (new ToggleActionEntry [] {
new ToggleActionEntry ("AudioscrobblerEnableAction", null,
Catalog.GetString ("_Enable Song Reporting From Banshee"), null,
Catalog.GetString ("Enable song reporting From Banshee"), OnToggleEnabled, Enabled)
});
actions.Add (new ToggleActionEntry [] {
new ToggleActionEntry ("AudioscrobblerDeviceEnableAction", null,
Catalog.GetString ("_Enable Song Reporting From Device"), null,
Catalog.GetString ("Enable song reporting From Device"), OnToggleDeviceEnabled, DeviceEnabled)
});
action_service.UIManager.InsertActionGroup (actions, 0);
ui_manager_id = action_service.UIManager.AddUiFromResource ("AudioscrobblerMenu.xml");
actions["AudioscrobblerVisitAction"].Sensitive = account.UserName != null && account.UserName != String.Empty;
}
public void Dispose ()
{
// Try and queue the currently playing track just in case it's queueable
// but the user hasn't hit next yet and quit/disposed the service.
if (ServiceManager.PlayerEngine.CurrentTrack != null) {
Queue (ServiceManager.PlayerEngine.CurrentTrack);
}
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.Get<Network> ().StateChanged -= HandleNetworkStateChanged;
if (DeviceEnabled) {
UnsubscribeForDeviceEvents ();
}
// When we stop the connection, queue ends up getting saved too, so the
// track we queued earlier should stay until next session.
connection.Stop ();
action_service.UIManager.RemoveUi (ui_manager_id);
action_service.UIManager.RemoveActionGroup (actions);
actions = null;
connection.SubmissionStart -= OnSubmissionStart;
connection.SubmissionUpdate -= OnSubmissionUpdate;
connection.SubmissionEnd -= OnSubmissionEnd;
}
List<IBatchScrobblerSource> sources_watched;
private void SubscribeForDeviceEvents ()
{
sources_watched = new List<IBatchScrobblerSource> ();
ServiceManager.SourceManager.SourceAdded += OnSourceAdded;
ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved;
}
private void UnsubscribeForDeviceEvents ()
{
ServiceManager.SourceManager.SourceAdded -= OnSourceAdded;
ServiceManager.SourceManager.SourceRemoved -= OnSourceRemoved;
foreach (var source in sources_watched) {
source.ReadyToScrobble -= OnReadyToScrobble;
}
sources_watched.Clear ();
sources_watched = null;
}
private void HandleNetworkStateChanged (object o, NetworkStateChangedArgs args)
{
connection.UpdateNetworkState (args.Connected);
}
// We need to time how long the song has played
internal class SongTimer
{
private long playtime = 0; // number of msecs played
public long PlayTime {
get { return playtime; }
}
private long previouspos = 0;
// number of events to ignore to get sync (since events may be fired in wrong order)
private int ignorenext = 0;
public void IncreasePosition ()
{
long increase = 0;
if (ignorenext == 0) {
increase = (ServiceManager.PlayerEngine.Position - previouspos);
if (increase > 0) {
playtime += increase;
}
} else {
ignorenext--;
}
previouspos = ServiceManager.PlayerEngine.Position;
}
public void SkipPosition ()
{
// Set newly seeked position
previouspos = ServiceManager.PlayerEngine.Position;
ignorenext = 2; // allow 2 iterates to sync
}
public void Reset ()
{
playtime = 0;
previouspos = 0;
ignorenext = 0;
}
}
SongTimer st = new SongTimer ();
private bool IsValidForSubmission (TrackInfo track)
{
return (track.Duration > MINIMUM_TRACK_DURATION &&
(track.MediaAttributes & TrackMediaAttributes.Music) != 0 &&
!String.IsNullOrEmpty (track.ArtistName) &&
!String.IsNullOrEmpty (track.TrackTitle));
}
private void Queue (TrackInfo track) {
if (track == null || st.PlayTime == 0 ||
!((ToggleAction) actions["AudioscrobblerEnableAction"]).Active) {
return;
}
Log.DebugFormat ("Track {3} had playtime of {0} msec ({4}sec), duration {1} msec, queued: {2}",
st.PlayTime, track.Duration.TotalMilliseconds, queued, track, st.PlayTime / 1000);
if (!queued && IsValidForSubmission (track) &&
(st.PlayTime > track.Duration.TotalMilliseconds / 2 ||
st.PlayTime > MINIMUM_TRACK_PLAYTIME.TotalMilliseconds)) {
if (!connection.Started) {
connection.Start ();
}
queue.Add (track, song_start_time);
queued = true;
}
}
private void OnPlayerEvent (PlayerEventArgs args)
{
switch (args.Event) {
case PlayerEvent.StartOfStream:
// Queue the previous track in case of a skip
Queue (last_track);
st.Reset ();
song_start_time = DateTime.Now;
last_track = ServiceManager.PlayerEngine.CurrentTrack;
queued = false;
now_playing_sent = false;
iterate_countdown = 4 * 4; /* we get roughly 4 events/sec */
break;
case PlayerEvent.Seek:
st.SkipPosition ();
break;
case PlayerEvent.Iterate:
// Queue as now playing
if (!now_playing_sent && iterate_countdown == 0) {
if (last_track != null &&
IsValidForSubmission (last_track) &&
((ToggleAction) actions["AudioscrobblerEnableAction"]).Active) {
connection.NowPlaying (last_track.ArtistName, last_track.TrackTitle,
last_track.AlbumTitle, last_track.Duration.TotalSeconds, last_track.TrackNumber);
}
now_playing_sent = true;
} else if (iterate_countdown > 0) {
iterate_countdown --;
}
st.IncreasePosition ();
break;
case PlayerEvent.EndOfStream:
Queue (last_track);
last_track = null;
iterate_countdown = 4 * 4;
break;
}
}
private void OnVisitOwnProfile (object o, EventArgs args)
{
account.VisitUserProfile (account.UserName);
}
private void OnToggleEnabled (object o, EventArgs args)
{
Enabled = ((ToggleAction) o).Active;
}
private void OnToggleDeviceEnabled (object o, EventArgs args)
{
DeviceEnabled = ((ToggleAction) o).Active;
}
internal bool Enabled {
get { return EngineEnabledSchema.Get (); }
set {
EngineEnabledSchema.Set (value);
((ToggleAction) actions["AudioscrobblerEnableAction"]).Active = value;
}
}
internal bool DeviceEnabled {
get { return DeviceEngineEnabledSchema.Get (); }
set {
if (DeviceEnabled == value)
return;
DeviceEngineEnabledSchema.Set (value);
((ToggleAction) actions["AudioscrobblerDeviceEnableAction"]).Active = value;
if (value) {
SubscribeForDeviceEvents ();
} else {
UnsubscribeForDeviceEvents ();
}
}
}
#region scrobbling
private void OnSourceAdded (SourceEventArgs args)
{
var scrobbler_source = args.Source as IBatchScrobblerSource;
if (scrobbler_source == null) {
return;
}
scrobbler_source.ReadyToScrobble += OnReadyToScrobble;
sources_watched.Add (scrobbler_source);
}
private void OnSourceRemoved (SourceEventArgs args)
{
var scrobbler_source = args.Source as IBatchScrobblerSource;
if (scrobbler_source == null) {
return;
}
sources_watched.Remove (scrobbler_source);
scrobbler_source.ReadyToScrobble -= OnReadyToScrobble;
}
private void OnReadyToScrobble (object source, ScrobblingBatchEventArgs args)
{
if (!connection.Started) {
connection.Start ();
}
int added_track_count = 0;
foreach (var track_entry in args.ScrobblingBatch) {
TrackInfo track = track_entry.Key;
if (IsValidForSubmission (track)) {
IList<DateTime> playtimes = track_entry.Value;
foreach (DateTime playtime in playtimes) {
queue.Add (track, playtime);
added_track_count++;
}
Log.DebugFormat ("Added to Last.fm queue: {0} - Number of plays: {1}", track, playtimes.Count);
} else {
Log.DebugFormat ("Track {0} failed validation check for Last.fm submission, skipping...",
track);
}
}
Log.InformationFormat ("Number of played tracks from device added to Last.fm queue: {0}", added_track_count);
}
private void OnSubmissionStart (object source, SubmissionStartEventArgs args)
{
// We only want to display something if more than one track is being submitted
if (args.TotalCount <= 1) {
return;
}
if (scrobble_job == null) {
scrobble_job = new UserJob (Catalog.GetString ("Scrobbling to Last.FM"),
Catalog.GetString ("Scrobbling to Last.FM..."));
scrobble_job.PriorityHints = PriorityHints.None;
scrobble_job.CanCancel = true;
scrobble_job.CancelRequested += OnScrobbleJobCancelRequest;
scrobble_job.Register ();
job_tracks_count = 0;
job_tracks_total = args.TotalCount;
}
UpdateJob ();
}
private void OnSubmissionUpdate (object source, SubmissionUpdateEventArgs args)
{
if (scrobble_job != null) {
job_tracks_count += args.UpdateCount;
UpdateJob ();
}
}
private void UpdateJob ()
{
scrobble_job.Status = String.Format (scrobbling_progress_message, job_tracks_count, job_tracks_total);
scrobble_job.Progress = job_tracks_count / (double) job_tracks_total;
}
private void OnSubmissionEnd (object source, EventArgs args)
{
if (scrobble_job != null) {
scrobble_job.Finish ();
scrobble_job = null;
}
}
private void OnScrobbleJobCancelRequest (object source, EventArgs args)
{
scrobble_job.Finish ();
scrobble_job = null;
}
#endregion
public static readonly SchemaEntry<string> LastScrobbleUrlSchema = new SchemaEntry<string> (
"plugins.audioscrobbler", "api_url",
null,
"AudioScrobbler API URL",
"URL for the AudioScrobbler API (supports turtle.libre.fm, for instance)"
);
public static readonly SchemaEntry<bool> EngineEnabledSchema = new SchemaEntry<bool> (
"plugins.audioscrobbler", "engine_enabled",
false,
"Engine enabled",
"Audioscrobbler reporting engine enabled"
);
public static readonly SchemaEntry<bool> DeviceEngineEnabledSchema = new SchemaEntry<bool> (
"plugins.audioscrobbler", "device_engine_enabled",
false,
"Device engine enabled",
"Audioscrobbler device reporting engine enabled"
);
string IService.ServiceName {
get { return "AudioscrobblerService"; }
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace SpyUO
{
public class PropsFilter : System.Windows.Forms.Form
{
private System.Windows.Forms.CheckedListBox clbProps;
private System.Windows.Forms.TextBox tbPropValue;
private System.Windows.Forms.Button bOk;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Label lMust;
private System.Windows.Forms.RadioButton rbHave;
private System.Windows.Forms.RadioButton rbNotHave;
private System.Windows.Forms.Label lValues;
private System.Windows.Forms.TextBox tbFormat;
private System.ComponentModel.Container components = null;
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if ( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
this.clbProps = new System.Windows.Forms.CheckedListBox();
this.tbPropValue = new System.Windows.Forms.TextBox();
this.bOk = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.lMust = new System.Windows.Forms.Label();
this.rbHave = new System.Windows.Forms.RadioButton();
this.rbNotHave = new System.Windows.Forms.RadioButton();
this.lValues = new System.Windows.Forms.Label();
this.tbFormat = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// clbProps
//
this.clbProps.Location = new System.Drawing.Point(8, 8);
this.clbProps.Name = "clbProps";
this.clbProps.Size = new System.Drawing.Size(224, 124);
this.clbProps.TabIndex = 0;
this.clbProps.SelectedIndexChanged += new System.EventHandler(this.clbProps_SelectedIndexChanged);
this.clbProps.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.clbProps_ItemCheck);
//
// tbPropValue
//
this.tbPropValue.AcceptsReturn = true;
this.tbPropValue.AcceptsTab = true;
this.tbPropValue.Enabled = false;
this.tbPropValue.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.tbPropValue.Location = new System.Drawing.Point(8, 168);
this.tbPropValue.Name = "tbPropValue";
this.tbPropValue.Size = new System.Drawing.Size(136, 22);
this.tbPropValue.TabIndex = 1;
this.tbPropValue.Text = "";
this.tbPropValue.TextChanged += new System.EventHandler(this.tbPropValue_TextChanged);
//
// bOk
//
this.bOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.bOk.Location = new System.Drawing.Point(144, 200);
this.bOk.Name = "bOk";
this.bOk.TabIndex = 3;
this.bOk.Text = "Ok";
//
// bCancel
//
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(24, 200);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 4;
this.bCancel.Text = "Cancel";
//
// lMust
//
this.lMust.Enabled = false;
this.lMust.Location = new System.Drawing.Point(8, 144);
this.lMust.Name = "lMust";
this.lMust.Size = new System.Drawing.Size(32, 16);
this.lMust.TabIndex = 5;
this.lMust.Text = "Must";
//
// rbHave
//
this.rbHave.Checked = true;
this.rbHave.Enabled = false;
this.rbHave.Location = new System.Drawing.Point(40, 136);
this.rbHave.Name = "rbHave";
this.rbHave.Size = new System.Drawing.Size(80, 16);
this.rbHave.TabIndex = 6;
this.rbHave.TabStop = true;
this.rbHave.Text = "have one";
this.rbHave.CheckedChanged += new System.EventHandler(this.rbHave_CheckedChanged);
//
// rbNotHave
//
this.rbNotHave.Enabled = false;
this.rbNotHave.Location = new System.Drawing.Point(40, 152);
this.rbNotHave.Name = "rbNotHave";
this.rbNotHave.Size = new System.Drawing.Size(80, 16);
this.rbNotHave.TabIndex = 7;
this.rbNotHave.Text = "have none";
this.rbNotHave.CheckedChanged += new System.EventHandler(this.rbNotHave_CheckedChanged);
//
// lValues
//
this.lValues.Enabled = false;
this.lValues.Location = new System.Drawing.Point(120, 144);
this.lValues.Name = "lValues";
this.lValues.Size = new System.Drawing.Size(120, 16);
this.lValues.TabIndex = 8;
this.lValues.Text = "of these values (sep: |)";
//
// tbFormat
//
this.tbFormat.Location = new System.Drawing.Point(152, 168);
this.tbFormat.Name = "tbFormat";
this.tbFormat.ReadOnly = true;
this.tbFormat.Size = new System.Drawing.Size(80, 20);
this.tbFormat.TabIndex = 9;
this.tbFormat.Text = "";
this.tbFormat.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// PropsFilter
//
this.AcceptButton = this.bOk;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(242, 232);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.tbFormat,
this.lValues,
this.rbNotHave,
this.rbHave,
this.lMust,
this.bCancel,
this.bOk,
this.tbPropValue,
this.clbProps});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PropsFilter";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Property filter";
this.ResumeLayout(false);
}
#endregion
private string[] m_TypeNames;
private string[] m_PropValues;
private bool[] m_PropsHave;
private string[] m_PropsFormat;
public PropsFilter( string[] propNames, string[] typeNames, string[] propValues, bool[] propsHave, string[] propsFormat )
{
InitializeComponent();
m_TypeNames = typeNames;
m_PropsFormat = propsFormat;
int length = propValues.Length;
m_PropValues = new string[length];
m_PropsHave = new bool[length];
for ( int i = 0; i < length; i++ )
{
string propValue = propValues[i];
m_PropValues[i] = propValue;
clbProps.Items.Add( propNames[i], propValue != null );
m_PropsHave[i] = propsHave[i];
}
}
private void clbProps_SelectedIndexChanged( object sender, EventArgs e )
{
int index = clbProps.SelectedIndex;
UpdatePropValue( clbProps.GetItemChecked( index ) );
}
private void clbProps_ItemCheck( object sender, ItemCheckEventArgs e )
{
UpdatePropValue( e.NewValue == CheckState.Checked );
}
private void UpdatePropValue( bool check )
{
int index = clbProps.SelectedIndex;
if ( index >= 0 )
{
tbPropValue.Text = m_PropValues[index];
rbHave.Checked = m_PropsHave[index];
rbNotHave.Checked = !m_PropsHave[index];
tbFormat.Text = m_PropsFormat[index].Replace( "{0", "{" + m_TypeNames[index] );
tbPropValue.Enabled = check;
lMust.Enabled = check;
rbHave.Enabled = check;
rbNotHave.Enabled = check;
lValues.Enabled = check;
}
else
{
tbPropValue.Enabled = false;
lMust.Enabled = false;
rbHave.Enabled = false;
rbNotHave.Enabled = false;
lValues.Enabled = false;
}
}
private void tbPropValue_TextChanged( object sender, System.EventArgs e )
{
int index = clbProps.SelectedIndex;
m_PropValues[index] = tbPropValue.Text;
}
private void rbHave_CheckedChanged( object sender, System.EventArgs e )
{
HaveChanged();
}
private void rbNotHave_CheckedChanged( object sender, System.EventArgs e )
{
HaveChanged();
}
private void HaveChanged()
{
int index = clbProps.SelectedIndex;
m_PropsHave[index] = rbHave.Checked;
}
public string[] GetPropValues()
{
int length = m_PropValues.Length;
string[] ret = new string[length];
for ( int i = 0; i < length; i++ )
{
if ( clbProps.GetItemChecked( i ) )
ret[i] = m_PropValues[i] != null ? m_PropValues[i] : "";
else
ret[i] = null;
}
return ret;
}
public bool[] GetPropHaveValues()
{
int length = m_PropsHave.Length;
bool[] ret = new bool[length];
for ( int i = 0; i < length; i++ )
{
if ( clbProps.GetItemChecked( i ) )
ret[i] = m_PropsHave[i];
else
ret[i] = true;
}
return ret;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.AppScriptPartWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;
using System.Linq;
using SiteRecovery.Tests;
using Microsoft.Rest.Azure.OData;
namespace RecoveryServices.SiteRecovery.Tests
{
public class ASRTests : SiteRecoveryTestsBase
{
private const string targetResourceGroup = "/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/prakccyrg";
private const string storageAccountId = "/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/Arpita-air/providers/Microsoft.Storage/storageAccounts/sah2atest";
private const string azureNetworkId = "/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/Arpita-air/providers/Microsoft.Network/virtualNetworks/vnh2atest";
private const string siteName = "SiteRecoveryTestSite1";
private const string vmmFabric = "ca667d2536f540cc57a566ae639081b123ad508d93caef2859237ca22f265866";
private const string location = "centraluseuap";
private const string providerName = "71f21bed-b00f-4869-9dbf-288e7cb4051d";
private const string policyName = "protectionprofile2";
private const string recoveryCloud = "Microsoft Azure";
private const string protectionContainerMappingName = "PCMapping";
private const string networkMappingName = "NWMapping";
private const string vmName = "VMforSDKFirst";
private const string vmId = "193ca098-991d-4a6f-be78-da2c6e7bd290";
private const string vmName2 = "VMforSDK";
private const string rpName = "rpTest1";
private const string emailAddress = "arpgup@microsoft.com";
private const string alertSettingName = "defaultAlertSetting";
private const string vmNetworkName = "4f704b8f-946c-4705-9844-11167e90102f";
private const string a2aPrimaryLocation = "westeurope";
private const string a2aRecoveryLocation = "northeurope";
private const string a2aPrimaryFabricName = "primaryFabric";
private const string a2aRecoveryFabricName = "recoveryFabric";
private const string a2aPrimaryContainerName = "primaryContainer";
private const string a2aRecoveryContainerName = "recoveryContainer";
private const string a2aPolicyName = "a2aPolicy";
private const string a2aPrimaryRecoveryContainerMappingName = "primaryToRecovery";
private const string a2aRecoveryPrimaryContainerMappingName = "recoveryToPrimary";
private const string a2aVirtualMachineToProtect =
"/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/sdkTestVMRG/providers/Microsoft.Compute/virtualMachines/sdkTestVM1";
private const string a2aVirtualMachineDiskToProtect =
"/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/sdkTestVMRG/providers/Microsoft.Compute/disks/sdkTestVM1_OsDisk_1_719b58f929ca4b97ba638f272b166a96";
private const string a2aStagingStorageAccount =
"/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/sdkTestVMRG/providers/Microsoft.Storage/storageAccounts/sdkcache";
private const string a2aRecoveryResourceGroup =
"/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/sdkTestVMRG-asr";
private const string a2aReplicationProtectedItemName = "sdkTestVm1";
private const string a2aVirtualMachineToValidate = "testVm1";
private const string a2aReplicationProtectionIntentName = "intentName1";
TestHelper testHelper { get; set; }
public ASRTests()
{
testHelper = new TestHelper();
}
[Fact]
public void CreateA2APolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var a2aPolicyCreationInput = new A2APolicyCreationInput
{
AppConsistentFrequencyInMinutes = 60,
RecoveryPointHistory = 720,
MultiVmSyncStatus = "Enable"
};
var createPolicyInput =
new CreatePolicyInput
{
Properties = new CreatePolicyInputProperties()
};
createPolicyInput.Properties.ProviderSpecificInput = a2aPolicyCreationInput;
var policy =
client.ReplicationPolicies.Create(a2aPolicyName, createPolicyInput);
Assert.True(
policy.Name == a2aPolicyName,
"Resource name can not be different.");
}
}
[Fact]
public void CreateA2AFabrics()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var fabricCreationInput = new FabricCreationInput();
fabricCreationInput.Properties = new FabricCreationInputProperties();
var azureFabricCreationInput = new AzureFabricCreationInput();
// Create primary fabric.
azureFabricCreationInput.Location = a2aPrimaryLocation;
fabricCreationInput.Properties.CustomDetails = azureFabricCreationInput;
var primaryFabric =
client.ReplicationFabrics.Create(a2aPrimaryFabricName, fabricCreationInput);
// var response = client.ReplicationFabrics.Get(a2aPrimaryFabricName);
Assert.True(
primaryFabric.Name == a2aPrimaryFabricName,
"Resource name can not be different.");
// Create recovery fabric.
azureFabricCreationInput.Location = a2aRecoveryLocation;
fabricCreationInput.Properties.CustomDetails = azureFabricCreationInput;
var recoveryFabric =
client.ReplicationFabrics.Create(a2aRecoveryFabricName, fabricCreationInput);
// response = client.ReplicationFabrics.Get(a2aRecoveryFabricName);
Assert.True(
recoveryFabric.Name == a2aRecoveryFabricName,
"Resource name can not be different.");
}
}
[Fact]
public void CreateA2AContainers()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var createProtectionContainerInput =
new CreateProtectionContainerInput
{
Properties = new CreateProtectionContainerInputProperties()
};
var primaryContainer =
client.ReplicationProtectionContainers.Create(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
createProtectionContainerInput);
Assert.True(
primaryContainer.Name == a2aPrimaryContainerName,
"Resource name can not be different.");
var recoveryContainer =
client.ReplicationProtectionContainers.Create(
a2aRecoveryFabricName,
a2aRecoveryContainerName,
createProtectionContainerInput);
Assert.True(
recoveryContainer.Name == a2aRecoveryContainerName,
"Resource name can not be different.");
}
}
[Fact]
public void CreateA2AContainerMappings()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var createProtectionContainerMappingInput =
new CreateProtectionContainerMappingInput
{
Properties = new CreateProtectionContainerMappingInputProperties()
};
var policy = client.ReplicationPolicies.Get(a2aPolicyName);
var primaryContainer =
client.ReplicationProtectionContainers.Get(
a2aPrimaryFabricName,
a2aPrimaryContainerName);
var recoveryContainer =
client.ReplicationProtectionContainers.Get(
a2aRecoveryFabricName,
a2aRecoveryContainerName);
// Create primary to recovery container mapping
createProtectionContainerMappingInput.Properties.PolicyId = policy.Id;
createProtectionContainerMappingInput.Properties.TargetProtectionContainerId =
recoveryContainer.Id;
createProtectionContainerMappingInput.Properties.ProviderSpecificInput =
new ReplicationProviderSpecificContainerMappingInput();
var primaryRecoveryContainerMapping =
client.ReplicationProtectionContainerMappings.Create(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aPrimaryRecoveryContainerMappingName,
createProtectionContainerMappingInput);
Assert.True(
primaryRecoveryContainerMapping.Name == a2aPrimaryRecoveryContainerMappingName,
"Resource name can not be different.");
// Create primary to recovery container mapping
createProtectionContainerMappingInput.Properties.TargetProtectionContainerId =
primaryContainer.Id;
var recoveryPrimaryContainerMapping =
client.ReplicationProtectionContainerMappings.Create(
a2aRecoveryFabricName,
a2aRecoveryContainerName,
a2aRecoveryPrimaryContainerMappingName,
createProtectionContainerMappingInput);
Assert.True(
recoveryPrimaryContainerMapping.Name == a2aRecoveryPrimaryContainerMappingName,
"Resource name can not be different.");
}
}
[Fact]
public void CreateA2AReplicationProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var policy = client.ReplicationPolicies.Get(a2aPolicyName);
var recoveryContainer =
client.ReplicationProtectionContainers.Get(
a2aRecoveryFabricName,
a2aRecoveryContainerName);
var a2aEnableProtectionInput = new A2AEnableProtectionInput();
a2aEnableProtectionInput.FabricObjectId = a2aVirtualMachineToProtect;
a2aEnableProtectionInput.RecoveryContainerId = recoveryContainer.Id;
a2aEnableProtectionInput.RecoveryResourceGroupId = a2aRecoveryResourceGroup;
a2aEnableProtectionInput.VmManagedDisks = new List<A2AVmManagedDiskInputDetails>();
var a2aVmManagedDiskInputDetails = new A2AVmManagedDiskInputDetails
{
DiskId = a2aVirtualMachineDiskToProtect,
PrimaryStagingAzureStorageAccountId = a2aStagingStorageAccount,
RecoveryResourceGroupId = a2aRecoveryResourceGroup,
RecoveryTargetDiskAccountType = "Standard_LRS",
RecoveryReplicaDiskAccountType = "Standard_LRS"
};
a2aEnableProtectionInput.VmManagedDisks.Add(a2aVmManagedDiskInputDetails);
var enableProtectionInput = new EnableProtectionInput
{
Properties = new EnableProtectionInputProperties()
};
enableProtectionInput.Properties.PolicyId = policy.Id;
enableProtectionInput.Properties.ProviderSpecificDetails = a2aEnableProtectionInput;
var replicationProtectedItem =
client.ReplicationProtectedItems.Create(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aReplicationProtectedItemName,
enableProtectionInput);
Assert.True(
replicationProtectedItem.Name == a2aReplicationProtectedItemName,
"Resource name can not be different.");
}
}
[Fact]
public void GetA2AResources()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var policy = client.ReplicationPolicies.Get(a2aPolicyName);
Assert.True(policy.Name == a2aPolicyName, "Resource name can not be different.");
var primaryFabric = client.ReplicationFabrics.Get(a2aPrimaryFabricName);
Assert.True(
primaryFabric.Name == a2aPrimaryFabricName,
"Resource name can not be different.");
var recoveryFabric = client.ReplicationFabrics.Get(a2aRecoveryFabricName);
Assert.True(
recoveryFabric.Name == a2aRecoveryFabricName,
"Resource name can not be different.");
var primaryContainer =
client.ReplicationProtectionContainers.Get(
a2aPrimaryFabricName,
a2aPrimaryContainerName);
Assert.True(
primaryContainer.Name == a2aPrimaryContainerName,
"Resource name can not be different.");
var recoveryContainer =
client.ReplicationProtectionContainers.Get(
a2aRecoveryFabricName,
a2aRecoveryContainerName);
Assert.True(
recoveryContainer.Name == a2aRecoveryContainerName,
"Resource name can not be different.");
var primaryRecoveryContainerMapping =
client.ReplicationProtectionContainerMappings.Get(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aPrimaryRecoveryContainerMappingName);
Assert.True(
primaryRecoveryContainerMapping.Name == a2aPrimaryRecoveryContainerMappingName,
"Resource name can not be different.");
var recoveryPrimaryContainerMapping =
client.ReplicationProtectionContainerMappings.Get(
a2aRecoveryFabricName,
a2aRecoveryContainerName,
a2aRecoveryPrimaryContainerMappingName);
Assert.True(
recoveryPrimaryContainerMapping.Name == a2aRecoveryPrimaryContainerMappingName,
"Resource name can not be different.");
var replicationProtectedItem =
client.ReplicationProtectedItems.Get(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aReplicationProtectedItemName);
Assert.True(
replicationProtectedItem.Name == a2aReplicationProtectedItemName,
"Resource name can not be different.");
}
}
[Fact]
public void ListA2AResources()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var policies= client.ReplicationPolicies.List();
Assert.True(policies.Count() == 1, "Only 1 policy got created via test.");
var fabrics = client.ReplicationFabrics.List();
Assert.True(fabrics.Count() == 2, "Only 2 fabrics got created via test.");
var containers = client.ReplicationProtectionContainers.List();
Assert.True(containers.Count() == 2, "Only 2 containers got created via test.");
var containerMappings =
client.ReplicationProtectionContainerMappings.List();
Assert.True(
containerMappings.Count() == 2,
"Only 2 container mappings got created via test.");
var replicationProtectedItems = client.ReplicationProtectedItems.List();
Assert.True(
replicationProtectedItems.Count() == 1,
"Only 1 replicationProtectedItem got created via test.");
}
}
[Fact]
public void DeleteA2AReplicationProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var disableProtectionInput = new DisableProtectionInput
{
Properties = new DisableProtectionInputProperties()
};
disableProtectionInput.Properties.ReplicationProviderInput =
new DisableProtectionProviderSpecificInput();
client.ReplicationProtectedItems.Delete(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aReplicationProtectedItemName,
disableProtectionInput);
var replicationProtectedItems = client.ReplicationProtectedItems.List();
Assert.True(
replicationProtectedItems.Count() == 0,
"Delted the replicationProtectedItem that got created via test.");
}
}
[Fact]
public void DeleteA2AContainerMappings()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var removeProtectionContainerMappingInput =
new RemoveProtectionContainerMappingInput
{
Properties = new RemoveProtectionContainerMappingInputProperties()
};
removeProtectionContainerMappingInput.Properties.ProviderSpecificInput =
new ReplicationProviderContainerUnmappingInput();
client.ReplicationProtectionContainerMappings.Delete(
a2aPrimaryFabricName,
a2aPrimaryContainerName,
a2aPrimaryRecoveryContainerMappingName,
removeProtectionContainerMappingInput);
client.ReplicationProtectionContainerMappings.Delete(
a2aRecoveryFabricName,
a2aRecoveryContainerName,
a2aRecoveryPrimaryContainerMappingName,
removeProtectionContainerMappingInput);
var containerMappings = client.ReplicationProtectionContainerMappings.List();
Assert.True(
containerMappings.Count() == 0,
"Delted 2 container mappings that got created via test.");
}
}
[Fact]
public void DeleteA2AContainers()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
client.ReplicationProtectionContainers.Delete(
a2aPrimaryFabricName,
a2aPrimaryContainerName);
client.ReplicationProtectionContainers.Delete(
a2aRecoveryFabricName,
a2aRecoveryContainerName);
var containers = client.ReplicationProtectionContainers.List();
Assert.True(
containers.Count() == 0,
"Delted 2 containers that got created via test.");
}
}
[Fact]
public void DeleteA2AFabrics()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
client.ReplicationFabrics.Delete(a2aPrimaryFabricName);
client.ReplicationFabrics.Delete(a2aRecoveryFabricName);
var fabrics = client.ReplicationFabrics.List();
Assert.True(fabrics.Count() == 0, "Delted 2 fabrics that got created via test.");
}
}
[Fact]
public void DeleteA2APolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
client.ReplicationPolicies.Delete(a2aPolicyName);
var policies = client.ReplicationPolicies.List();
Assert.True(policies.Count() == 0, "Delted the policy that got created via test.");
}
}
[Fact]
public void CreateA2AReplicationProtectionIntent()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var a2aCreateProtectionIntentInput = new A2ACreateProtectionIntentInput();
a2aCreateProtectionIntentInput.FabricObjectId = a2aVirtualMachineToProtect;
a2aCreateProtectionIntentInput.AutoProtectionOfDataDisk = "Enabled";
a2aCreateProtectionIntentInput.PrimaryLocation = a2aPrimaryLocation;
a2aCreateProtectionIntentInput.RecoveryLocation = a2aRecoveryLocation;
a2aCreateProtectionIntentInput.RecoverySubscriptionId = "b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c";
a2aCreateProtectionIntentInput.RecoveryResourceGroupId = a2aRecoveryResourceGroup;
a2aCreateProtectionIntentInput.RecoveryAvailabilityType = "Single";
a2aCreateProtectionIntentInput.ProtectionProfileCustomInput = new NewProtectionProfile
{
PolicyName = "intentPolicy",
RecoveryPointHistory = 1440,
CrashConsistentFrequencyInMinutes = 10,
AppConsistentFrequencyInMinutes = 60,
MultiVmSyncStatus = "Enable"
};
var createProtectionIntentInput = new CreateProtectionIntentInput
{
Properties = new CreateProtectionIntentProperties()
};
createProtectionIntentInput.Properties.ProviderSpecificDetails = a2aCreateProtectionIntentInput;
var replicationProtectionIntent =
client.ReplicationProtectionIntents.Create(
a2aReplicationProtectionIntentName,
createProtectionIntentInput);
Assert.True(
replicationProtectionIntent.Name == a2aReplicationProtectionIntentName,
"Resource name can not be different.");
}
}
[Fact]
public void ListA2AProtectionIntents()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var protectionItents = client.ReplicationProtectionIntents.List();
}
}
[Fact]
public void GetA2AProtectionIntent()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "sdkVTRG", "sdkVault1");
var client = testHelper.SiteRecoveryClient;
var protectionItent = client.ReplicationProtectionIntents.Get(a2aReplicationProtectionIntentName);
}
}
[Fact]
public void CreateSite()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
FabricCreationInput siteInput = new FabricCreationInput();
siteInput.Properties = new FabricCreationInputProperties();
var client = testHelper.SiteRecoveryClient;
var site = client.ReplicationFabrics.Create(siteName, siteInput);
var response = client.ReplicationFabrics.Get(siteName);
Assert.True(response.Name == siteName, "Site Name can not be different");
}
}
[Fact]
public void GetSite()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
Assert.NotNull(fabric.Id);
}
}
[Fact]
public void ListSite()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabricList = client.ReplicationFabrics.List();
Assert.True(fabricList.Count() > 0, "Atleast one fabric should be present");
}
}
[Fact]
public void DeleteSite()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationFabrics.Delete(siteName);
}
}
[Fact]
public void PurgeSite()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationFabrics.Purge(siteName);
}
}
[Fact]
public void CheckConsistency()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationFabrics.CheckConsistency(siteName);
var fabric = client.ReplicationFabrics.Get(siteName);
}
}
[Fact]
public void RenewCertificate()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RenewCertificateInputProperties inputProperties = new RenewCertificateInputProperties()
{
RenewCertificateType = "Cloud"
};
RenewCertificateInput input = new RenewCertificateInput()
{
Properties = inputProperties
};
client.ReplicationFabrics.RenewCertificate(siteName, input);
var fabric = client.ReplicationFabrics.Get(siteName);
}
}
[Fact]
public void GetRSP()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var recoveryServivesProviderResponse =
client.ReplicationRecoveryServicesProviders.Get(fabric.Name, providerName);
Assert.NotNull(recoveryServivesProviderResponse.Properties.FriendlyName);
Assert.NotNull(recoveryServivesProviderResponse.Name);
Assert.NotNull(recoveryServivesProviderResponse.Id);
}
}
[Fact]
public void ListRspByFabric()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var rspList = client.ReplicationRecoveryServicesProviders.ListByReplicationFabrics(fabric.Name);
Assert.True(rspList.Count() > 0, "Atleast one replication recovery services provider should be present");
}
}
[Fact]
public void ListRsp()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var rspList = client.ReplicationRecoveryServicesProviders.List();
Assert.True(rspList.Count() > 0, "Atleast one replication recovery services provider should be present");
}
}
[Fact]
public void DeleteRsp()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
client.ReplicationRecoveryServicesProviders.Delete(fabric.Name, providerName);
}
}
[Fact]
public void PurgeRsp()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var purgeProviderName = "d4f5707e-16df-4e60-92df-fea789694c62";
var fabric = client.ReplicationFabrics.Get(siteName);
client.ReplicationRecoveryServicesProviders.Purge(fabric.Name, purgeProviderName);
}
}
[Fact]
public void RefreshRsp()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
client.ReplicationRecoveryServicesProviders.RefreshProvider(fabric.Name, providerName);
var rsp = client.ReplicationRecoveryServicesProviders.Get(fabric.Name, providerName);
Assert.NotNull(rsp.Id);
}
}
[Fact]
public void GetContainer()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabricResponse = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabricResponse.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabricResponse.Name,
protectionContainerList.FirstOrDefault().Name);
Assert.NotNull(protectionContainer.Properties.FriendlyName);
Assert.NotNull(protectionContainer.Name);
Assert.NotNull(protectionContainer.Id);
}
}
[Fact]
public void EnumerateContainer()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabricResponse = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabricResponse.Name).ToList();
Assert.True(protectionContainerList.Count > 0, "Atleast one container should be present.");
}
}
[Fact]
public void ListAllContainers()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabricResponse = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.List().ToList();
Assert.True(protectionContainerList.Count > 0, "Atleast one container should be present.");
}
}
[Fact]
public void CreatePolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
HyperVReplicaAzurePolicyInput h2ASpecificInput = new HyperVReplicaAzurePolicyInput()
{
RecoveryPointHistoryDuration = 4,
ApplicationConsistentSnapshotFrequencyInHours = 2,
ReplicationInterval = 300,
OnlineReplicationStartTime = null,
StorageAccounts = new List<string>() { storageAccountId }
};
CreatePolicyInputProperties inputProperties = new CreatePolicyInputProperties()
{
ProviderSpecificInput = h2ASpecificInput
};
CreatePolicyInput input = new CreatePolicyInput()
{
Properties = inputProperties
};
var response = client.ReplicationPolicies.Create(policyName, input);
var policy = client.ReplicationPolicies.Get(policyName);
}
}
[Fact]
public void GetPolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var policy = client.ReplicationPolicies.Get(policyName);
Assert.NotNull(policy.Id);
Assert.NotNull(policy.Name);
}
}
[Fact]
public void ListPolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var policyList = client.ReplicationPolicies.List();
}
}
[Fact]
public void UpdatePolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
HyperVReplicaAzurePolicyInput h2ASpecificInput = new HyperVReplicaAzurePolicyInput()
{
RecoveryPointHistoryDuration = 3,
ApplicationConsistentSnapshotFrequencyInHours = 2,
ReplicationInterval = 300,
OnlineReplicationStartTime = null,
StorageAccounts = new List<string>() { "/subscriptions/b364ed8d-4279-4bf8-8fd1-56f8fa0ae05c/resourceGroups/Arpita-air/providers/Microsoft.Storage/storageAccounts/sah2atest2" }
};
UpdatePolicyInputProperties inputProperties = new UpdatePolicyInputProperties()
{
ReplicationProviderSettings = h2ASpecificInput
};
UpdatePolicyInput input = new UpdatePolicyInput()
{
Properties = inputProperties
};
var policy = client.ReplicationPolicies.Update(policyName, input);
var response = client.ReplicationPolicies.Get(policyName);
Assert.NotNull(response.Id);
Assert.NotNull(response.Name);
}
}
[Fact]
public void DeletePolicy()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationPolicies.Delete(policyName);
}
}
[Fact]
public void CreatePCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name,
protectionContainerList.FirstOrDefault().Name);
var policy = client.ReplicationPolicies.Get(policyName);
CreateProtectionContainerMappingInputProperties containerMappingInputProperties =
new CreateProtectionContainerMappingInputProperties()
{
PolicyId = policy.Id,
ProviderSpecificInput = new ReplicationProviderSpecificContainerMappingInput(),
TargetProtectionContainerId = recoveryCloud
};
CreateProtectionContainerMappingInput containerMappingInput = new CreateProtectionContainerMappingInput()
{
Properties = containerMappingInputProperties
};
var response = client.ReplicationProtectionContainerMappings.Create(
fabric.Name, protectionContainer.Name, protectionContainerMappingName, containerMappingInput);
var protectionContainerMapping = client.ReplicationProtectionContainerMappings.Get(
fabric.Name, protectionContainer.Name, protectionContainerMappingName);
Assert.NotNull(protectionContainerMapping.Id);
}
}
[Fact]
public void GetPCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name,
protectionContainerList.FirstOrDefault().Name);
var protectionContainerMapping = client.ReplicationProtectionContainerMappings.Get(
fabric.Name, protectionContainer.Name, protectionContainerMappingName);
Assert.NotNull(protectionContainerMapping.Id);
}
}
[Fact]
public void EnumeratePCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault();
var protectionContainerMapping = client.ReplicationProtectionContainerMappings.ListByReplicationProtectionContainers(fabric.Name, protectionContainer.Name);
}
}
[Fact]
public void ListAllPCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainerMapping = client.ReplicationProtectionContainerMappings.List();
}
}
[Fact]
public void DeletePCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name,
protectionContainerList.FirstOrDefault().Name);
client.ReplicationProtectionContainerMappings.Delete(
fabric.Name, protectionContainer.Name, protectionContainerMappingName, new RemoveProtectionContainerMappingInput());
}
}
[Fact]
public void PurgePCMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault();
client.ReplicationProtectionContainerMappings.Purge(fabric.Name, protectionContainer.Name, protectionContainerMappingName);
}
}
[Fact]
public void GetProtectableItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name,
protectionContainerList.FirstOrDefault().Name);
var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers(
fabric.Name, protectionContainer.Name);
var protectableItem = protectableItemList.First(item =>
item.Properties.FriendlyName.Equals(vmName, StringComparison.OrdinalIgnoreCase));
Assert.NotNull(protectableItem.Id);
}
}
[Fact]
public void EnumerateProtectableItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(fabric.Name,
protectionContainerList.FirstOrDefault().Name);
var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers(
fabric.Name, protectionContainer.Name).ToList();
Assert.True(protectableItemList.Count > 0, "Atleast one protectable item should be present.");
}
}
[Fact]
public void CreateProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var policy = client.ReplicationPolicies.Get(policyName);
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(fabric.Name).FirstOrDefault();
var protectableItemList = client.ReplicationProtectableItems.ListByReplicationProtectionContainers(
fabric.Name, protectionContainer.Name).ToList();
var protectableItem = protectableItemList.First(item =>
item.Properties.FriendlyName.Equals(vmName2, StringComparison.OrdinalIgnoreCase));
var vhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails[0].VhdId;
DiskDetails osDisk = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails
.FirstOrDefault(item => item.VhdType == "OperatingSystem");
if (osDisk != null)
{
vhdId = osDisk.VhdId;
}
HyperVReplicaAzureEnableProtectionInput h2AEnableDRInput =
new HyperVReplicaAzureEnableProtectionInput()
{
HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId,
OsType = "Windows",
VhdId = vhdId,
VmName = protectableItem.Properties.FriendlyName,
TargetStorageAccountId = (policy.Properties.ProviderSpecificDetails as HyperVReplicaAzurePolicyDetails)
.ActiveStorageAccountId,
TargetAzureV2ResourceGroupId = targetResourceGroup,
TargetAzureVmName = protectableItem.Properties.FriendlyName
};
EnableProtectionInputProperties enableDRInputProperties = new EnableProtectionInputProperties()
{
PolicyId = policy.Id,
ProtectableItemId = protectableItem.Id,
ProviderSpecificDetails = h2AEnableDRInput
};
EnableProtectionInput enableDRInput = new EnableProtectionInput()
{
Properties = enableDRInputProperties
};
client.ReplicationProtectedItems.Create(fabric.Name, protectionContainer.Name, protectableItem.Properties.FriendlyName, enableDRInput);
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
}
}
[Fact]
public void GetProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainerList =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).ToList();
var protectionContainer = client.ReplicationProtectionContainers.Get(siteName,
protectionContainerList.FirstOrDefault().Name);
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmId);
Assert.NotNull(protectedItem.Id);
}
}
[Fact]
public void EnumerateProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItemsList = client.ReplicationProtectedItems.ListByReplicationProtectionContainers(siteName, protectionContainer.Name);
Assert.NotNull(protectedItemsList);
}
}
[Fact]
public void ListAllProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectedItemsList = client.ReplicationProtectedItems.List();
Assert.NotNull(protectedItemsList);
}
}
[Fact]
public void UpdateProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
var ipconfig = new IPConfigInputDetails{
RecoverySubnetName = "Subnet1"
};
var ipconfigs = new List<IPConfigInputDetails>();
ipconfigs.Add(ipconfig);
VMNicInputDetails nicInput = new VMNicInputDetails()
{
NicId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails).VmNics[0].NicId,
IpConfigs = ipconfigs,
SelectionType = "SelectedByUser"
};
UpdateReplicationProtectedItemInputProperties updateInputProperties = new UpdateReplicationProtectedItemInputProperties()
{
RecoveryAzureVMName = protectedItem.Properties.FriendlyName,
RecoveryAzureVMSize = "Basic_A0",
SelectedRecoveryAzureNetworkId = azureNetworkId,
VmNics = new List<VMNicInputDetails>() { nicInput },
LicenseType = LicenseType.WindowsServer,
ProviderSpecificDetails = new HyperVReplicaAzureUpdateReplicationProtectedItemInput()
{
RecoveryAzureV2ResourceGroupId = targetResourceGroup
}
};
UpdateReplicationProtectedItemInput updateInput = new UpdateReplicationProtectedItemInput()
{
Properties = updateInputProperties
};
var response = client.ReplicationProtectedItems.Update(siteName, protectionContainer.Name, vmName2, updateInput);
var updatedProtecteditem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
}
}
[Fact]
public void DeleteProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
DisableProtectionInputProperties inputProperties = new DisableProtectionInputProperties()
{
DisableProtectionReason = DisableProtectionReason.NotSpecified,
ReplicationProviderInput = new DisableProtectionProviderSpecificInput()
};
DisableProtectionInput input = new DisableProtectionInput()
{
Properties = inputProperties
};
client.ReplicationProtectedItems.Delete(siteName, protectionContainer.Name, vmName2, input);
}
}
[Fact]
public void PurgeProtectedItem()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
client.ReplicationProtectedItems.Purge(siteName, protectionContainer.Name, vmId);
}
}
[Fact]
public void RepairReplication()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
client.ReplicationProtectedItems.RepairReplication(siteName, protectionContainer.Name, vmName2);
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
Assert.NotNull(protectedItem.Id);
}
}
[Fact]
public void TestFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmId);
string networkId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails)
.SelectedRecoveryAzureNetworkId;
HyperVReplicaAzureTestFailoverInput h2AFOInput = new HyperVReplicaAzureTestFailoverInput();
TestFailoverInputProperties tfoInputProperties = new TestFailoverInputProperties()
{
NetworkId = networkId,
NetworkType = string.IsNullOrEmpty(networkId) ? null : "VmNetworkAsInput",
ProviderSpecificDetails = h2AFOInput
};
TestFailoverInput tfoInput = new TestFailoverInput()
{
Properties = tfoInputProperties
};
var response = client.ReplicationProtectedItems.TestFailover(siteName, protectionContainer.Name, vmId, tfoInput);
}
}
[Fact]
public void TestFailoverCleanup()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmId);
TestFailoverCleanupInputProperties inputProperties = new TestFailoverCleanupInputProperties()
{
Comments = "Cleaning up"
};
TestFailoverCleanupInput input = new TestFailoverCleanupInput()
{
Properties = inputProperties
};
client.ReplicationProtectedItems.TestFailoverCleanup(
siteName, protectionContainer.Name, vmId, input);
}
}
[Fact]
public void PlannedFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
PlannedFailoverInputProperties inputProperties = new PlannedFailoverInputProperties();
if (protectedItem.Properties.ActiveLocation == "Recovery")
{
HyperVReplicaAzureFailbackProviderInput h2AFailbackInput = new HyperVReplicaAzureFailbackProviderInput()
{
RecoveryVmCreationOption = "NoAction",
DataSyncOption = "ForSynchronization"
};
inputProperties.ProviderSpecificDetails = h2AFailbackInput;
}
else
{
HyperVReplicaAzurePlannedFailoverProviderInput h2AFailoverInput = new HyperVReplicaAzurePlannedFailoverProviderInput();
inputProperties.ProviderSpecificDetails = h2AFailoverInput;
}
PlannedFailoverInput input = new PlannedFailoverInput()
{
Properties = inputProperties
};
client.ReplicationProtectedItems.PlannedFailover(siteName, protectionContainer.Name, vmName2, input);
}
}
[Fact]
public void UnplannedFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
HyperVReplicaAzureUnplannedFailoverInput h2AFailoverInput = new HyperVReplicaAzureUnplannedFailoverInput();
UnplannedFailoverInputProperties inputProperties = new UnplannedFailoverInputProperties()
{
FailoverDirection = "PrimaryToRecovery",
SourceSiteOperations = "NotRequired",
ProviderSpecificDetails = h2AFailoverInput
};
UnplannedFailoverInput input = new UnplannedFailoverInput()
{
Properties = inputProperties
};
var response = client.ReplicationProtectedItems.UnplannedFailover(siteName, protectionContainer.Name, vmName2, input);
var updatedProtectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
}
}
[Fact]
public void CommitFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
client.ReplicationProtectedItems.FailoverCommit(siteName, protectionContainer.Name, vmName2);
}
}
[Fact]
public void Reprotect()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectableItem = client.ReplicationProtectableItems.ListByReplicationProtectionContainers(
siteName, protectionContainer.Name).FirstOrDefault(item =>
item.Properties.FriendlyName.Equals(vmName2, StringComparison.OrdinalIgnoreCase));
var protectedItem = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
var vhdId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails[0].VhdId;
DiskDetails osDisk = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).DiskDetails
.FirstOrDefault(item => item.VhdType == "OperatingSystem");
if (osDisk != null)
{
vhdId = osDisk.VhdId;
}
HyperVReplicaAzureReprotectInput h2AInput = new HyperVReplicaAzureReprotectInput()
{
HvHostVmId = (protectableItem.Properties.CustomDetails as HyperVVirtualMachineDetails).SourceItemId,
OsType = "Windows",
VHDId = vhdId,
VmName = protectableItem.Properties.FriendlyName,
StorageAccountId = (protectedItem.Properties.ProviderSpecificDetails as HyperVReplicaAzureReplicationDetails).RecoveryAzureStorageAccount
};
ReverseReplicationInputProperties inputProperties = new ReverseReplicationInputProperties()
{
FailoverDirection = "PrimaryToRecovery",
ProviderSpecificDetails = h2AInput
};
ReverseReplicationInput input = new ReverseReplicationInput()
{
Properties = inputProperties
};
client.ReplicationProtectedItems.Reprotect(siteName, protectionContainer.Name, vmName2, input);
}
}
[Fact]
public void GetRecoveryPoints()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmName2).ToList();
var recoveryPoint = client.RecoveryPoints.Get(siteName, protectionContainer.Name, vmName2, rps[rps.Count() / 2].Name);
}
}
[Fact]
public void ListRecoveryPoints()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmId);
}
}
[Fact]
public void ApplyRecoveryPoint()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var protectionContainer =
client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var rps = client.RecoveryPoints.ListByReplicationProtectedItems(siteName, protectionContainer.Name, vmName2).ToList();
HyperVReplicaAzureApplyRecoveryPointInput h2APitInput = new HyperVReplicaAzureApplyRecoveryPointInput();
ApplyRecoveryPointInputProperties inputProperties = new ApplyRecoveryPointInputProperties()
{
RecoveryPointId = rps[rps.Count()/2].Id,
ProviderSpecificDetails = h2APitInput
};
ApplyRecoveryPointInput input = new ApplyRecoveryPointInput()
{
Properties = inputProperties
};
client.ReplicationProtectedItems.ApplyRecoveryPoint(siteName, protectionContainer.Name, vmName2, input);
}
}
[Fact]
public void CreateRecoveryPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem1 = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmId);
RecoveryPlanProtectedItem rpVm1 = new RecoveryPlanProtectedItem()
{
Id = protectedItem1.Id,
VirtualMachineId = protectedItem1.Name
};
RecoveryPlanGroup rpGroup = new RecoveryPlanGroup()
{
GroupType = RecoveryPlanGroupType.Boot,
ReplicationProtectedItems = new List<RecoveryPlanProtectedItem>() { rpVm1},
StartGroupActions = new List<RecoveryPlanAction>(),
EndGroupActions = new List<RecoveryPlanAction>()
};
CreateRecoveryPlanInputProperties inputProperties = new CreateRecoveryPlanInputProperties()
{
PrimaryFabricId = fabric.Id,
RecoveryFabricId = recoveryCloud,
FailoverDeploymentModel = FailoverDeploymentModel.ResourceManager,
Groups = new List<RecoveryPlanGroup>() { rpGroup }
};
CreateRecoveryPlanInput input = new CreateRecoveryPlanInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.Create(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void GetRecoveryPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void UpdateRecoveryPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var fabric = client.ReplicationFabrics.Get(siteName);
var protectionContainer = client.ReplicationProtectionContainers.ListByReplicationFabrics(siteName).FirstOrDefault();
var protectedItem2 = client.ReplicationProtectedItems.Get(siteName, protectionContainer.Name, vmName2);
RecoveryPlanProtectedItem rpVm2 = new RecoveryPlanProtectedItem()
{
Id = protectedItem2.Id,
VirtualMachineId = protectedItem2.Name
};
RecoveryPlanGroup rpGroup = new RecoveryPlanGroup()
{
GroupType = RecoveryPlanGroupType.Boot,
ReplicationProtectedItems = new List<RecoveryPlanProtectedItem>() { rpVm2 },
StartGroupActions = new List<RecoveryPlanAction>(),
EndGroupActions = new List<RecoveryPlanAction>()
};
UpdateRecoveryPlanInputProperties inputProperties = new UpdateRecoveryPlanInputProperties()
{
Groups = new List<RecoveryPlanGroup>() { rpGroup }
};
UpdateRecoveryPlanInput input = new UpdateRecoveryPlanInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.Update(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void DeleteRecoveryPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationRecoveryPlans.Delete(rpName);
}
}
[Fact]
public void RPTestFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput();
RecoveryPlanTestFailoverInputProperties inputProperties = new RecoveryPlanTestFailoverInputProperties()
{
NetworkId = azureNetworkId,
FailoverDirection = PossibleOperationsDirections.PrimaryToRecovery,
NetworkType = string.IsNullOrEmpty(azureNetworkId) ? null : "VmNetworkAsInput",
ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput }
};
RecoveryPlanTestFailoverInput input = new RecoveryPlanTestFailoverInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.TestFailover(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPTestFailoverCleanup()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RecoveryPlanTestFailoverCleanupInputProperties inputProperties = new RecoveryPlanTestFailoverCleanupInputProperties()
{
Comments = "Cleaning up"
};
RecoveryPlanTestFailoverCleanupInput input = new RecoveryPlanTestFailoverCleanupInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.TestFailoverCleanup(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPPlannedFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput();
RecoveryPlanPlannedFailoverInputProperties inputProperties = new RecoveryPlanPlannedFailoverInputProperties()
{
FailoverDirection = PossibleOperationsDirections.PrimaryToRecovery,
ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput }
};
RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.PlannedFailover(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPUnplannedFailover()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RecoveryPlanHyperVReplicaAzureFailoverInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailoverInput();
RecoveryPlanUnplannedFailoverInputProperties inputProperties = new RecoveryPlanUnplannedFailoverInputProperties()
{
FailoverDirection = PossibleOperationsDirections.PrimaryToRecovery,
SourceSiteOperations = SourceSiteOperations.NotRequired,
ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput }
};
RecoveryPlanUnplannedFailoverInput input = new RecoveryPlanUnplannedFailoverInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.UnplannedFailover(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPFailoverCommit()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationRecoveryPlans.FailoverCommit(rpName);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPFailback()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
RecoveryPlanHyperVReplicaAzureFailbackInput h2AInput = new RecoveryPlanHyperVReplicaAzureFailbackInput()
{
DataSyncOption = DataSyncStatus.ForSynchronization,
RecoveryVmCreationOption = AlternateLocationRecoveryOption.NoAction
};
RecoveryPlanPlannedFailoverInputProperties inputProperties = new RecoveryPlanPlannedFailoverInputProperties()
{
FailoverDirection = PossibleOperationsDirections.RecoveryToPrimary,
ProviderSpecificDetails = new List<RecoveryPlanProviderSpecificFailoverInput>() { h2AInput }
};
RecoveryPlanPlannedFailoverInput input = new RecoveryPlanPlannedFailoverInput()
{
Properties = inputProperties
};
client.ReplicationRecoveryPlans.PlannedFailover(rpName, input);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void RPReprotect()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationRecoveryPlans.Reprotect(rpName);
var rp = client.ReplicationRecoveryPlans.Get(rpName);
}
}
[Fact]
public void CreateAlertSettings()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
ConfigureAlertRequestProperties properties = new ConfigureAlertRequestProperties()
{
SendToOwners = false.ToString(),
CustomEmailAddresses = new List<string>() { emailAddress },
Locale = "en-US"
};
ConfigureAlertRequest request = new ConfigureAlertRequest()
{
Properties = properties
};
client.ReplicationAlertSettings.Create(alertSettingName, request);
var alertSetting = client.ReplicationAlertSettings.Get(alertSettingName);
}
}
[Fact]
public void GetAlertSettings()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var alertSetting = client.ReplicationAlertSettings.Get(alertSettingName);
}
}
[Fact]
public void ListAlertSettings()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var alertSetting = client.ReplicationAlertSettings.List();
}
}
[Fact(Skip = "Understand test scenario")]
public void GetReplicationEvent()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var events = client.ReplicationEvents.List().ToList();
var replicationEvent = client.ReplicationEvents.Get(events[0].Name);
}
}
[Fact]
public void ListReplicationEvent()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var events = client.ReplicationEvents.List();
}
}
[Fact]
public void GetNetworks()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var network = client.ReplicationNetworks.Get(vmmFabric, vmNetworkName);
}
}
[Fact]
public void ListNetworks()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var networkList = client.ReplicationNetworks.List();
}
}
[Fact]
public void EnumerateNetworks()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var networkList = client.ReplicationNetworks.ListByReplicationFabrics(vmmFabric);
}
}
[Fact]
public void CreateNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var network = client.ReplicationNetworks.Get(vmmFabric, vmNetworkName);
CreateNetworkMappingInputProperties inputProperties = new CreateNetworkMappingInputProperties()
{
RecoveryFabricName = recoveryCloud,
RecoveryNetworkId = azureNetworkId,
FabricSpecificDetails = new VmmToAzureCreateNetworkMappingInput()
};
CreateNetworkMappingInput input = new CreateNetworkMappingInput()
{
Properties = inputProperties
};
client.ReplicationNetworkMappings.Create(vmmFabric, vmNetworkName, networkMappingName, input);
var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName);
}
}
[Fact]
public void GetNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName);
}
}
[Fact]
public void ListNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var networkMappingList = client.ReplicationNetworkMappings.List();
}
}
[Fact]
public void EnumerateNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var networkMappingList = client.ReplicationNetworkMappings.ListByReplicationNetworks(vmmFabric, vmNetworkName);
}
}
[Fact]
public void UpdateNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
UpdateNetworkMappingInputProperties inputProperties = new UpdateNetworkMappingInputProperties()
{
RecoveryFabricName = recoveryCloud,
RecoveryNetworkId = azureNetworkId,
FabricSpecificDetails = new VmmToAzureUpdateNetworkMappingInput()
};
UpdateNetworkMappingInput input = new UpdateNetworkMappingInput()
{
Properties = inputProperties
};
client.ReplicationNetworkMappings.Update(vmmFabric, vmNetworkName, networkMappingName, input);
var networkMapping = client.ReplicationNetworkMappings.Get(vmmFabric, vmNetworkName, networkMappingName);
}
}
[Fact]
public void DeleteNetworkMapping()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationNetworkMappings.Delete(vmmFabric, vmNetworkName, networkMappingName);
}
}
[Fact]
public void ListEventByQuery()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
var querydata = new ODataQuery<EventQueryParameter>("Severity eq 'Critical'");
client.ReplicationEvents.List(querydata);
}
}
[Fact]
public void GetHealthDetails()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context);
var client = testHelper.SiteRecoveryClient;
client.ReplicationVaultHealth.Get();
}
}
[Fact]
public void GetReplicationEligibilityResults()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "testRg1", "");
var client = testHelper.SiteRecoveryClient;
var replicationEligibilityResults = client.ReplicationEligibilityResults.Get(a2aVirtualMachineToValidate);
Assert.NotNull(replicationEligibilityResults);
}
}
[Fact]
public void EnumerateReplicationEligibilityResults()
{
using (var context = MockContext.Start(this.GetType()))
{
testHelper.Initialize(context, "testRg1", "");
var client = testHelper.SiteRecoveryClient;
var replicationEligibilityResultsCollection = client.ReplicationEligibilityResults.List(a2aVirtualMachineToValidate);
Assert.NotNull(replicationEligibilityResultsCollection);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class SolutionCrawlerLogger
{
private const string Id = "Id";
private const string Kind = "Kind";
private const string Analyzer = "Analyzer";
private const string DocumentCount = "DocumentCount";
private const string Enabled = "Enabled";
private const string AnalyzerCount = "AnalyzerCount";
private const string PersistentStorage = "PersistentStorage";
private const string GlobalOperation = "GlobalOperation";
private const string HigherPriority = "HigherPriority";
private const string LowerPriority = "LowerPriority";
private const string TopLevel = "TopLevel";
private const string MemberLevel = "MemberLevel";
private const string NewWorkItem = "NewWorkItem";
private const string UpdateWorkItem = "UpdateWorkItem";
private const string ProjectEnqueue = "ProjectEnqueue";
private const string ResetStates = "ResetStates";
private const string ProjectNotExist = "ProjectNotExist";
private const string DocumentNotExist = "DocumentNotExist";
private const string ProcessProject = "ProcessProject";
private const string OpenDocument = "OpenDocument";
private const string CloseDocument = "CloseDocument";
private const string SolutionHash = "SolutionHash";
private const string ProcessDocument = "ProcessDocument";
private const string ProcessDocumentCancellation = "ProcessDocumentCancellation";
private const string ProcessProjectCancellation = "ProcessProjectCancellation";
private const string ActiveFileEnqueue = "ActiveFileEnqueue";
private const string ActiveFileProcessDocument = "ActiveFileProcessDocument";
private const string ActiveFileProcessDocumentCancellation = "ActiveFileProcessDocumentCancellation";
private const string Max = "Maximum";
private const string Min = "Minimum";
private const string Median = "Median";
private const string Mean = "Mean";
private const string Mode = "Mode";
private const string Range = "Range";
private const string Count = "Count";
public static void LogRegistration(int correlationId, Workspace workspace)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Kind] = workspace.Kind;
}));
}
public static void LogUnregistration(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogReanalyze(int correlationId, IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds)
{
Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
m[DocumentCount] = documentIds == null ? 0 : documentIds.Count();
}));
}
public static void LogOptionChanged(int correlationId, bool value)
{
Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Enabled] = value;
}));
}
public static void LogActiveFileAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer,
correlationId, workspace, reordered);
}
public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
LogAnalyzersWorker(
FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer,
correlationId, workspace, reordered);
}
private static void LogAnalyzersWorker(
FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered)
{
if (workspace.Kind == WorkspaceKind.Preview)
{
return;
}
// log registered analyzers.
Logger.Log(analyzersId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[AnalyzerCount] = reordered.Length;
}));
foreach (var analyzer in reordered)
{
Logger.Log(analyzerId, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
m[Analyzer] = analyzer.ToString();
}));
}
}
public static void LogWorkCoordiantorShutdownTimeout(int correlationId)
{
Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
}));
}
public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind)
{
logAggregator.IncreaseCount(kind);
}
public static void LogWorkCoordiantorShutdown(int correlationId, LogAggregator logAggregator)
{
Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m =>
{
m[Id] = correlationId;
foreach (var kv in logAggregator)
{
var change = ((WorkspaceChangeKind)kv.Key).ToString();
m[change] = kv.Value.GetCount();
}
}));
}
public static void LogGlobalOperation(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(GlobalOperation);
}
public static void LogActiveFileEnqueue(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ActiveFileEnqueue);
}
public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId projectId)
{
logAggregator.IncreaseCount(ProjectEnqueue);
}
public static void LogWorkItemEnqueue(
LogAggregator logAggregator, string language, DocumentId documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath activeMember, bool added)
{
logAggregator.IncreaseCount(language);
logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem);
if (documentId != null)
{
logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel);
if (lowPriority)
{
logAggregator.IncreaseCount(LowerPriority);
logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id));
}
}
foreach (var reason in reasons)
{
logAggregator.IncreaseCount(reason);
}
}
public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(HigherPriority);
logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId));
}
public static void LogResetStates(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ResetStates);
}
public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers)
{
Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m =>
{
var solutionHash = GetSolutionHash(solution);
m[Id] = correlationId;
m[SolutionHash] = solutionHash.ToString();
var statMap = new Dictionary<string, List<int>>();
foreach (var kv in logAggregator)
{
if (kv.Key is string)
{
m[kv.Key.ToString()] = kv.Value.GetCount();
continue;
}
if (kv.Key is ValueTuple<string, Guid>)
{
var tuple = (ValueTuple<string, Guid>)kv.Key;
var list = statMap.GetOrAdd(tuple.Item1, _ => new List<int>());
list.Add(kv.Value.GetCount());
continue;
}
throw ExceptionUtilities.Unreachable;
}
foreach (var kv in statMap)
{
var key = kv.Key.ToString();
var result = LogAggregator.GetStatistics(kv.Value);
m[CreateProperty(key, Max)] = result.Maximum;
m[CreateProperty(key, Min)] = result.Minimum;
m[CreateProperty(key, Median)] = result.Median;
m[CreateProperty(key, Mean)] = result.Mean;
m[CreateProperty(key, Mode)] = result.Mode;
m[CreateProperty(key, Range)] = result.Range;
m[CreateProperty(key, Count)] = result.Count;
}
}));
foreach (var analyzer in analyzers)
{
var diagIncrementalAnalyzer = analyzer as BaseDiagnosticIncrementalAnalyzer;
if (diagIncrementalAnalyzer != null)
{
diagIncrementalAnalyzer.LogAnalyzerCountSummary();
break;
}
}
}
private static int GetSolutionHash(Solution solution)
{
if (solution != null && solution.FilePath != null)
{
return solution.FilePath.ToLowerInvariant().GetHashCode();
}
return 0;
}
private static string CreateProperty(string parent, string child)
{
return parent + "." + child;
}
public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(CloseDocument);
logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId));
}
public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId)
{
logAggregator.IncreaseCount(OpenDocument);
logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId));
}
public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ActiveFileProcessDocument);
}
else
{
logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation);
}
}
public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessDocument);
}
else
{
logAggregator.IncreaseCount(ProcessDocumentCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId));
}
public static void LogProcessDocumentNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(DocumentNotExist);
}
public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed)
{
if (processed)
{
logAggregator.IncreaseCount(ProcessProject);
}
else
{
logAggregator.IncreaseCount(ProcessProjectCancellation);
}
logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId));
}
public static void LogProcessProjectNotExist(LogAggregator logAggregator)
{
logAggregator.IncreaseCount(ProjectNotExist);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography {
/// <summary>
/// Wrapper for NCrypt's implementation of elliptic curve DSA
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class ECDsaCng : ECDsa {
private static KeySizes[] s_legalKeySizes = new KeySizes[] { new KeySizes(256, 384, 128), new KeySizes(521, 521, 0) };
private CngKey m_key;
private CngAlgorithm m_hashAlgorithm = CngAlgorithm.Sha256;
//
// Constructors
//
public ECDsaCng() : this(521) {
Contract.Ensures(LegalKeySizesValue != null);
}
public ECDsaCng(int keySize) {
Contract.Ensures(LegalKeySizesValue != null);
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
LegalKeySizesValue = s_legalKeySizes;
KeySize = keySize;
}
[SecuritySafeCritical]
public ECDsaCng(CngKey key) {
Contract.Ensures(LegalKeySizesValue != null);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
if (key == null) {
throw new ArgumentNullException("key");
}
if (key.AlgorithmGroup != CngAlgorithmGroup.ECDsa) {
throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDsaRequiresECDsaKey), "key");
}
if (!NCryptNative.NCryptSupported) {
throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported));
}
LegalKeySizesValue = s_legalKeySizes;
// Make a copy of the key so that we continue to work if it gets disposed before this algorithm
//
// This requires an assert for UnmanagedCode since we'll need to access the raw handles of the key
// and the handle constructor of CngKey. The assert is safe since ECDsaCng will never expose the
// key handles to calling code (without first demanding UnmanagedCode via the Handle property of
// CngKey).
//
// We also need to dispose of the key handle since CngKey.Handle returns a duplicate
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
using (SafeNCryptKeyHandle keyHandle = key.Handle) {
Key = CngKey.Open(keyHandle, key.IsEphemeral ? CngKeyHandleOpenOptions.EphemeralKey : CngKeyHandleOpenOptions.None);
}
CodeAccessPermission.RevertAssert();
KeySize = m_key.KeySize;
}
/// <summary>
/// Hash algorithm to use when generating a signature over arbitrary data
/// </summary>
public CngAlgorithm HashAlgorithm {
get {
Contract.Ensures(Contract.Result<CngAlgorithm>() != null);
return m_hashAlgorithm;
}
set {
Contract.Ensures(m_hashAlgorithm != null);
if (value == null) {
throw new ArgumentNullException("value");
}
m_hashAlgorithm = value;
}
}
/// <summary>
/// Key to use for signing
/// </summary>
public CngKey Key {
get {
Contract.Ensures(Contract.Result<CngKey>() != null);
Contract.Ensures(Contract.Result<CngKey>().AlgorithmGroup == CngAlgorithmGroup.ECDsa);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
// If the size of the key no longer matches our stored value, then we need to replace it with
// a new key of the correct size.
if (m_key != null && m_key.KeySize != KeySize) {
m_key.Dispose();
m_key = null;
}
if (m_key == null) {
// Map the current key size to a CNG algorithm name
CngAlgorithm algorithm = null;
switch (KeySize) {
case 256:
algorithm = CngAlgorithm.ECDsaP256;
break;
case 384:
algorithm = CngAlgorithm.ECDsaP384;
break;
case 521:
algorithm = CngAlgorithm.ECDsaP521;
break;
default:
Debug.Assert(false, "Illegal key size set");
break;
}
m_key = CngKey.Create(algorithm);
}
return m_key;
}
private set {
Contract.Requires(value != null);
Contract.Ensures(m_key != null && m_key.AlgorithmGroup == CngAlgorithmGroup.ECDsa);
if (value.AlgorithmGroup != CngAlgorithmGroup.ECDsa) {
throw new ArgumentException(SR.GetString(SR.Cryptography_ArgECDsaRequiresECDsaKey));
}
if (m_key != null) {
m_key.Dispose();
}
//
// We do not duplicate the handle because the only time the user has access to the key itself
// to dispose underneath us is when they construct via the CngKey constructor, which does a
// copy. Otherwise all key lifetimes are controlled directly by the ECDsaCng class.
//
m_key = value;
KeySize = m_key.KeySize;
}
}
/// <summary>
/// Clean up the algorithm
/// </summary>
protected override void Dispose(bool disposing) {
try {
if (m_key != null) {
m_key.Dispose();
}
}
finally {
base.Dispose(disposing);
}
}
//
// XML Import
//
// #ECCXMLFormat
//
// There is currently not a standard XML format for ECC keys, so we will not implement the default
// To/FromXmlString so that we're not tied to one format when a standard one does exist. Instead we'll
// use an overload which allows the user to specify the format they'd like to serialize into.
//
// See code:System.Security.Cryptography.Rfc4050KeyFormatter#RFC4050ECKeyFormat for information about
// the currently supported format.
//
public override void FromXmlString(string xmlString) {
throw new NotImplementedException(SR.GetString(SR.Cryptography_ECXmlSerializationFormatRequired));
}
public void FromXmlString(string xml, ECKeyXmlFormat format) {
if (xml == null) {
throw new ArgumentNullException("xml");
}
if (format != ECKeyXmlFormat.Rfc4050) {
throw new ArgumentOutOfRangeException("format");
}
Key = Rfc4050KeyFormatter.FromXml(xml);
}
//
// Signature generation
//
public byte[] SignData(byte[] data) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
return SignData(data, 0, data.Length);
}
[SecuritySafeCritical]
public byte[] SignData(byte[] data, int offset, int count) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashCore(data, offset, count);
byte[] hashValue = hashAlgorithm.HashFinal();
return SignHash(hashValue);
}
}
[SecuritySafeCritical]
public byte[] SignData(Stream data) {
Contract.Ensures(Contract.Result<byte[]>() != null);
if (data == null) {
throw new ArgumentNullException("data");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashStream(data);
byte[] hashValue = hashAlgorithm.HashFinal();
return SignHash(hashValue);
}
}
[SecuritySafeCritical]
public override byte[] SignHash(byte[] hash) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
// Make sure we're allowed to sign using this key
KeyContainerPermission permission = Key.BuildKeyContainerPermission(KeyContainerPermissionFlags.Sign);
if (permission != null) {
permission.Demand();
}
// Now that know we have permission to use this key for signing, pull the key value out, which
// will require unmanaged code permission
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
// This looks odd, but the key handle is actually a duplicate so we need to dispose it
using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
CodeAccessPermission.RevertAssert();
return NCryptNative.SignHash(keyHandle, hash);
}
}
//
// XML Export
//
// See code:System.Security.Cryptography.ECDsaCng#ECCXMLFormat and
// code:System.Security.Cryptography.Rfc4050KeyFormatter#RFC4050ECKeyFormat for information about
// XML serialization of elliptic curve keys
//
public override string ToXmlString(bool includePrivateParameters) {
throw new NotImplementedException(SR.GetString(SR.Cryptography_ECXmlSerializationFormatRequired));
}
public string ToXmlString(ECKeyXmlFormat format) {
Contract.Ensures(Contract.Result<string>() != null);
if (format != ECKeyXmlFormat.Rfc4050) {
throw new ArgumentOutOfRangeException("format");
}
return Rfc4050KeyFormatter.ToXml(Key);
}
//
// Signature verification
//
public bool VerifyData(byte[] data, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
return VerifyData(data, 0, data.Length, signature);
}
[SecuritySafeCritical]
public bool VerifyData(byte[] data, int offset, int count, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (offset < 0 || offset > data.Length) {
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > data.Length - offset) {
throw new ArgumentOutOfRangeException("count");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashCore(data, offset, count);
byte[] hashValue = hashAlgorithm.HashFinal();
return VerifyHash(hashValue, signature);
}
}
[SecuritySafeCritical]
public bool VerifyData(Stream data, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashStream(data);
byte[] hashValue = hashAlgorithm.HashFinal();
return VerifyHash(hashValue, signature);
}
}
[SecuritySafeCritical]
public override bool VerifyHash(byte[] hash, byte[] signature) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
// We need to get the raw key handle to verify the signature. Asserting here is safe since verifiation
// is not a protected operation, and we do not expose the handle to the user code.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
// This looks odd, but Key.Handle is really a duplicate so we need to dispose it
using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
CodeAccessPermission.RevertAssert();
return NCryptNative.VerifySignature(keyHandle, hash, signature);
}
}
/// <summary>
/// Helper property to get the NCrypt key handle
/// </summary>
private SafeNCryptKeyHandle KeyHandle {
[SecuritySafeCritical]
get { return Key.Handle; }
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) {
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(offset >= 0 && offset <= data.Length);
Debug.Assert(count >= 0 && count <= data.Length - offset);
Debug.Assert(!String.IsNullOrEmpty(hashAlgorithm.Name));
using (BCryptHashAlgorithm hasher = new BCryptHashAlgorithm(new CngAlgorithm(hashAlgorithm.Name), BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hasher.HashCore(data, offset, count);
return hasher.HashFinal();
}
}
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) {
// we're sealed and the base should have checked this before calling us
Debug.Assert(data != null);
Debug.Assert(!String.IsNullOrEmpty(hashAlgorithm.Name));
using (BCryptHashAlgorithm hasher = new BCryptHashAlgorithm(new CngAlgorithm(hashAlgorithm.Name), BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hasher.HashStream(data);
return hasher.HashFinal();
}
}
}
}
| |
//
// PhotoVersionCommands.cs
//
// Author:
// Anton Keks <anton@azib.net>
// Ettore Perazzoli <ettore@src.gnome.org>
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (C) 2003-2010 Novell, Inc.
// Copyright (C) 2009-2010 Anton Keks
// Copyright (C) 2003 Ettore Perazzoli
// Copyright (C) 2010 Ruben Vermeersch
//
// 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 Gtk;
using Mono.Unix;
using FSpot;
using FSpot.UI.Dialog;
using Hyena;
using Hyena.Widgets;
public class PhotoVersionCommands
{
private class VersionNameRequest : BuilderDialog {
private Photo photo;
[GtkBeans.Builder.Object] Button ok_button;
[GtkBeans.Builder.Object] Entry version_name_entry;
[GtkBeans.Builder.Object] Label prompt_label;
[GtkBeans.Builder.Object] Label already_in_use_label;
public enum RequestType {
Create,
Rename
}
private RequestType request_type;
private void Update ()
{
string new_name = version_name_entry.Text;
if (photo.VersionNameExists (new_name)
&& ! (request_type == RequestType.Rename
&& new_name == photo.GetVersion (photo.DefaultVersionId).Name)) {
already_in_use_label.Markup = "<small>This name is already in use</small>";
ok_button.Sensitive = false;
return;
}
already_in_use_label.Text = String.Empty;
if (new_name.Length == 0)
ok_button.Sensitive = false;
else
ok_button.Sensitive = true;
}
private void HandleVersionNameEntryChanged (object obj, EventArgs args)
{
Update ();
}
public VersionNameRequest (RequestType request_type, Photo photo, Gtk.Window parent_window) : base ("version_name_dialog.ui", "version_name_dialog")
{
this.request_type = request_type;
this.photo = photo;
switch (request_type) {
case RequestType.Create:
this.Title = Catalog.GetString ("Create New Version");
prompt_label.Text = Catalog.GetString ("Name:");
break;
case RequestType.Rename:
this.Title = Catalog.GetString ("Rename Version");
prompt_label.Text = Catalog.GetString ("New name:");
version_name_entry.Text = photo.GetVersion (photo.DefaultVersionId).Name;
version_name_entry.SelectRegion (0, -1);
break;
}
version_name_entry.Changed += HandleVersionNameEntryChanged;
version_name_entry.ActivatesDefault = true;
this.TransientFor = parent_window;
this.DefaultResponse = ResponseType.Ok;
Update ();
}
public ResponseType Run (out string name)
{
ResponseType response = (ResponseType) this.Run ();
name = version_name_entry.Text;
if (request_type == RequestType.Rename && name == photo.GetVersion (photo.DefaultVersionId).Name)
response = ResponseType.Cancel;
this.Destroy ();
return response;
}
}
// Creating a new version.
public class Create {
public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window)
{
VersionNameRequest request = new VersionNameRequest (VersionNameRequest.RequestType.Create,
photo, parent_window);
string name;
ResponseType response = request.Run (out name);
if (response != ResponseType.Ok)
return false;
try {
photo.DefaultVersionId = photo.CreateVersion (name, photo.DefaultVersionId, true);
store.Commit (photo);
return true;
} catch (Exception e) {
HandleException ("Could not create a new version", e, parent_window);
return false;
}
}
}
// Deleting a version.
public class Delete {
public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window)
{
string ok_caption = Catalog.GetString ("Delete");
string msg = String.Format (Catalog.GetString ("Really delete version \"{0}\"?"), photo.DefaultVersion.Name);
string desc = Catalog.GetString ("This removes the version and deletes the corresponding file from disk.");
try {
if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent,
MessageType.Warning, msg, desc, ok_caption)) {
photo.DeleteVersion (photo.DefaultVersionId);
store.Commit (photo);
return true;
}
} catch (Exception e) {
HandleException ("Could not delete a version", e, parent_window);
}
return false;
}
}
// Renaming a version.
public class Rename {
public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window)
{
VersionNameRequest request = new VersionNameRequest (VersionNameRequest.RequestType.Rename,
photo, parent_window);
string new_name;
ResponseType response = request.Run (out new_name);
if (response != ResponseType.Ok)
return false;
try {
photo.RenameVersion (photo.DefaultVersionId, new_name);
store.Commit (photo);
return true;
} catch (Exception e) {
HandleException ("Could not rename a version", e, parent_window);
return false;
}
}
}
// Detaching a version (making it a separate photo).
public class Detach {
public bool Execute (PhotoStore store, Photo photo, Gtk.Window parent_window)
{
string ok_caption = Catalog.GetString ("De_tach");
string msg = String.Format (Catalog.GetString ("Really detach version \"{0}\" from \"{1}\"?"), photo.DefaultVersion.Name, photo.Name.Replace("_", "__"));
string desc = Catalog.GetString ("This makes the version appear as a separate photo in the library. To undo, drag the new photo back to its parent.");
try {
if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent,
MessageType.Warning, msg, desc, ok_caption)) {
Photo new_photo = store.CreateFrom (photo, photo.RollId);
new_photo.CopyAttributesFrom (photo);
photo.DeleteVersion (photo.DefaultVersionId, false, true);
store.Commit (new Photo[] {new_photo, photo});
return true;
}
} catch (Exception e) {
HandleException ("Could not detach a version", e, parent_window);
}
return false;
}
}
// Reparenting a photo as version of another one
public class Reparent {
public bool Execute (PhotoStore store, Photo [] photos, Photo new_parent, Gtk.Window parent_window)
{
string ok_caption = Catalog.GetString ("Re_parent");
string msg = String.Format (Catalog.GetPluralString ("Really reparent \"{0}\" as version of \"{1}\"?",
"Really reparent {2} photos as versions of \"{1}\"?", photos.Length),
new_parent.Name.Replace ("_", "__"), photos[0].Name.Replace ("_", "__"), photos.Length);
string desc = Catalog.GetString ("This makes the photos appear as a single one in the library. The versions can be detached using the Photo menu.");
try {
if (ResponseType.Ok == HigMessageDialog.RunHigConfirmation(parent_window, DialogFlags.DestroyWithParent,
MessageType.Warning, msg, desc, ok_caption)) {
uint highest_rating = new_parent.Rating;
string new_description = new_parent.Description;
foreach (Photo photo in photos) {
highest_rating = Math.Max(photo.Rating, highest_rating);
if (string.IsNullOrEmpty(new_description))
new_description = photo.Description;
new_parent.AddTag (photo.Tags);
foreach (uint version_id in photo.VersionIds) {
new_parent.DefaultVersionId = new_parent.CreateReparentedVersion (photo.GetVersion (version_id) as PhotoVersion);
store.Commit (new_parent);
}
uint [] version_ids = photo.VersionIds;
Array.Reverse (version_ids);
foreach (uint version_id in version_ids) {
photo.DeleteVersion (version_id, true, true);
}
store.Remove (photo);
}
new_parent.Rating = highest_rating;
new_parent.Description = new_description;
store.Commit (new_parent);
return true;
}
}
catch (Exception e) {
HandleException ("Could not reparent photos", e, parent_window);
}
return false;
}
}
private static void HandleException (string msg, Exception e, Gtk.Window parent_window) {
Log.DebugException (e);
msg = Catalog.GetString (msg);
string desc = String.Format (Catalog.GetString ("Received exception \"{0}\"."), e.Message);
HigMessageDialog md = new HigMessageDialog (parent_window, DialogFlags.DestroyWithParent,
Gtk.MessageType.Error, ButtonsType.Ok, msg, desc);
md.Run ();
md.Destroy ();
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace STIOnboardingPortal.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests.VersioningAndUnification.AppConfig
{
public sealed class NonSpecificVersionStrictPrimary : ResolveAssemblyReferenceTestFixture
{
/// <summary>
/// Return the default search paths.
/// </summary>
/// <value></value>
internal new string[] DefaultPaths
{
get { return new string[] { @"C:\MyComponents\v0.5", @"C:\MyComponents\v1.0", @"C:\MyComponents\v2.0", @"C:\MyComponents\v3.0" }; }
}
/// <summary>
/// In this case,
/// - A single primary non-version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// - The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void Exists()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "false");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary non-version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes a *different* assembly version name from
// 1.0.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// One entry in the app.config file should not be able to impact the mapping of an assembly
/// with a different name.
/// </summary>
[Fact]
public void ExistsDifferentName()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "false");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='DontUnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary non-version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from range 0.0.0.0-1.5.0.0 to 2.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void ExistsOldVersionRange()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "false");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-1.5.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary non-version-strict reference was passed in to assembly version 1.0.0.0
/// - An app.config was passed in that promotes assembly version from 1.0.0.0 to 4.0.0.0
/// - Version 1.0.0.0 of the file exists.
/// - Version 4.0.0.0 of the file *does not* exist.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0.
/// Rationale:
/// Primary references are never unified. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void HighVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "false");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='1.0.0.0' newVersion='4.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
/// <summary>
/// In this case,
/// - A single primary non-version-strict reference was passed in to assembly version 0.5.0.0
/// - An app.config was passed in that promotes assembly version from 0.0.0.0-2.0.0.0 to 2.0.0.0
/// - Version 0.5.0.0 of the file *does not* exists.
/// - Version 2.0.0.0 of the file exists.
/// Expected:
/// -- The resulting assembly returned should be 1.0.0.0 (remember this is non-version-strict)
/// Rationale:
/// Primary references are never unified--even those that don't exist on disk. This is because:
/// (a) The user expects that a primary reference will be respected.
/// (b) When FindDependencies is false and AutoUnify is true, we'd have to find all
/// dependencies anyway to make things work consistently. This would be a significant
/// perf hit when loading large solutions.
/// </summary>
[Fact]
public void LowVersionDoesntExist()
{
// Create the engine.
MockEngine engine = new MockEngine();
ITaskItem[] assemblyNames = new TaskItem[]
{
new TaskItem("UnifyMe, Version=0.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
};
assemblyNames[0].SetMetadata("SpecificVersion", "false");
// Construct the app.config.
string appConfigFile = WriteAppConfig
(
" <dependentAssembly>\n" +
" <assemblyIdentity name='UnifyMe' PublicKeyToken='b77a5c561934e089' culture='neutral' />\n" +
" <bindingRedirect oldVersion='0.0.0.0-2.0.0.0' newVersion='2.0.0.0' />\n" +
" </dependentAssembly>\n"
);
// Now, pass feed resolved primary references into ResolveAssemblyReference.
ResolveAssemblyReference t = new ResolveAssemblyReference();
t.BuildEngine = engine;
t.Assemblies = assemblyNames;
t.SearchPaths = DefaultPaths;
t.AppConfigFile = appConfigFile;
bool succeeded = Execute(t);
Assert.True(succeeded);
Assert.Equal(1, t.ResolvedFiles.Length);
AssertNoCase("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL", t.ResolvedFiles[0].GetMetadata("FusionName"));
// Cleanup.
File.Delete(appConfigFile);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/1/2010 2:03:50 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// Represents segment between 2 vertices.
/// </summary>
public class Segment
{
#region Private Variables
/// <summary>
/// The start point of the segment
/// </summary>
public Vertex P1 { get; set; }
/// <summary>
/// the end point of the segment
/// </summary>
public Vertex P2 { get; set; }
/// <summary>
/// Gets or sets the precision for calculating equality, but this is just a re-direction to Vertex.Epsilon
/// </summary>
public static double Epsilon
{
get { return Vertex.Epsilon; }
set { Vertex.Epsilon = value; }
}
#endregion
#region Constructors
/// <summary>
/// Creates a segment from double valued ordinates.
/// </summary>
public Segment(double x1, double y1, double x2, double y2)
{
P1 = new Vertex(x1, y1);
P2 = new Vertex(x2, y2);
}
/// <summary>
/// Creates a new instance of Segment
/// </summary>
public Segment(Vertex p1, Vertex p2)
{
P1 = p1;
P2 = p2;
}
#endregion
#region Methods
/// <summary>
/// Uses the intersection count to detect if there is an intersection
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Intersects(Segment other)
{
return (IntersectionCount(other) > 0);
}
/// <summary>
/// Calculates the shortest distance to this line segment from the specified MapWinGIS.Point
/// </summary>
/// <param name="point">A MapWinGIS.Point specifing the location to find the distance to the line</param>
/// <returns>A double value that is the shortest distance from the given Point to this line segment</returns>
public double DistanceTo(Coordinate point)
{
Vertex p = new Vertex(point.X, point.Y);
Vertex pt = ClosestPointTo(p);
Vector dist = new Vector(new Coordinate(pt.X, pt.Y), point);
return dist.Length2D;
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <returns>The point on this segment that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point)
{
EndPointInteraction endPointFlag;
return ClosestPointTo(point, false, out endPointFlag);
}
/// <summary>
/// Returns a vertex representing the closest point on this line segment from a given vertex
/// </summary>
/// <param name="point">The point we want to be close to</param>
/// <param name="isInfiniteLine">If true treat the line as infinitly long</param>
/// <param name="endPointFlag">Outputs 0 if the vertex is on the line segment, 1 if beyond P0, 2 if beyong P1 and -1 if P1=P2</param>
/// <returns>The point on this segment or infinite line that is closest to the given point</returns>
public Vertex ClosestPointTo(Vertex point, bool isInfiniteLine, out EndPointInteraction endPointFlag)
{
// If the points defining this segment are the same, we treat the segment as a point
// special handling to avoid 0 in denominator later
if (P2.X == P1.X && P2.Y == P1.Y)
{
endPointFlag = EndPointInteraction.P1equalsP2;
return P1;
}
//http://softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm
Vector v = ToVector(); // vector from p1 to p2 in the segment
v.Z = 0;
Vector w = new Vector(P1.ToCoordinate(), point.ToCoordinate()); // vector from p1 to Point
w.Z = 0;
double c1 = w.Dot(v); // the dot product represents the projection onto the line
if (c1 < 0)
{
endPointFlag = EndPointInteraction.PastP1;
if (!isInfiniteLine) // The closest point on the segment to Point is p1
return P1;
}
double c2 = v.Dot(v);
if (c2 <= c1)
{
endPointFlag = EndPointInteraction.PastP2;
if (!isInfiniteLine) // The closest point on the segment to Point is p2
return P2;
}
// The closest point on the segment is perpendicular to the point,
// but somewhere on the segment between P1 and P2
endPointFlag = EndPointInteraction.OnLine;
double b = c1 / c2;
v = v.Multiply(b);
Vertex pb = new Vertex(P1.X + v.X, P1.Y + v.Y);
return pb;
}
/// <summary>
/// Casts this to a vector
/// </summary>
/// <returns></returns>
public Vector ToVector()
{
double x = P2.X - P1.X;
double y = P2.Y - P1.Y;
return new Vector(x, y, 0);
}
/// <summary>
/// Determines the shortest distance between two segments
/// </summary>
/// <param name="lineSegment">Segment, The line segment to test against this segment</param>
/// <returns>Double, the shortest distance between two segments</returns>
public double DistanceTo(Segment lineSegment)
{
//http://www.geometryalgorithms.com/Archive/algorithm_0106/algorithm_0106.htm
const double smallNum = 0.00000001;
Vector u = ToVector(); // Segment 1
Vector v = lineSegment.ToVector(); // Segment 2
Vector w = ToVector();
double a = u.Dot(u); // length of segment 1
double b = u.Dot(v); // length of segment 2 projected onto line 1
double c = v.Dot(v); // length of segment 2
double d = u.Dot(w); //
double e = v.Dot(w);
double dist = a * c - b * b;
double sc, sN, sD = dist;
double tc, tN, tD = dist;
// compute the line parameters of the two closest points
if (dist < smallNum)
{
// the lines are almost parallel force using point P0 on segment 1
// to prevent possible division by 0 later
sN = 0.0;
sD = 1.0;
tN = e;
tD = c;
}
else
{
// get the closest points on the infinite lines
sN = (b * e - c * d);
tN = (a * e - b * d);
if (sN < 0.0)
{
// sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
}
else if (sN > sD)
{
// sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0)
{
// tc < 0 => the t=0 edge is visible
tN = 0.0;
// recompute sc for this edge
if (-d < 0.0)
{
sN = 0.0;
}
else if (-d > a)
{
sN = sD;
}
else
{
sN = -d;
sD = a;
}
}
else if (tN > tD)
{
// tc > 1 => the t = 1 edge is visible
// recompute sc for this edge
if ((-d + b) < 0.0)
{
sN = 0;
}
else if ((-d + b) > a)
{
sN = sD;
}
else
{
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
if (Math.Abs(sN) < smallNum)
{
sc = 0.0;
}
else
{
sc = sN / sD;
}
if (Math.Abs(tN) < smallNum)
{
tc = 0.0;
}
else
{
tc = tN / tD;
}
// get the difference of the two closest points
Vector dU = u.Multiply(sc);
Vector dV = v.Multiply(tc);
Vector dP = (w.Add(dU)).Subtract(dV);
// S1(sc) - S2(tc)
return dP.Length2D;
}
/// <summary>
/// Returns 0 if no intersections occur, 1 if an intersection point is found,
/// and 2 if the segments are colinear and overlap.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int IntersectionCount(Segment other)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double x3 = other.P1.X;
double y3 = other.P1.Y;
double x4 = other.P2.X;
double y4 = other.P2.Y;
double denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
//The case of two degenerate segements
if ((x1 == x2) && (y1 == y2) && (x3 == x4) && (y3 == y4))
{
if ((x1 != x3) || (y1 != y3))
return 0;
}
// if denom is 0, then the two lines are parallel
double na = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
double nb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
// if denom is 0 AND na and nb are 0, then the lines are coincident and DO intersect
if (Math.Abs(denom) < Epsilon && Math.Abs(na) < Epsilon && Math.Abs(nb) < Epsilon) return 2;
// If denom is 0, but na or nb are not 0, then the lines are parallel and not coincident
if (denom == 0) return 0;
double ua = na / denom;
double ub = nb / denom;
if (ua < 0 || ua > 1) return 0; // not intersecting with segment a
if (ub < 0 || ub > 1) return 0; // not intersecting with segment b
// If we get here, then one intersection exists and it is found on both line segments
return 1;
}
/// <summary>
/// Tests to see if the specified segment contains the point within Epsilon tollerance.
/// </summary>
/// <returns></returns>
public bool IntersectsVertex(Vertex point)
{
double x1 = P1.X;
double y1 = P1.Y;
double x2 = P2.X;
double y2 = P2.Y;
double pX = point.X;
double pY = point.Y;
// COllinear
if (Math.Abs((x2 - x1) * (pY - y1) - (pX - x1) * (y2 - y1)) > Epsilon) return false;
// In the x is in bounds and it is colinear, it is on the segment
if (x1 < x2)
{
if (x1 <= pX && pX <= x2) return true;
}
else
{
if (x2 <= pX && pX <= x1) return true;
}
return false;
}
#endregion
}
}
| |
using System;
using System.Text;
using System.IO;
namespace SilentOrbit.Code
{
/// <summary>
/// Static and instance helpers for code generation
/// </summary>
public class CodeWriter : IDisposable
{
#region Settings
public static string DefaultIndentPrefix = " ";
public static string DefaultNewLine = "\r\n";
public string IndentPrefix;
public string NewLine;
#endregion
#region Constructors
readonly TextWriter w;
MemoryStream ms = new MemoryStream();
/// <summary>
/// Writes to memory, get the code using the "Code" property
/// </summary>
public CodeWriter()
{
this.IndentPrefix = DefaultIndentPrefix;
this.NewLine = DefaultNewLine;
ms = new MemoryStream();
w = new StreamWriter(ms, Encoding.UTF8);
//w.NewLine = NewLine; // does not appear to work
}
/// <summary>
/// Writes code directly to file
/// </summary>
public CodeWriter(string csPath)
{
this.IndentPrefix = DefaultIndentPrefix;
this.NewLine = DefaultNewLine;
w = new StreamWriter(csPath, false, Encoding.UTF8);
}
/// <summary>
/// Return the generated code as a string.
/// </summary>
public string Code
{
get
{
w.Flush();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public virtual void Flush()
{
w.Flush();
}
public virtual void Dispose()
{
w.Close();
}
#endregion
#region Indentation
/// <summary>
/// Level of indentation
/// </summary>
public int IndentLevel { get; private set; }
/// <summary>
/// Accumulated prefixes over indentations
/// </summary>
string prefix = "";
public void Indent()
{
IndentLevel += 1;
prefix += IndentPrefix;
}
public void Dedent()
{
IndentLevel -= 1;
if (IndentLevel < 0)
throw new InvalidOperationException("Indent error");
prefix = prefix.Substring(0, prefix.Length - IndentPrefix.Length);
}
#endregion
public void Attribute(string attributeConstructor)
{
WriteLine("[" + attributeConstructor + "]");
}
/// <summary>
/// Write leading bracket and indent
/// </summary>
/// <param name="str">String.</param>
public void Bracket()
{
WriteLine("{");
Indent();
}
/// <summary>
/// Write leading bracket and indent
/// </summary>
/// <param name="str">Line before bracket</param>
public void Bracket(string str)
{
WriteLine(str);
WriteLine("{");
Indent();
}
public void Using(string str)
{
WriteLine("using (" + str + ")");
WriteLine("{");
Indent();
}
public void IfBracket(string str)
{
WriteLine("if (" + str + ")");
WriteLine("{");
Indent();
}
public void WhileBracket(string str)
{
WriteLine("while (" + str + ")");
WriteLine("{");
Indent();
}
public void Switch(string str)
{
Bracket("switch (" + str + ")");
Indent();
}
public void SwitchEnd()
{
Dedent();
EndBracket();
}
public void Case(string str)
{
Dedent();
WriteLine("case " + str + ":");
Indent();
}
public void Case(int id)
{
Dedent();
WriteLine("case " + id + ":");
Indent();
}
public void CaseDefault()
{
Dedent();
WriteLine("default:");
Indent();
}
public void ForeachBracket(string str)
{
WriteLine("foreach (" + str + ")");
WriteLine("{");
Indent();
}
public void EndBracket()
{
Dedent();
WriteLine("}");
}
public void EndBracketSpace()
{
Dedent();
WriteLine("}");
WriteLine();
}
/// <summary>
/// Writes a singe line indented.
/// </summary>
public void WriteIndent(string str)
{
WriteLine(IndentPrefix + str);
}
public void WriteLine(string line)
{
foreach (string l in SplitTrimEnd(line))
{
string pl = (prefix + l).TrimEnd(' ', '\t');
w.Write(pl + NewLine);
}
}
public void WriteLine()
{
WriteLine("");
}
#region Comments
public void Comment(string code)
{
if (code == null)
return;
const string commentPrefix = "// ";
prefix += commentPrefix;
foreach (string line in SplitTrimEnd(code))
WriteLine(line);
prefix = prefix.Substring(0, prefix.Length - commentPrefix.Length);
}
public void Summary(string summary)
{
if (summary == null || summary.Trim() == "")
return;
string[] lines = SplitTrimEnd(summary);
if (lines.Length == 1)
{
WriteLine("/// <summary>" + lines[0] + "</summary>");
return;
}
prefix += "/// ";
WriteLine("<summary>");
foreach (string line in lines)
WriteLine("<para>" + line + "</para>");
WriteLine("</summary>");
prefix = prefix.Substring(0, prefix.Length - 4);
}
#endregion
/// <summary>
/// Split string into an array of lines and trim whitespace at the end
/// </summary>
static string[] SplitTrimEnd(string text)
{
var lines = text.Replace("\r\n", "\n").Replace('\r', '\n').Split('\n');
for (int n = 0; n < lines.Length; n++)
lines[n] = lines[n].TrimEnd(' ', '\t');
return lines;
}
}
}
| |
//
// TypeReference.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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.Cecil.Metadata;
using Mono.Collections.Generic;
namespace Mono.Cecil
{
public enum MetadataType : byte
{
Void = ElementType.Void,
Boolean = ElementType.Boolean,
Char = ElementType.Char,
SByte = ElementType.I1,
Byte = ElementType.U1,
Int16 = ElementType.I2,
UInt16 = ElementType.U2,
Int32 = ElementType.I4,
UInt32 = ElementType.U4,
Int64 = ElementType.I8,
UInt64 = ElementType.U8,
Single = ElementType.R4,
Double = ElementType.R8,
String = ElementType.String,
Pointer = ElementType.Ptr,
ByReference = ElementType.ByRef,
ValueType = ElementType.ValueType,
Class = ElementType.Class,
Var = ElementType.Var,
Array = ElementType.Array,
GenericInstance = ElementType.GenericInst,
TypedByReference = ElementType.TypedByRef,
IntPtr = ElementType.I,
UIntPtr = ElementType.U,
FunctionPointer = ElementType.FnPtr,
Object = ElementType.Object,
MVar = ElementType.MVar,
RequiredModifier = ElementType.CModReqD,
OptionalModifier = ElementType.CModOpt,
Sentinel = ElementType.Sentinel,
Pinned = ElementType.Pinned,
}
public class TypeReference : MemberReference, IGenericParameterProvider, IGenericContext
{
string @namespace;
bool value_type;
int hashCode = -1;
static int instance_id;
internal IMetadataScope scope;
internal ModuleDefinition module;
internal ElementType etype = ElementType.None;
string fullname;
protected Collection<GenericParameter> generic_parameters;
public override string Name
{
get { return base.Name; }
set
{
base.Name = value;
fullname = null;
}
}
public virtual string Namespace
{
get { return @namespace; }
set
{
@namespace = value;
fullname = null;
}
}
public virtual bool IsValueType
{
get { return value_type; }
set { value_type = value; }
}
public override ModuleDefinition Module
{
get
{
if (module != null)
return module;
var declaring_type = this.DeclaringType;
if (declaring_type != null)
return declaring_type.Module;
return null;
}
}
IGenericParameterProvider IGenericContext.Type
{
get { return this; }
}
IGenericParameterProvider IGenericContext.Method
{
get { return null; }
}
GenericParameterType IGenericParameterProvider.GenericParameterType
{
get { return GenericParameterType.Type; }
}
public virtual bool HasGenericParameters
{
get { return !Mixin.IsNullOrEmpty(generic_parameters); }
}
public virtual Collection<GenericParameter> GenericParameters
{
get
{
if (generic_parameters != null)
return generic_parameters;
return generic_parameters = new GenericParameterCollection(this);
}
}
public virtual IMetadataScope Scope
{
get
{
var declaring_type = this.DeclaringType;
if (declaring_type != null)
return declaring_type.Scope;
return scope;
}
}
public bool IsNested
{
get { return this.DeclaringType != null; }
}
public override TypeReference DeclaringType
{
get { return base.DeclaringType; }
set
{
base.DeclaringType = value;
fullname = null;
}
}
public override string FullName
{
get
{
if (fullname != null)
return fullname;
if (IsNested)
return fullname = DeclaringType.FullName + "/" + Name;
if (string.IsNullOrEmpty(@namespace))
return fullname = Name;
return fullname = @namespace + "." + Name;
}
}
public virtual bool IsByReference
{
get { return false; }
}
public virtual bool IsPointer
{
get { return false; }
}
public virtual bool IsSentinel
{
get { return false; }
}
public virtual bool IsArray
{
get { return false; }
}
public virtual bool IsGenericParameter
{
get { return false; }
}
public virtual bool IsGenericInstance
{
get { return false; }
}
public virtual bool IsRequiredModifier
{
get { return false; }
}
public virtual bool IsOptionalModifier
{
get { return false; }
}
public virtual bool IsPinned
{
get { return false; }
}
public virtual bool IsFunctionPointer
{
get { return false; }
}
public override int GetHashCode()
{
if (hashCode == -1)
hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);
return hashCode;
}
public virtual bool IsPrimitive
{
get { return Mixin.IsPrimitive(etype); }
}
public virtual MetadataType MetadataType
{
get
{
switch (etype)
{
case ElementType.None:
return IsValueType ? MetadataType.ValueType : MetadataType.Class;
default:
return (MetadataType)etype;
}
}
}
protected TypeReference(string @namespace, string name)
: base(name)
{
this.@namespace = @namespace ?? string.Empty;
this.token = new MetadataToken(TokenType.TypeRef, 0);
}
public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
: this(@namespace, name)
{
this.module = module;
this.scope = scope;
}
public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :
this(@namespace, name, module, scope)
{
value_type = valueType;
}
public virtual TypeReference GetElementType()
{
return this;
}
public virtual TypeDefinition Resolve()
{
var module = this.Module;
if (module == null)
throw new NotSupportedException();
return module.Resolve(this);
}
}
static partial class Mixin
{
public static bool IsPrimitive(ElementType self)
{
switch (self)
{
case ElementType.Boolean:
case ElementType.Char:
case ElementType.I:
case ElementType.U:
case ElementType.I1:
case ElementType.U1:
case ElementType.I2:
case ElementType.U2:
case ElementType.I4:
case ElementType.U4:
case ElementType.I8:
case ElementType.U8:
case ElementType.R4:
case ElementType.R8:
return true;
default:
return false;
}
}
public static bool IsTypeOf(TypeReference self, string @namespace, string name)
{
return self.Name == name
&& self.Namespace == @namespace;
}
public static bool IsTypeSpecification(TypeReference type)
{
switch (type.etype)
{
case ElementType.Array:
case ElementType.ByRef:
case ElementType.CModOpt:
case ElementType.CModReqD:
case ElementType.FnPtr:
case ElementType.GenericInst:
case ElementType.MVar:
case ElementType.Pinned:
case ElementType.Ptr:
case ElementType.SzArray:
case ElementType.Sentinel:
case ElementType.Var:
return true;
}
return false;
}
public static TypeDefinition CheckedResolve(TypeReference self)
{
var type = self.Resolve();
if (type == null)
throw new ResolutionException(self);
return type;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SocketAddress.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Text;
using System.Globalization;
using System.Diagnostics.Contracts;
// a little perf app measured these times when comparing the internal
// buffer implemented as a managed byte[] or unmanaged memory IntPtr
// that's why we use byte[]
// byte[] total ms:19656
// IntPtr total ms:25671
/// <devdoc>
/// <para>
/// This class is used when subclassing EndPoint, and provides indication
/// on how to format the memeory buffers that winsock uses for network addresses.
/// </para>
/// </devdoc>
public class SocketAddress {
internal const int IPv6AddressSize = 28;
internal const int IPv4AddressSize = 16;
internal int m_Size;
internal byte[] m_Buffer;
private const int WriteableOffset = 2;
private const int MaxSize = 32; // IrDA requires 32 bytes
private bool m_changed = true;
private int m_hash;
//
// Address Family
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public AddressFamily Family {
get {
int family;
#if BIGENDIAN
family = ((int)m_Buffer[0]<<8) | m_Buffer[1];
#else
family = m_Buffer[0] | ((int)m_Buffer[1]<<8);
#endif
return (AddressFamily)family;
}
}
//
// Size of this SocketAddress
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Size {
get {
return m_Size;
}
}
//
// access to unmanaged serialized data. this doesn't
// allow access to the first 2 bytes of unmanaged memory
// that are supposed to contain the address family which
// is readonly.
//
// <SECREVIEW> you can still use negative offsets as a back door in case
// winsock changes the way it uses SOCKADDR. maybe we want to prohibit it?
// maybe we should make the class sealed to avoid potentially dangerous calls
// into winsock with unproperly formatted data? </SECREVIEW>
//
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte this[int offset] {
get {
//
// access
//
if (offset<0 || offset>=Size) {
throw new IndexOutOfRangeException();
}
return m_Buffer[offset];
}
set {
if (offset<0 || offset>=Size) {
throw new IndexOutOfRangeException();
}
if (m_Buffer[offset] != value) {
m_changed = true;
}
m_Buffer[offset] = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SocketAddress(AddressFamily family) : this(family, MaxSize) {
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SocketAddress(AddressFamily family, int size) {
if (size<WriteableOffset) {
//
// it doesn't make sense to create a socket address with less tha
// 2 bytes, that's where we store the address family.
//
throw new ArgumentOutOfRangeException("size");
}
m_Size = size;
m_Buffer = new byte[(size/IntPtr.Size+2)*IntPtr.Size];//sizeof DWORD
#if BIGENDIAN
m_Buffer[0] = unchecked((byte)((int)family>>8));
m_Buffer[1] = unchecked((byte)((int)family ));
#else
m_Buffer[0] = unchecked((byte)((int)family ));
m_Buffer[1] = unchecked((byte)((int)family>>8));
#endif
}
internal SocketAddress(IPAddress ipAddress)
: this(ipAddress.AddressFamily,
((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize)) {
// No Port
m_Buffer[2] = (byte)0;
m_Buffer[3] = (byte)0;
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) {
// No handling for Flow Information
m_Buffer[4] = (byte)0;
m_Buffer[5] = (byte)0;
m_Buffer[6] = (byte)0;
m_Buffer[7] = (byte)0;
// Scope serialization
long scope = ipAddress.ScopeId;
m_Buffer[24] = (byte)scope;
m_Buffer[25] = (byte)(scope >> 8);
m_Buffer[26] = (byte)(scope >> 16);
m_Buffer[27] = (byte)(scope >> 24);
// Address serialization
byte[] addressBytes = ipAddress.GetAddressBytes();
for (int i = 0; i < addressBytes.Length; i++) {
m_Buffer[8 + i] = addressBytes[i];
}
} else {
// IPv4 Address serialization
m_Buffer[4] = unchecked((byte)(ipAddress.m_Address));
m_Buffer[5] = unchecked((byte)(ipAddress.m_Address >> 8));
m_Buffer[6] = unchecked((byte)(ipAddress.m_Address >> 16));
m_Buffer[7] = unchecked((byte)(ipAddress.m_Address >> 24));
}
}
internal SocketAddress(IPAddress ipaddress, int port)
: this (ipaddress) {
m_Buffer[2] = (byte)(port >> 8);
m_Buffer[3] = (byte)port;
}
internal IPAddress GetIPAddress() {
if (Family == AddressFamily.InterNetworkV6) {
Contract.Assert(Size >= IPv6AddressSize);
byte[] address = new byte[IPAddress.IPv6AddressBytes];
for (int i = 0; i < address.Length; i++) {
address[i] = m_Buffer[i + 8];
}
long scope = (long)((m_Buffer[27] << 24) +
(m_Buffer[26] << 16) +
(m_Buffer[25] << 8) +
(m_Buffer[24]));
return new IPAddress(address, scope);
} else if (Family == AddressFamily.InterNetwork) {
Contract.Assert(Size >= IPv4AddressSize);
long address = (long)(
(m_Buffer[4] & 0x000000FF) |
(m_Buffer[5] << 8 & 0x0000FF00) |
(m_Buffer[6] << 16 & 0x00FF0000) |
(m_Buffer[7] << 24)
) & 0x00000000FFFFFFFF;
return new IPAddress(address);
} else {
throw new SocketException(SocketError.AddressFamilyNotSupported);
}
}
internal IPEndPoint GetIPEndPoint() {
IPAddress address = GetIPAddress();
int port = (int)((m_Buffer[2] << 8 & 0xFF00) | (m_Buffer[3]));
return new IPEndPoint(address, port);
}
//
// For ReceiveFrom we need to pin address size, using reserved m_Buffer space
//
internal void CopyAddressSizeIntoBuffer()
{
m_Buffer[m_Buffer.Length-IntPtr.Size] = unchecked((byte)(m_Size));
m_Buffer[m_Buffer.Length-IntPtr.Size+1] = unchecked((byte)(m_Size >> 8));
m_Buffer[m_Buffer.Length-IntPtr.Size+2] = unchecked((byte)(m_Size >> 16));
m_Buffer[m_Buffer.Length-IntPtr.Size+3] = unchecked((byte)(m_Size >> 24));
}
//
// Can be called after the above method did work
//
internal int GetAddressSizeOffset()
{
return m_Buffer.Length-IntPtr.Size;
}
//
//
// For ReceiveFrom we need to update the address size upon IO return
//
internal unsafe void SetSize(IntPtr ptr)
{
// Apparently it must be less or equal the original value since ReceiveFrom cannot reallocate the address buffer
m_Size = *(int*)ptr;
}
public override bool Equals(object comparand) {
SocketAddress castedComparand = comparand as SocketAddress;
if (castedComparand == null || this.Size != castedComparand.Size) {
return false;
}
for(int i=0; i<this.Size; i++) {
if(this[i]!=castedComparand[i]) {
return false;
}
}
return true;
}
public override int GetHashCode() {
if (m_changed) {
m_changed = false;
m_hash = 0;
int i;
int size = Size & ~3;
for (i = 0; i < size; i += 4) {
m_hash ^= (int)m_Buffer[i]
| ((int)m_Buffer[i+1] << 8)
| ((int)m_Buffer[i+2] << 16)
| ((int)m_Buffer[i+3] << 24);
}
if ((Size & 3) != 0) {
int remnant = 0;
int shift = 0;
for (; i < Size; ++i) {
remnant |= ((int)m_Buffer[i]) << shift;
shift += 8;
}
m_hash ^= remnant;
}
}
return m_hash;
}
public override string ToString() {
StringBuilder bytes = new StringBuilder();
for(int i=WriteableOffset; i<this.Size; i++) {
if (i>WriteableOffset) {
bytes.Append(",");
}
bytes.Append(this[i].ToString(NumberFormatInfo.InvariantInfo));
}
return Family.ToString() + ":" + Size.ToString(NumberFormatInfo.InvariantInfo) + ":{" + bytes.ToString() + "}";
}
} // class SocketAddress
} // namespace System.Net
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Diagnostics;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Caches;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Util;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.ReSharper.Psi.Util;
namespace JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration.Api
{
[SolutionComponent]
public class UnityApi
{
// https://docs.unity3d.com/Documentation/Manual/script-Serialization.html
private static readonly JetHashSet<IClrTypeName> ourUnityBuiltinSerializedFieldTypes = new JetHashSet<IClrTypeName>
{
KnownTypes.Vector2, KnownTypes.Vector3, KnownTypes.Vector4,
KnownTypes.Vector2Int, KnownTypes.Vector3Int,
KnownTypes.Rect, KnownTypes.RectInt, KnownTypes.RectOffset,
KnownTypes.Quaternion,
KnownTypes.Matrix4x4,
KnownTypes.Color, KnownTypes.Color32,
KnownTypes.LayerMask,
KnownTypes.Bounds, KnownTypes.BoundsInt,
KnownTypes.AnimationCurve,
KnownTypes.Gradient,
KnownTypes.GUIStyle
};
private readonly UnityVersion myUnityVersion;
private readonly UnityTypeCache myUnityTypeCache;
private readonly UnityTypesProvider myUnityTypesProvider;
private readonly KnownTypesCache myKnownTypesCache;
public UnityApi(UnityVersion unityVersion, UnityTypeCache unityTypeCache, UnityTypesProvider unityTypesProvider, KnownTypesCache knownTypesCache)
{
myUnityVersion = unityVersion;
myUnityTypeCache = unityTypeCache;
myUnityTypesProvider = unityTypesProvider;
myKnownTypesCache = knownTypesCache;
}
public bool IsUnityType([NotNullWhen(true)] ITypeElement? type) => type != null && myUnityTypeCache.IsUnityType(type);
public bool IsComponentSystemType([NotNullWhen(true)] ITypeElement? typeElement)
{
// This covers ComponentSystem, JobComponentSystem and SystemBase
return typeElement.DerivesFrom(KnownTypes.ComponentSystemBase);
}
// A serialised field cannot be abstract or generic, but a type declaration that will be serialised can be. This
// method differentiates between a type declaration and a type usage. Consider renaming if we ever need to
// expose stricter checking publicly
public bool IsSerializableTypeDeclaration([NotNullWhen(true)] ITypeElement? type)
{
// We only support type declarations in a project. We shouldn't get any other type
if (type?.Module is IProjectPsiModule projectPsiModule)
{
var project = projectPsiModule.Project;
return IsSerializableType(type, project, false);
}
return false;
}
// NOTE: This method assumes that the type is not a descendant of UnityEngine.Object!
private bool IsSerializableType([NotNullWhen(true)] ITypeElement? type, IProject project, bool isTypeUsage,
bool hasSerializeReference = false)
{
if (type is not (IStruct or IClass))
return false;
if (isTypeUsage)
{
// Type usage (e.g. field declaration) is stricter. Means it must be a concrete type with no type
// parameters, unless the type usage is for [SerializeReference], which allows abstract types
if (type is IModifiersOwner { IsAbstract: true } && !hasSerializeReference)
return false;
// Unity 2020.1 allows fields to have generic types. It's currently undocumented, but there are no
// limitations on the number of type parameters, or even nested type parameters. The base type needs to
// be serializable, but type parameters don't (if a non-serializable type parameter is used as a field,
// it just isn't serialised).
// https://blogs.unity3d.com/2020/03/17/unity-2020-1-beta-is-now-available-for-feedback/
var unityVersion = myUnityVersion.GetActualVersion(project);
if (unityVersion < new Version(2020, 1) && type is ITypeParametersOwner typeParametersOwner &&
typeParametersOwner.TypeParameters.Count > 0)
{
return false;
}
}
if (type is IClass @class && @class.IsStaticClass())
return false;
// System.Dictionary is special cased and excluded. We can see this in UnitySerializationLogic.cs in the
// reference source repo. It also excludes anything with a full name beginning "System.", which includes
// "System.Version" (which is marked [Serializable]). However, it doesn't exclude string, int, etc.
// TODO: Rewrite this whole section to properly mimic UnitySerializationLogic.cs
var name = type.GetClrName();
if (Equals(name, KnownTypes.SystemVersion) || Equals(name, PredefinedType.GENERIC_DICTIONARY_FQN))
return false;
using (CompilationContextCookie.GetExplicitUniversalContextIfNotSet())
return type.HasAttributeInstance(PredefinedType.SERIALIZABLE_ATTRIBUTE_CLASS, true);
}
public bool IsEventFunction([NotNullWhen(true)] IMethod? method) => method != null && GetUnityEventFunction(method) != null;
public bool IsSerialisedField([NotNullWhen(true)] IField? field)
{
if (field == null || field.IsStatic || field.IsConstant || field.IsReadonly)
return false;
var containingType = field.ContainingType;
if (!IsUnityType(containingType) && !IsSerializableTypeDeclaration(containingType))
return false;
// [NonSerialized] trumps everything, even if there's a [SerializeField] as well
if (field.HasAttributeInstance(PredefinedType.NONSERIALIZED_ATTRIBUTE_CLASS, false))
return false;
var hasSerializeReference = field.HasAttributeInstance(KnownTypes.SerializeReference, false);
if (field.GetAccessRights() != AccessRights.PUBLIC
&& !field.HasAttributeInstance(KnownTypes.SerializeField, false)
&& !hasSerializeReference)
{
return false;
}
// We need the project to get the current Unity version. this is only called for type usage (e.g. field
// type), so it's safe to assume that the field is in a source file belonging to a project
var project = (field.Module as IProjectPsiModule)?.Project;
// Rules for what field types can be serialised.
// See https://docs.unity3d.com/ScriptReference/SerializeField.html
return project != null &&
(IsSimpleSerialisedFieldType(field.Type, project, hasSerializeReference) ||
IsSerialisedFieldContainerType(field.Type, project, hasSerializeReference));
}
private bool IsSimpleSerialisedFieldType([NotNullWhen(true)] IType? type, IProject project,
bool hasSerializeReference)
{
// We include type parameter types (T) in this test, which Unity obviously won't. We treat them as
// serialised fields rather than show false positive redundant attribute warnings, etc. Adding the test
// here allows us to support T[] and List<T>
return type != null && (type.IsSimplePredefined()
|| type.IsEnumType()
|| IsUnityBuiltinType(type)
|| type.GetTypeElement().DerivesFrom(KnownTypes.Object)
|| IsSerializableType(type.GetTypeElement(), project, true, hasSerializeReference)
|| type.IsTypeParameterType());
}
private bool IsSerialisedFieldContainerType([NotNullWhen(true)] IType? type, IProject project,
bool hasSerializeReference)
{
if (type is IArrayType { Rank: 1 } arrayType &&
IsSimpleSerialisedFieldType(arrayType.ElementType, project, hasSerializeReference))
{
return true;
}
if (type is IDeclaredType declaredType &&
Equals(declaredType.GetClrName(), PredefinedType.GENERIC_LIST_FQN))
{
var substitution = declaredType.GetSubstitution();
var typeParameter = declaredType.GetTypeElement()?.TypeParameters[0];
if (typeParameter != null)
{
var substitutedType = substitution.Apply(typeParameter);
return substitutedType.IsTypeParameterType() ||
IsSimpleSerialisedFieldType(substitutedType, project, hasSerializeReference);
}
}
return false;
}
// Best effort attempt at preventing false positives for type members that are actually being used inside a
// scene. We don't have enough information to do this by name, so we'll mark all potential event handlers as
// implicitly used by Unity
// See https://github.com/Unity-Technologies/UnityCsReference/blob/02f8e8ca594f156dd6b2088ad89451143ca1b87e/Editor/Mono/Inspector/UnityEventDrawer.cs#L397
//
// Unity Editor will only list public methods, but will invoke any method, even if it's private.
public bool IsPotentialEventHandler([NotNullWhen(true)] IMethod? method, bool isFindUsages = true)
{
if (method == null || !method.ReturnType.IsVoid())
return false;
// Type.GetMethods() returns public instance methods only
if (method.GetAccessRights() != AccessRights.PUBLIC && !isFindUsages|| method.IsStatic)
return false;
return IsUnityType(method.ContainingType) &&
!method.HasAttributeInstance(PredefinedType.OBSOLETE_ATTRIBUTE_CLASS, true);
}
public bool IsPotentialEventHandler([NotNullWhen(true)] IProperty? property, bool isFindUsages = true) =>
IsPotentialEventHandler(property?.Setter, isFindUsages);
public IEnumerable<UnityEventFunction> GetEventFunctions(ITypeElement type, Version unityVersion)
{
var types = myUnityTypesProvider.Types;
unityVersion = types.NormaliseSupportedVersion(unityVersion);
foreach (var unityType in UnityTypeUtils.GetBaseUnityTypes(myUnityTypesProvider, type, unityVersion, myKnownTypesCache))
{
foreach (var function in unityType.GetEventFunctions(unityVersion))
yield return function;
}
}
public UnityEventFunction? GetUnityEventFunction(IMethod method) => GetUnityEventFunction(method, out _);
public UnityEventFunction? GetUnityEventFunction(IMethod method, out MethodSignatureMatch match)
{
Assertion.Assert(method.IsValid(), "DeclaredElement is not valid");
match = MethodSignatureMatch.NoMatch;
if (method.Module is not IProjectPsiModule projectPsiModule)
return null;
var unityVersion = GetNormalisedActualVersion(projectPsiModule.Project);
return GetUnityEventFunction(method, unityVersion, out match);
}
public UnityEventFunction? GetUnityEventFunction(IMethod method, Version unityVersion,
out MethodSignatureMatch match)
{
match = MethodSignatureMatch.NoMatch;
var containingType = method.ContainingType;
if (containingType == null) return null;
foreach (var type in UnityTypeUtils.GetBaseUnityTypes(containingType, unityVersion, myUnityTypesProvider, myKnownTypesCache))
{
foreach (var function in type.GetEventFunctions(unityVersion))
{
match = function.Match(method);
if (function.Match(method) != MethodSignatureMatch.NoMatch)
return function;
}
}
return null;
}
public Version GetNormalisedActualVersion(IProject project) =>
myUnityTypesProvider.Types.NormaliseSupportedVersion(myUnityVersion.GetActualVersion(project));
private static bool IsUnityBuiltinType(IType type)
{
return type is IDeclaredType declaredType &&
ourUnityBuiltinSerializedFieldTypes.Contains(declaredType.GetClrName());
}
}
}
| |
//
// MetaMetadataField.cs
// s.im.pl serialization
//
// Generated by DotNetTranslator on 11/16/10.
// Copyright 2010 Interface Ecology Lab.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Ecologylab.BigSemantics.MetadataNS;
using Simpl.Fundamental.Generic;
using Simpl.Serialization.Attributes;
using Simpl.Serialization;
using Simpl.Serialization.Types;
using Simpl.Serialization.Types.Element;
using System.Text.RegularExpressions;
using Ecologylab.BigSemantics.MetaMetadataNS;
namespace Ecologylab.BigSemantics.MetaMetadataNS
{
[SimplInherit]
[SimplDescriptorClasses(new[] { typeof(MetaMetadataClassDescriptor), typeof(MetaMetadataFieldDescriptor)})]
public abstract class MetaMetadataField : ElementState, IMappable<String>, IEnumerable<MetaMetadataField>
{
#region Variables
private static readonly List<MetaMetadataField> EMPTY_COLLECTION = new List<MetaMetadataField>(0);
private static readonly IEnumerator<MetaMetadataField> EMPTY_ITERATOR = EMPTY_COLLECTION.GetEnumerator();
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String name;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
[MmDontInherit]
private String comment;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String tag;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplCollection("xpath")]
[SimplNoWrap]
private List<String> xpaths;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String contextNode;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplMap]
// [SimplClasses(new Type[] { typeof(MetaMetadataField), typeof(MetaMetadataScalarField), typeof(MetaMetadataCompositeField), typeof(MetaMetadataCollectionField) })]
[SimplScope(MetaMetadataFieldTranslationScope.NAME)]
[SimplNoWrap]
protected DictionaryList<String, MetaMetadataField> kids;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private Boolean hide;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private Boolean alwaysShow;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String style;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private Single layer;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String navigatesTo;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String shadows;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private String label;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private Boolean isFacet;
/// <summary>
/// missing java doc comments or could not find the source file.
/// </summary>
[SimplScalar]
private Boolean ignoreInTermVector;
/// <summary>
///
/// The name of natural id if this field is used as one.
/// </summary>
[SimplScalar]
private String asNaturalId;
/// <summary>
///
/// schema.org microdata item_prop name.
/// </summary>
[SimplScalar]
private String schemaOrgItemprop;
[SimplScalar]
private String fieldParserKey;
[SimplScalar]
private String otherTags;
[SimplScalar]
private bool extractAsHtml;
protected MetadataClassDescriptor metadataClassDescriptor;
private bool fieldsSortedForDisplay = false;
protected Type metadataClass;
protected MetadataFieldDescriptor metadataFieldDescriptor;
private HashSet<String> nonDisplayedFieldNames = new HashSet<String>();
private String _displayedLabel = null;
private bool _bindFieldDescriptorsFinished;
/**
* from which field this one inherits. could be null if this field is declared for the first time.
*/
[SimplComposite]
[SimplScope(NestedMetaMetadataFieldTypesScope.Name)]
[SimplWrap]
[MmDontInherit]
private MetaMetadataField superField = null;
[SimplScalar]
[MmDontInherit]
protected bool inheritDone;
/**
* in which meta-metadata this field is declared.
*/
[SimplComposite]
[MmDontInherit]
private MetaMetadata declaringMmd = null;
[SimplComposite]
[MmDontInherit]
private MetaMetadata inlineMmd = null;
private MetadataFieldDescriptorProxy _fieldDescriptorProxy;
[SimplMap("generic_type_var")]
[SimplMapKeyField("name")]
[SimplNoWrap]
protected MmdGenericTypeVarScope genericTypeVars;
[SimplScalar]
[MmDontInherit]
private bool usedForInlineMmdDef;
private MetaMetadataRepository _metaMetadataRepository = null;
public MetaMetadataRepository Repository
{
get
{
var result = _metaMetadataRepository;
if (result == null)
{
var parent = this.Parent;
while (parent != null && !(parent is MetaMetadataRepository))
{
parent = parent.Parent;
}
result = parent as MetaMetadataRepository;
_metaMetadataRepository = result;
}
return result;
}
set { _metaMetadataRepository = value; }
}
#endregion
public MmdGenericTypeVarScope GenericTypeVars
{
get { return genericTypeVars; }
set { genericTypeVars = value; }
}
public static List<MmdGenericTypeVar> EMPTY_GENERIC_TYPE_VAR_COLLECTION = new List<MmdGenericTypeVar>();
public List<MmdGenericTypeVar> getMetaMetadataGenericTypeVars()
{
return genericTypeVars == null ? EMPTY_GENERIC_TYPE_VAR_COLLECTION : new List<MmdGenericTypeVar>(genericTypeVars.Values);
}
public MetaMetadataField()
{
_fieldDescriptorProxy = new MetadataFieldDescriptorProxy(this);
}
protected void SortForDisplay()
{
DictionaryList<String, MetaMetadataField> childMetaMetadata = Kids;
if (childMetaMetadata != null)
{
childMetaMetadata.ValuesInList.Sort(delegate(MetaMetadataField f1, MetaMetadataField f2) { return -Math.Sign(f1.Layer - f2.Layer); });
}
fieldsSortedForDisplay = true;
}
public DictionaryList<String, MetaMetadataField> InitializeChildMetaMetadata()
{
this.kids = new DictionaryList<string, MetaMetadataField>();
return this.kids;
}
///<summary>
/// get the nested fields inside of this one.
///</summary>
public virtual DictionaryList<String, MetaMetadataField> GetChildMetaMetadata()
{
return kids;
}
internal virtual bool GetClassAndBindDescriptors(SimplTypesScope metadataTScope)
{
return true;
}
public int GetFieldType()
{
if (metadataFieldDescriptor != null)
return metadataFieldDescriptor.FdType;
Type thisType = GetType();
if (thisType == typeof(MetaMetadataCompositeField))
return FieldTypes.CompositeElement;
if (thisType == typeof(MetaMetadataCollectionField))
{
MetaMetadataCollectionField coll = (MetaMetadataCollectionField)this;
if (coll.ChildScalarType != null)
return FieldTypes.CollectionScalar;
else
return FieldTypes.CollectionElement;
}
else
return FieldTypes.Scalar;
}
internal Type GetMetadataClass(SimplTypesScope metadataTScope)
{
Type result = metadataClass;
if (result == null)
{
MetadataClassDescriptor descriptor = this.MetadataClassDescriptor;
result= (descriptor == null ? null : descriptor.DescribedClass);
metadataClass = result;
}
return result;
}
// internal void InheritNonDefaultAttributes(MetaMetadataField inheritFrom)
// {
// ClassDescriptor classDescriptor = ClassDescriptor;
//
// foreach (FieldDescriptor fieldDescriptor in classDescriptor.AttributeFieldDescriptors)
// {
// ScalarType scalarType = null;//TODO FIXME fieldDescriptor.GetScalarType();
// try
// {
// if (scalarType != null && scalarType.IsDefaultValue(fieldDescriptor.Field, this)
// && !scalarType.IsDefaultValue(fieldDescriptor.Field, inheritFrom))
// {
// Object value = fieldDescriptor.Field.GetValue(inheritFrom);
// fieldDescriptor.Field.SetValue(this, value);
// //Console.WriteLine("inherit\t" + this.Name + "." + fieldDescriptor.FieldName + "\t= " + value);
// }
// }
// catch (Exception e)
// {
// // TODO Auto-generated catch block
// Console.WriteLine("inherit\t" + this.Name + "." + fieldDescriptor.Name + " Failed, ignore it.\n" + e);
// }
// }
//
// }
public String GetTagForTranslationScope()
{
return Tag ?? Name;
}
#region Properties
public string DisplayedLabel
{
get { return Label ?? Name; }
}
public String Name
{
get{return name;}
set{name = value;}
}
public String Comment
{
get{return comment;}
set{comment = value;}
}
public virtual String Tag
{
get{return tag;}
set{tag = value;}
}
public List<String> Xpaths
{
get{return xpaths;}
set{xpaths = value;}
}
public String ContextNode
{
get{return contextNode;}
set{contextNode = value;}
}
public DictionaryList<String, MetaMetadataField> Kids
{
get { return kids ?? (kids = new DictionaryList<string, MetaMetadataField>()); }
set{kids = value;}
}
public Boolean Hide
{
get{return hide;}
set{hide = value;}
}
public Boolean AlwaysShow
{
get{return alwaysShow;}
set{alwaysShow = value;}
}
public String Style
{
get{return style;}
set{style = value;}
}
public Single Layer
{
get{return layer;}
set{layer = value;}
}
public String NavigatesTo
{
get{return navigatesTo;}
set{navigatesTo = value;}
}
public String Shadows
{
get{return shadows;}
set{shadows = value;}
}
public String Label
{
get{return label;}
set{label = value;}
}
public Boolean IsFacet
{
get{return isFacet;}
set{isFacet = value;}
}
public Boolean IgnoreInTermVector
{
get{return ignoreInTermVector;}
set{ignoreInTermVector = value;}
}
public String FieldParserKey
{
get { return fieldParserKey; }
set { fieldParserKey = value; }
}
public Boolean HasChildren()
{
return kids != null && kids.Count > 0;
}
// public String Type
// {
// get { return null; }
// }
public virtual String GetMmdType()
{
return null;
}
public virtual String GetMmdExtendsAttribute()
{
return null;
}
public MetadataClassDescriptor MetadataClassDescriptor
{
get { return metadataClassDescriptor; }
set
{
metadataClassDescriptor = value;
metadataClass = value.DescribedClass;
}
}
#endregion
public String Key()
{
return name;
}
public MetadataFieldDescriptor MetadataFieldDescriptor
{
get { return metadataFieldDescriptor; }
set{ metadataFieldDescriptor = value; }
}
public MetaMetadataField SuperField
{
get { return superField; }
set { superField = value; }
}
public MetaMetadata DeclaringMmd
{
get { return declaringMmd; }
set { declaringMmd = value; }
}
public MetaMetadata InlineMmd
{
get { return inlineMmd; }
set { inlineMmd = value; }
}
public HashSet<string> NonDisplayedFieldNames
{
get { return nonDisplayedFieldNames; }
set { nonDisplayedFieldNames = value; }
}
public string AsNaturalId
{
get { return asNaturalId; }
set { asNaturalId = value; }
}
public Type MetadataClass
{
get
{
if (metadataClass == null && MetadataClassDescriptor != null)
metadataClass = MetadataClassDescriptor.DescribedClass;
return metadataClass;
}
}
public MetaMetadataField LookupChild(String name)
{
MetaMetadataField result;
kids.TryGetValue(name, out result);
return result;
}
public IEnumerator<MetaMetadataField> GetEnumerator()
{
return (kids != null) ? kids.Values.GetEnumerator() : EMPTY_ITERATOR;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public String GetDisplayedLabel()
{
String result = _displayedLabel;
if (result == null)
{
if (label != null)
result = label;
else
result = name.Replace("_", " ");
_displayedLabel = result;
}
return result;
}
public bool IsChildFieldDisplayed(String childName)
{
return NonDisplayedFieldNames == null ? true : !NonDisplayedFieldNames.Contains(childName);
}
/**
* get the type name of this field, in terms of meta-metadata.
*
* TODO redefining this.
*
* @return the type name.
*/
abstract public String GetTypeName();
public void InheritAttributes(MetaMetadataField inheritFrom)
{
var classDescriptor = ClassDescriptor.GetClassDescriptor(this);
foreach (MetaMetadataFieldDescriptor fieldDescriptor in classDescriptor.AllFieldDescriptors)
{
if (fieldDescriptor.IsInheritable)
{
ScalarType scalarType = fieldDescriptor.ScalarType;
try
{
if (scalarType != null
&& scalarType.IsDefaultValue(fieldDescriptor.Field, this)
&& !scalarType.IsDefaultValue(fieldDescriptor.Field, inheritFrom))
{
Object value = fieldDescriptor.Field.GetValue(inheritFrom);
fieldDescriptor.Field.SetValue(this, value);
Debug.WriteLine("inherit\t" + this.Name + "." + fieldDescriptor.Name + "\t= " + value);
}
}
catch (Exception e)
{
Debug.WriteLine(inheritFrom.Name + " doesn't have field " + fieldDescriptor.Name + ", ignore it.");
// e.printStackTrace();
}
}
}
}
public MetadataFieldDescriptor BindMetadataFieldDescriptor(SimplTypesScope metadataTScope, MetadataClassDescriptor metadataCd)
{
MetadataFieldDescriptor metadataFd = MetadataFieldDescriptor;
if (metadataFd == null)
{
metadataFd = MetadataFieldDescriptor;
String fieldName = this.GetFieldName(false);
if (metadataFd == null)
{
FieldDescriptor fd = metadataCd.GetFieldDescriptorByFieldName(fieldName);
metadataFd = (MetadataFieldDescriptor)fd;
if (metadataFd != null)
{
// FIXME is the following "if" statement still useful? I never see the condition is
// true. can we remove it? -- yin 7/26/2011
// if we don't have a field, then this is a wrapped collection, so we need to get the
// wrapped field descriptor
if (metadataFd.Field == null)
{
FieldDescriptor wfd = metadataFd.WrappedFd;
metadataFd = (MetadataFieldDescriptor)wfd;
}
MetadataFieldDescriptor = metadataFd;
if (MetadataFieldDescriptor != null)
{
// it is possible that the fieldescriptor in the fieldDescriptor proxy has been removed during clone.
// if so, make a new fieldDescriptorProxy.
if (!_fieldDescriptorProxy.FieldDescriptorExists())
_fieldDescriptorProxy = new MetadataFieldDescriptorProxy(this);
CustomizeFieldDescriptor(metadataTScope, _fieldDescriptorProxy);
}
if (MetadataFieldDescriptor != metadataFd)
{
// the field descriptor has been modified in customizeFieldDescriptor()!
// we need to update it in the class descriptor so that deserialization of metadata
// objects can work correctly, e.g. using the right classDescriptor for a composite
// field or a right elementClassDescriptor for a collection field.
CustomizeFieldDescriptorInClass(metadataTScope, metadataCd);
//String tagName = this.metadataFieldDescriptor.TagName;
//int fieldType = this.metadataFieldDescriptor.FdType;
//if (fieldType == FieldTypes.CollectionElement || fieldType == FieldTypes.MapElement)
// tagName = this.metadataFieldDescriptor.CollectionOrMapTagName;
//metadataClassDescriptor.AllFieldDescriptorsByTagNames.Put(tagName,
// this.metadataFieldDescriptor);
}
}
}
else
{
Debug.WriteLine("Ignoring <" + fieldName +
"> because no corresponding MetadataFieldDescriptor can be found.");
}
}
return metadataFieldDescriptor;
}
private void CustomizeFieldDescriptorInClass(SimplTypesScope metadataTScope, MetadataClassDescriptor metadataCd)
{
MetadataFieldDescriptor oldFD =
(MetadataFieldDescriptor) metadataCd.GetFieldDescriptorByFieldName(GetFieldName(false));
String newTagName = MetadataFieldDescriptor.TagName;
metadataCd.Replace(oldFD, MetadataFieldDescriptor);
MetadataFieldDescriptor wrapperFD = (MetadataFieldDescriptor) MetadataFieldDescriptor.Wrapper;
if (wrapperFD != null)
{
MetadataFieldDescriptor clonedWrapperFD = wrapperFD.Clone();
clonedWrapperFD.TagName = newTagName;
clonedWrapperFD.WrappedFd = metadataFieldDescriptor;
metadataCd.Replace(wrapperFD, clonedWrapperFD);
}
int fieldType = MetadataFieldDescriptor.FdType;
if (fieldType == FieldTypes.CollectionElement || fieldType == FieldTypes.MapElement)
{
if (!MetadataFieldDescriptor.IsWrapped)
{
string childTagName = MetadataFieldDescriptor.CollectionOrMapTagName;
oldFD = (MetadataFieldDescriptor) metadataCd.GetFieldDescriptorByTag(childTagName);
metadataCd.Replace(oldFD, MetadataFieldDescriptor);
}
}
}
protected virtual void CustomizeFieldDescriptor(SimplTypesScope metadataTScope, MetadataFieldDescriptorProxy fieldDescriptorProxy)
{
fieldDescriptorProxy.SetTagName(Tag ?? Name);
}
private string GetFieldName(bool capitalized)
{
if (capitalized)
return GetCapFieldName();
string result = _fieldNameInCSharp;
if(result == null)
{
result = XmlTools.FieldNameFromElementName(Name);
_fieldNameInCSharp = result;
}
return _fieldNameInCSharp;
}
private String _fieldNameInCSharp = null;
private String _capFieldNameInCSharp = null;
public String GetCapFieldName()
{
String rst = _capFieldNameInCSharp;
if (rst == null)
{
rst = XmlTools.CamelCaseFromXMLElementName(Name, true);
_capFieldNameInCSharp = rst;
}
return _capFieldNameInCSharp;
}
private String _toString = null;
public override string ToString()
{
String result = _toString;
if (result == null)
{
result = this.GetType().Name + ParentString() + "<" + this.Name + ">";
_toString = result;
}
return result;
}
public String ParentString()
{
StringBuilder result = new StringBuilder();
ElementState parent = this.Parent;
while (parent is MetaMetadataField)
{
MetaMetadataField pf = (MetaMetadataField) parent;
result.Insert(0, "<" + pf.Name + ">");
parent = parent.Parent;
}
return result.ToString();
}
/**
* this class encapsulate the clone-on-write behavior of metadata field descriptor associated
* with this field.
*
* @author quyin
*
*/
protected internal class MetadataFieldDescriptorProxy
{
private MetaMetadataField outer;
public MetadataFieldDescriptorProxy(MetaMetadataField outer)
{
this.outer = outer;
}
private void CloneFieldDescriptorOnWrite()
{
if (outer.MetadataFieldDescriptor.DescriptorClonedFrom == null)
outer.MetadataFieldDescriptor = outer.MetadataFieldDescriptor.Clone();
}
public void SetTagName(String newTagName)
{
if (newTagName != null && !newTagName.Equals(outer.MetadataFieldDescriptor.TagName))
{
CloneFieldDescriptorOnWrite();
outer.MetadataFieldDescriptor.TagName = newTagName;
}
}
public void SetElementClassDescriptor(MetadataClassDescriptor metadataClassDescriptor)
{
if (metadataClassDescriptor != outer.MetadataFieldDescriptor.ElementClassDescriptor)
{
CloneFieldDescriptorOnWrite();
outer.MetadataFieldDescriptor.SetElementClassDescriptor(metadataClassDescriptor);
}
}
public void SetCollectionOrMapTagName(String childTag)
{
if (childTag != null && !childTag.Equals(outer.MetadataFieldDescriptor.CollectionOrMapTagName))
{
CloneFieldDescriptorOnWrite();
outer.MetadataFieldDescriptor.CollectionOrMapTagName = childTag;
}
}
public void SetWrapped(bool wrapped)
{
if (wrapped != outer.MetadataFieldDescriptor.IsWrapped)
{
CloneFieldDescriptorOnWrite();
outer.MetadataFieldDescriptor.IsWrapped = wrapped;
}
}
public Boolean FieldDescriptorExists()
{
return outer.metadataFieldDescriptor != null;
}
}
internal MetaMetadataField Clone()
{
return (MetaMetadataField) this.MemberwiseClone();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NAudio.Utils;
using NAudio.Midi;
namespace MarkHeath.MidiUtils
{
class MidiConverter
{
public event EventHandler<ProgressEventArgs> Progress;
int filesConverted;
int filesCopied;
int directoriesCreated;
int errors;
DateTime startTime;
Properties.Settings settings;
Regex ezdFileName;
NamingRules namingRules;
public MidiConverter(NamingRules namingRules)
{
settings = Properties.Settings.Default;
this.namingRules = namingRules;
ezdFileName = new Regex(namingRules.FilenameRegex);
}
public void Start()
{
filesConverted = 0;
filesCopied = 0;
directoriesCreated = 0;
errors = 0;
startTime = DateTime.Now;
LogInformation("{0} Beginning to Convert MIDI Files...", startTime);
LogInformation("Processing using EZdrummer MIDI Converter v{0}", System.Windows.Forms.Application.ProductVersion);
LogInformation("Output MIDI type {0}", settings.OutputMidiType);
LogInformation("Output Channel Number {0}", settings.OutputChannelNumber == -1 ? "Unchanged" : settings.OutputChannelNumber.ToString());
// warn user if they are using hidden settings
if (settings.RemoveSequencerSpecific)
{
LogWarning("Sequencer Specific Messages will be turned off");
}
if (settings.RemoveEmptyTracks)
{
LogWarning("Empty type 1 tracks will be removed");
}
if (!settings.RecreateEndTrackMarkers)
{
LogWarning("End track markers will be left where they are");
}
if (settings.TrimTextEvents)
{
LogWarning("Text events will have whitespace trimmed");
}
if (settings.AddNameMarker)
{
LogWarning("Name markers will be added");
}
if (settings.RemoveExtraTempoEvents)
{
LogWarning("Extra tempo events will be removed");
}
if (settings.RemoveExtraMarkers)
{
LogWarning("Extra markers will be removed");
}
ProcessFolder(settings.InputFolder, settings.OutputFolder, new string[0]);
TimeSpan timeTaken = DateTime.Now - startTime;
LogInformation("Finished in {0}", timeTaken);
LogInformation(Summary);
}
private string[] CreateNewContext(string[] oldContext, string newContextItem)
{
string[] newContext = new string[oldContext.Length + 1];
for (int n = 0; n < oldContext.Length; n++)
{
newContext[n] = oldContext[n];
}
newContext[oldContext.Length] = newContextItem;
return newContext;
}
private void ProcessFolder(string folder, string outputFolder, string[] context)
{
string[] midiFiles = Directory.GetFiles(folder);
foreach (string midiFile in midiFiles)
{
try
{
ProcessFile(midiFile, outputFolder, context);
}
catch (Exception e)
{
LogError("Unexpected error processing file {0}", midiFile);
LogError(e.ToString());
errors++;
}
}
string[] subfolders = Directory.GetDirectories(folder);
foreach (string subfolder in subfolders)
{
string folderName = Path.GetFileName(subfolder);
string newOutputFolder = Path.Combine(outputFolder, folderName);
string[] newContext = CreateNewContext(context, folderName);
if (!Directory.Exists(newOutputFolder))
{
if (settings.VerboseOutput)
{
LogTrace("Creating folder {0}", newOutputFolder);
}
Directory.CreateDirectory(newOutputFolder);
directoriesCreated++;
}
ProcessFolder(subfolder, newOutputFolder, newContext);
}
}
private void ProcessFile(string file, string outputFolder, string[] context)
{
bool copy = false;
string fileName = Path.GetFileName(file);
string target = Path.Combine(outputFolder, fileName);
if (Path.GetExtension(file).ToLower() == ".mid")
{
MidiFile midiFile = new MidiFile(file);
ConvertMidi(midiFile, target, CreateNewContext(context, Path.GetFileNameWithoutExtension(file)));
filesConverted++;
}
else
{
copy = true;
}
if (copy)
{
if (settings.VerboseOutput)
{
LogTrace("Copying File {0} to {1}", fileName, target);
}
File.Copy(file, target);
filesCopied++;
}
}
private void ConvertMidi(MidiFile midiFile, string target, string[] context)
{
string fileNameWithoutExtension = context[context.Length - 1];
string name = null;
long endTrackTime = -1;
if (settings.UseFileName)
{
name = fileNameWithoutExtension;
}
if (settings.ApplyNamingRules)
{
if (ezdFileName.Match(fileNameWithoutExtension).Success)
{
name = CreateEzdName(context);
}
}
int outputFileType = midiFile.FileFormat;
int outputTrackCount;
if (settings.OutputMidiType == OutputMidiType.Type0)
{
outputFileType = 0;
}
else if (settings.OutputMidiType == OutputMidiType.Type1)
{
outputFileType = 1;
}
if (outputFileType == 0)
{
outputTrackCount = 1;
}
else
{
if (midiFile.FileFormat == 0)
outputTrackCount = 2;
else
outputTrackCount = Math.Max(midiFile.Tracks,2); // at least two tracks because we'll move notes onto track 1 always
}
MidiEventCollection events = new MidiEventCollection(outputFileType, midiFile.DeltaTicksPerQuarterNote);
for (int track = 0; track < outputTrackCount; track++)
{
events.AddTrack();
}
if (name != null)
{
for (int track = 0; track < outputTrackCount; track++)
{
events[track].Add(new TextEvent(name, MetaEventType.SequenceTrackName, 0));
}
if (settings.AddNameMarker)
{
events[0].Add(new TextEvent(name, MetaEventType.Marker, 0));
}
}
foreach (MidiEvent midiEvent in midiFile.Events[0])
{
if (settings.OutputChannelNumber != -1)
midiEvent.Channel = settings.OutputChannelNumber;
MetaEvent metaEvent = midiEvent as MetaEvent;
if (metaEvent != null)
{
bool exclude = false;
switch (metaEvent.MetaEventType)
{
case MetaEventType.SequenceTrackName:
if (name != null)
{
exclude = true;
}
break;
case MetaEventType.SequencerSpecific:
exclude = settings.RemoveSequencerSpecific;
break;
case MetaEventType.EndTrack:
exclude = settings.RecreateEndTrackMarkers;
endTrackTime = metaEvent.AbsoluteTime;
break;
case MetaEventType.SetTempo:
if (metaEvent.AbsoluteTime != 0 && settings.RemoveExtraTempoEvents)
{
LogWarning("Removing a tempo event ({0}bpm) at {1} from {2}", ((TempoEvent)metaEvent).Tempo, metaEvent.AbsoluteTime, target);
exclude = true;
}
break;
case MetaEventType.TextEvent:
if (settings.TrimTextEvents)
{
TextEvent textEvent = (TextEvent)midiEvent;
textEvent.Text = textEvent.Text.Trim();
if (textEvent.Text.Length == 0)
{
exclude = true;
}
}
break;
case MetaEventType.Marker:
if (settings.AddNameMarker && midiEvent.AbsoluteTime == 0)
{
exclude = true;
}
if (settings.RemoveExtraMarkers && midiEvent.AbsoluteTime > 0)
{
LogWarning("Removing a marker ({0}) at {1} from {2}", ((TextEvent)metaEvent).Text, metaEvent.AbsoluteTime, target);
exclude = true;
}
break;
}
if (!exclude)
{
events[0].Add(midiEvent);
}
}
else
{
if (outputFileType == 1)
events[1].Add(midiEvent);
else
events[0].Add(midiEvent);
}
}
// now do track 1 (Groove Monkee)
for (int inputTrack = 1; inputTrack < midiFile.Tracks; inputTrack++)
{
int outputTrack;
if(outputFileType == 1)
outputTrack = inputTrack;
else
outputTrack = 0;
foreach (MidiEvent midiEvent in midiFile.Events[inputTrack])
{
if (settings.OutputChannelNumber != -1)
midiEvent.Channel = settings.OutputChannelNumber;
bool exclude = false;
MetaEvent metaEvent = midiEvent as MetaEvent;
if (metaEvent != null)
{
switch (metaEvent.MetaEventType)
{
case MetaEventType.SequenceTrackName:
if (name != null)
{
exclude = true;
}
break;
case MetaEventType.SequencerSpecific:
exclude = settings.RemoveSequencerSpecific;
break;
case MetaEventType.EndTrack:
exclude = settings.RecreateEndTrackMarkers;
break;
}
}
if (!exclude)
{
events[outputTrack].Add(midiEvent);
}
}
if(outputFileType == 1 && settings.RecreateEndTrackMarkers)
{
AppendEndMarker(events[outputTrack]);
}
}
if (settings.RecreateEndTrackMarkers)
{
if (outputFileType == 1)
{
// make sure track 1 has an end track marker
AppendEndMarker(events[1]);
}
// make sure that track zero has an end track marker
AppendEndMarker(events[0]);
}
else
{
// if we are converting type 0 to type 1 without recreating end markers,
// then we still need to add an end marker to track 1
if (midiFile.FileFormat == 0)
{
// use the time we got from track 0 as the end track time for track 1
if (endTrackTime == -1)
{
LogError("Error adding track 1 end marker");
// make it a valid MIDI file anyway
AppendEndMarker(events[1]);
}
else
{
events[1].Add(new MetaEvent(MetaEventType.EndTrack, 0, endTrackTime));
}
}
}
if (settings.VerboseOutput)
{
LogTrace("Processing {0}: {1}", name, target);
}
if (settings.RemoveEmptyTracks)
{
MidiEventCollection newList = new MidiEventCollection(events.MidiFileType, events.DeltaTicksPerQuarterNote);
int removed = 0;
for (int track = 0; track < events.Tracks; track++)
{
IList<MidiEvent> trackEvents = events[track];
if (track < 2)
{
newList.AddTrack(events[track]);
}
else
{
if(HasNotes(trackEvents))
{
newList.AddTrack(trackEvents);
}
else
{
removed++;
}
}
}
if (removed > 0)
{
events = newList;
LogWarning("Removed {0} empty tracks from {1} ({2} remain)", removed, target, events.Tracks);
}
}
MidiFile.Export(target, events);
}
private bool HasNotes(IList<MidiEvent> midiEvents)
{
return midiEvents.Any(midiEvent => midiEvent.CommandCode == MidiCommandCode.NoteOn);
}
private bool IsEndTrack(MidiEvent midiEvent)
{
var meta = midiEvent as MetaEvent;
return meta?.MetaEventType == MetaEventType.EndTrack;
}
private void AppendEndMarker(IList<MidiEvent> eventList)
{
long absoluteTime = 0;
if (eventList.Count > 0)
absoluteTime = eventList[eventList.Count - 1].AbsoluteTime;
if (!IsEndTrack(eventList.LastOrDefault()))
eventList.Add(new MetaEvent(MetaEventType.EndTrack, 0, absoluteTime));
}
private string CreateEzdName(string[] context)
{
StringBuilder name = new StringBuilder();
int contextLevels = Math.Min(namingRules.ContextDepth, context.Length);
for (int n = 0; n < contextLevels; n++)
{
string filtered = ApplyNameFilters(context[context.Length - contextLevels + n]);
if (filtered.Length > 0)
{
name.Append(filtered);
if (n != contextLevels - 1)
name.Append(namingRules.ContextSeparator);
}
}
return name.ToString();
}
private string ApplyNameFilters(string name)
{
foreach (NamingRule rule in namingRules.Rules)
{
name = Regex.Replace(name, rule.Regex, rule.Replacement);
}
return name;
}
private void LogTrace(string message, params object[] args)
{
OnProgress(this, new ProgressEventArgs(ProgressMessageType.Trace,
message, args));
}
private void LogInformation(string message, params object[] args)
{
OnProgress(this, new ProgressEventArgs(ProgressMessageType.Information,
message, args));
}
private void LogWarning(string message, params object[] args)
{
OnProgress(this, new ProgressEventArgs(ProgressMessageType.Warning,
message, args));
}
private void LogError(string message, params object[] args)
{
OnProgress(this, new ProgressEventArgs(ProgressMessageType.Error,
message, args));
}
protected void OnProgress(object sender, ProgressEventArgs args)
{
if (Progress != null)
{
Progress(sender, args);
}
}
public string Summary
{
get
{
return String.Format("Files Converted {0}\r\nFiles Copied {1}\r\nFolders Created {2}\r\nErrors {3}", filesConverted, filesCopied, directoriesCreated, errors);
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// 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 Microsoft.OneDrive.Sdk
{
using System;
using System.Threading.Tasks;
public partial class OneDriveClient : IDisposable
{
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating the client.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
IAuthenticationProvider authenticationProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
new ServiceInfoProvider(authenticationProvider),
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="authenticationProvider">The <see cref="IAuthenticationProvider"/> for authenticating the client.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
IAuthenticationProvider authenticationProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
clientSecret,
new ServiceInfoProvider(authenticationProvider),
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static async Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
IServiceInfoProvider serviceInfoProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
var client = OneDriveClient.GetMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
credentialCache,
httpProvider,
serviceInfoProvider);
await client.AuthenticateAsync();
return client;
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static async Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
IServiceInfoProvider serviceInfoProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
var client = OneDriveClient.GetMicrosoftAccountClient(
appId,
returnUrl,
scopes,
clientSecret,
credentialCache,
httpProvider,
serviceInfoProvider);
await client.AuthenticateAsync();
return client;
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="webAuthenticationUi">The <see cref="IWebAuthenticationUi"/> for displaying authentication UI to the user.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
IWebAuthenticationUi webAuthenticationUi,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
webAuthenticationUi,
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="webAuthenticationUi">The <see cref="IWebAuthenticationUi"/> for displaying authentication UI to the user.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
IWebAuthenticationUi webAuthenticationUi,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
clientSecret,
new ServiceInfoProvider(webAuthenticationUi),
credentialCache,
httpProvider);
}
/// <summary>
/// Creates a OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static IOneDriveClient GetMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null,
IServiceInfoProvider serviceInfoProvider = null)
{
var appConfig = new AppConfig
{
MicrosoftAccountAppId = appId,
MicrosoftAccountClientSecret = clientSecret,
MicrosoftAccountReturnUrl = returnUrl,
MicrosoftAccountScopes = scopes,
};
return new OneDriveClient(appConfig, credentialCache, httpProvider, serviceInfoProvider);
}
/// <summary>
/// Creates a OneDrive client for use against OneDrive consumer.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <param name="webAuthenticationUi">The <see cref="IWebAuthenticationUi"/> for displaying authentication UI to the user.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static IOneDriveClient GetMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null,
IWebAuthenticationUi webAuthenticationUi = null)
{
return OneDriveClient.GetMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
credentialCache,
httpProvider,
new ServiceInfoProvider(webAuthenticationUi));
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer for silent (refresh token) authentication.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="refreshToken">The refresh token for silent authentication.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetSilentlyAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string refreshToken,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
refreshToken,
new ServiceInfoProvider(),
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer for silent (refresh token) authentication.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="refreshToken">The refresh token for silent authentication.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetSilentlyAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
string refreshToken,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
clientSecret,
refreshToken,
new ServiceInfoProvider(),
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer for silent (refresh token) authentication.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="refreshToken">The refresh token for silent authentication.</param>
/// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static Task<IOneDriveClient> GetSilentlyAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string refreshToken,
IServiceInfoProvider serviceInfoProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
return OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
appId,
returnUrl,
scopes,
/* clientSecret */ null,
refreshToken,
serviceInfoProvider,
credentialCache,
httpProvider);
}
/// <summary>
/// Creates an authenticated OneDrive client for use against OneDrive consumer for silent (refresh token) authentication.
/// </summary>
/// <param name="appId">The application ID for Microsoft account authentication.</param>
/// <param name="returnUrl">The application return URL for Microsoft account authentication.</param>
/// <param name="scopes">The requested scopes for Microsoft account authentication.</param>
/// <param name="clientSecret">The client secret for Microsoft account authentication.</param>
/// <param name="refreshToken">The refresh token for silent authentication.</param>
/// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
/// <param name="credentialCache">The cache instance for storing user credentials.</param>
/// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
/// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
public static async Task<IOneDriveClient> GetSilentlyAuthenticatedMicrosoftAccountClient(
string appId,
string returnUrl,
string[] scopes,
string clientSecret,
string refreshToken,
IServiceInfoProvider serviceInfoProvider,
CredentialCache credentialCache = null,
IHttpProvider httpProvider = null)
{
var clientServiceInfoProvider = serviceInfoProvider ?? new ServiceInfoProvider();
var client = OneDriveClient.GetMicrosoftAccountClient(
appId,
returnUrl,
scopes,
clientSecret,
credentialCache,
httpProvider,
clientServiceInfoProvider) as OneDriveClient;
if (client.ServiceInfo == null)
{
client.ServiceInfo = await clientServiceInfoProvider.GetServiceInfo(
client.appConfig,
client.credentialCache,
client.HttpProvider,
client.ClientType);
}
client.AuthenticationProvider.CurrentAccountSession = new AccountSession { RefreshToken = refreshToken };
await client.AuthenticateAsync();
return client;
}
/// <summary>
/// Gets the default drive.
/// </summary>
public IDriveRequestBuilder Drive
{
get
{
return new DriveRequestBuilder(string.Format("{0}/{1}", this.BaseUrl, Constants.Url.Drive), this);
}
}
/// <summary>
/// Gets item request builder for the specified item path.
/// <returns>The item request builder.</returns>
/// </summary>
public IItemRequestBuilder ItemWithPath(string path)
{
return new ItemRequestBuilder(
string.Format("{0}{1}:", this.BaseUrl, path),
this);
}
public void Dispose()
{
var httpProvider = this.HttpProvider as HttpProvider;
if (httpProvider != null)
{
httpProvider.Dispose();
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Monitor.Model;
using Monitor.Model.Api;
using Monitor.Model.Sessions;
using Monitor.Properties;
namespace Monitor.ViewModel.NewSession
{
public class NewApiSessionViewModel : ViewModelBase, IDataErrorInfo, INewSessionViewModel
{
private readonly IApiClient _apiClient;
private readonly ISessionService _sessionService;
private ProjectViewModel _selectedProject;
private InstanceViewModel _selectedInstance;
private ObservableCollection<ProjectViewModel> _projects = new ObservableCollection<ProjectViewModel>();
private ObservableCollection<InstanceViewModel> _instances = new ObservableCollection<InstanceViewModel>();
private string _userId;
private string _endpointAddress;
private string _accessToken;
public NewApiSessionViewModel(IApiClient apiClient, ISessionService sessionService)
{
_apiClient = apiClient;
_sessionService = sessionService;
ConnectCommand = new RelayCommand(Connect, IsConnectionSettingsValid);
OpenCommand = new RelayCommand(Open, CanOpen);
LoadFromSettings();
// Try to initially make a connection
if (IsConnectionSettingsValid())
{
Connect();
}
}
private void Open()
{
_sessionService.OpenApi(new ApiSessionParameters
{
InstanceId = SelectedInstance.Id,
ProjectId = SelectedProject.ProjectId,
InstanceType = SelectedInstance.Type
});
}
private bool CanOpen()
{
var fieldsToValidate = new[]
{
nameof(SelectedProject),
nameof(SelectedInstance),
};
return fieldsToValidate.All(field => string.IsNullOrEmpty(this[field]));
}
public string UserId
{
get { return _userId; }
set
{
_userId = value;
RaisePropertyChanged();
ConnectCommand.RaiseCanExecuteChanged();
}
}
public string EndpointAddress
{
get { return _endpointAddress; }
set
{
_endpointAddress = value;
RaisePropertyChanged();
ConnectCommand.RaiseCanExecuteChanged();
}
}
public string AccessToken
{
get { return _accessToken; }
set
{
_accessToken = value;
RaisePropertyChanged();
ConnectCommand.RaiseCanExecuteChanged();
}
}
public RelayCommand ConnectCommand { get; }
public RelayCommand OpenCommand { get; }
public ObservableCollection<ProjectViewModel> Projects
{
get { return _projects; }
private set
{
_projects = value;
RaisePropertyChanged();
}
}
public ObservableCollection<InstanceViewModel> Instances
{
get { return _instances; }
set
{
_instances = value;
RaisePropertyChanged();
}
}
public ProjectViewModel SelectedProject
{
get { return _selectedProject; }
set
{
_selectedProject = value;
RaisePropertyChanged();
// Refresh instances when SelectedProject changed
RefreshInstancesAsync();
}
}
public InstanceViewModel SelectedInstance
{
get { return _selectedInstance; }
set
{
_selectedInstance = value;
RaisePropertyChanged();
OpenCommand.RaiseCanExecuteChanged();
}
}
public string this[string columnName]
{
get
{
string result = string.Empty;
switch (columnName)
{
case nameof(UserId):
int userId;
if (!int.TryParse(UserId, out userId)) result = "User Id should be a numeric value.";
break;
case nameof(EndpointAddress):
if (string.IsNullOrWhiteSpace(EndpointAddress)) result = "Endpoint Address is required.";
Uri uri;
if (!Uri.TryCreate(EndpointAddress, UriKind.Absolute, out uri)) result = "Address is invalid";
break;
case nameof(AccessToken):
if (string.IsNullOrWhiteSpace(AccessToken)) result = "Access token is required.";
break;
case nameof(SelectedProject):
if (SelectedProject == null) result = "Project is required";
break;
case nameof(SelectedInstance):
if (SelectedInstance == null) result = "Instance is required";
else if (!SelectedInstance.IsCompleted)
result = "Due to API restrictions, only completed instances can be opened";
break;
}
return result;
}
}
public string Error => null;
public bool IsConnectionSettingsValid()
{
var fieldsToValidate = new[]
{
nameof(UserId),
nameof(EndpointAddress),
nameof(AccessToken)
};
return fieldsToValidate.All(field => string.IsNullOrEmpty(this[field]));
}
public bool IsConnected => _apiClient.Connected;
private void Connect()
{
_apiClient.Initialize(int.Parse(UserId), AccessToken, EndpointAddress);
RaisePropertyChanged(() => IsConnected);
if (IsConnected)
{
// Save the connection settings, as this connection is now valid
SaveConnectionSettings();
RefreshProjectsAsync();
}
else
{
Projects.Clear();
Instances.Clear();
}
}
private void LoadFromSettings()
{
var settings = Settings.Default;
UserId = settings.ApiUserId.ToString();
EndpointAddress = settings.ApiBaseUrl;
AccessToken = settings.ApiAccessToken;
}
private void SaveConnectionSettings()
{
var settings = Settings.Default;
settings.ApiUserId = int.Parse(UserId);
settings.ApiBaseUrl = EndpointAddress;
settings.ApiAccessToken = AccessToken;
}
private async void RefreshProjectsAsync()
{
var projects = await _apiClient.GetProjectsAsync();
Projects = new ObservableCollection<ProjectViewModel>(projects.OrderByDescending(p => p.Modified).Select(p => new ProjectViewModel
{
Name = p.Name,
ProjectId = p.ProjectId,
Created = p.Created,
Modified = p.Modified
}));
SelectedProject = Projects.FirstOrDefault();
}
private async void RefreshInstancesAsync()
{
if (SelectedProject == null)
{
SelectedInstance = null;
Instances.Clear();
return;
}
var instances = await _apiClient.GetBacktestsAsync(SelectedProject.ProjectId);
Instances = new ObservableCollection<InstanceViewModel>(instances.Where(i => i.Completed).Select(i => new InstanceViewModel
{
Name = i.Name,
Id = i.BacktestId,
Type = ResultType.Backtest,
Note = i.Note,
Progress = i.Progress
}));
SelectedInstance = Instances.FirstOrDefault();
}
public string Header { get; } = "From API";
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
public static class MarkerFetcher
{
public static Data<Variable> FindMethodExtractMarkers<Local, Parameter, Method, Field, Property, Event, Typ, Attribute, Assembly, Expression, Variable>(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Typ, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
where Typ : IEquatable<Typ>
where Expression : IEquatable<Expression>
where Variable : IEquatable<Variable>
{
return TypeBindings<Local, Parameter, Method, Field, Property, Event, Typ, Attribute, Assembly, Expression, Variable>.RunTheAnalysis(mdriver);
}
public struct Data<Variable>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.Version >= 0);
}
#endregion
#region State
public int Version { get; private set; }
public Info Precondition { get; private set; }
public Info Postcondition { get; private set; }
public Info Invariant { get; private set; }
#endregion
#region Constructors
private Data(int version, Info Precondition, Info Postcondition, Info Invariant)
: this()
{
Contract.Requires(version >= 0);
this.Version = version;
this.Precondition = Precondition;
this.Postcondition = Postcondition;
this.Invariant = Invariant;
}
#endregion
public Data<Variable> UpdatePrecondition(APC pc, FList<Variable> Variables)
{
return new Data<Variable>(this.Version + 1, new Info() { PC = pc, Variables = Variables }, this.Postcondition, this.Invariant);
}
public Data<Variable> UpdatePostcondition(APC pc, Variable retVar, FList<Variable> Variables)
{
return new Data<Variable>(this.Version + 1, this.Precondition, new Info() { PC = pc, ReturnVariable = retVar, Variables = Variables }, this.Invariant);
}
public Data<Variable> UpdatePostcondition(APC pc, FList<Variable> Variables)
{
return new Data<Variable>(this.Version + 1, this.Precondition, new Info() { PC = pc, Variables = Variables }, this.Invariant);
}
public Data<Variable> UpdateInvariant(APC pc, FList<Variable> Variables)
{
return new Data<Variable>(this.Version + 1, this.Precondition, this.Postcondition, new Info() { PC = pc, Variables = Variables });
}
public struct Info
{
public bool HasReturnVariable { get; private set; }
private Variable returnVariable;
public Variable ReturnVariable
{
get
{
return this.returnVariable;
}
internal set
{
HasReturnVariable = true;
this.returnVariable = value;
}
}
public APC PC { get; internal set; }
public FList<Variable> Variables { get; internal set; }
}
}
public static class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable>
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
public static Data<Variable> RunTheAnalysis(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
{
var analysis = new MarkersFetcherAnalysis(mdriver);
var closure = mdriver.HybridLayer.CreateForward(analysis, new DFAOptions { Trace = mdriver.Options.TraceDFA, Timeout = mdriver.Options.Timeout, EnforceFairJoin = mdriver.Options.EnforceFairJoin, IterationsBeforeWidening = mdriver.Options.IterationsBeforeWidening, TraceTimePerInstruction = mdriver.Options.TraceTimings, TraceMemoryPerInstruction = mdriver.Options.TraceMemoryConsumption }, null);
closure(analysis.GetTopValue());
return analysis.Result;
}
[ContractVerification(true)]
class MarkersFetcherAnalysis
: MSILVisitor<APC, Local, Parameter, Method, Field, Type, Variable, Variable, Data<Variable>, Data<Variable>>
, IAbstractAnalysis<Local, Parameter, Method, Field, Property, Type, Expression, Attribute, Assembly, Data<Variable>, Variable>
{
#region Constants
const string PRECONDITIONMARKER = "__PreconditionMarker";
const string POSTCONDITIONMARKER = "__PostconditionMarker";
const string INVARIANTMARKER = "___ClousotInvariantAt";
#endregion
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.mDriver != null);
}
#endregion
#region State
public Data<Variable> Result { get; private set; }
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mDriver;
#endregion
#region Constructor
public MarkersFetcherAnalysis(
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver)
{
Contract.Requires(mdriver != null);
this.mDriver = mdriver;
}
#endregion
#region overridden
public override Data<Variable> Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, Data<Variable> data)
// where TypeList : IIndexable<Type>
// where ArgList : IIndexable<Variable>
{
var mdd = this.mDriver.MetaDataDecoder;
Contract.Assert(mdd != null); // was an assume
var methodName = mdd.Name(method);
var skipFirstArgument = !mdd.IsStatic(method); // We want to skip the first parameter when it is this
/*
if (methodName == null)
{
return data;
}
*/
Contract.Assert(methodName != null);
if (methodName.Contains(PRECONDITIONMARKER))
{
// For preconditions, to get Ps, the only variables we are intested in ref values
// As we have problems with the symbolic values, we assume the contract that the Roslyn integration passes us only the variables that will be used byRef in the call
var variablesForPs = FList<Variable>.Empty;
var i = mdd.IsStatic(method) ? 0 : 1;
foreach (var p in mdd.Parameters(method).Enumerate())
{
Contract.Assume(i < args.Count, "Assuming the global invariant");
variablesForPs = variablesForPs.Cons(args[i]);
i++;
}
return data.UpdatePrecondition(pc, variablesForPs);
}
if (methodName.Contains(POSTCONDITIONMARKER))
{
// We use the protocol that if the last parameter is set to true, then the but last actual parameter is the sv of the value
// returned from the extract method
if (args.Count > 0) // sanity check to make the code more robust
{
Type t;
object value;
if (this.mDriver.Context.ValueContext.IsConstant(pc, args[args.Count - 1], out t, out value)
&& mdd.System_Int32.Equals(t) && value.Equals(1) && args.Count > 1)
{
var retVar = args[args.Count - 2];
return data.UpdatePostcondition(pc, retVar, AddVariablesForsArrayLengths(pc, ToFList(args, args.Count - 2, skipFirstArgument)));
}
return data.UpdatePostcondition(pc, AddVariablesForsArrayLengths(pc, ToFList(args, skipThis: skipFirstArgument)));
}
}
if (methodName.Contains(INVARIANTMARKER))
{
return data.UpdateInvariant(pc, AddVariablesForsArrayLengths(pc, ToFList(args, skipThis: skipFirstArgument)));
}
return data;
}
public override Data<Variable> Return(APC pc, Variable source, Data<Variable> data)
{
this.Result = data;
return data;
}
#endregion
#region Default: Do nothing
protected override Data<Variable> Default(APC pc, Data<Variable> data)
{
return data;
}
#endregion
#region Utils
private FList<Variable> AddVariablesForsArrayLengths(APC pc, FList<Variable> variables)
{
Contract.Ensures(variables == null || Contract.Result<FList<Variable>>() != null);
if(variables == FList<Variable>.Empty)
{
return variables;
}
var postPC = pc.Post();
var arrayLenghts = FList<Variable>.Empty;
foreach (var v in variables.GetEnumerable())
{
Variable vLength;
if (this.mDriver.Context.ValueContext.TryGetArrayLength(postPC, v, out vLength))
{
arrayLenghts = arrayLenghts.Cons(vLength);
}
}
if (!arrayLenghts.IsEmpty())
{
variables = variables.Append(arrayLenghts);
Contract.Assert(variables != null);
}
return variables;
}
[Pure]
public static FList<Variable> ToFList<IIndexable>(IIndexable args, int length = -1, bool skipThis=true)
where IIndexable : IIndexable<Variable>
{
var head = FList<Variable>.Empty;
if (args == null)
return head;
var count = 0;
if (length == -1)
length = args.Count;
foreach (var x in args.Enumerate())
{
if (count++ == length)
break;
// skip this?
if (skipThis && count == 1)
continue;
head.Append(head);
head = head.Cons(x);
}
return head;
}
#endregion
public Data<Variable> GetTopValue()
{
return new Data<Variable>();
}
public Data<Variable> GetBottomValue()
{
return new Data<Variable>();
}
public IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, Data<Variable>> fixpoint)
{
return null;
}
public Data<Variable> EdgeConversion(APC from, APC next, bool joinPoint, IFunctionalMap<Variable, FList<Variable>> edgeData, Data<Variable> newState)
{
// We do not want to convert the variables!
return newState;
}
public Data<Variable> Join(Pair<APC, APC> edge, Data<Variable> newState, Data<Variable> prevState, out bool weaker, bool widen)
{
if(newState.Version >= prevState.Version)
{
if(newState.Precondition.PC.Equals(prevState.Precondition.PC) &&
newState.Postcondition.PC.Equals(prevState.Postcondition.PC) &&
newState.Invariant.PC.Equals(prevState.Invariant.PC))
{
weaker = false;
return prevState;
}
weaker = true;
return newState;
}
else
{
weaker = false;
return prevState;
}
}
public Data<Variable> MutableVersion(Data<Variable> state)
{
return state;
}
public Data<Variable> ImmutableVersion(Data<Variable> state)
{
return state;
}
public void Dump(Pair<Data<Variable>, System.IO.TextWriter> pair)
{
pair.Two.WriteLine(pair.One.Version);
}
public bool IsBottom(APC pc, Data<Variable> state)
{
return false;
}
public bool IsTop(APC pc, Data<Variable> state)
{
return false;
}
public IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Variable, Variable, Data<Variable>, Data<Variable>> Visitor()
{
return this;
}
public Predicate<APC> CacheStates(IFixpointInfo<APC, Data<Variable>> fixpointInfo)
{
return apc => false;
}
}
}
}
}
| |
using System;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/************************************************************************************************************
This test does the following:
A directed weighted graph is constructed with 'n' nodes and random edges.
All the nodes are made reachable.
A random node is deleted and the entire graph is restructured by deleting the related edges
and entries in the adjacent-node list.
n is 800 here
*************************************************************************************************************/
namespace DefaultNamespace
{
public class Graph
{
private Vertex _vfirst = null;
private Vertex _vlast = null;
private Edge _efirst = null;
private Edge _elast = null;
private int _weightSum = 0;
public static int Nodes;
public Graph(int n) { Nodes = n; }
public void SetWeightSum()
{
Edge temp = _efirst;
_weightSum = 0;
while (temp != null)
{
_weightSum += temp.Weight;
temp = temp.Next;
}
}
public int GetWeightSum()
{
return _weightSum;
}
public void BuildEdge(int v1, int v2)
{
Vertex n1 = null, n2 = null;
Vertex temp = _vfirst;
while (temp != null)
{
int i = Decimal.Compare(v1, temp.Name);
if (i == 0)
{
//found 1st node..
n1 = temp;
break;
}
else temp = temp.Next;
}
//check if edge already exists
for (int i = 0; i < n1.Num_Edges; i++)
{
int j = Decimal.Compare(v2, n1.Adjacent[i].Name);
if (j == 0) return;
}
temp = _vfirst;
while (temp != null)
{
int i = Decimal.Compare(v2, temp.Name);
if (i == 0)
{
//found 2nd node..
n2 = temp;
break;
}
else temp = temp.Next;
}
n1.Adjacent[n1.Num_Edges++] = n2;
Edge temp2 = new Edge(n1, n2);
if (_efirst == null)
{
_efirst = temp2;
_elast = temp2;
}
else
{
temp2.AddEdge(_elast, temp2);
_elast = temp2;
}
}
public void BuildGraph()
{
// Build Nodes
TestLibrary.Logging.WriteLine("Building Vertices...");
for (int i = 0; i < Nodes; i++)
{
Vertex temp = new Vertex(i);
if (_vfirst == null)
{
_vfirst = temp;
_vlast = temp;
}
else
{
temp.AddVertex(_vlast, temp);
_vlast = temp;
}
TestLibrary.Logging.WriteLine("Vertex {0} built...", i);
}
// Build Edges
TestLibrary.Logging.WriteLine("Building Edges...");
DateTime time = DateTime.Now;
Int32 seed = (Int32)time.Ticks;
Random rand = new Random(seed);
for (int i = 0; i < Nodes; i++)
{
int j = rand.Next(0, Nodes);
for (int k = 0; k < j; k++)
{
int v2;
while ((v2 = rand.Next(0, Nodes)) == i) ; //select a random node, also avoid self-loops
BuildEdge(i, v2); //build edge betn node i and v2
//TestLibrary.Logging.WriteLine("Edge built between {0} and {1}...",i,v2);
}
}
}
public void CheckIfReachable()
{
int[] temp = new int[Nodes];
Vertex t1 = _vfirst;
TestLibrary.Logging.WriteLine("Making all vertices reachable...");
while (t1 != null)
{
for (int i = 0; i < t1.Num_Edges; i++)
{
if (temp[t1.Adjacent[i].Name] == 0)
temp[t1.Adjacent[i].Name] = 1;
}
t1 = t1.Next;
}
for (int v2 = 0; v2 < Nodes; v2++)
{
if (temp[v2] == 0)
{ //this vertex is not connected
DateTime time = DateTime.Now;
Int32 seed = (Int32)time.Ticks;
Random rand = new Random(seed);
int v1;
while ((v1 = rand.Next(0, Nodes)) == v2) ; //select a random node, also avoid self-loops
BuildEdge(v1, v2);
temp[v2] = 1;
}
}
}
/*public void TraverseGraph() {
Vertex root = Vfirst;
int i=0,j=0;
Vertex next = root.Adjacent[i];
while(j<Nodes) {
TestLibrary.Logging.WriteLine("root: " + root.Name);
while(next != null) {
TestLibrary.Logging.WriteLine(next.Name);
if(next.Name == j) {break;}
next = next.Adjacent[0];
}
i++;
if((next = root.Adjacent[i]) == null) {
i=0;
j++;
if(root == Vlast) break;
else root = root.Next;
next = root.Adjacent[i];
}
}
}*/
public void DeleteVertex()
{
Vertex temp1 = null;
Vertex temp2 = _vfirst;
DateTime time = DateTime.Now;
Int32 seed = (Int32)time.Ticks;
Random rand = new Random(seed);
int j = rand.Next(0, Nodes);
//TestLibrary.Logging.WriteLine("Deleting vertex: " + j);
while (temp2 != null)
{
int i = Decimal.Compare(j, temp2.Name);
if (i == 0)
{
if (temp2 == _vfirst)
{
temp2 = null;
_vfirst = _vfirst.Next;
break;
}
temp1.Next = temp2.Next;
temp2 = null;
break;
}
else
{
temp1 = temp2;
temp2 = temp2.Next;
}
}
// Restructuring the Graph
TestLibrary.Logging.WriteLine("Restructuring the Graph...");
temp2 = _vfirst;
while (temp2 != null)
{
temp2.DeleteAdjacentEntry(j);
temp2 = temp2.Next;
}
Edge e1 = null;
Edge e2 = _efirst;
Edge temp = null;
while (e2 != null)
{
int v1 = Decimal.Compare(j, e2.v1.Name);
int v2 = Decimal.Compare(j, e2.v2.Name);
if ((v1 == 0) || (v2 == 0))
{
if (e2 == _efirst)
{
temp = e2;
e2 = e2.Next;
_efirst = _efirst.Next;
temp = null;
}
else
{
temp = e1;
e1.Next = e2.Next;
e2 = e2.Next;
}
}
else
{
e1 = e2;
e2 = e2.Next;
}
}
}
public void PrintGraph()
{
// Print Vertices
Vertex temp = _vfirst;
while (temp != null)
{
TestLibrary.Logging.WriteLine("Vertex: {0}", temp.Name);
TestLibrary.Logging.WriteLine("Adjacent Vertices:");
for (int i = 0; i < temp.Num_Edges; i++)
{
TestLibrary.Logging.WriteLine(temp.Adjacent[i].Name);
}
temp = temp.Next;
}
//Print Edges
Edge temp2 = _efirst;
int edge = 0;
while (temp2 != null)
{
TestLibrary.Logging.WriteLine("Edge " + edge++);
TestLibrary.Logging.WriteLine("Weight: {0}, v1: {1}, v2: {2}", temp2.Weight, temp2.v1.Name, temp2.v2.Name);
temp2 = temp2.Next;
}
SetWeightSum();
TestLibrary.Logging.WriteLine("Sum of Weights is: {0}", GetWeightSum());
}
}
public class Vertex
{
public int Name;
//public bool Visited = false;
public Vertex Next;
public Vertex[] Adjacent;
public Edge[] Edges;
public int Num_Edges = 0;
public Vertex(int val)
{
Name = val;
Next = null;
Adjacent = new Vertex[Graph.Nodes];
}
public void AddVertex(Vertex x, Vertex y)
{
x.Next = y;
}
public void DeleteAdjacentEntry(int n)
{
int temp = Num_Edges;
for (int i = 0; i < temp; i++)
{
if (n == Adjacent[i].Name)
{
for (int j = i; j < Num_Edges; j++)
Adjacent[j] = Adjacent[j + 1];
Num_Edges--;
return;
}
}
}
}
public class Edge
{
public int Weight;
public Vertex v1, v2;
public Edge Next;
public Edge(Vertex n1, Vertex n2)
{
v1 = n1;
v2 = n2;
int seed = n1.Name + n2.Name;
Random rand = new Random(seed);
Weight = rand.Next(0, 50);
}
public void AddEdge(Edge x, Edge y)
{
x.Next = y;
}
}
public class Test
{
public static int Main()
{
TestLibrary.Logging.WriteLine("Building Graph with 800 vertices...");
Graph MyGraph = new Graph(800); // graph with 800 nodes
MyGraph.BuildGraph();
TestLibrary.Logging.WriteLine("Checking if all vertices are reachable...");
MyGraph.CheckIfReachable();
//TestLibrary.Logging.WriteLine("Printing the Graph...");
//MyGraph.PrintGraph();
TestLibrary.Logging.WriteLine("Deleting a random vertex...");
MyGraph.DeleteVertex();
//MyGraph.PrintGraph();
TestLibrary.Logging.WriteLine("Done");
TestLibrary.Logging.WriteLine("Test Passed");
return 100;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Build.Framework;
namespace GodotSharpTools.Build
{
public class BuildInstance : IDisposable
{
[MethodImpl(MethodImplOptions.InternalCall)]
private extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode);
[MethodImpl(MethodImplOptions.InternalCall)]
private extern static void godot_icall_BuildInstance_get_MSBuildInfo(ref string msbuildPath, ref string frameworkPath);
private struct MSBuildInfo
{
public string path;
public string frameworkPathOverride;
}
private static MSBuildInfo GetMSBuildInfo()
{
MSBuildInfo msbuildInfo = new MSBuildInfo();
godot_icall_BuildInstance_get_MSBuildInfo(ref msbuildInfo.path, ref msbuildInfo.frameworkPathOverride);
if (msbuildInfo.path == null)
throw new FileNotFoundException("Cannot find the MSBuild executable.");
return msbuildInfo;
}
private string solution;
private string config;
private Process process;
private int exitCode;
public int ExitCode { get { return exitCode; } }
public bool IsRunning { get { return process != null && !process.HasExited; } }
public BuildInstance(string solution, string config)
{
this.solution = solution;
this.config = config;
}
public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
MSBuildInfo msbuildInfo = GetMSBuildInfo();
List<string> customPropertiesList = new List<string>();
if (customProperties != null)
customPropertiesList.AddRange(customProperties);
if (msbuildInfo.frameworkPathOverride != null)
customPropertiesList.Add("FrameworkPathOverride=" + msbuildInfo.frameworkPathOverride);
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList);
ProcessStartInfo startInfo = new ProcessStartInfo(msbuildInfo.path, compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
}
return true;
}
public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
if (process != null)
throw new InvalidOperationException("Already in use");
MSBuildInfo msbuildInfo = GetMSBuildInfo();
List<string> customPropertiesList = new List<string>();
if (customProperties != null)
customPropertiesList.AddRange(customProperties);
if (msbuildInfo.frameworkPathOverride.Length > 0)
customPropertiesList.Add("FrameworkPathOverride=" + msbuildInfo.frameworkPathOverride);
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList);
ProcessStartInfo startInfo = new ProcessStartInfo(msbuildInfo.path, compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(BuildProcess_Exited);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return true;
}
private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, List<string> customProperties)
{
string arguments = string.Format(@"""{0}"" /v:normal /t:Build ""/p:{1}"" ""/l:{2},{3};{4}""",
solution,
"Configuration=" + config,
typeof(GodotBuildLogger).FullName,
loggerAssemblyPath,
loggerOutputDir
);
foreach (string customProperty in customProperties)
{
arguments += " \"/p:" + customProperty + "\"";
}
return arguments;
}
private void RemovePlatformVariable(StringDictionary environmentVariables)
{
// EnvironmentVariables is case sensitive? Seriously?
List<string> platformEnvironmentVariables = new List<string>();
foreach (string env in environmentVariables.Keys)
{
if (env.ToUpper() == "PLATFORM")
platformEnvironmentVariables.Add(env);
}
foreach (string env in platformEnvironmentVariables)
environmentVariables.Remove(env);
}
private void BuildProcess_Exited(object sender, System.EventArgs e)
{
exitCode = process.ExitCode;
godot_icall_BuildInstance_ExitCallback(solution, config, exitCode);
Dispose();
}
public void Dispose()
{
if (process != null)
{
process.Dispose();
process = null;
}
}
}
public class GodotBuildLogger : ILogger
{
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
public void Initialize(IEventSource eventSource)
{
if (null == Parameters)
throw new LoggerException("Log directory was not set.");
string[] parameters = Parameters.Split(';');
string logDir = parameters[0];
if (String.IsNullOrEmpty(logDir))
throw new LoggerException("Log directory was not set.");
if (parameters.Length > 1)
throw new LoggerException("Too many parameters passed.");
string logFile = Path.Combine(logDir, "msbuild_log.txt");
string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");
try
{
if (!Directory.Exists(logDir))
Directory.CreateDirectory(logDir);
this.logStreamWriter = new StreamWriter(logFile);
this.issuesStreamWriter = new StreamWriter(issuesFile);
}
catch (Exception ex)
{
if
(
ex is UnauthorizedAccessException
|| ex is ArgumentNullException
|| ex is PathTooLongException
|| ex is DirectoryNotFoundException
|| ex is NotSupportedException
|| ex is ArgumentException
|| ex is SecurityException
|| ex is IOException
)
{
throw new LoggerException("Failed to create log file: " + ex.Message);
}
else
{
// Unexpected failure
throw;
}
}
eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted);
eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised);
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
}
void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
{
string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message);
if (e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape());
issuesStreamWriter.WriteLine(errorLine);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile);
if (e.ProjectFile != null && e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty);
issuesStreamWriter.WriteLine(warningLine);
}
void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
{
// BuildMessageEventArgs adds Importance to BuildEventArgs
// Let's take account of the verbosity setting we've been passed in deciding whether to log the message
if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal))
|| (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal))
|| (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
)
{
WriteLineWithSenderAndMessage(String.Empty, e);
}
}
void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
{
// TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
// To keep this log clean, this logger will ignore these events.
}
void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
{
WriteLine(e.Message);
indent++;
}
void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
{
indent--;
WriteLine(e.Message);
}
/// <summary>
/// Write a line to the log, adding the SenderName
/// </summary>
private void WriteLineWithSender(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line);
}
else
{
WriteLine(e.SenderName + ": " + line);
}
}
/// <summary>
/// Write a line to the log, adding the SenderName and Message
/// (these parameters are on all MSBuild event argument objects)
/// </summary>
private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line + e.Message);
}
else
{
WriteLine(e.SenderName + ": " + line + e.Message);
}
}
private void WriteLine(string line)
{
for (int i = indent; i > 0; i--)
{
logStreamWriter.Write("\t");
}
logStreamWriter.WriteLine(line);
}
public void Shutdown()
{
logStreamWriter.Close();
issuesStreamWriter.Close();
}
public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
{
return this.Verbosity >= checkVerbosity;
}
private StreamWriter logStreamWriter;
private StreamWriter issuesStreamWriter;
private int indent;
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEngine;
/// <summary>
/// Controls the player's movement in virtual reality.
/// </summary>
[RequireComponent(typeof(CharacterController))]
public class OVRPlayerController : MonoBehaviour
{
/// <summary>
/// The rate acceleration during movement.
/// </summary>
public float Acceleration = 0.1f;
/// <summary>
/// The rate of damping on movement.
/// </summary>
public float Damping = 0.3f;
/// <summary>
/// The rate of additional damping when moving sideways or backwards.
/// </summary>
public float BackAndSideDampen = 0.5f;
/// <summary>
/// The force applied to the character when jumping.
/// </summary>
public float JumpForce = 0.3f;
/// <summary>
/// The rate of rotation when using a gamepad.
/// </summary>
public float RotationAmount = 1.5f;
/// <summary>
/// The rate of rotation when using the keyboard.
/// </summary>
public float RotationRatchet = 45.0f;
/// <summary>
/// The player will rotate in fixed steps if Snap Rotation is enabled.
/// </summary>
[Tooltip("The player will rotate in fixed steps if Snap Rotation is enabled.")]
public bool SnapRotation = true;
/// <summary>
/// How many fixed speeds to use with linear movement? 0=linear control
/// </summary>
[Tooltip("How many fixed speeds to use with linear movement? 0=linear control")]
public int FixedSpeedSteps;
/// <summary>
/// If true, reset the initial yaw of the player controller when the Hmd pose is recentered.
/// </summary>
public bool HmdResetsY = true;
/// <summary>
/// If true, tracking data from a child OVRCameraRig will update the direction of movement.
/// </summary>
public bool HmdRotatesY = true;
/// <summary>
/// Modifies the strength of gravity.
/// </summary>
public float GravityModifier = 0.379f;
/// <summary>
/// If true, each OVRPlayerController will use the player's physical height.
/// </summary>
public bool useProfileData = true;
/// <summary>
/// The CameraHeight is the actual height of the HMD and can be used to adjust the height of the character controller, which will affect the
/// ability of the character to move into areas with a low ceiling.
/// </summary>
[NonSerialized]
public float CameraHeight;
/// <summary>
/// This event is raised after the character controller is moved. This is used by the OVRAvatarLocomotion script to keep the avatar transform synchronized
/// with the OVRPlayerController.
/// </summary>
public event Action<Transform> TransformUpdated;
/// <summary>
/// This bool is set to true whenever the player controller has been teleported. It is reset after every frame. Some systems, such as
/// CharacterCameraConstraint, test this boolean in order to disable logic that moves the character controller immediately
/// following the teleport.
/// </summary>
[NonSerialized] // This doesn't need to be visible in the inspector.
public bool Teleported;
/// <summary>
/// This event is raised immediately after the camera transform has been updated, but before movement is updated.
/// </summary>
public event Action CameraUpdated;
/// <summary>
/// This event is raised right before the character controller is actually moved in order to provide other systems the opportunity to
/// move the character controller in response to things other than user input, such as movement of the HMD. See CharacterCameraConstraint.cs
/// for an example of this.
/// </summary>
public event Action PreCharacterMove;
/// <summary>
/// When true, user input will be applied to linear movement. Set this to false whenever the player controller needs to ignore input for
/// linear movement.
/// </summary>
public bool EnableLinearMovement = true;
/// <summary>
/// When true, user input will be applied to rotation. Set this to false whenever the player controller needs to ignore input for rotation.
/// </summary>
public bool EnableRotation = true;
protected CharacterController Controller = null;
protected OVRCameraRig CameraRig = null;
private float MoveScale = 1.0f;
private Vector3 MoveThrottle = Vector3.zero;
private float FallSpeed = 0.0f;
private OVRPose? InitialPose;
public float InitialYRotation { get; private set; }
private float MoveScaleMultiplier = 1.0f;
private float RotationScaleMultiplier = 1.0f;
private bool SkipMouseRotation = true; // It is rare to want to use mouse movement in VR, so ignore the mouse by default.
private bool HaltUpdateMovement = false;
private bool prevHatLeft = false;
private bool prevHatRight = false;
private float SimulationRate = 60f;
private float buttonRotation = 0f;
private bool ReadyToSnapTurn; // Set to true when a snap turn has occurred, code requires one frame of centered thumbstick to enable another snap turn.
void Start()
{
// Add eye-depth as a camera offset from the player controller
var p = CameraRig.transform.localPosition;
p.z = OVRManager.profile.eyeDepth;
CameraRig.transform.localPosition = p;
}
void Awake()
{
Controller = gameObject.GetComponent<CharacterController>();
if(Controller == null)
Debug.LogWarning("OVRPlayerController: No CharacterController attached.");
// We use OVRCameraRig to set rotations to cameras,
// and to be influenced by rotation
OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>();
if(CameraRigs.Length == 0)
Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached.");
else if (CameraRigs.Length > 1)
Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached.");
else
CameraRig = CameraRigs[0];
InitialYRotation = transform.rotation.eulerAngles.y;
}
void OnEnable()
{
OVRManager.display.RecenteredPose += ResetOrientation;
if (CameraRig != null)
{
CameraRig.UpdatedAnchors += UpdateTransform;
}
}
void OnDisable()
{
OVRManager.display.RecenteredPose -= ResetOrientation;
if (CameraRig != null)
{
CameraRig.UpdatedAnchors -= UpdateTransform;
}
}
void Update()
{
//Use keys to ratchet rotation
if (Input.GetKeyDown(KeyCode.Q))
buttonRotation -= RotationRatchet;
if (Input.GetKeyDown(KeyCode.E))
buttonRotation += RotationRatchet;
}
protected virtual void UpdateController()
{
if (useProfileData)
{
if (InitialPose == null)
{
// Save the initial pose so it can be recovered if useProfileData
// is turned off later.
InitialPose = new OVRPose()
{
position = CameraRig.transform.localPosition,
orientation = CameraRig.transform.localRotation
};
}
var p = CameraRig.transform.localPosition;
if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.EyeLevel)
{
p.y = OVRManager.profile.eyeHeight - (0.5f * Controller.height) + Controller.center.y;
}
else if (OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.FloorLevel)
{
p.y = - (0.5f * Controller.height) + Controller.center.y;
}
CameraRig.transform.localPosition = p;
}
else if (InitialPose != null)
{
// Return to the initial pose if useProfileData was turned off at runtime
CameraRig.transform.localPosition = InitialPose.Value.position;
CameraRig.transform.localRotation = InitialPose.Value.orientation;
InitialPose = null;
}
CameraHeight = CameraRig.centerEyeAnchor.localPosition.y;
if (CameraUpdated != null)
{
CameraUpdated();
}
UpdateMovement();
Vector3 moveDirection = Vector3.zero;
float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime));
MoveThrottle.x /= motorDamp;
MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y;
MoveThrottle.z /= motorDamp;
moveDirection += MoveThrottle * SimulationRate * Time.deltaTime;
// Gravity
if (Controller.isGrounded && FallSpeed <= 0)
FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f)));
else
FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime);
moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime;
if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f)
{
// Offset correction for uneven ground
float bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude);
moveDirection -= bumpUpOffset * Vector3.up;
}
if (PreCharacterMove != null)
{
PreCharacterMove();
Teleported = false;
}
Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1));
// Move contoller
Controller.Move(moveDirection);
Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1));
if (predictedXZ != actualXZ)
MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime);
}
public virtual void UpdateMovement()
{
if (HaltUpdateMovement)
return;
if (EnableLinearMovement)
{
bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow);
bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow);
bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow);
bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow);
bool dpad_move = false;
if (OVRInput.Get(OVRInput.Button.DpadUp))
{
moveForward = true;
dpad_move = true;
}
if (OVRInput.Get(OVRInput.Button.DpadDown))
{
moveBack = true;
dpad_move = true;
}
MoveScale = 1.0f;
if ((moveForward && moveLeft) || (moveForward && moveRight) ||
(moveBack && moveLeft) || (moveBack && moveRight))
MoveScale = 0.70710678f;
// No positional movement if we are in the air
if (!Controller.isGrounded)
MoveScale = 0.0f;
MoveScale *= SimulationRate * Time.deltaTime;
// Compute this for key movement
float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
// Run!
if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
moveInfluence *= 2.0f;
Quaternion ort = transform.rotation;
Vector3 ortEuler = ort.eulerAngles;
ortEuler.z = ortEuler.x = 0f;
ort = Quaternion.Euler(ortEuler);
if (moveForward)
MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward);
if (moveBack)
MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back);
if (moveLeft)
MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left);
if (moveRight)
MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right);
moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;
#if !UNITY_ANDROID // LeftTrigger not avail on Android game pad
moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);
#endif
Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
// If speed quantization is enabled, adjust the input to the number of fixed speed steps.
if (FixedSpeedSteps > 0)
{
primaryAxis.y = Mathf.Round(primaryAxis.y * FixedSpeedSteps) / FixedSpeedSteps;
primaryAxis.x = Mathf.Round(primaryAxis.x * FixedSpeedSteps) / FixedSpeedSteps;
}
if (primaryAxis.y > 0.0f)
MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward);
if (primaryAxis.y < 0.0f)
MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence *
BackAndSideDampen * Vector3.back);
if (primaryAxis.x < 0.0f)
MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence *
BackAndSideDampen * Vector3.left);
if (primaryAxis.x > 0.0f)
MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen *
Vector3.right);
}
if (EnableRotation)
{
Vector3 euler = transform.rotation.eulerAngles;
float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier;
bool curHatLeft = OVRInput.Get(OVRInput.Button.PrimaryShoulder);
if (curHatLeft && !prevHatLeft)
euler.y -= RotationRatchet;
prevHatLeft = curHatLeft;
bool curHatRight = OVRInput.Get(OVRInput.Button.SecondaryShoulder);
if (curHatRight && !prevHatRight)
euler.y += RotationRatchet;
prevHatRight = curHatRight;
euler.y += buttonRotation;
buttonRotation = 0f;
#if !UNITY_ANDROID || UNITY_EDITOR
if (!SkipMouseRotation)
euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f;
#endif
if (SnapRotation)
{
if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickLeft))
{
if (ReadyToSnapTurn)
{
euler.y -= RotationRatchet;
ReadyToSnapTurn = false;
}
}
else if (OVRInput.Get(OVRInput.Button.SecondaryThumbstickRight))
{
if (ReadyToSnapTurn)
{
euler.y += RotationRatchet;
ReadyToSnapTurn = false;
}
}
else
{
ReadyToSnapTurn = true;
}
}
else
{
Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
euler.y += secondaryAxis.x * rotateInfluence;
}
transform.rotation = Quaternion.Euler(euler);
}
}
/// <summary>
/// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player.
/// </summary>
public void UpdateTransform(OVRCameraRig rig)
{
Transform root = CameraRig.trackingSpace;
Transform centerEye = CameraRig.centerEyeAnchor;
if (HmdRotatesY && !Teleported)
{
Vector3 prevPos = root.position;
Quaternion prevRot = root.rotation;
transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f);
root.position = prevPos;
root.rotation = prevRot;
}
UpdateController();
if (TransformUpdated != null)
{
TransformUpdated(root);
}
}
/// <summary>
/// Jump! Must be enabled manually.
/// </summary>
public bool Jump()
{
if (!Controller.isGrounded)
return false;
MoveThrottle += new Vector3(0, transform.lossyScale.y * JumpForce, 0);
return true;
}
/// <summary>
/// Stop this instance.
/// </summary>
public void Stop()
{
Controller.Move(Vector3.zero);
MoveThrottle = Vector3.zero;
FallSpeed = 0.0f;
}
/// <summary>
/// Gets the move scale multiplier.
/// </summary>
/// <param name="moveScaleMultiplier">Move scale multiplier.</param>
public void GetMoveScaleMultiplier(ref float moveScaleMultiplier)
{
moveScaleMultiplier = MoveScaleMultiplier;
}
/// <summary>
/// Sets the move scale multiplier.
/// </summary>
/// <param name="moveScaleMultiplier">Move scale multiplier.</param>
public void SetMoveScaleMultiplier(float moveScaleMultiplier)
{
MoveScaleMultiplier = moveScaleMultiplier;
}
/// <summary>
/// Gets the rotation scale multiplier.
/// </summary>
/// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier)
{
rotationScaleMultiplier = RotationScaleMultiplier;
}
/// <summary>
/// Sets the rotation scale multiplier.
/// </summary>
/// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param>
public void SetRotationScaleMultiplier(float rotationScaleMultiplier)
{
RotationScaleMultiplier = rotationScaleMultiplier;
}
/// <summary>
/// Gets the allow mouse rotation.
/// </summary>
/// <param name="skipMouseRotation">Allow mouse rotation.</param>
public void GetSkipMouseRotation(ref bool skipMouseRotation)
{
skipMouseRotation = SkipMouseRotation;
}
/// <summary>
/// Sets the allow mouse rotation.
/// </summary>
/// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param>
public void SetSkipMouseRotation(bool skipMouseRotation)
{
SkipMouseRotation = skipMouseRotation;
}
/// <summary>
/// Gets the halt update movement.
/// </summary>
/// <param name="haltUpdateMovement">Halt update movement.</param>
public void GetHaltUpdateMovement(ref bool haltUpdateMovement)
{
haltUpdateMovement = HaltUpdateMovement;
}
/// <summary>
/// Sets the halt update movement.
/// </summary>
/// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param>
public void SetHaltUpdateMovement(bool haltUpdateMovement)
{
HaltUpdateMovement = haltUpdateMovement;
}
/// <summary>
/// Resets the player look rotation when the device orientation is reset.
/// </summary>
public void ResetOrientation()
{
if (HmdResetsY && !HmdRotatesY)
{
Vector3 euler = transform.rotation.eulerAngles;
euler.y = InitialYRotation;
transform.rotation = Quaternion.Euler(euler);
}
}
}
| |
namespace EIDSS.Reports.Document.Human.Aggregate
{
partial class CaseAggregateReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CaseAggregateReport));
this.tableInterval = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellInputStartDate = new DevExpress.XtraReports.UI.XRTableCell();
this.cellDefis = new DevExpress.XtraReports.UI.XRTableCell();
this.cellInputEndDate = new DevExpress.XtraReports.UI.XRTableCell();
this.lblUnit = new DevExpress.XtraReports.UI.XRLabel();
this.FlexSubreport = new DevExpress.XtraReports.UI.XRSubreport();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UsePadding = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.StylePriority.UseBorders = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.FlexSubreport});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.Controls.SetChildIndex(this.FlexSubreport, 0);
this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0);
//
// xrPageInfo1
//
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.lblUnit,
this.tableInterval});
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 2.4324737947142387;
this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0);
this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0);
this.cellReportHeader.Controls.SetChildIndex(this.lblUnit, 0);
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 2.9086758403192223;
//
// cellBaseCountry
//
this.cellBaseCountry.Weight = 1.0799539637985065;
//
// cellBaseLeftHeader
//
this.cellBaseLeftHeader.Weight = 0.90314603093871226;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableInterval
//
this.tableInterval.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.Name = "tableInterval";
this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10});
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellInputStartDate,
this.cellDefis,
this.cellInputEndDate});
this.xrTableRow10.Name = "xrTableRow10";
this.xrTableRow10.Weight = 0.26865671641791045;
//
// cellInputStartDate
//
resources.ApplyResources(this.cellInputStartDate, "cellInputStartDate");
this.cellInputStartDate.Name = "cellInputStartDate";
this.cellInputStartDate.StylePriority.UseFont = false;
this.cellInputStartDate.StylePriority.UseTextAlignment = false;
this.cellInputStartDate.Weight = 0.88952849345181539;
//
// cellDefis
//
resources.ApplyResources(this.cellDefis, "cellDefis");
this.cellDefis.Name = "cellDefis";
this.cellDefis.StylePriority.UseFont = false;
this.cellDefis.StylePriority.UseTextAlignment = false;
this.cellDefis.Weight = 0.031135701733142042;
//
// cellInputEndDate
//
resources.ApplyResources(this.cellInputEndDate, "cellInputEndDate");
this.cellInputEndDate.Name = "cellInputEndDate";
this.cellInputEndDate.StylePriority.UseFont = false;
this.cellInputEndDate.StylePriority.UseTextAlignment = false;
this.cellInputEndDate.Weight = 0.936343821606215;
//
// lblUnit
//
this.lblUnit.Borders = DevExpress.XtraPrinting.BorderSide.None;
resources.ApplyResources(this.lblUnit, "lblUnit");
this.lblUnit.Name = "lblUnit";
this.lblUnit.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.lblUnit.StylePriority.UseBorders = false;
this.lblUnit.StylePriority.UseFont = false;
this.lblUnit.StylePriority.UseTextAlignment = false;
//
// FlexSubreport
//
resources.ApplyResources(this.FlexSubreport, "FlexSubreport");
this.FlexSubreport.Name = "FlexSubreport";
//
// CaseAggregateReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader});
this.ExportOptions.Xls.SheetName = resources.GetString("CaseAggregateReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("CaseAggregateReport.ExportOptions.Xlsx.SheetName");
this.Landscape = true;
this.PageHeight = 827;
this.PageWidth = 1169;
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell cellInputStartDate;
private DevExpress.XtraReports.UI.XRTableCell cellDefis;
private DevExpress.XtraReports.UI.XRTableCell cellInputEndDate;
private DevExpress.XtraReports.UI.XRTable tableInterval;
private DevExpress.XtraReports.UI.XRLabel lblUnit;
private DevExpress.XtraReports.UI.XRSubreport FlexSubreport;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using System.Data.Common;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
namespace System.Data.SqlTypes
{
[XmlSchemaProvider("GetXsdType")]
public sealed class SqlChars : INullable, IXmlSerializable, ISerializable
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
// SqlChars has five possible states
// 1) SqlChars is Null
// - m_stream must be null, m_lCuLen must be x_lNull
// 2) SqlChars contains a valid buffer,
// - m_rgchBuf must not be null, and m_stream must be null
// 3) SqlChars contains a valid pointer
// - m_rgchBuf could be null or not,
// if not null, content is garbage, should never look into it.
// - m_stream must be null.
// 4) SqlChars contains a SqlStreamChars
// - m_stream must not be null
// - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it.
// - m_lCurLen must be x_lNull.
// 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed)
//
internal char[] _rgchBuf; // Data buffer
private long _lCurLen; // Current data length
internal SqlStreamChars _stream;
private SqlBytesCharsState _state;
private char[] _rgchWorkBuf; // A 1-char work buffer.
// The max data length that we support at this time.
private const long x_lMaxLen = int.MaxValue;
private const long x_lNull = -1L;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
// Public default constructor used for XML serialization
public SqlChars()
{
SetNull();
}
// Create a SqlChars with an in-memory buffer
public SqlChars(char[] buffer)
{
_rgchBuf = buffer;
_stream = null;
if (_rgchBuf == null)
{
_state = SqlBytesCharsState.Null;
_lCurLen = x_lNull;
}
else
{
_state = SqlBytesCharsState.Buffer;
_lCurLen = _rgchBuf.Length;
}
_rgchWorkBuf = null;
AssertValid();
}
// Create a SqlChars from a SqlString
public SqlChars(SqlString value) : this(value.IsNull ? null : value.Value.ToCharArray())
{
}
// Create a SqlChars from a SqlStreamChars
internal SqlChars(SqlStreamChars s)
{
_rgchBuf = null;
_lCurLen = x_lNull;
_stream = s;
_state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
_rgchWorkBuf = null;
AssertValid();
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// INullable
public bool IsNull
{
get
{
return _state == SqlBytesCharsState.Null;
}
}
// Property: the in-memory buffer of SqlChars
// Return Buffer even if SqlChars is Null.
public char[] Buffer
{
get
{
if (FStream())
{
CopyStreamToBuffer();
}
return _rgchBuf;
}
}
// Property: the actual length of the data
public long Length
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return _stream.Length;
default:
return _lCurLen;
}
}
}
// Property: the max length of the data
// Return MaxLength even if SqlChars is Null.
// When the buffer is also null, return -1.
// If containing a Stream, return -1.
public long MaxLength
{
get
{
switch (_state)
{
case SqlBytesCharsState.Stream:
return -1L;
default:
return (_rgchBuf == null) ? -1L : _rgchBuf.Length;
}
}
}
// Property: get a copy of the data in a new char[] array.
public char[] Value
{
get
{
char[] buffer;
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
if (_stream.Length > x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
buffer = new char[_stream.Length];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(buffer, 0, checked((int)_stream.Length));
break;
default:
buffer = new char[_lCurLen];
Array.Copy(_rgchBuf, 0, buffer, 0, (int)_lCurLen);
break;
}
return buffer;
}
}
// class indexer
public char this[long offset]
{
get
{
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (_rgchWorkBuf == null)
_rgchWorkBuf = new char[1];
Read(offset, _rgchWorkBuf, 0, 1);
return _rgchWorkBuf[0];
}
set
{
if (_rgchWorkBuf == null)
_rgchWorkBuf = new char[1];
_rgchWorkBuf[0] = value;
Write(offset, _rgchWorkBuf, 0, 1);
}
}
internal SqlStreamChars Stream
{
get
{
return FStream() ? _stream : new StreamOnSqlChars(this);
}
set
{
_lCurLen = x_lNull;
_stream = value;
_state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
AssertValid();
}
}
public StorageState Storage
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return StorageState.Stream;
case SqlBytesCharsState.Buffer:
return StorageState.Buffer;
default:
return StorageState.UnmanagedBuffer;
}
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public void SetNull()
{
_lCurLen = x_lNull;
_stream = null;
_state = SqlBytesCharsState.Null;
AssertValid();
}
// Set the current length of the data
// If the SqlChars is Null, setLength will make it non-Null.
public void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
if (FStream())
{
_stream.SetLength(value);
}
else
{
// If there is a buffer, even the value of SqlChars is Null,
// still allow setting length to zero, which will make it not Null.
// If the buffer is null, raise exception
//
if (null == _rgchBuf)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (value > _rgchBuf.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else if (IsNull)
// At this point we know that value is small enough
// Go back in buffer mode
_state = SqlBytesCharsState.Buffer;
_lCurLen = value;
}
AssertValid();
}
// Read data of specified length from specified offset into a buffer
public long Read(long offset, char[] buffer, int offsetInBuffer, int count)
{
if (IsNull)
throw new SqlNullValueException();
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offsetInBuffer > buffer.Length || offsetInBuffer < 0)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
// Adjust count based on data length
if (count > Length - offset)
count = (int)(Length - offset);
if (count != 0)
{
switch (_state)
{
case SqlBytesCharsState.Stream:
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Read(buffer, offsetInBuffer, count);
break;
default:
Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count);
break;
}
}
return count;
}
// Write data of specified length into the SqlChars from specified offset
public void Write(long offset, char[] buffer, int offsetInBuffer, int count)
{
if (FStream())
{
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Write(buffer, offsetInBuffer, count);
}
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (_rgchBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset > _rgchBuf.Length)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
if (count > _rgchBuf.Length - offset)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (IsNull)
{
// If NULL and there is buffer inside, we only allow writing from
// offset zero.
//
if (offset != 0)
throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage);
// treat as if our current length is zero.
// Note this has to be done after all inputs are validated, so that
// we won't throw exception after this point.
//
_lCurLen = 0;
_state = SqlBytesCharsState.Buffer;
}
else if (offset > _lCurLen)
{
// Don't allow writing from an offset that this larger than current length.
// It would leave uninitialized data in the buffer.
//
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
}
if (count != 0)
{
Array.Copy(buffer, offsetInBuffer, _rgchBuf, offset, count);
// If the last position that has been written is after
// the current data length, reset the length
if (_lCurLen < offset + count)
_lCurLen = offset + count;
}
}
AssertValid();
}
public SqlString ToSqlString()
{
return IsNull ? SqlString.Null : new string(Value);
}
// --------------------------------------------------------------
// Conversion operators
// --------------------------------------------------------------
// Alternative method: ToSqlString()
public static explicit operator SqlString(SqlChars value)
{
return value.ToSqlString();
}
// Alternative method: constructor SqlChars(SqlString)
public static explicit operator SqlChars(SqlString value)
{
return new SqlChars(value);
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
[Conditional("DEBUG")]
private void AssertValid()
{
Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream);
if (IsNull)
{
}
else
{
Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream());
Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length));
Debug.Assert(!FStream() || (_lCurLen == x_lNull));
}
Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1);
}
// whether the SqlChars contains a Stream
internal bool FStream()
{
return _state == SqlBytesCharsState.Stream;
}
// Copy the data from the Stream to the array buffer.
// If the SqlChars doesn't hold a buffer or the buffer
// is not big enough, allocate new char array.
private void CopyStreamToBuffer()
{
Debug.Assert(FStream());
long lStreamLen = _stream.Length;
if (lStreamLen >= x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (_rgchBuf == null || _rgchBuf.Length < lStreamLen)
_rgchBuf = new char[lStreamLen];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(_rgchBuf, 0, (int)lStreamLen);
_stream = null;
_lCurLen = lStreamLen;
_state = SqlBytesCharsState.Buffer;
AssertValid();
}
private void SetBuffer(char[] buffer)
{
_rgchBuf = buffer;
_lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length;
_stream = null;
_state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer;
AssertValid();
}
// --------------------------------------------------------------
// XML Serialization
// --------------------------------------------------------------
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(XmlReader r)
{
char[] value = null;
string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
r.ReadElementString();
SetNull();
}
else
{
value = r.ReadElementString().ToCharArray();
SetBuffer(value);
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
char[] value = Buffer;
writer.WriteString(new string(value, 0, (int)(Length)));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("string", XmlSchema.Namespace);
}
// --------------------------------------------------------------
// Serialization using ISerializable
// --------------------------------------------------------------
// State information is not saved. The current state is converted to Buffer and only the underlying
// array is serialized, except for Null, in which case this state is kept.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
// --------------------------------------------------------------
// Static fields, properties
// --------------------------------------------------------------
// Get a Null instance.
// Since SqlChars is mutable, have to be property and create a new one each time.
public static SqlChars Null
{
get
{
return new SqlChars((char[])null);
}
}
} // class SqlChars
// StreamOnSqlChars is a stream build on top of SqlChars, and
// provides the Stream interface. The purpose is to help users
// to read/write SqlChars object.
internal sealed class StreamOnSqlChars : SqlStreamChars
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
private SqlChars _sqlchars; // the SqlChars object
private long _lPosition;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
internal StreamOnSqlChars(SqlChars s)
{
_sqlchars = s;
_lPosition = 0;
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
public override bool IsNull
{
get
{
return _sqlchars == null || _sqlchars.IsNull;
}
}
public override long Length
{
get
{
CheckIfStreamClosed("get_Length");
return _sqlchars.Length;
}
}
public override long Position
{
get
{
CheckIfStreamClosed("get_Position");
return _lPosition;
}
set
{
CheckIfStreamClosed("set_Position");
if (value < 0 || value > _sqlchars.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else
_lPosition = value;
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public override long Seek(long offset, SeekOrigin origin)
{
CheckIfStreamClosed();
long lPosition = 0;
switch (origin)
{
case SeekOrigin.Begin:
if (offset < 0 || offset > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = offset;
break;
case SeekOrigin.Current:
lPosition = _lPosition + offset;
if (lPosition < 0 || lPosition > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = lPosition;
break;
case SeekOrigin.End:
lPosition = _sqlchars.Length + offset;
if (lPosition < 0 || lPosition > _sqlchars.Length)
throw ADP.ArgumentOutOfRange(nameof(offset));
_lPosition = lPosition;
break;
default:
throw ADP.ArgumentOutOfRange(nameof(offset));
}
return _lPosition;
}
// The Read/Write/Readchar/Writechar simply delegates to SqlChars
public override int Read(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count);
_lPosition += icharsRead;
return icharsRead;
}
public override void Write(char[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
_sqlchars.Write(_lPosition, buffer, offset, count);
_lPosition += count;
}
public override void SetLength(long value)
{
CheckIfStreamClosed();
_sqlchars.SetLength(value);
if (_lPosition > value)
_lPosition = value;
}
protected override void Dispose(bool disposing)
{
// When m_sqlchars is null, it means the stream has been closed, and
// any opearation in the future should fail.
// This is the only case that m_sqlchars is null.
_sqlchars = null;
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
private bool FClosed()
{
return _sqlchars == null;
}
private void CheckIfStreamClosed([CallerMemberName] string methodname = "")
{
if (FClosed())
throw ADP.StreamClosed(methodname);
}
} // class StreamOnSqlChars
} // namespace System.Data.SqlTypes
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Edge.Template;
using Microsoft.TemplateEngine.Utils;
using Microsoft.TemplateEngine.Cli.CommandParsing;
namespace Microsoft.TemplateEngine.Cli.HelpAndUsage
{
public static class TemplateDetailsDisplay
{
public static void ShowTemplateGroupHelp(IReadOnlyList<ITemplateMatchInfo> templateGroup, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, TemplateCreator templateCreator, bool showImplicitlyHiddenParams = false)
{
if (templateGroup.Count == 0 || !TemplateListResolver.AreAllTemplatesSameGroupIdentity(templateGroup))
{
return;
}
IReadOnlyList<ITemplateInfo> templateInfoList = templateGroup.Select(x => x.Info).ToList();
ShowTemplateDetailHeaders(templateInfoList);
TemplateGroupParameterDetails? groupParameterDetails = DetermineParameterDispositionsForTemplateGroup(templateInfoList, environmentSettings, commandInput, hostDataLoader, templateCreator);
if (groupParameterDetails != null)
{
// get the input params valid for any param in the group
IReadOnlyDictionary<string, string> inputTemplateParams = CoalesceInputParameterValuesFromTemplateGroup(templateGroup);
ShowParameterHelp(inputTemplateParams, showImplicitlyHiddenParams, groupParameterDetails.Value, environmentSettings);
}
else
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.MissingTemplateContentDetected, commandInput.CommandName).Bold().Red());
}
}
private static void ShowTemplateDetailHeaders(IReadOnlyList<ITemplateInfo> templateGroup)
{
// Use the highest precedence template for most of the output
ITemplateInfo preferredTemplate = templateGroup.OrderByDescending(x => x.Precedence).First();
// use all templates to get the language choices
HashSet<string> languages = new HashSet<string>();
foreach (ITemplateInfo templateInfo in templateGroup)
{
if (templateInfo.Tags != null && templateInfo.Tags.TryGetValue("language", out ICacheTag languageTag))
{
languages.UnionWith(languageTag.ChoicesAndDescriptions.Keys.Where(x => !string.IsNullOrWhiteSpace(x)).ToList());
}
}
if (languages != null && languages.Any())
{
Reporter.Output.WriteLine($"{preferredTemplate.Name} ({string.Join(", ", languages)})");
}
else
{
Reporter.Output.WriteLine(preferredTemplate.Name);
}
if (!string.IsNullOrWhiteSpace(preferredTemplate.Author))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.Author, preferredTemplate.Author));
}
if (!string.IsNullOrWhiteSpace(preferredTemplate.Description))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.Description, preferredTemplate.Description));
}
if (!string.IsNullOrEmpty(preferredTemplate.ThirdPartyNotices))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.ThirdPartyNotices, preferredTemplate.ThirdPartyNotices));
}
}
private static void ShowParameterHelp(IReadOnlyDictionary<string, string> inputParams, bool showImplicitlyHiddenParams, TemplateGroupParameterDetails parameterDetails, IEngineEnvironmentSettings environmentSettings)
{
if (!string.IsNullOrEmpty(parameterDetails.AdditionalInfo))
{
Reporter.Error.WriteLine(parameterDetails.AdditionalInfo.Bold().Red());
Reporter.Output.WriteLine();
}
IEnumerable<ITemplateParameter> filteredParams = TemplateParameterHelpBase.FilterParamsForHelp(parameterDetails.AllParams.ParameterDefinitions, parameterDetails.ExplicitlyHiddenParams,
showImplicitlyHiddenParams, parameterDetails.HasPostActionScriptRunner, parameterDetails.ParametersToAlwaysShow);
bool anyParamsShowingDefaultForSwitchWithNoValue = false;
if (filteredParams.Any())
{
HelpFormatter<ITemplateParameter> formatter = new HelpFormatter<ITemplateParameter>(environmentSettings, filteredParams, 2, null, true);
formatter.DefineColumn(
param =>
{
string options;
if (string.Equals(param.Name, "allow-scripts", StringComparison.OrdinalIgnoreCase))
{
options = "--" + param.Name;
}
else
{
// the key is guaranteed to exist
IList<string> variants = parameterDetails.GroupVariantsForCanonicals[param.Name].ToList();
options = string.Join("|", variants.Reverse());
}
return " " + options;
},
LocalizableStrings.Options
);
formatter.DefineColumn(delegate (ITemplateParameter param)
{
StringBuilder displayValue = new StringBuilder(255);
displayValue.AppendLine(param.Documentation);
if (string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase))
{
int longestChoiceLength = param.Choices.Keys.Max(x => x.Length);
foreach (KeyValuePair<string, string> choiceInfo in param.Choices)
{
displayValue.Append(" " + choiceInfo.Key.PadRight(longestChoiceLength + 4));
if (!string.IsNullOrWhiteSpace(choiceInfo.Value))
{
displayValue.Append("- " + choiceInfo.Value);
}
displayValue.AppendLine();
}
}
else
{
displayValue.Append(param.DataType ?? "string");
displayValue.AppendLine(" - " + param.Priority.ToString());
}
// determine the configured value
string configuredValue = null;
if (parameterDetails.AllParams.ResolvedValues.TryGetValue(param, out object resolvedValueObject))
{
// Set the configured value as long as it's non-empty and not the default value.
// If it's the default, we're not sure if it was explicitly entered or not.
// Below, there's a check if the user entered a value. If so, set it.
string resolvedValue = resolvedValueObject?.ToString() ?? string.Empty;
if (!string.IsNullOrEmpty(resolvedValue))
{
// bools get ToString() values of "True" & "False", but most templates use "true" & "false"
// So do a case-insensitive comparison on bools, case-sensitive on other values.
StringComparison comparisonType = string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase)
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
if (!string.Equals(param.DefaultValue, resolvedValue, comparisonType))
{
configuredValue = resolvedValue;
}
}
}
// If the resolved value is null/empty, or the default, only display the configured value if
// the user explicitly specified it or if it can be resolved from the DefaultIfOptionWithoutValue (or bool='true' for backwards compat).
if (string.IsNullOrEmpty(configuredValue))
{
bool handled = false;
if (parameterDetails.GroupUserParamsWithDefaultValues.Contains(param.Name))
{
if (param is IAllowDefaultIfOptionWithoutValue parameterWithNoValueDefault)
{
if (!string.IsNullOrEmpty(parameterWithNoValueDefault.DefaultIfOptionWithoutValue))
{
configuredValue = parameterWithNoValueDefault.DefaultIfOptionWithoutValue;
handled = true;
}
}
else if (string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase))
{
// Before the introduction of DefaultIfOptionWithoutValue, bool params were handled like this.
// Other param types didn't have any analogous handling.
configuredValue = "true";
handled = true;
}
}
if (!handled)
{
// If the user explicitly specified the switch, the value is in the inputParams, so try to retrieve it here.
inputParams.TryGetValue(param.Name, out configuredValue);
}
}
// display the configured value if there is one
if (!string.IsNullOrEmpty(configuredValue))
{
string realValue = configuredValue;
if (parameterDetails.InvalidParams.Contains(param.Name) ||
(string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase)
&& !param.Choices.ContainsKey(configuredValue)))
{
realValue = realValue.Bold().Red();
}
else if (parameterDetails.AllParams.TryGetRuntimeValue(environmentSettings, param.Name, out object runtimeVal) && runtimeVal != null)
{
realValue = runtimeVal.ToString();
}
displayValue.AppendLine(string.Format(LocalizableStrings.ConfiguredValue, realValue));
}
// display the default value if there is one
if (!string.IsNullOrEmpty(param.DefaultValue))
{
if (param is IAllowDefaultIfOptionWithoutValue paramWithNoValueDefault
&& !string.IsNullOrEmpty(paramWithNoValueDefault.DefaultIfOptionWithoutValue)
&& !string.Equals(paramWithNoValueDefault.DefaultIfOptionWithoutValue, param.DefaultValue, StringComparison.Ordinal))
{
// the regular default, and the default if the switch is provided without a value
displayValue.AppendLine(string.Format(LocalizableStrings.DefaultValuePlusSwitchWithoutValueDefault, param.DefaultValue, paramWithNoValueDefault.DefaultIfOptionWithoutValue));
anyParamsShowingDefaultForSwitchWithNoValue = true;
}
else
{
// only the regular default
displayValue.AppendLine(string.Format(LocalizableStrings.DefaultValue, param.DefaultValue));
}
}
return displayValue.ToString();
}, string.Empty);
Reporter.Output.WriteLine(formatter.Layout());
if (anyParamsShowingDefaultForSwitchWithNoValue)
{
Reporter.Output.WriteLine(LocalizableStrings.SwitchWithoutValueDefaultFootnote);
}
}
else
{
Reporter.Output.WriteLine(LocalizableStrings.NoParameters);
}
}
// Returns a composite of the input parameters and values which are valid for any template in the group.
private static IReadOnlyDictionary<string, string> CoalesceInputParameterValuesFromTemplateGroup(IReadOnlyList<ITemplateMatchInfo> templateGroup)
{
Dictionary<string, string> inputValues = new Dictionary<string, string>();
foreach (ITemplateMatchInfo template in templateGroup.OrderBy(x => x.Info.Precedence))
{
foreach (KeyValuePair<string, string> paramAndValue in template.GetValidTemplateParameters())
{
inputValues[paramAndValue.Key] = paramAndValue.Value;
}
}
return inputValues;
}
private static TemplateGroupParameterDetails? DetermineParameterDispositionsForTemplateGroup(IReadOnlyList<ITemplateInfo> templateGroup, IEngineEnvironmentSettings environmentSettings, INewCommandInput commandInput, IHostSpecificDataLoader hostDataLoader, TemplateCreator templateCreator)
{
HashSet<string> groupUserParamsWithInvalidValues = new HashSet<string>(StringComparer.Ordinal);
bool groupHasPostActionScriptRunner = false;
List<IParameterSet> parameterSetsForAllTemplatesInGroup = new List<IParameterSet>();
IDictionary<string, InvalidParameterInfo> invalidParametersForGroup = new Dictionary<string, InvalidParameterInfo>(StringComparer.Ordinal);
bool firstInList = true;
Dictionary<string, IReadOnlyList<string>> defaultVariantsForCanonicals = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
Dictionary<string, IReadOnlyList<string>> groupVariantsForCanonicals = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
HashSet<string> groupUserParamsWithDefaultValues = new HashSet<string>(StringComparer.Ordinal);
Dictionary<string, bool> parameterHidingDisposition = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
HashSet<string> parametersToAlwaysShow = new HashSet<string>(StringComparer.Ordinal);
foreach (ITemplateInfo templateInfo in templateGroup.OrderByDescending(x => x.Precedence))
{
TemplateUsageInformation? usageInformationNullable = TemplateUsageHelp.GetTemplateUsageInformation(templateInfo, environmentSettings, commandInput, hostDataLoader, templateCreator);
if (usageInformationNullable == null)
{
return null;
}
TemplateUsageInformation usageInformation = usageInformationNullable.Value;
HostSpecificTemplateData hostSpecificTemplateData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo);
HashSet<string> parametersToExplicitlyHide = hostSpecificTemplateData?.HiddenParameterNames ?? new HashSet<string>(StringComparer.Ordinal);
foreach (ITemplateParameter parameter in usageInformation.AllParameters.ParameterDefinitions)
{
//If the parameter has previously been encountered...
if (parameterHidingDisposition.TryGetValue(parameter.Name, out bool isCurrentlyHidden))
{
//...and it was hidden, but it's not hidden in this template in the group,
// remove its hiding, otherwise leave it as is
if (isCurrentlyHidden && !parametersToExplicitlyHide.Contains(parameter.Name))
{
parameterHidingDisposition[parameter.Name] = false;
}
}
else
{
//...otherwise, since this is the first time the parameter has been seen,
// its hiding state should be used as the current disposition
parameterHidingDisposition[parameter.Name] = parametersToExplicitlyHide.Contains(parameter.Name);
}
}
if (firstInList)
{
invalidParametersForGroup = usageInformation.InvalidParameters.ToDictionary(x => x.Canonical, x => x);
firstInList = false;
}
else
{
invalidParametersForGroup = InvalidParameterInfo.IntersectWithExisting(invalidParametersForGroup, usageInformation.InvalidParameters);
}
groupUserParamsWithInvalidValues.IntersectWith(usageInformation.UserParametersWithInvalidValues); // intersect because if the value is valid for any version, it's valid.
groupHasPostActionScriptRunner |= usageInformation.HasPostActionScriptRunner;
parameterSetsForAllTemplatesInGroup.Add(usageInformation.AllParameters);
// If this template has name overrides (either long or short), it's opinionated.
// If it's the first opinionated template about the param, use its variants.
// Else this template is not opinionated, note its values if there aren't defaults for the param already.
// At the end, anything in the default list that isn't in the opinionated list will get merged in.
// TODO: write tests for this code (and the rest of this method while we're at it)
foreach (KeyValuePair<string, IReadOnlyList<string>> canonicalAndVariants in usageInformation.VariantsForCanonicals)
{
if (hostSpecificTemplateData.LongNameOverrides.ContainsKey(canonicalAndVariants.Key) || hostSpecificTemplateData.ShortNameOverrides.ContainsKey(canonicalAndVariants.Key))
{
// this template is opinionated about this parameter. If no previous template is opinionated about this param, use this template's variants.
if (!groupVariantsForCanonicals.ContainsKey(canonicalAndVariants.Key))
{
groupVariantsForCanonicals[canonicalAndVariants.Key] = canonicalAndVariants.Value;
}
}
else
{
// this template is not opinionated about this parameter. If no previous template had defaults for this param, use this template's defaults.
if (!defaultVariantsForCanonicals.ContainsKey(canonicalAndVariants.Key))
{
defaultVariantsForCanonicals[canonicalAndVariants.Key] = canonicalAndVariants.Value;
}
}
}
// If any template says the user input value is the default, include it here.
groupUserParamsWithDefaultValues.UnionWith(usageInformation.UserParametersWithDefaultValues);
parametersToAlwaysShow.UnionWith(hostSpecificTemplateData.ParametersToAlwaysShow);
}
// aggregate the parameter variants
foreach (KeyValuePair<string, IReadOnlyList<string>> defaultVariants in defaultVariantsForCanonicals)
{
if (!groupVariantsForCanonicals.ContainsKey(defaultVariants.Key))
{
// there were no opinionated variants, take the preferred default.
groupVariantsForCanonicals[defaultVariants.Key] = defaultVariants.Value;
}
}
IParameterSet allGroupParameters = new TemplateGroupParameterSet(parameterSetsForAllTemplatesInGroup);
string parameterErrors = InvalidParameterInfo.InvalidParameterListToString(invalidParametersForGroup.Values.ToList());
HashSet<string> parametersToHide = new HashSet<string>(parameterHidingDisposition.Where(x => x.Value).Select(x => x.Key), StringComparer.Ordinal);
return new TemplateGroupParameterDetails
{
AllParams = allGroupParameters,
AdditionalInfo = parameterErrors,
InvalidParams = groupUserParamsWithInvalidValues.ToList(),
ExplicitlyHiddenParams = parametersToHide,
GroupVariantsForCanonicals = groupVariantsForCanonicals,
GroupUserParamsWithDefaultValues = groupUserParamsWithDefaultValues,
HasPostActionScriptRunner = groupHasPostActionScriptRunner,
ParametersToAlwaysShow = parametersToAlwaysShow,
};
}
private struct TemplateGroupParameterDetails
{
public IParameterSet AllParams;
public string AdditionalInfo; // TODO: rename (probably)
public IReadOnlyList<string> InvalidParams;
public HashSet<string> ExplicitlyHiddenParams;
public IReadOnlyDictionary<string, IReadOnlyList<string>> GroupVariantsForCanonicals;
public HashSet<string> GroupUserParamsWithDefaultValues;
public bool HasPostActionScriptRunner;
public HashSet<string> ParametersToAlwaysShow;
}
}
}
| |
#region Using Statements
using CameraRenderTargetProject.Components;
using System;
using System.Collections.Generic;
using WaveEngine.Common;
using WaveEngine.Common.Graphics;
using WaveEngine.Common.Math;
using WaveEngine.Components.Animation;
using WaveEngine.Components.Cameras;
using WaveEngine.Components.Graphics3D;
using WaveEngine.Components.UI;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Resources;
using WaveEngine.Framework.Services;
using WaveEngine.ImageEffects;
using WaveEngine.Materials;
#endregion
namespace CameraRenderTargetProject
{
public class MyScene : Scene
{
// Cameras
List<FixedCamera> cameras;
// Camera rendertargets
Dictionary<FixedCamera, RenderTarget> cameraRenderTargets;
// Current camera Index
int currentCameraIndex;
TextBlock textBlock;
protected override void CreateScene()
{
this.CreateUI();
this.CreateCameras();
this.CreateStage();
this.CreateIsis();
}
private void CreateUI()
{
Button changeCameraBtn = new Button()
{
Text = "Change Camera",
HorizontalAlignment = WaveEngine.Framework.UI.HorizontalAlignment.Left,
VerticalAlignment = WaveEngine.Framework.UI.VerticalAlignment.Top,
Margin = new WaveEngine.Framework.UI.Thickness(20),
Width = 160,
Height = 60
};
changeCameraBtn.Click += changeCameraBtn_Click;
EntityManager.Add(changeCameraBtn);
this.textBlock = new TextBlock()
{
Text = "",
VerticalAlignment = WaveEngine.Framework.UI.VerticalAlignment.Top,
HorizontalAlignment = WaveEngine.Framework.UI.HorizontalAlignment.Left,
Margin = new WaveEngine.Framework.UI.Thickness(20, 100,0,0)
};
EntityManager.Add(this.textBlock);
}
private void changeCameraBtn_Click(object sender, EventArgs e)
{
this.currentCameraIndex = (this.currentCameraIndex + 1) % this.cameras.Count;
this.SetActiveCamera(this.currentCameraIndex);
}
private void CreateCameras()
{
this.cameras = new List<FixedCamera>();
this.cameraRenderTargets = new Dictionary<FixedCamera, RenderTarget>();
// Free camera
FreeCamera camera = new FreeCamera("Free Camera", new Vector3(0.519f, 1.822f, 5.789f), new Vector3(1.55f, 1.372f, 0.75f))
{
NearPlane = 0.01f,
FarPlane = 15,
FieldOfView = MathHelper.ToRadians(80),
Speed = 3
};
EntityManager.Add(camera);
this.cameras.Add(camera);
// Security Camera 1
this.CreateSecurityCamera(new Vector3(-2.768f, 2.513f, 0), new Vector3(0.429f, 0.426f, -3.807f), new Vector3(-0.2f, 0.867f, 4.451f), TimeSpan.Zero);
// Security Camera 2
this.CreateSecurityCamera(new Vector3(2.272f, 2.513f, -2.657f), new Vector3(-4.51f, 0.112f, -2.086f), new Vector3(0.441f, 0.349f, 0.374f), TimeSpan.FromSeconds(3));
// Security Camera 3
this.CreateSecurityCamera(new Vector3(2.844f, 2.513f, 5.561f), new Vector3(1.763f, 0.349f, 0.374f), new Vector3(-2.285f, 0.349f, 4.394f), TimeSpan.FromSeconds(5));
}
private void CreateSecurityCamera(Vector3 position, Vector3 startLookAt, Vector3 endLookAt, TimeSpan timeOffset)
{
FixedCamera camera = new FixedCamera("securityCam_" + this.cameras.Count, position, startLookAt)
{
// Create RenderTarget to the camera
RenderTarget = WaveServices.GraphicsDevice.RenderTargets.CreateRenderTarget(350, 256),
FieldOfView = MathHelper.ToRadians(80),
NearPlane = 0.01f,
FarPlane = 15,
};
camera.Entity.AddComponent(new SecurityCameraBehavior(startLookAt, endLookAt, timeOffset));
camera.Entity.AddComponent(ImageEffects.FilmGrain());
camera.Entity.AddComponent(ImageEffects.ScanLines());
// This camera will not render the GUI layer
camera.LayerMask[DefaultLayers.GUI] = false;
// Register as secondary camera
EntityManager.Add(camera);
this.cameras.Add(camera);
this.cameraRenderTargets[camera] = camera.RenderTarget;
}
/// <summary>
/// Creates the scenery.
/// </summary>
private void CreateStage()
{
// create materials
var materialsMap = new Dictionary<string, Material>()
{
{"stageWall", new DualTextureMaterial("Content/Textures/stageWall_Diffuse.wpk", "Content/Textures/stageLightingMap.wpk", DefaultLayers.Opaque)},
{"stageWall2", new DualTextureMaterial("Content/Textures/stageWall2_Diffuse.wpk", "Content/Textures/stageLightingMap.wpk", DefaultLayers.Opaque)},
{"stageFloor", new DualTextureMaterial("Content/Textures/stageFloor_Diffuse.wpk", "Content/Textures/stageLightingMap.wpk", DefaultLayers.Opaque)},
{"stageDoor", new DualTextureMaterial("Content/Textures/stageDoor_Diffuse.wpk", "Content/Textures/stageLightingMap.wpk", DefaultLayers.Opaque)},
{"stageCeiling001", new DualTextureMaterial("Content/Textures/stageCeiling_Diffuse.wpk", "Content/Textures/stageLightingMap.wpk", DefaultLayers.Opaque)},
{"screen_0", new BasicMaterial(this.cameras[1].RenderTarget, DefaultLayers.Opaque)},
{"screen_1", new BasicMaterial(this.cameras[2].RenderTarget, DefaultLayers.Opaque)},
{"screen_2", new BasicMaterial(this.cameras[3].RenderTarget, DefaultLayers.Opaque)},
};
Entity stage = new Entity("stage")
.AddComponent(new Transform3D())
.AddComponent(new Model("Content/Models/Stage.wpk"))
.AddComponent(new ModelRenderer())
.AddComponent(new MaterialsMap(materialsMap));
EntityManager.Add(stage);
}
/// <summary>
/// Creates main character.
/// </summary>
private void CreateIsis()
{
PointLight light = new PointLight("light", new Vector3(-1.783f, 2.503f, 0))
{
IsVisible = true,
Color = new Color("f0f2ff"),
Attenuation = 20
};
EntityManager.Add(light);
Entity isis = new Entity("Isis")
.AddComponent(new Transform3D() { Position = Vector3.UnitY * 0.15f, Scale = Vector3.One * 1.14f, Rotation = Vector3.UnitY * MathHelper.ToRadians(-25) })
.AddComponent(new SkinnedModel("Content/Models/isis.wpk"))
.AddComponent(new SkinnedModelRenderer())
.AddComponent(new Animation3D("Content/Models/isis-animations.wpk"))
.AddComponent(new MaterialsMap(new NormalMappingMaterial("Content/Textures/isis-difuse.wpk", "Content/Textures/isis-normal.wpk", DefaultLayers.Opaque) { AmbientColor = Color.White * 0.6f }));
EntityManager.Add(isis);
isis.FindComponent<Animation3D>().PlayAnimation("Idle", true);
}
private void SetActiveCamera(int cameraIndex)
{
var activeCamera = this.cameras[cameraIndex];
activeCamera.RenderTarget = null;
activeCamera.LayerMask[DefaultLayers.GUI] = true;
this.RenderManager.SetActiveCamera3D(activeCamera.Entity);
this.textBlock.Text = string.Format("Active Camera: {0}", activeCamera.Entity.Name);
for (int i = 0; i < this.cameras.Count; i++)
{
var camera = this.cameras[i];
if (cameraIndex != i)
{
if (this.cameraRenderTargets.ContainsKey(camera))
{
camera.RenderTarget = this.cameraRenderTargets[camera];
camera.LayerMask[DefaultLayers.GUI] = false;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
public class PatternMatcherTests
{
[Fact]
public void BreakIntoCharacterParts_EmptyIdentifier()
{
VerifyBreakIntoCharacterParts(string.Empty, Array.Empty<string>());
}
[Fact]
public void BreakIntoCharacterParts_SimpleIdentifier()
{
VerifyBreakIntoCharacterParts("foo", "foo");
}
[Fact]
public void BreakIntoCharacterParts_PrefixUnderscoredIdentifier()
{
VerifyBreakIntoCharacterParts("_foo", "_", "foo");
}
[Fact]
public void BreakIntoCharacterParts_UnderscoredIdentifier()
{
VerifyBreakIntoCharacterParts("f_oo", "f", "_", "oo");
}
[Fact]
public void BreakIntoCharacterParts_PostfixUnderscoredIdentifier()
{
VerifyBreakIntoCharacterParts("foo_", "foo", "_");
}
[Fact]
public void BreakIntoCharacterParts_PrefixUnderscoredIdentifierWithCapital()
{
VerifyBreakIntoCharacterParts("_Foo", "_", "Foo");
}
[Fact]
public void BreakIntoCharacterParts_MUnderscorePrefixed()
{
VerifyBreakIntoCharacterParts("m_foo", "m", "_", "foo");
}
[Fact]
public void BreakIntoCharacterParts_CamelCaseIdentifier()
{
VerifyBreakIntoCharacterParts("FogBar", "Fog", "Bar");
}
[Fact]
public void BreakIntoCharacterParts_MixedCaseIdentifier()
{
VerifyBreakIntoCharacterParts("fogBar", "fog", "Bar");
}
[Fact]
public void BreakIntoCharacterParts_TwoCharacterCapitalIdentifier()
{
VerifyBreakIntoCharacterParts("UIElement", "U", "I", "Element");
}
[Fact]
public void BreakIntoCharacterParts_NumberSuffixedIdentifier()
{
VerifyBreakIntoCharacterParts("Foo42", "Foo", "42");
}
[Fact]
public void BreakIntoCharacterParts_NumberContainingIdentifier()
{
VerifyBreakIntoCharacterParts("Fog42Bar", "Fog", "42", "Bar");
}
[Fact]
public void BreakIntoCharacterParts_NumberPrefixedIdentifier()
{
// 42Bar is not a valid identifier in either C# or VB, but it is entirely conceivable the user might be
// typing it trying to do a substring match
VerifyBreakIntoCharacterParts("42Bar", "42", "Bar");
}
[Fact]
[WorkItem(544296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544296")]
public void BreakIntoWordParts_VerbatimIdentifier()
{
VerifyBreakIntoWordParts("@int:", "int");
}
[Fact]
[WorkItem(537875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537875")]
public void BreakIntoWordParts_AllCapsConstant()
{
VerifyBreakIntoWordParts("C_STYLE_CONSTANT", "C", "_", "STYLE", "_", "CONSTANT");
}
[Fact]
[WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")]
public void BreakIntoWordParts_SingleLetterPrefix1()
{
VerifyBreakIntoWordParts("UInteger", "U", "Integer");
}
[Fact]
[WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")]
public void BreakIntoWordParts_SingleLetterPrefix2()
{
VerifyBreakIntoWordParts("IDisposable", "I", "Disposable");
}
[Fact]
[WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")]
public void BreakIntoWordParts_TwoCharacterCapitalIdentifier()
{
VerifyBreakIntoWordParts("UIElement", "UI", "Element");
}
[Fact]
[WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")]
public void BreakIntoWordParts_XDocument()
{
VerifyBreakIntoWordParts("XDocument", "X", "Document");
}
[Fact]
[WorkItem(540087, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540087")]
public void BreakIntoWordParts_XMLDocument1()
{
VerifyBreakIntoWordParts("XMLDocument", "XML", "Document");
}
[Fact]
public void BreakIntoWordParts_XMLDocument2()
{
VerifyBreakIntoWordParts("XmlDocument", "Xml", "Document");
}
[Fact]
public void BreakIntoWordParts_TwoUppercaseCharacters()
{
VerifyBreakIntoWordParts("SimpleUIElement", "Simple", "UI", "Element");
}
private void VerifyBreakIntoWordParts(string original, params string[] parts)
{
AssertEx.Equal(parts, BreakIntoWordParts(original));
}
private void VerifyBreakIntoCharacterParts(string original, params string[] parts)
{
AssertEx.Equal(parts, BreakIntoCharacterParts(original));
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveExact()
{
var match = TryMatchSingleWordPattern("[|Foo|]", "Foo");
Assert.Equal(PatternMatchKind.Exact, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_SingleWordPreferCaseSensitiveExactInsensitive()
{
var match = TryMatchSingleWordPattern("[|foo|]", "Foo");
Assert.Equal(PatternMatchKind.Exact, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitivePrefix()
{
var match = TryMatchSingleWordPattern("[|Fo|]o", "Fo");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitivePrefixCaseInsensitive()
{
var match = TryMatchSingleWordPattern("[|Fo|]o", "fo");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchSimple()
{
var match = TryMatchSingleWordPattern("[|F|]og[|B|]ar", "FB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
Assert.InRange((int)match.Value.CamelCaseWeight, 1, int.MaxValue);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchPartialPattern()
{
var match = TryMatchSingleWordPattern("[|Fo|]g[|B|]ar", "FoB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern1()
{
var match = TryMatchSingleWordPattern("FogBar", "FBB");
Assert.Null(match);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern2()
{
var match = TryMatchSingleWordPattern("FogBar", "FoooB");
Assert.Null(match);
}
[Fact]
public void TryMatchSingleWordPattern_CamelCaseMatchPartiallyUnmatched()
{
var match = TryMatchSingleWordPattern("FogBarBaz", "FZ");
Assert.Null(match);
}
[Fact]
public void TryMatchSingleWordPattern_CamelCaseMatchCompletelyUnmatched()
{
var match = TryMatchSingleWordPattern("FogBarBaz", "ZZ");
Assert.Null(match);
}
[Fact]
[WorkItem(544975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544975")]
public void TryMatchSingleWordPattern_TwoUppercaseCharacters()
{
var match = TryMatchSingleWordPattern("[|Si|]mple[|UI|]Element", "SiUI");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.True(match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern()
{
var match = TryMatchSingleWordPattern("Fog[|B|]ar", "b");
Assert.Equal(PatternMatchKind.Substring, match.Value.Kind);
Assert.False(match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern2()
{
var match = TryMatchSingleWordPattern("[|F|]og[|B|]ar", "fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName()
{
var match = TryMatchSingleWordPattern("[|_f|]og[|B|]ar", "_fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName2()
{
var match = TryMatchSingleWordPattern("_[|f|]og[|B|]ar", "fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredNameInsensitive()
{
var match = TryMatchSingleWordPattern("[|_F|]og[|B|]ar", "_fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore()
{
var match = TryMatchSingleWordPattern("[|F|]og_[|B|]ar", "FB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore2()
{
var match = TryMatchSingleWordPattern("[|F|]og[|_B|]ar", "F_B");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore3()
{
var match = TryMatchSingleWordPattern("Fog_Bar", "F__B");
Assert.Null(match);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore4()
{
var match = TryMatchSingleWordPattern("[|F|]og[|_B|]ar", "f_B");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore5()
{
var match = TryMatchSingleWordPattern("[|F|]og[|_B|]ar", "F_b");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights1()
{
var match1 = TryMatchSingleWordPattern("[|F|]og[|B|]arBaz", "FB");
var match2 = TryMatchSingleWordPattern("[|F|]ooFlob[|B|]az", "FB");
// We should prefer something that starts at the beginning if possible
Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights2()
{
var match1 = TryMatchSingleWordPattern("BazBar[|F|]oo[|F|]oo[|F|]oo", "FFF");
var match2 = TryMatchSingleWordPattern("Baz[|F|]ogBar[|F|]oo[|F|]oo", "FFF");
// Contiguous things should also be preferred
Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights3()
{
var match1 = TryMatchSingleWordPattern("[|F|]ogBar[|F|]oo[|F|]oo", "FFF");
var match2 = TryMatchSingleWordPattern("Bar[|F|]oo[|F|]oo[|F|]oo", "FFF");
// The weight of being first should be greater than the weight of being contiguous
Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals()
{
var match = TryMatchSingleWordPattern("[|Foo|]", "foo");
Assert.Equal(PatternMatchKind.Exact, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals2()
{
var match = TryMatchSingleWordPattern("[|Foo|]", "Foo");
// Since it's actually case sensitive, we'll report it as such even though we didn't prefer it
Assert.Equal(PatternMatchKind.Exact, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix()
{
var match = TryMatchSingleWordPattern("[|Fog|]Bar", "fog");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix2()
{
var match = TryMatchSingleWordPattern("[|Fog|]Bar", "Fog");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase1()
{
var match = TryMatchSingleWordPattern("[|F|]og[|B|]ar", "FB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase2()
{
var match = TryMatchSingleWordPattern("[|F|]og[|B|]ar", "fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase3()
{
var match = TryMatchSingleWordPattern("[|f|]og[|B|]ar", "fB");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseSensitiveWhenPrefix()
{
var match = TryMatchSingleWordPattern("[|fog|]BarFoo", "Fog");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.False(match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_PreferCaseInsensitiveWhenPrefix()
{
var match = TryMatchSingleWordPattern("[|fog|]BarFoo", "Fog");
Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind);
Assert.Equal(false, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_CamelCase1()
{
var match = TryMatchSingleWordPattern("[|Fo|]oBarry[|Bas|]il", "FoBas");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_CamelCase2()
{
Assert.Null(TryMatchSingleWordPattern("FooActBarCatAlp", "FooAlpBarCat"));
}
[Fact]
public void TryMatchSingleWordPattern_CamelCase3()
{
var match = TryMatchSingleWordPattern("[|AbCd|]xxx[|Ef|]Cd[|Gh|]", "AbCdEfGh");
Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind);
Assert.Equal(true, match.Value.IsCaseSensitive);
}
private void AssertContainsType(PatternMatchKind type, IEnumerable<PatternMatch> results)
{
Assert.True(results.Any(r => r.Kind == type));
}
[Fact]
public void MatchMultiWordPattern_ExactWithLowercase()
{
var match = TryMatchMultiWordPattern("[|AddMetadataReference|]", "addmetadatareference");
AssertContainsType(PatternMatchKind.Exact, match);
}
[Fact]
public void MatchMultiWordPattern_SingleLowercasedSearchWord1()
{
var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "add");
AssertContainsType(PatternMatchKind.Prefix, match);
}
[Fact]
public void MatchMultiWordPattern_SingleLowercasedSearchWord2()
{
var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "metadata");
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_SingleUppercaseSearchWord1()
{
var match = TryMatchMultiWordPattern("[|Add|]MetadataReference", "Add");
AssertContainsType(PatternMatchKind.Prefix, match);
}
[Fact]
public void MatchMultiWordPattern_SingleUppercaseSearchWord2()
{
var match = TryMatchMultiWordPattern("Add[|Metadata|]Reference", "Metadata");
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_SingleUppercaseSearchLetter1()
{
var match = TryMatchMultiWordPattern("[|A|]ddMetadataReference", "A");
AssertContainsType(PatternMatchKind.Prefix, match);
}
[Fact]
public void MatchMultiWordPattern_SingleUppercaseSearchLetter2()
{
var match = TryMatchMultiWordPattern("Add[|M|]etadataReference", "M");
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_TwoLowercaseWords()
{
var match = TryMatchMultiWordPattern("[|Add|][|Metadata|]Reference", "add metadata");
AssertContainsType(PatternMatchKind.Prefix, match);
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_TwoUppercaseLettersSeparateWords()
{
var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "A M");
AssertContainsType(PatternMatchKind.Prefix, match);
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_TwoUppercaseLettersOneWord()
{
var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadataReference", "AM");
AssertContainsType(PatternMatchKind.CamelCase, match);
}
[Fact]
public void MatchMultiWordPattern_Mixed1()
{
var match = TryMatchMultiWordPattern("Add[|Metadata|][|Ref|]erence", "ref Metadata");
Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring }));
}
[Fact]
public void MatchMultiWordPattern_Mixed2()
{
var match = TryMatchMultiWordPattern("Add[|M|]etadata[|Ref|]erence", "ref M");
Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring }));
}
[Fact]
public void MatchMultiWordPattern_MixedCamelCase()
{
var match = TryMatchMultiWordPattern("[|A|]dd[|M|]etadata[|Re|]ference", "AMRe");
AssertContainsType(PatternMatchKind.CamelCase, match);
}
[Fact]
public void MatchMultiWordPattern_BlankPattern()
{
Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", string.Empty));
}
[Fact]
public void MatchMultiWordPattern_WhitespaceOnlyPattern()
{
Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", " "));
}
[Fact]
public void MatchMultiWordPattern_EachWordSeparately1()
{
var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "add Meta");
AssertContainsType(PatternMatchKind.Prefix, match);
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_EachWordSeparately2()
{
var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add meta");
AssertContainsType(PatternMatchKind.Prefix, match);
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_EachWordSeparately3()
{
var match = TryMatchMultiWordPattern("[|Add|][|Meta|]dataReference", "Add Meta");
AssertContainsType(PatternMatchKind.Prefix, match);
AssertContainsType(PatternMatchKind.Substring, match);
}
[Fact]
public void MatchMultiWordPattern_MixedCasing1()
{
Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "mEta"));
}
[Fact]
public void MatchMultiWordPattern_MixedCasing2()
{
Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "Data"));
}
[Fact]
public void MatchMultiWordPattern_AsteriskSplit()
{
var match = TryMatchMultiWordPattern("Get[|K|]ey[|W|]ord", "K*W");
Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring }));
}
[WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")]
[Fact]
public void MatchMultiWordPattern_LowercaseSubstring1()
{
Assert.Null(TryMatchMultiWordPattern("Operator", "a"));
}
[WorkItem(544628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544628")]
[Fact]
public void MatchMultiWordPattern_LowercaseSubstring2()
{
var match = TryMatchMultiWordPattern("Foo[|A|]ttribute", "a");
AssertContainsType(PatternMatchKind.Substring, match);
Assert.False(match.First().IsCaseSensitive);
}
[Fact]
public void TryMatchSingleWordPattern_CultureAwareSingleWordPreferCaseSensitiveExactInsensitive()
{
var previousCulture = Thread.CurrentThread.CurrentCulture;
var turkish = CultureInfo.GetCultureInfo("tr-TR");
Thread.CurrentThread.CurrentCulture = turkish;
try
{
var match = TryMatchSingleWordPattern("[|ioo|]", "\u0130oo"); // u0130 = Capital I with dot
Assert.Equal(PatternMatchKind.Exact, match.Value.Kind);
Assert.False(match.Value.IsCaseSensitive);
}
finally
{
Thread.CurrentThread.CurrentCulture = previousCulture;
}
}
[Fact]
public void MatchAllLowerPattern1()
{
Assert.NotNull(TryMatchSingleWordPattern("FogBar[|ChangedEventArgs|]", "changedeventargs"));
}
[Fact]
public void MatchAllLowerPattern2()
{
Assert.Null(TryMatchSingleWordPattern("FogBarChangedEventArgs", "changedeventarrrgh"));
}
[Fact]
public void MatchAllLowerPattern3()
{
Assert.NotNull(TryMatchSingleWordPattern("A[|BCD|]EFGH", "bcd"));
}
[Fact]
public void MatchAllLowerPattern4()
{
Assert.Null(TryMatchSingleWordPattern("AbcdefghijEfgHij", "efghij"));
}
private static IList<string> PartListToSubstrings(string identifier, StringBreaks parts)
{
List<string> result = new List<string>();
for (int i = 0; i < parts.Count; i++)
{
var span = parts[i];
result.Add(identifier.Substring(span.Start, span.Length));
}
return result;
}
private static IList<string> BreakIntoCharacterParts(string identifier)
{
return PartListToSubstrings(identifier, StringBreaker.BreakIntoCharacterParts(identifier));
}
private static IList<string> BreakIntoWordParts(string identifier)
{
return PartListToSubstrings(identifier, StringBreaker.BreakIntoWordParts(identifier));
}
private static PatternMatch? TryMatchSingleWordPattern(string candidate, string pattern)
{
IList<TextSpan> spans;
MarkupTestFile.GetSpans(candidate, out candidate, out spans);
var match = new PatternMatcher(pattern).MatchSingleWordPattern_ForTestingOnly(candidate);
if (match == null)
{
Assert.True(spans == null || spans.Count == 0);
}
else
{
Assert.Equal<TextSpan>(match.Value.MatchedSpans, spans);
}
return match;
}
private static IEnumerable<PatternMatch> TryMatchMultiWordPattern(string candidate, string pattern)
{
IList<TextSpan> expectedSpans;
MarkupTestFile.GetSpans(candidate, out candidate, out expectedSpans);
var matches = new PatternMatcher(pattern).GetMatches(candidate, includeMatchSpans: true);
if (matches.IsDefaultOrEmpty)
{
Assert.True(expectedSpans == null || expectedSpans.Count == 0);
return null;
}
else
{
var actualSpans = matches.SelectMany(m => m.MatchedSpans).OrderBy(s => s.Start).ToList();
Assert.Equal(expectedSpans, actualSpans);
return matches;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 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.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Options;
using NUnit.Engine;
namespace NUnit.ConsoleRunner
{
/// <summary>
/// This class provides the entry point for the console runner.
/// </summary>
public class Program
{
//static Logger log = InternalTrace.GetLogger(typeof(Runner));
static ConsoleOptions Options = new ConsoleOptions(new DefaultOptionsProvider());
private static ExtendedTextWriter _outWriter;
// This has to be lazy otherwise NoColor command line option is not applied correctly
private static ExtendedTextWriter OutWriter
{
get
{
if (_outWriter == null) _outWriter = new ColorConsoleWriter(!Options.NoColor);
return _outWriter;
}
}
[STAThread]
public static int Main(string[] args)
{
try
{
Options.Parse(args);
}
catch (OptionException ex)
{
WriteHeader();
OutWriter.WriteLine(ColorStyle.Error, string.Format(ex.Message, ex.OptionName));
return ConsoleRunner.INVALID_ARG;
}
//ColorConsole.Enabled = !Options.NoColor;
// Create SettingsService early so we know the trace level right at the start
//SettingsService settingsService = new SettingsService();
//InternalTraceLevel level = (InternalTraceLevel)settingsService.GetSetting("Options.InternalTraceLevel", InternalTraceLevel.Default);
//if (options.trace != InternalTraceLevel.Default)
// level = options.trace;
//InternalTrace.Initialize("nunit3-console_%p.log", level);
//log.Info("NUnit3-console.exe starting");
try
{
if (Options.ShowVersion || !Options.NoHeader)
WriteHeader();
if (Options.ShowHelp || args.Length == 0)
{
WriteHelpText();
return ConsoleRunner.OK;
}
// We already showed version as a part of the header
if (Options.ShowVersion)
return ConsoleRunner.OK;
if (!Options.Validate())
{
using (new ColorConsole(ColorStyle.Error))
{
foreach (string message in Options.ErrorMessages)
Console.Error.WriteLine(message);
}
return ConsoleRunner.INVALID_ARG;
}
if (Options.InputFiles.Count == 0)
{
using (new ColorConsole(ColorStyle.Error))
Console.Error.WriteLine("Error: no inputs specified");
return ConsoleRunner.OK;
}
using (ITestEngine engine = TestEngineActivator.CreateInstance(false))
{
if (Options.WorkDirectory != null)
engine.WorkDirectory = Options.WorkDirectory;
if (Options.InternalTraceLevel != null)
engine.InternalTraceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), Options.InternalTraceLevel);
try
{
return new ConsoleRunner(engine, Options, OutWriter).Execute();
}
catch (TestSelectionParserException ex)
{
OutWriter.WriteLine(ColorStyle.Error, ex.Message);
return ConsoleRunner.INVALID_ARG;
}
catch (FileNotFoundException ex)
{
OutWriter.WriteLine(ColorStyle.Error, ex.Message);
return ConsoleRunner.INVALID_ASSEMBLY;
}
catch (DirectoryNotFoundException ex)
{
OutWriter.WriteLine(ColorStyle.Error, ex.Message);
return ConsoleRunner.INVALID_ASSEMBLY;
}
catch (Exception ex)
{
OutWriter.WriteLine(ColorStyle.Error, ex.ToString());
return ConsoleRunner.UNEXPECTED_ERROR;
}
finally
{
if (Options.WaitBeforeExit)
{
using (new ColorConsole(ColorStyle.Warning))
{
Console.Out.WriteLine("\nPress any key to continue . . .");
Console.ReadKey(true);
}
}
// log.Info( "NUnit3-console.exe terminating" );
}
}
}
finally
{
Console.ResetColor();
}
}
private static void WriteHeader()
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
string versionText = executingAssembly.GetName().Version.ToString(3);
string programName = "NUnit Console Runner";
string copyrightText = "Copyright (C) 2016 Charlie Poole.\r\nAll Rights Reserved.";
string configText = String.Empty;
object[] attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attrs.Length > 0)
programName = ((AssemblyTitleAttribute)attrs[0]).Title;
attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if ( attrs.Length > 0 )
copyrightText = ((AssemblyCopyrightAttribute)attrs[0]).Copyright;
attrs = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
if ( attrs.Length > 0 )
{
string configuration = ( ( AssemblyConfigurationAttribute )attrs[0] ).Configuration;
if ( !String.IsNullOrEmpty( configuration ) )
{
configText = string.Format( "({0})", ( ( AssemblyConfigurationAttribute )attrs[0] ).Configuration );
}
}
OutWriter.WriteLine(ColorStyle.Header, string.Format("{0} {1} {2}", programName, versionText, configText));
OutWriter.WriteLine(ColorStyle.SubHeader, copyrightText);
OutWriter.WriteLine();
}
private static void WriteHelpText()
{
OutWriter.WriteLine();
OutWriter.WriteLine(ColorStyle.Header, "NUNIT3-CONSOLE [inputfiles] [options]");
OutWriter.WriteLine();
OutWriter.WriteLine(ColorStyle.Default, "Runs a set of NUnit tests from the console.");
OutWriter.WriteLine();
OutWriter.WriteLine(ColorStyle.SectionHeader, "InputFiles:");
OutWriter.WriteLine(ColorStyle.Default, " One or more assemblies or test projects of a recognized type.");
OutWriter.WriteLine();
OutWriter.WriteLine(ColorStyle.SectionHeader, "Options:");
using (new ColorConsole(ColorStyle.Default))
{
Options.WriteOptionDescriptions(Console.Out);
}
OutWriter.WriteLine();
OutWriter.WriteLine(ColorStyle.SectionHeader, "Description:");
using (new ColorConsole(ColorStyle.Default))
{
OutWriter.WriteLine(" By default, this command runs the tests contained in the");
OutWriter.WriteLine(" assemblies and projects specified. If the --explore option");
OutWriter.WriteLine(" is used, no tests are executed but a description of the tests");
OutWriter.WriteLine(" is saved in the specified or default format.");
OutWriter.WriteLine();
OutWriter.WriteLine(" The --where option is intended to extend or replace the earlier");
OutWriter.WriteLine(" --test, --include and --exclude options by use of a selection expression");
OutWriter.WriteLine(" describing exactly which tests to use. Examples of usage are:");
OutWriter.WriteLine(" --where:cat==Data");
OutWriter.WriteLine(" --where \"method =~ /DataTest*/ && cat = Slow\"");
OutWriter.WriteLine();
OutWriter.WriteLine(" Care should be taken in combining --where with --test or --testlist.");
OutWriter.WriteLine(" The test and where specifications are implicitly joined using &&, so");
OutWriter.WriteLine(" that BOTH sets of criteria must be satisfied in order for a test to run.");
OutWriter.WriteLine(" See the docs for more information and a full description of the syntax");
OutWriter.WriteLine(" information and a full description of the syntax.");
OutWriter.WriteLine();
OutWriter.WriteLine(" Several options that specify processing of XML output take");
OutWriter.WriteLine(" an output specification as a value. A SPEC may take one of");
OutWriter.WriteLine(" the following forms:");
OutWriter.WriteLine(" --OPTION:filename");
OutWriter.WriteLine(" --OPTION:filename;format=formatname");
OutWriter.WriteLine(" --OPTION:filename;transform=xsltfile");
OutWriter.WriteLine();
OutWriter.WriteLine(" The --result option may use any of the following formats:");
OutWriter.WriteLine(" nunit3 - the native XML format for NUnit 3.0");
OutWriter.WriteLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
OutWriter.WriteLine();
OutWriter.WriteLine(" The --explore option may use any of the following formats:");
OutWriter.WriteLine(" nunit3 - the native XML format for NUnit 3.0");
OutWriter.WriteLine(" cases - a text file listing the full names of all test cases.");
OutWriter.WriteLine(" If --explore is used without any specification following, a list of");
OutWriter.WriteLine(" test cases is output to the writer.");
OutWriter.WriteLine();
OutWriter.WriteLine(" If none of the options {--result, --explore, --noxml} is used,");
OutWriter.WriteLine(" NUnit saves the results to TestResult.xml in nunit3 format");
OutWriter.WriteLine();
OutWriter.WriteLine(" Any transforms provided must handle input in the native nunit3 format.");
OutWriter.WriteLine();
//writer.WriteLine("Options that take values may use an equal sign, a colon");
//writer.WriteLine("or a space to separate the option from its value.");
//writer.WriteLine();
}
}
}
}
| |
/*
* Anarres C Preprocessor
* Copyright (c) 2007-2008, Shevek
*
* 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.Text;
using System.Globalization;
namespace CppNet {
/** Does not handle digraphs. */
public class LexerSource : Source {
static bool isJavaIdentifierStart(int c) {
return char.IsLetter((char)c) || c == '$' || c == '_';
}
static bool isJavaIdentifierPart(int c)
{
return char.IsLetter((char)c) || c == '$' || c == '_' || char.IsDigit((char)c);
}
static bool isIdentifierIgnorable(int c) {
return c >= 0 && c <= 8 ||
c >= 0xE && c <= 0x1B ||
c >= 0x7F && c <= 0x9F ||
CharUnicodeInfo.GetUnicodeCategory((char)c) == UnicodeCategory.Format;
}
static int digit(char ch, int radix)
{
string alphabet;
switch(radix) {
case 8:
alphabet = "012345678";
break;
case 10:
alphabet = "0123456789";
break;
case 16:
ch = char.ToLower(ch);
alphabet = "0123456789abcdef";
break;
default:
throw new NotSupportedException();
}
return alphabet.IndexOf(ch);
}
private static readonly bool DEBUG = false;
private JoinReader reader;
private bool ppvalid;
private bool bol;
private bool include;
private bool digraphs;
/* Unread. */
private int u0, u1;
private int ucount;
private int line;
private int column;
private int lastcolumn;
private bool cr;
/* ppvalid is:
* false in StringLexerSource,
* true in FileLexerSource */
public LexerSource(TextReader r, bool ppvalid) {
this.reader = new JoinReader(r);
this.ppvalid = ppvalid;
this.bol = true;
this.include = false;
this.digraphs = true;
this.ucount = 0;
this.line = 1;
this.column = 0;
this.lastcolumn = -1;
this.cr = false;
}
override internal void init(Preprocessor pp) {
base.init(pp);
this.digraphs = pp.getFeature(Feature.DIGRAPHS);
this.reader.init(pp, this);
}
override public int getLine() {
return line;
}
override public int getColumn() {
return column;
}
override internal bool isNumbered() {
return true;
}
/* Error handling. */
private void _error(String msg, bool error) {
int _l = line;
int _c = column;
if (_c == 0) {
_c = lastcolumn;
_l--;
}
else {
_c--;
}
if (error)
base.error(_l, _c, msg);
else
base.warning(_l, _c, msg);
}
/* Allow JoinReader to call this. */
internal void error(String msg)
{
_error(msg, true);
}
/* Allow JoinReader to call this. */
internal void warning(String msg) {
_error(msg, false);
}
/* A flag for string handling. */
internal void setInclude(bool b)
{
this.include = b;
}
/*
private bool _isLineSeparator(int c) {
return Character.getType(c) == Character.LINE_SEPARATOR
|| c == -1;
}
*/
/* XXX Move to JoinReader and canonicalise newlines. */
private static bool isLineSeparator(int c) {
switch ((char)c) {
case '\r':
case '\n':
case '\u2028':
case '\u2029':
case '\u000B':
case '\u000C':
case '\u0085':
return true;
default:
return (c == -1);
}
}
private int read() {
System.Diagnostics.Debug.Assert(ucount <= 2, "Illegal ucount: " + ucount);
switch (ucount) {
case 2:
ucount = 1;
return u1;
case 1:
ucount = 0;
return u0;
}
if (reader == null)
return -1;
int c = reader.read();
switch (c) {
case '\r':
cr = true;
line++;
lastcolumn = column;
column = 0;
break;
case '\n':
if (cr) {
cr = false;
break;
}
goto case '\u2028';
/* fallthrough */
case '\u2028':
case '\u2029':
case '\u000B':
case '\u000C':
case '\u0085':
cr = false;
line++;
lastcolumn = column;
column = 0;
break;
default:
cr = false;
column++;
break;
}
/*
if (isLineSeparator(c)) {
line++;
lastcolumn = column;
column = 0;
}
else {
column++;
}
*/
return c;
}
/* You can unget AT MOST one newline. */
private void unread(int c) {
/* XXX Must unread newlines. */
if (c != -1) {
if (isLineSeparator(c)) {
line--;
column = lastcolumn;
cr = false;
}
else {
column--;
}
switch (ucount) {
case 0:
u0 = c;
ucount = 1;
break;
case 1:
u1 = c;
ucount = 2;
break;
default:
throw new InvalidOperationException(
"Cannot unget another character!"
);
}
// reader.unread(c);
}
}
/* Consumes the rest of the current line into an invalid. */
private Token invalid(StringBuilder text, String reason) {
int d = read();
while (!isLineSeparator(d)) {
text.Append((char)d);
d = read();
}
unread(d);
return new Token(Token.INVALID, text.ToString(), reason);
}
private Token ccomment() {
StringBuilder text = new StringBuilder("/*");
int d;
do {
do {
d = read();
text.Append((char)d);
} while (d != '*');
do {
d = read();
text.Append((char)d);
} while (d == '*');
} while (d != '/');
return new Token(Token.CCOMMENT, text.ToString());
}
private Token cppcomment() {
StringBuilder text = new StringBuilder("//");
int d = read();
while (!isLineSeparator(d)) {
text.Append((char)d);
d = read();
}
unread(d);
return new Token(Token.CPPCOMMENT, text.ToString());
}
private int escape(StringBuilder text) {
int d = read();
switch (d) {
case 'a': text.Append('a'); return 0x07;
case 'b': text.Append('b'); return '\b';
case 'f': text.Append('f'); return '\f';
case 'n': text.Append('n'); return '\n';
case 'r': text.Append('r'); return '\r';
case 't': text.Append('t'); return '\t';
case 'v': text.Append('v'); return 0x0b;
case '\\': text.Append('\\'); return '\\';
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
int len = 0;
int val = 0;
do {
val = (val << 3) + digit((char)d, 8);
text.Append((char)d);
d = read();
} while(++len < 3 && digit((char)d, 8) != -1);
unread(d);
return val;
case 'x':
len = 0;
val = 0;
do {
val = (val << 4) + digit((char)d, 16);
text.Append((char)d);
d = read();
} while(++len < 2 && digit((char)d, 16) != -1);
unread(d);
return val;
/* Exclude two cases from the warning. */
case '"': text.Append('"'); return '"';
case '\'': text.Append('\''); return '\'';
default:
warning("Unnecessary escape character " + (char)d);
text.Append((char)d);
return d;
}
}
private Token character() {
StringBuilder text = new StringBuilder("'");
int d = read();
if (d == '\\') {
text.Append('\\');
d = escape(text);
}
else if (isLineSeparator(d)) {
unread(d);
return new Token(Token.INVALID, text.ToString(),
"Unterminated character literal");
}
else if (d == '\'') {
text.Append('\'');
return new Token(Token.INVALID, text.ToString(),
"Empty character literal");
}
else if (char.IsControl((char)d)) {
text.Append('?');
return invalid(text, "Illegal unicode character literal");
}
else {
text.Append((char)d);
}
int e = read();
if (e != '\'') {
// error("Illegal character constant");
/* We consume up to the next ' or the rest of the line. */
for (;;) {
if (isLineSeparator(e)) {
unread(e);
break;
}
text.Append((char)e);
if (e == '\'')
break;
e = read();
}
return new Token(Token.INVALID, text.ToString(),
"Illegal character constant " + text);
}
text.Append('\'');
/* XXX It this a bad cast? */
return new Token(Token.CHARACTER,
text.ToString(), (char)d);
}
private Token String(char open, char close) {
StringBuilder text = new StringBuilder();
text.Append(open);
StringBuilder buf = new StringBuilder();
for (;;) {
int c = read();
if (c == close) {
break;
}
else if (c == '\\') {
text.Append('\\');
if (!include) {
char d = (char)escape(text);
buf.Append(d);
}
}
else if (c == -1) {
unread(c);
// error("End of file in string literal after " + buf);
return new Token(Token.INVALID, text.ToString(),
"End of file in string literal after " + buf);
}
else if (isLineSeparator(c)) {
unread(c);
// error("Unterminated string literal after " + buf);
return new Token(Token.INVALID, text.ToString(),
"Unterminated string literal after " + buf);
}
else {
text.Append((char)c);
buf.Append((char)c);
}
}
text.Append(close);
return new Token(close == '>' ? Token.HEADER : Token.STRING,
text.ToString(), buf.ToString());
}
private Token _number(StringBuilder text, long val, int d) {
int bits = 0;
for (;;) {
/* XXX Error check duplicate bits. */
if (d == 'U' || d == 'u') {
bits |= 1;
text.Append((char)d);
d = read();
}
else if (d == 'L' || d == 'l') {
if ((bits & 4) != 0)
/* XXX warn */ ;
bits |= 2;
text.Append((char)d);
d = read();
}
else if (d == 'I' || d == 'i') {
if ((bits & 2) != 0)
/* XXX warn */ ;
bits |= 4;
text.Append((char)d);
d = read();
}
else if (char.IsLetter((char)d)) {
unread(d);
return new Token(Token.INVALID, text.ToString(),
"Invalid suffix \"" + (char)d +
"\" on numeric constant");
}
else {
unread(d);
return new Token(Token.INTEGER,
text.ToString(), (long)val);
}
}
}
/* We already chewed a zero, so empty is fine. */
private Token number_octal() {
StringBuilder text = new StringBuilder("0");
int d = read();
long val = 0;
while (digit((char)d, 8) != -1) {
val = (val << 3) + digit((char)d, 8);
text.Append((char)d);
d = read();
}
return _number(text, val, d);
}
/* We do not know whether know the first digit is valid. */
private Token number_hex(char x) {
StringBuilder text = new StringBuilder("0");
text.Append(x);
int d = read();
if (digit((char)d, 16) == -1) {
unread(d);
// error("Illegal hexadecimal constant " + (char)d);
return new Token(Token.INVALID, text.ToString(),
"Illegal hexadecimal digit " + (char)d +
" after "+ text);
}
long val = 0;
do {
val = (val << 4) + digit((char)d, 16);
text.Append((char)d);
d = read();
} while (digit((char)d, 16) != -1);
return _number(text, val, d);
}
/* We know we have at least one valid digit, but empty is not
* fine. */
/* XXX This needs a complete rewrite. */
private Token number_decimal(int c) {
StringBuilder text = new StringBuilder((char)c);
int d = c;
long val = 0;
do {
val = val * 10 + digit((char)d, 10);
text.Append((char)d);
d = read();
} while (digit((char)d, 10) != -1);
return _number(text, val, d);
}
private Token identifier(int c) {
StringBuilder text = new StringBuilder();
int d;
text.Append((char)c);
for (;;) {
d = read();
if (isIdentifierIgnorable(d))
;
else if (isJavaIdentifierPart(d))
text.Append((char)d);
else
break;
}
unread(d);
return new Token(Token.IDENTIFIER, text.ToString());
}
private Token whitespace(int c) {
StringBuilder text = new StringBuilder();
int d;
text.Append((char)c);
for (;;) {
d = read();
if (ppvalid && isLineSeparator(d)) /* XXX Ugly. */
break;
if (char.IsWhiteSpace((char)d))
text.Append((char)d);
else
break;
}
unread(d);
return new Token(Token.WHITESPACE, text.ToString());
}
/* No token processed by cond() contains a newline. */
private Token cond(char c, int yes, int no) {
int d = read();
if (c == d)
return new Token(yes);
unread(d);
return new Token(no);
}
public override Token token() {
Token tok = null;
int _l = line;
int _c = column;
int c = read();
int d;
switch (c) {
case '\n':
if (ppvalid) {
bol = true;
if (include) {
tok = new Token(Token.NL, _l, _c, "\n");
}
else {
int nls = 0;
do {
nls++;
d = read();
} while (d == '\n');
unread(d);
char[] text = new char[nls];
for (int i = 0; i < text.Length; i++)
text[i] = '\n';
// Skip the bol = false below.
tok = new Token(Token.NL, _l, _c, new String(text));
}
if (DEBUG)
System.Console.Error.WriteLine("lx: Returning NL: " + tok);
return tok;
}
/* Let it be handled as whitespace. */
break;
case '!':
tok = cond('=', Token.NE, '!');
break;
case '#':
if (bol)
tok = new Token(Token.HASH);
else
tok = cond('#', Token.PASTE, '#');
break;
case '+':
d = read();
if (d == '+')
tok = new Token(Token.INC);
else if (d == '=')
tok = new Token(Token.PLUS_EQ);
else
unread(d);
break;
case '-':
d = read();
if (d == '-')
tok = new Token(Token.DEC);
else if (d == '=')
tok = new Token(Token.SUB_EQ);
else if (d == '>')
tok = new Token(Token.ARROW);
else
unread(d);
break;
case '*':
tok = cond('=', Token.MULT_EQ, '*');
break;
case '/':
d = read();
if (d == '*')
tok = ccomment();
else if (d == '/')
tok = cppcomment();
else if (d == '=')
tok = new Token(Token.DIV_EQ);
else
unread(d);
break;
case '%':
d = read();
if (d == '=')
tok = new Token(Token.MOD_EQ);
else if (digraphs && d == '>')
tok = new Token('}'); // digraph
else if (digraphs && d == ':') {
bool paste = true;
d = read();
if (d != '%') {
unread(d);
tok = new Token('#'); // digraph
paste = false;
}
d = read();
if (d != ':') {
unread(d); // Unread 2 chars here.
unread('%');
tok = new Token('#'); // digraph
paste = false;
}
if(paste) {
tok = new Token(Token.PASTE); // digraph
}
}
else
unread(d);
break;
case ':':
/* :: */
d = read();
if (digraphs && d == '>')
tok = new Token(']'); // digraph
else
unread(d);
break;
case '<':
if (include) {
tok = String('<', '>');
}
else {
d = read();
if (d == '=')
tok = new Token(Token.LE);
else if (d == '<')
tok = cond('=', Token.LSH_EQ, Token.LSH);
else if (digraphs && d == ':')
tok = new Token('['); // digraph
else if (digraphs && d == '%')
tok = new Token('{'); // digraph
else
unread(d);
}
break;
case '=':
tok = cond('=', Token.EQ, '=');
break;
case '>':
d = read();
if (d == '=')
tok = new Token(Token.GE);
else if (d == '>')
tok = cond('=', Token.RSH_EQ, Token.RSH);
else
unread(d);
break;
case '^':
tok = cond('=', Token.XOR_EQ, '^');
break;
case '|':
d = read();
if (d == '=')
tok = new Token(Token.OR_EQ);
else if (d == '|')
tok = cond('=', Token.LOR_EQ, Token.LOR);
else
unread(d);
break;
case '&':
d = read();
if (d == '&')
tok = cond('=', Token.LAND_EQ, Token.LAND);
else if (d == '=')
tok = new Token(Token.AND_EQ);
else
unread(d);
break;
case '.':
d = read();
if (d == '.')
tok = cond('.', Token.ELLIPSIS, Token.RANGE);
else
unread(d);
/* XXX decimal fraction */
break;
case '0':
/* octal or hex */
d = read();
if (d == 'x' || d == 'X')
tok = number_hex((char)d);
else {
unread(d);
tok = number_octal();
}
break;
case '\'':
tok = character();
break;
case '"':
tok = String('"', '"');
break;
case -1:
close();
tok = new Token(Token.EOF, _l, _c, "<eof>");
break;
}
if (tok == null) {
if (char.IsWhiteSpace((char)c)) {
tok = whitespace(c);
}
else if (char.IsDigit((char)c)) {
tok = number_decimal(c);
}
else if (isJavaIdentifierStart(c)) {
tok = identifier(c);
}
else {
tok = new Token(c);
}
}
if (bol) {
switch (tok.getType()) {
case Token.WHITESPACE:
case Token.CCOMMENT:
break;
default:
bol = false;
break;
}
}
tok.setLocation(_l, _c);
if (DEBUG)
System.Console.WriteLine("lx: Returning " + tok);
// (new Exception("here")).printStackTrace(System.out);
return tok;
}
public override void close()
{
if(reader != null) {
reader.close();
reader = null;
}
base.close();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// <copyright file="TargetCollection_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Tests for all Public TargetCollection objects</summary>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Collections.Generic;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Tests for TargetCollection
/// </summary>
[TestFixture]
public class TargetCollection_Tests
{
#region Common Helpers
/// <summary>
/// Basic project content with several targets, where depends on targets is used
/// </summary>
private const string ProjectContentSeveralTargets = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1' DependsOnTargets='t2' Inputs='in' Outputs='out'/>
<Target Name='t2' DependsOnTargets='t3' Condition=""'true' == 'true'"">
<Message Text='t2.task' />
</Target>
<Target Name='t3' DependsOnTargets='t4'>
<Message Text='t3.task' />
</Target>
<Target Name='t4'>
<Message Text='t4.task' />
</Target>
<Target Name='t5'>
<Message Text='t5.task' />
</Target>
</Project>
";
/// <summary>
/// Basic project content with no targets - an emtpy project
/// </summary>
private const string ProjectContentNoTargets = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>
";
/// <summary>
/// Engine that is used through out test class
/// </summary>
private Engine engine;
/// <summary>
/// Project that is used through out test class
/// </summary>
private Project project;
/// <summary>
/// Creates the engine and parent object.
/// </summary>
[SetUp()]
public void Initialize()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
engine = new Engine();
project = new Project(engine);
}
/// <summary>
/// Unloads projects
/// </summary>
[TearDown()]
public void Cleanup()
{
engine.UnloadProject(project);
engine.UnloadAllProjects();
ObjectModelHelpers.DeleteTempProjectDirectory();
}
#endregion
#region Count Tests
/// <summary>
/// Tests TargetCollection.Count with many targets
/// </summary>
[Test]
public void CountMany()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(5, targets.Count);
}
/// <summary>
/// Tests TargetCollection.Count with some targets that are imported
/// </summary>
[Test]
public void CountWithImportedTargets()
{
string importProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t2'>
<Message Text='imported.t2.task' />
</Target>
<Target Name='t3' />
</Project>
";
string projectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='parent.t1.task' />
</Target>
<Import Project='import.proj' />
</Project>
";
Project p = GetProjectThatImportsAnotherProject(importProjectContents, projectContents);
TargetCollection targets = p.Targets;
Assertion.AssertEquals(3, targets.Count);
}
/// <summary>
/// Tests TargetCollection.Count when the imported project and parent project both contain
/// a target of the same name.
/// </summary>
[Test]
public void CountWhenImportedAndParentBothContainSameTarget()
{
string importProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='imported.t2.task' />
</Target>
</Project>
";
string parentProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='parent.t1.task' />
</Target>
<Import Project='import.proj' />
</Project>
";
Project p = GetProjectThatImportsAnotherProject(importProjectContents, parentProjectContents);
TargetCollection targets = p.Targets;
Assertion.AssertEquals(1, targets.Count);
}
/// <summary>
/// Tests TargetCollection.Count when no targets exist
/// </summary>
[Test]
public void CountWithNoTargets()
{
project.LoadXml(ProjectContentNoTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(0, targets.Count);
}
/// <summary>
/// Tests TargetCollection.Count after adding a new target
/// </summary>
[Test]
public void CountAfterAddingNewTarget()
{
project.LoadXml(ProjectContentSeveralTargets);
project.Targets.AddNewTarget("t6");
TargetCollection targets = project.Targets;
Assertion.AssertEquals(6, targets.Count);
}
/// <summary>
/// Tests TargetCollection.Count after removing a target
/// </summary>
[Test]
public void CountAfterRemovingTarget()
{
project.LoadXml(ProjectContentSeveralTargets);
Target t = GetSpecificTargetFromProject(project, "t5");
project.Targets.RemoveTarget(t);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(4, targets.Count);
}
#endregion
#region Exists Tests
/// <summary>
/// Tests TargetCollection.Exists when target exists
/// </summary>
[Test]
public void ExistsWhenTargetExists()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(true, targets.Exists("t2"));
}
/// <summary>
/// Tests TargetCollection.Exists when target doesn't exist
/// </summary>
[Test]
public void ExistsWhenTargetDoesNotExist()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(false, targets.Exists("tNot"));
}
/// <summary>
/// Tests TargetCollection.Exists of an imported target
/// </summary>
[Test]
public void ExistsOfImportedTarget()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
TargetCollection targets = p.Targets;
Assertion.AssertEquals(true, targets.Exists("t4"));
}
/// <summary>
/// Tests TargetCollection.Exists of a target that comes from an import as well as parent project
/// </summary>
[Test]
public void ExistsWhenImportedTargetAndParentTargetHaveSameName()
{
string importProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='imported.t2.task' />
</Target>
</Project>
";
string parentProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='parent.t1.task' />
</Target>
<Target Name='t2' />
<Import Project='import.proj' />
</Project>
";
Project p = GetProjectThatImportsAnotherProject(importProjectContents, parentProjectContents);
TargetCollection targets = p.Targets;
Assertion.AssertEquals(true, targets.Exists("t1"));
}
#endregion
#region AddNewTarget Tests
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target
/// </summary>
[Test]
public void AddNewTargetSimple()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget("tNew");
Assertion.AssertEquals(true, targets.Exists("tNew"));
Assertion.AssertEquals(6, targets.Count);
}
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target of the same name
/// </summary>
[Test]
public void AddNewTargetWhenTargetOfSameNameAlreadyExists()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget("t1");
Assertion.AssertEquals(true, targets.Exists("t1"));
Assertion.AssertEquals(5, targets.Count);
}
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target with an String.Empty name
/// </summary>
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void AddNewTargetEmptyStringName()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget(String.Empty);
}
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target with a null name
/// </summary>
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void AddNewTargetNullName()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget(null);
}
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target with special characters in the name
/// </summary>
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void AddNewTargetSpecialCharacterName()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget("%24%40%3b%5c%25");
}
/// <summary>
/// Tests TargetCollection.AddNewTarget by adding a new target to a project with no other targets
/// </summary>
[Test]
public void AddNewTargetWhenNoOtherTargetsExist()
{
project.LoadXml(ProjectContentNoTargets);
TargetCollection targets = project.Targets;
targets.AddNewTarget("t");
Assertion.AssertEquals(true, targets.Exists("t"));
Assertion.AssertEquals(1, targets.Count);
}
#endregion
#region RemoveTarget Tests
/// <summary>
/// Tests TargetCollection.RemoveTarget by removing an existing target
/// </summary>
[Test]
public void RemoveTargetOfExistingTarget()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.RemoveTarget(GetSpecificTargetFromProject(project, "t1"));
Assertion.AssertEquals(false, targets.Exists("t1"));
}
/// <summary>
/// Tests TargetCollection.RemoveTarget passing in null
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void RemoveTargetNull()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.RemoveTarget(null);
}
/// <summary>
/// Tests TargetCollection.RemoveTarget of an imported target
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void RemoveTargetFromImport()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
TargetCollection targets = p.Targets;
targets.RemoveTarget(GetSpecificTargetFromProject(p, "t2"));
}
#endregion
#region CopyTo Tests
/// <summary>
/// Tests TargetCollection.CopyTo basic case
/// </summary>
[Test]
public void CopyToSimple()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
object[] array = new object[targets.Count];
targets.CopyTo(array, 0);
List<string> listOfTargets = new List<string>();
foreach (Target t in array)
{
listOfTargets.Add(t.Name);
}
// This originates in a hashtable, whose ordering is undefined
// and indeed changes in CLR4
listOfTargets.Sort();
Assertion.AssertEquals(targets["t1"].Name, listOfTargets[0]);
Assertion.AssertEquals(targets["t2"].Name, listOfTargets[1]);
Assertion.AssertEquals(targets["t3"].Name, listOfTargets[2]);
Assertion.AssertEquals(targets["t4"].Name, listOfTargets[3]);
Assertion.AssertEquals(targets["t5"].Name, listOfTargets[4]);
}
/// <summary>
/// Tests TargetCollection.CopyTo passing in a null
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void CopyToNull()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
targets.CopyTo(null, 0);
}
/// <summary>
/// Tests TargetCollection.CopyTo when you attempt CopyTo into an Array that's not long enough
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CopyToArrayThatsNotLargeEnough()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
object[] array = new object[2];
targets.CopyTo(array, 0);
}
#endregion
#region IsSynchronized Tests
/// <summary>
/// Tests TargetCollection.IsSynchronized for the default case
/// </summary>
[Test]
public void IsSynchronizedDefault()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals(false, targets.IsSynchronized);
}
#endregion
#region TargetThis Tests
/// <summary>
/// Tests TargetCollection["targetname"].property where no imports exist
/// </summary>
[Test]
public void TargetThisNoImports()
{
project.LoadXml(ProjectContentSeveralTargets);
TargetCollection targets = project.Targets;
Assertion.AssertEquals("in", targets["t1"].Inputs);
Assertion.AssertEquals("out", targets["t1"].Outputs);
Assertion.AssertEquals(false, targets["t2"].IsImported);
Assertion.AssertEquals("'true' == 'true'", targets["t2"].Condition);
Assertion.AssertEquals("t3", targets["t2"].DependsOnTargets);
Assertion.AssertEquals("t2", targets["t2"].Name);
}
/// <summary>
/// Tests TargetCollection["targetname"].property where imports exist
/// </summary>
[Test]
public void TargetThisWithImports()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
TargetCollection targets = p.Targets;
Assertion.AssertEquals("in", targets["t3"].Inputs);
Assertion.AssertEquals("out", targets["t3"].Outputs);
Assertion.AssertEquals(true, targets["t3"].IsImported);
Assertion.AssertEquals("'true' == 'true'", targets["t3"].Condition);
Assertion.AssertEquals("t2", targets["t3"].DependsOnTargets);
Assertion.AssertEquals("t3", targets["t3"].Name);
}
#endregion
#region Helpers
/// <summary>
/// Gets a specified Target from a Project
/// </summary>
/// <param name="p">Project</param>
/// <param name="nameOfTarget">Target name of the Target you want</param>
/// <returns>Target requested. null if specific target isn't found</returns>
private Target GetSpecificTargetFromProject(Project p, string nameOfTarget)
{
foreach (Target t in p.Targets)
{
if (String.Equals(t.Name, nameOfTarget, StringComparison.OrdinalIgnoreCase))
{
return t;
}
}
return null;
}
/// <summary>
/// Gets a Project that imports another Project
/// </summary>
/// <param name="importProjectContents">Project Contents of the imported Project, to get default content, pass in an empty string</param>
/// <param name="parentProjectContents">Project Contents of the Parent Project, to get default content, pass in an empty string</param>
/// <returns>Project</returns>
private Project GetProjectThatImportsAnotherProject(string importProjectContents, string parentProjectContents)
{
if (String.IsNullOrEmpty(importProjectContents))
{
importProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t2' />
<Target Name='t3' DependsOnTargets='t2' Inputs='in' Outputs='out' Condition=""'true' == 'true'""/>
<Target Name='t4' />
</Project>
";
}
if (String.IsNullOrEmpty(parentProjectContents))
{
parentProjectContents = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<Target Name='t1'>
<Message Text='parent.t1.task' />
</Target>
<Import Project='import.proj' />
</Project>
";
}
ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", importProjectContents);
ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", parentProjectContents);
return ObjectModelHelpers.LoadProjectFileInTempProjectDirectory("main.proj", null);
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c)2011 Pearson Education, Inc., or associates.
// All rights reserved.
//
// This software is the confidential and proprietary information of
// Data Solutions ("Confidential Information"). You shall not disclose
// such Confidential Information and shall use it only in accordance with the
// terms of the llicense agreement you entered into with Data Solutions..
//
using System;
using System.Collections.Generic;
namespace Edustructures.SifWorks
{
/// <summary> Encapsulates a SIF version number.
///
/// The Adk uses instances of SifVersion rather than strings to identify
/// versions of SIF. Typically you do not need to obtain a SifVersion instance
/// directly except for when initializing the class framework with the
/// <c>Adk.initialize</c> method. Rather, classes for which SIF version is
/// a property, such as SifDataObject and Query, provide a <c>getSIFVersion</c>
/// method to obtain the version associated with an object.
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> 1.0
/// </version>
[Serializable]
public class SifVersion : IComparable
{
/// <summary> Gets the major version number</summary>
public virtual int Major
{
get { return fVersion.Major; }
}
/// <summary> Gets the minor version number</summary>
public virtual int Minor
{
get { return fVersion.Minor; }
}
/// <summary> Gets the revision number</summary>
public virtual int Revision
{
get { return fVersion.Revision; }
}
/// <summary> Get the SIF namespace for this version of the specification.
///
/// </summary>
/// <returns> If the SifVersion is less than SIF 1.1, a namespace in the form
/// "http://www.sifinfo.org/v1.0r2/messages" is returned, where the full
/// SIF Version number is included in the namespace. For SIF 1.x and
/// later, a namespace in the form "http://www.sifinfo.org/infrastructure/1.x"
/// is returned, where only the major version number is included in the
/// namespace.
/// </returns>
public virtual string Xmlns
{
get
{
if (CompareTo(SIF11) < 0)
{
return "http://www.sifinfo.org/v" + this.ToString() + "/messages";
}
return "http://specification.sifinfo.org" + "/" + fVersion.Major + ".x";
}
}
/// <summary>Identifies the SIF 1.1 Specification </summary>
public static readonly SifVersion SIF11 = new SifVersion(1, 1, 0);
/// <summary>Identifies the SIF 1.5r1 Specification</summary>
public static readonly SifVersion SIF15r1 = new SifVersion(1, 5, 1);
/// <summary>Identifies the SIF 2.0 Specification</summary>
public static readonly SifVersion SIF20 = new SifVersion(2, 0, 0);
/// <summary>Identifies the SIF 2.0r1 Specification</summary>
public static readonly SifVersion SIF20r1 = new SifVersion(2, 0, 1);
/// <summary>Identifies the SIF 2.1 Specification</summary>
public static readonly SifVersion SIF21 = new SifVersion(2, 1, 0);
/// <summary>Identifies the SIF 2.2 Specification</summary>
public static readonly SifVersion SIF22 = new SifVersion(2, 2, 0);
//// WARNING: MAKE SURE TO UPDATE THE GETINSTANCE METHOD WHEN ADDING NEW VERSIONS ////
/// <summary>Identifies the latest SIF Specification supported by the SIFWorks Adk </summary>
public static readonly SifVersion LATEST = SIF21;
/// <summary>
/// Returns the earliest SIFVersion supported by the ADK for the major version
/// number of SIF specified. For example, passing the value 1 returns <c>SifVersion.SIF11</c>
/// </summary>
/// <param name="major"></param>
/// <returns>The latest version of SIF that the ADK supports for the specified
/// major version</returns>
public static SifVersion GetEarliest(int major)
{
switch (major)
{
case 1:
return SifVersion.SIF11;
case 2:
return SifVersion.SIF20r1;
}
return null;
}
/// <summary> Constructs a version object
///
/// </summary>
/// <param name="major">The major version number
/// </param>
/// <param name="minor">The minor version number
/// </param>
/// <param name="revision">The revision number
/// </param>
private SifVersion(int major,
int minor,
int revision)
{
fVersion = new Version(major, minor, 0, revision);
}
/// <summary> Gets a SifVersion instance</summary>
/// <remarks>
/// <para>
/// This method always returns the same version instance for the given version
/// numbers. If the version number match on official version supported by the ADK,
/// that version instance is returned. Otherwise, a new SIFVersion instance is
/// created and returned. The sam SifVersion instance will always be returned for
/// the same paramters
/// </para>
/// </remarks>
/// <returns> A SifVersion instance to encapsulate the version information
/// provided to this method. If the <i>major</i>, <i>minor</i>, and
/// <i>revision</i> numbers match one of the versions supported by the
/// Adk (e.g. SifVersion.SIF10r1, SifVersion.SIF10r2, etc.), that object
/// is returned. Otherwise, a new instance is created. Thus, you are
/// guaranteed to always receive the same SifVersion instance or a given
/// version number supported by the Adk.
/// </returns>
private static SifVersion GetInstance(int major,
int minor,
int revision)
{
// Check for versions explicitly supported by the ADK first
if (major == 2)
{
if (minor == 0)
{
if (revision == 0)
{
return SIF20;
}
else if (revision == 1)
{
return SIF20r1;
}
}
if (minor == 1 && revision == 0)
{
return SIF21;
}
}
else if (major == 1)
{
if (minor == 5 && revision == 1)
{
return SIF15r1;
}
else if (minor == 1 && revision == 0)
{
return SIF11;
}
}
// No explicit support found. Return a newly-fabricated instance
// to support this version of SIF
String tag = ToString(major, minor, revision, '.');
SifVersion ver;
if (sVersions == null)
{
sVersions = new Dictionary<string, SifVersion>();
}
if (!sVersions.TryGetValue(tag, out ver))
{
ver = new SifVersion(major, minor, revision);
sVersions[tag] = ver;
}
return ver;
}
/// <summary> Parse a <c>SifVersion</c> from a string</summary>
/// <param name="versionStr">A version string in the format "1.0r1"</param>
/// <returns> A SifVersion instance encapsulating the version string</returns>
/// <exception cref="ArgumentException">is thrown if the version string is invalid</exception>
public static SifVersion Parse(string versionStr)
{
if (versionStr == null)
{
throw new ArgumentNullException("Version to parse cannot be null", "versionStr");
}
try
{
string v = versionStr.ToLower();
int i = v.IndexOf('.');
int major = Int32.Parse(v.Substring(0, i));
int minor;
int revision = 0;
int r = v.IndexOf('r');
if (r == -1)
{
String minorStr = v.Substring(i + 1);
if (minorStr.Equals("*"))
{
// hack
//return Adk.SifVersion;
return SifVersion.SIF20r1;
// This a 1.* or 2.* version. Return the latest version supported
//return getLatest( major );
// if( twoDotStar.compareTo( ADK.getSIFVersion() ) > 0 ){
// twoDotStar = ADK.getSIFVersion();
// }
// return twoDotStar;
}
else
{
minor = Int32.Parse(minorStr);
}
}
else
{
minor = Int32.Parse(v.Substring(i + 1, r - i - 1));
revision = Int32.Parse(v.Substring(r + 1));
}
return GetInstance(major, minor, revision);
}
catch (Exception thr)
{
throw new ArgumentException(versionStr + " is an invalid version string", thr);
}
}
/// <summary>
/// Returns the latest SIFVersion supported by the ADK for the major version
/// number of SIF specified. For example, passing the value 1 returns
/// <c>SifVersion.15r1</c>
/// </summary>
/// <param name="major"></param>
/// <returns></returns>
public static SifVersion GetLatest(int major)
{
switch (major)
{
case 1:
return SIF15r1;
case 2:
return LATEST;
}
return null;
}
/// <summary> Parse a <c>SifVersion</c> from a <i>xmlns</i> attribute value
///
/// If the xmlns attribute is in the form "http://www.sifinfo.org/v1.0r1/messages",
/// the version identified by the namespace is returned (e.g. "1.0r1"). If the
/// xmlns attribute is in the form "http://www.sifinfo.org/infrastructure/1.x",
/// the latest version of SIF identified by the major version number is
/// returned.
///
/// </summary>
/// <param name="xmlns">A SIF xmlns attribute value (e.g. "http://www.sifinfo.org/v1.0r1/messages",
/// "http://www.sifinfo.org/infrastructure/1x.", etc)
///
/// </param>
/// <returns> A SifVersion object encapsulating the version of SIF identified
/// by the xmlns value, or null if the xmlns is invalid
/// </returns>
public static SifVersion ParseXmlns(string xmlns)
{
//
// Determine the SIFVersion:
//
if (xmlns != null)
{
if (xmlns.EndsWith(".x"))
{
// http://www.sifinfo.org/infrastructure/1.x
// NOTE: This works until SIF 10.x
int location = xmlns.LastIndexOf('/');
char majorCh = xmlns[location + 1];
if (char.IsDigit(majorCh))
{
int major = majorCh - 48;
return GetLatest(major);
}
}
}
return null;
}
/// <summary> Gets the string representation of the version</summary>
/// <returns> The tag passed to the constructor. If null, a version in the
/// form <i>major</i>.<i>minor</i>r<i>revision</i> is returned with no
/// padding.
/// </returns>
public override string ToString()
{
return ToString(this.Major, this.Minor, this.Revision, '.');
}
/// <summary>
/// Formats a SIF Version String for the ToString() and ToSymbol() methods
/// </summary>
/// <param name="major"></param>
/// <param name="minor"></param>
/// <param name="revision"></param>
/// <returns></returns>
private static String ToString(int major,
int minor,
int revision,
char seperator)
{
if (revision < 1)
{
return String.Format("{1}{0}{2}", seperator, major, minor);
}
else
{
return String.Format("{1}{0}{2}r{3}", seperator, major, minor, revision);
}
}
/// <summary> Gets the string representation of the version using an underscore instead
/// of a period as the delimiter
/// </summary>
public virtual string ToSymbol()
{
return ToString(this.Major, this.Minor, this.Revision, '_');
}
#region Private Members
/// <summary>
/// The dictionary of current active versions
/// </summary>
private static IDictionary<String, SifVersion> sVersions = null;
/// <summary>
/// The current version
/// </summary>
protected readonly Version fVersion;
#endregion
#region Comparison
public override bool Equals(object obj)
{
// Test reference comparison first ( fastest )
if (ReferenceEquals(this, obj))
{
return true;
}
if ((!ReferenceEquals(obj, null)) &&
(obj.GetType().Equals(this.GetType())))
{
return fVersion.Equals(((SifVersion)obj).fVersion);
}
return false;
}
public override int GetHashCode()
{
return fVersion.GetHashCode();
}
/// <summary> Compare this version to another</summary>
/// <param name="version">The version to compare</param>
/// <returns> -1 if this version is earlier than <c>version</c>, 0 if
/// the versions are equal, or 1 if this version is greater than <c>
/// version</c> or <c>version</c> is null
/// </returns>
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
if (!(version is SifVersion))
{
throw new ArgumentException
(string.Format
("{0} cannot be compared to a SifVersion object", version.GetType().FullName));
}
return fVersion.CompareTo(((SifVersion)version).fVersion);
}
public static bool operator >(SifVersion version1,
SifVersion version2)
{
return version1.fVersion > version2.fVersion;
}
public static bool operator <(SifVersion version1,
SifVersion version2)
{
return version1.fVersion < version2.fVersion;
}
public static bool operator >=(SifVersion version1,
SifVersion version2)
{
return version1.fVersion >= version2.fVersion;
}
public static bool operator <=(SifVersion version1,
SifVersion version2)
{
return version1.fVersion <= version2.fVersion;
}
#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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for compute.
/// </summary>
public partial class ComputeApiTest
{
/** Java binary class name. */
private const string JavaBinaryCls = "PlatformComputeJavaBinarizable";
/** */
private const string DefaultCacheName = "default";
/** First node. */
private IIgnite _grid1;
/** Second node. */
private IIgnite _grid2;
/** Third node. */
private IIgnite _grid3;
/// <summary>
/// Initialization routine.
/// </summary>
[TestFixtureSetUp]
public void InitClient()
{
var configs = GetConfigs();
_grid1 = Ignition.Start(Configuration(configs.Item1));
_grid2 = Ignition.Start(Configuration(configs.Item2));
_grid3 = Ignition.Start(Configuration(configs.Item3));
// Wait for rebalance.
var events = _grid1.GetEvents();
events.EnableLocal(EventType.CacheRebalanceStopped);
events.WaitForLocal(EventType.CacheRebalanceStopped);
}
/// <summary>
/// Gets the configs.
/// </summary>
protected virtual Tuple<string, string, string> GetConfigs()
{
return Tuple.Create(
"Config\\Compute\\compute-grid1.xml",
"Config\\Compute\\compute-grid2.xml",
"Config\\Compute\\compute-grid3.xml");
}
/// <summary>
/// Gets the expected compact footers setting.
/// </summary>
protected virtual bool CompactFooter
{
get { return true; }
}
[TestFixtureTearDown]
public void StopClient()
{
Ignition.StopAll(true);
}
[TearDown]
public void AfterTest()
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
/// <summary>
/// Test that it is possible to get projection from grid.
/// </summary>
[Test]
public void TestProjection()
{
IClusterGroup prj = _grid1.GetCluster();
Assert.NotNull(prj);
Assert.AreEqual(prj, prj.Ignite);
// Check that default Compute projection excludes client nodes.
CollectionAssert.AreEquivalent(prj.ForServers().GetNodes(), prj.GetCompute().ClusterGroup.GetNodes());
}
/// <summary>
/// Test non-existent cache.
/// </summary>
[Test]
public void TestNonExistentCache()
{
Assert.Catch(typeof(ArgumentException), () =>
{
_grid1.GetCache<int, int>("bad_name");
});
}
/// <summary>
/// Test node content.
/// </summary>
[Test]
public void TestNodeContent()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
foreach (IClusterNode node in nodes)
{
Assert.NotNull(node.Addresses);
Assert.IsTrue(node.Addresses.Count > 0);
Assert.Throws<NotSupportedException>(() => node.Addresses.Add("addr"));
Assert.NotNull(node.GetAttributes());
Assert.IsTrue(node.GetAttributes().Count > 0);
Assert.Throws<NotSupportedException>(() => node.GetAttributes().Add("key", "val"));
Assert.NotNull(node.HostNames);
Assert.Throws<NotSupportedException>(() => node.HostNames.Add("h"));
Assert.IsTrue(node.Id != Guid.Empty);
Assert.IsTrue(node.Order > 0);
Assert.NotNull(node.GetMetrics());
}
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestClusterMetrics()
{
var cluster = _grid1.GetCluster();
IClusterMetrics metrics = cluster.GetMetrics();
Assert.IsNotNull(metrics);
Assert.AreEqual(cluster.GetNodes().Count, metrics.TotalNodes);
Thread.Sleep(2000);
IClusterMetrics newMetrics = cluster.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestNodeMetrics()
{
var node = _grid1.GetCluster().GetNode();
IClusterMetrics metrics = node.GetMetrics();
Assert.IsNotNull(metrics);
Assert.IsTrue(metrics == node.GetMetrics());
Thread.Sleep(2000);
IClusterMetrics newMetrics = node.GetMetrics();
Assert.IsFalse(metrics == newMetrics);
Assert.IsTrue(metrics.LastUpdateTime < newMetrics.LastUpdateTime);
}
/// <summary>
/// Test cluster metrics.
/// </summary>
[Test]
public void TestResetMetrics()
{
var cluster = _grid1.GetCluster();
Thread.Sleep(2000);
var metrics1 = cluster.GetMetrics();
cluster.ResetMetrics();
var metrics2 = cluster.GetMetrics();
Assert.IsNotNull(metrics1);
Assert.IsNotNull(metrics2);
}
/// <summary>
/// Test node ping.
/// </summary>
[Test]
public void TestPingNode()
{
var cluster = _grid1.GetCluster();
Assert.IsTrue(cluster.GetNodes().Select(node => node.Id).All(cluster.PingNode));
Assert.IsFalse(cluster.PingNode(Guid.NewGuid()));
}
/// <summary>
/// Tests the topology version.
/// </summary>
[Test]
public void TestTopologyVersion()
{
var cluster = _grid1.GetCluster();
var topVer = cluster.TopologyVersion;
Ignition.Stop(_grid3.Name, true);
Assert.AreEqual(topVer + 1, _grid1.GetCluster().TopologyVersion);
_grid3 = Ignition.Start(Configuration(GetConfigs().Item3));
Assert.AreEqual(topVer + 2, _grid1.GetCluster().TopologyVersion);
}
/// <summary>
/// Tests the topology by version.
/// </summary>
[Test]
public void TestTopology()
{
var cluster = _grid1.GetCluster();
Assert.AreEqual(1, cluster.GetTopology(1).Count);
Assert.AreEqual(null, cluster.GetTopology(int.MaxValue));
// Check that Nodes and Topology return the same for current version
var topVer = cluster.TopologyVersion;
var top = cluster.GetTopology(topVer);
var nodes = cluster.GetNodes();
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
// Stop/start node to advance version and check that history is still correct
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
try
{
top = cluster.GetTopology(topVer);
Assert.AreEqual(top.Count, nodes.Count);
Assert.IsTrue(top.All(nodes.Contains));
}
finally
{
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
}
}
/// <summary>
/// Test nodes in full topology.
/// </summary>
[Test]
public void TestNodes()
{
Assert.IsNotNull(_grid1.GetCluster().GetNode());
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
// Check subsequent call on the same topology.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
Assert.IsTrue(Ignition.Stop(_grid2.Name, true));
// Check subsequent calls on updating topologies.
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 2);
_grid2 = Ignition.Start(Configuration(GetConfigs().Item2));
nodes = _grid1.GetCluster().GetNodes();
Assert.IsTrue(nodes.Count == 3);
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds".
/// </summary>
[Test]
public void TestForNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterNode first = nodes.ElementAt(0);
IClusterNode second = nodes.ElementAt(1);
IClusterGroup singleNodePrj = _grid1.GetCluster().ForNodeIds(first.Id);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodeIds(new List<Guid> { first.Id });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(first);
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
singleNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first });
Assert.AreEqual(1, singleNodePrj.GetNodes().Count);
Assert.AreEqual(first.Id, singleNodePrj.GetNodes().First().Id);
IClusterGroup multiNodePrj = _grid1.GetCluster().ForNodeIds(first.Id, second.Id);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodeIds(new[] {first, second}.Select(x => x.Id));
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(first, second);
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
multiNodePrj = _grid1.GetCluster().ForNodes(new List<IClusterNode> { first, second });
Assert.AreEqual(2, multiNodePrj.GetNodes().Count);
Assert.IsTrue(multiNodePrj.GetNodes().Contains(first));
Assert.IsTrue(multiNodePrj.GetNodes().Contains(second));
}
/// <summary>
/// Test "ForNodes" and "ForNodeIds". Make sure lazy enumerables are enumerated only once.
/// </summary>
[Test]
public void TestForNodesLaziness()
{
var nodes = _grid1.GetCluster().GetNodes().Take(2).ToArray();
var callCount = 0;
Func<IClusterNode, IClusterNode> nodeSelector = node =>
{
callCount++;
return node;
};
Func<IClusterNode, Guid> idSelector = node =>
{
callCount++;
return node.Id;
};
var projection = _grid1.GetCluster().ForNodes(nodes.Select(nodeSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(2, callCount);
projection = _grid1.GetCluster().ForNodeIds(nodes.Select(idSelector));
Assert.AreEqual(2, projection.GetNodes().Count);
Assert.AreEqual(4, callCount);
}
/// <summary>
/// Test for local node projection.
/// </summary>
[Test]
public void TestForLocal()
{
IClusterGroup prj = _grid1.GetCluster().ForLocal();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(_grid1.GetCluster().GetLocalNode(), prj.GetNodes().First());
}
/// <summary>
/// Test for remote nodes projection.
/// </summary>
[Test]
public void TestForRemotes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForRemotes();
Assert.AreEqual(2, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
}
/// <summary>
/// Test for daemon nodes projection.
/// </summary>
[Test]
public void TestForDaemons()
{
Assert.AreEqual(0, _grid1.GetCluster().ForDaemons().GetNodes().Count);
using (var ignite = Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = GetConfigs().Item1,
IgniteInstanceName = "daemonGrid",
IsDaemon = true
})
)
{
var prj = _grid1.GetCluster().ForDaemons();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.AreEqual(ignite.GetCluster().GetLocalNode().Id, prj.GetNode().Id);
Assert.IsTrue(prj.GetNode().IsDaemon);
Assert.IsTrue(ignite.GetCluster().GetLocalNode().IsDaemon);
}
}
/// <summary>
/// Test for host nodes projection.
/// </summary>
[Test]
public void TestForHost()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForHost(nodes.First());
Assert.AreEqual(3, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(1)));
Assert.IsTrue(nodes.Contains(prj.GetNodes().ElementAt(2)));
}
/// <summary>
/// Test for oldest, youngest and random projections.
/// </summary>
[Test]
public void TestForOldestYoungestRandom()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForYoungest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForOldest();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
prj = _grid1.GetCluster().ForRandom();
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
}
/// <summary>
/// Tests ForServers projection.
/// </summary>
[Test]
public void TestForServers()
{
var cluster = _grid1.GetCluster();
var servers = cluster.ForServers().GetNodes();
Assert.AreEqual(2, servers.Count);
Assert.IsTrue(servers.All(x => !x.IsClient));
var serverAndClient =
cluster.ForNodeIds(new[] { _grid2, _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(1, serverAndClient.ForServers().GetNodes().Count);
var client = cluster.ForNodeIds(new[] { _grid3 }.Select(x => x.GetCluster().GetLocalNode().Id));
Assert.AreEqual(0, client.ForServers().GetNodes().Count);
}
/// <summary>
/// Test for attribute projection.
/// </summary>
[Test]
public void TestForAttribute()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
IClusterGroup prj = _grid1.GetCluster().ForAttribute("my_attr", "value1");
Assert.AreEqual(1, prj.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prj.GetNode()));
Assert.AreEqual("value1", prj.GetNodes().First().GetAttribute<string>("my_attr"));
}
/// <summary>
/// Test for cache/data/client projections.
/// </summary>
[Test]
public void TestForCacheNodes()
{
ICollection<IClusterNode> nodes = _grid1.GetCluster().GetNodes();
// Cache nodes.
IClusterGroup prjCache = _grid1.GetCluster().ForCacheNodes("cache1");
Assert.AreEqual(2, prjCache.GetNodes().Count);
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(0)));
Assert.IsTrue(nodes.Contains(prjCache.GetNodes().ElementAt(1)));
// Data nodes.
IClusterGroup prjData = _grid1.GetCluster().ForDataNodes("cache1");
Assert.AreEqual(2, prjData.GetNodes().Count);
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(0)));
Assert.IsTrue(prjCache.GetNodes().Contains(prjData.GetNodes().ElementAt(1)));
// Client nodes.
IClusterGroup prjClient = _grid1.GetCluster().ForClientNodes("cache1");
Assert.AreEqual(0, prjClient.GetNodes().Count);
}
/// <summary>
/// Test for cache predicate.
/// </summary>
[Test]
public void TestForPredicate()
{
IClusterGroup prj1 = _grid1.GetCluster().ForPredicate(new NotAttributePredicate("value1").Apply);
Assert.AreEqual(2, prj1.GetNodes().Count);
IClusterGroup prj2 = prj1.ForPredicate(new NotAttributePredicate("value2").Apply);
Assert.AreEqual(1, prj2.GetNodes().Count);
string val;
prj2.GetNodes().First().TryGetAttribute("my_attr", out val);
Assert.IsTrue(val == null || (!val.Equals("value1") && !val.Equals("value2")));
}
/// <summary>
/// Attribute predicate.
/// </summary>
private class NotAttributePredicate
{
/** Required attribute value. */
private readonly string _attrVal;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrVal">Required attribute value.</param>
public NotAttributePredicate(string attrVal)
{
_attrVal = attrVal;
}
/** <inhreitDoc /> */
public bool Apply(IClusterNode node)
{
string val;
node.TryGetAttribute("my_attr", out val);
return val == null || !val.Equals(_attrVal);
}
}
/// <summary>
/// Tests the action broadcast.
/// </summary>
[Test]
public void TestBroadcastAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Broadcast(new ComputeAction(id));
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().BroadcastAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(2, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunAction()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(new ComputeAction(id));
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
id = Guid.NewGuid();
_grid1.GetCompute().RunAsync(new ComputeAction(id)).Wait();
Assert.AreEqual(1, ComputeAction.InvokeCount(id));
}
/// <summary>
/// Tests single action run.
/// </summary>
[Test]
public void TestRunActionAsyncCancel()
{
using (var cts = new CancellationTokenSource())
{
// Cancel while executing
var task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
cts.Cancel();
Assert.IsTrue(task.IsCanceled);
// Use cancelled token
task = _grid1.GetCompute().RunAsync(new ComputeAction(), cts.Token);
Assert.IsTrue(task.IsCanceled);
}
}
/// <summary>
/// Tests multiple actions run.
/// </summary>
[Test]
public void TestRunActions()
{
var id = Guid.NewGuid();
_grid1.GetCompute().Run(Enumerable.Range(0, 10).Select(x => new ComputeAction(id)));
Assert.AreEqual(10, ComputeAction.InvokeCount(id));
var id2 = Guid.NewGuid();
_grid1.GetCompute().RunAsync(Enumerable.Range(0, 10).Select(x => new ComputeAction(id2))).Wait();
Assert.AreEqual(10, ComputeAction.InvokeCount(id2));
}
/// <summary>
/// Tests affinity run.
/// </summary>
[Test]
public void TestAffinityRun()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] {_grid1, _grid2}.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
_grid1.GetCompute().AffinityRun(cacheName, affinityKey, new ComputeAction());
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
_grid1.GetCompute().AffinityRunAsync(cacheName, affinityKey, new ComputeAction()).Wait();
Assert.AreEqual(node.Id, ComputeAction.LastNodeId);
}
}
/// <summary>
/// Tests affinity call.
/// </summary>
[Test]
public void TestAffinityCall()
{
const string cacheName = DefaultCacheName;
// Test keys for non-client nodes
var nodes = new[] { _grid1, _grid2 }.Select(x => x.GetCluster().GetLocalNode());
var aff = _grid1.GetAffinity(cacheName);
foreach (var node in nodes)
{
var primaryKey = TestUtils.GetPrimaryKey(_grid1, cacheName, node);
var affinityKey = aff.GetAffinityKey<int, int>(primaryKey);
var result = _grid1.GetCompute().AffinityCall(cacheName, affinityKey, new ComputeFunc());
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
// Async.
ComputeFunc.InvokeCount = 0;
result = _grid1.GetCompute().AffinityCallAsync(cacheName, affinityKey, new ComputeFunc()).Result;
Assert.AreEqual(result, ComputeFunc.InvokeCount);
Assert.AreEqual(node.Id, ComputeFunc.LastNodeId);
}
}
/// <summary>
/// Test simple dotNet task execution.
/// </summary>
[Test]
public void TestNetTaskSimple()
{
Assert.AreEqual(2, _grid1.GetCompute()
.Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Res);
Assert.AreEqual(2, _grid1.GetCompute()
.ExecuteAsync<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof(NetSimpleTask), new NetSimpleJobArgument(1)).Result.Res);
Assert.AreEqual(4, _grid1.GetCompute().Execute(new NetSimpleTask(), new NetSimpleJobArgument(2)).Res);
Assert.AreEqual(6, _grid1.GetCompute().ExecuteAsync(new NetSimpleTask(), new NetSimpleJobArgument(3))
.Result.Res);
}
/// <summary>
/// Tests the exceptions.
/// </summary>
[Test]
public void TestExceptions()
{
Assert.Throws<AggregateException>(() => _grid1.GetCompute().Broadcast(new InvalidComputeAction()));
Assert.Throws<AggregateException>(
() => _grid1.GetCompute().Execute<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>(
typeof (NetSimpleTask), new NetSimpleJobArgument(-1)));
// Local.
var ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForLocal().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Compute job has failed on local node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
// Remote.
ex = Assert.Throws<AggregateException>(() =>
_grid1.GetCluster().ForRemotes().GetCompute().Broadcast(new ExceptionalComputeAction()));
Assert.IsNotNull(ex.InnerException);
#if NETCOREAPP2_0
// Exceptions can't be serialized on .NET Core
Assert.AreEqual("Operation is not supported on this platform.",
ex.InnerException.Message);
#else
Assert.AreEqual("Compute job has failed on remote node, examine InnerException for details.",
ex.InnerException.Message);
Assert.IsNotNull(ex.InnerException.InnerException);
Assert.AreEqual(ExceptionalComputeAction.ErrorText, ex.InnerException.InnerException.Message);
#endif
}
#if !NETCOREAPP2_0
/// <summary>
/// Tests the footer setting.
/// </summary>
[Test]
public void TestFooterSetting()
{
Assert.AreEqual(CompactFooter, ((Impl.Ignite) _grid1).Marshaller.CompactFooter);
foreach (var g in new[] {_grid1, _grid2, _grid3})
Assert.AreEqual(CompactFooter, g.GetConfiguration().BinaryConfiguration.CompactFooter);
}
#endif
/// <summary>
/// Create configuration.
/// </summary>
/// <param name="path">XML config path.</param>
private static IgniteConfiguration Configuration(string path)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(PlatformComputeBinarizable)),
new BinaryTypeConfiguration(typeof(PlatformComputeNetBinarizable)),
new BinaryTypeConfiguration(JavaBinaryCls),
new BinaryTypeConfiguration(typeof(PlatformComputeEnum)),
new BinaryTypeConfiguration(typeof(InteropComputeEnumFieldTest))
},
NameMapper = new BinaryBasicNameMapper { IsSimpleName = true }
},
SpringConfigUrl = path
};
}
}
class PlatformComputeBinarizable
{
public int Field
{
get;
set;
}
}
class PlatformComputeNetBinarizable : PlatformComputeBinarizable
{
}
[Serializable]
class NetSimpleTask : IComputeTask<NetSimpleJobArgument, NetSimpleJobResult, NetSimpleTaskResult>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<NetSimpleJobResult>, IClusterNode> Map(IList<IClusterNode> subgrid,
NetSimpleJobArgument arg)
{
var jobs = new Dictionary<IComputeJob<NetSimpleJobResult>, IClusterNode>();
for (int i = 0; i < subgrid.Count; i++)
{
var job = arg.Arg > 0 ? new NetSimpleJob {Arg = arg} : new InvalidNetSimpleJob();
jobs[job] = subgrid[i];
}
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<NetSimpleJobResult> res,
IList<IComputeJobResult<NetSimpleJobResult>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public NetSimpleTaskResult Reduce(IList<IComputeJobResult<NetSimpleJobResult>> results)
{
return new NetSimpleTaskResult(results.Sum(res => res.Data.Res));
}
}
[Serializable]
class NetSimpleJob : IComputeJob<NetSimpleJobResult>
{
public NetSimpleJobArgument Arg;
/** <inheritDoc /> */
public NetSimpleJobResult Execute()
{
return new NetSimpleJobResult(Arg.Arg);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
class InvalidNetSimpleJob : NetSimpleJob, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
[Serializable]
class NetSimpleJobArgument
{
public int Arg;
public NetSimpleJobArgument(int arg)
{
Arg = arg;
}
}
[Serializable]
class NetSimpleTaskResult
{
public int Res;
public NetSimpleTaskResult(int res)
{
Res = res;
}
}
[Serializable]
class NetSimpleJobResult
{
public int Res;
public NetSimpleJobResult(int res)
{
Res = res;
}
}
[Serializable]
class ComputeAction : IComputeAction
{
[InstanceResource]
#pragma warning disable 649
private IIgnite _grid;
public static ConcurrentBag<Guid> Invokes = new ConcurrentBag<Guid>();
public static Guid LastNodeId;
public Guid Id { get; set; }
public ComputeAction()
{
// No-op.
}
public ComputeAction(Guid id)
{
Id = id;
}
public void Invoke()
{
Thread.Sleep(10);
Invokes.Add(Id);
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
}
public static int InvokeCount(Guid id)
{
return Invokes.Count(x => x == id);
}
}
class InvalidComputeAction : ComputeAction, IBinarizable
{
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
class ExceptionalComputeAction : IComputeAction
{
public const string ErrorText = "Expected user exception";
public void Invoke()
{
throw new OverflowException(ErrorText);
}
}
interface IUserInterface<out T>
{
T Invoke();
}
interface INestedComputeFunc : IComputeFunc<int>
{
}
[Serializable]
class ComputeFunc : INestedComputeFunc, IUserInterface<int>
{
[InstanceResource]
private IIgnite _grid;
public static int InvokeCount;
public static Guid LastNodeId;
int IComputeFunc<int>.Invoke()
{
Thread.Sleep(10);
InvokeCount++;
LastNodeId = _grid.GetCluster().GetLocalNode().Id;
return InvokeCount;
}
int IUserInterface<int>.Invoke()
{
// Same signature as IComputeFunc<int>, but from different interface
throw new Exception("Invalid method");
}
public int Invoke()
{
// Same signature as IComputeFunc<int>, but due to explicit interface implementation this is a wrong method
throw new Exception("Invalid method");
}
}
public enum PlatformComputeEnum : ushort
{
Foo,
Bar,
Baz
}
public class InteropComputeEnumFieldTest
{
public PlatformComputeEnum InteropEnum { get; set; }
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.MetaData;
using Microsoft.Zelig.MetaData.Normalized;
using Microsoft.Zelig.Runtime.TypeSystem;
public abstract class CallingConvention : ITransformationContextTarget
{
public enum Direction
{
Caller,
Callee,
}
public abstract class CallState : ITransformationContextTarget
{
//
// State
//
private Direction m_direction;
//
// Constructor Methods
//
protected CallState() // Default constructor required by TypeSystemSerializer.
{
}
protected CallState( Direction direction )
{
m_direction = direction;
}
//
// Helper Methods
//
public abstract RegisterDescriptor GetNextRegister( Platform platform ,
TypeRepresentation sourceTd ,
TypeRepresentation fragmentTd ,
ControlFlowGraphStateForCodeTransformation.KindOfFragment kind );
public abstract int GetNextIndex( Platform platform ,
TypeRepresentation sourceTd ,
TypeRepresentation fragmentTd ,
ControlFlowGraphStateForCodeTransformation.KindOfFragment kind );
public abstract bool CanMapToRegister( Platform platform ,
TypeRepresentation td );
public abstract bool CanMapResultToRegister( Platform platform ,
TypeRepresentation td );
public virtual void ApplyTransformation( TransformationContext context )
{
TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context;
context2.Push( this );
context2.Transform( ref m_direction );
context2.Pop();
}
//
// Access Methods
//
public Direction Direction
{
get
{
return m_direction;
}
}
}
//
// State
//
protected TypeSystemForCodeTransformation m_typeSystem;
//
// Constructor Methods
//
protected CallingConvention() // Default constructor required by TypeSystemSerializer.
{
}
protected CallingConvention( TypeSystemForCodeTransformation typeSystem )
{
m_typeSystem = typeSystem;
}
//
// Helper Methods
//
public virtual void ApplyTransformation( TransformationContext context )
{
TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context;
context2.Push( this );
context2.Transform( ref m_typeSystem );
context2.Pop();
}
//--//
public abstract void RegisterForNotifications( TypeSystemForCodeTransformation ts ,
CompilationSteps.DelegationCache cache );
public virtual void ExpandCallsClosure( CompilationSteps.ComputeCallsClosure computeCallsClosure )
{
}
//--//
public Expression[] AssignArgument( ControlFlowGraphStateForCodeTransformation cfg ,
Operator insertionOp ,
Expression ex ,
Abstractions.CallingConvention.CallState callState )
{
return AssignArgument( cfg, insertionOp, ex, ex.Type, callState );
}
public Expression[] AssignReturnValue( ControlFlowGraphStateForCodeTransformation cfg ,
Operator insertionOp ,
VariableExpression exReturnValue ,
Abstractions.CallingConvention.CallState callState )
{
if(exReturnValue != null)
{
return AssignReturnValue( cfg, insertionOp, exReturnValue, exReturnValue.Type, callState );
}
else
{
return null;
}
}
//--//
public abstract CallState CreateCallState( Direction direction );
public abstract Expression[] AssignArgument( ControlFlowGraphStateForCodeTransformation cfg ,
Operator insertionOp ,
Expression ex ,
TypeRepresentation td ,
Abstractions.CallingConvention.CallState callState );
public abstract Expression[] AssignReturnValue( ControlFlowGraphStateForCodeTransformation cfg ,
Operator insertionOp ,
VariableExpression exReturnValue ,
TypeRepresentation tdReturnValue ,
Abstractions.CallingConvention.CallState callState );
public abstract VariableExpression[] CollectExpressionsToInvalidate( ControlFlowGraphStateForCodeTransformation cfg ,
CallOperator op ,
Expression[] resFragments );
public abstract bool ShouldSaveRegister( RegisterDescriptor regDesc );
//--//
protected static VariableExpression[] MergeFragments( VariableExpression[] exDstArray ,
Expression[] exSrcArray )
{
if(exSrcArray != null)
{
foreach(Expression exSrc in exSrcArray)
{
VariableExpression var = exSrc as VariableExpression;
if(var != null)
{
exDstArray = AddUniqueToFragment( exDstArray, var );
}
}
}
return exDstArray;
}
protected static VariableExpression[] AddUniqueToFragment( VariableExpression[] array ,
VariableExpression var )
{
for(int i = array.Length; --i >= 0; )
{
if(array[i].IsTheSamePhysicalEntity( var ))
{
return array;
}
}
return ArrayUtility.AppendToNotNullArray( array, var );
}
protected static VariableExpression[] CollectAddressTakenExpressionsToInvalidate( ControlFlowGraphStateForCodeTransformation cfg ,
VariableExpression[] res ,
Operator context )
{
VariableExpression[] variables = cfg.DataFlow_SpanningTree_Variables;
VariableExpression.Property[] varProps = cfg.DataFlow_PropertiesOfVariables;
for(int varIdx = 0; varIdx < variables.Length; varIdx++)
{
if((varProps[varIdx] & VariableExpression.Property.AddressTaken) != 0)
{
VariableExpression var = variables[varIdx];
Expression[] fragments = cfg.GetFragmentsForExpression( var );
if(fragments != null)
{
res = MergeFragments( res, fragments );
}
else
{
res = AddUniqueToFragment( res, var );
}
}
}
return res;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/consumer.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 Google.Api {
/// <summary>Holder for reflection information generated from google/api/consumer.proto</summary>
public static partial class ConsumerReflection {
#region Descriptor
/// <summary>File descriptor for google/api/consumer.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConsumerReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chlnb29nbGUvYXBpL2NvbnN1bWVyLnByb3RvEgpnb29nbGUuYXBpIj0KEVBy",
"b2plY3RQcm9wZXJ0aWVzEigKCnByb3BlcnRpZXMYASADKAsyFC5nb29nbGUu",
"YXBpLlByb3BlcnR5IqwBCghQcm9wZXJ0eRIMCgRuYW1lGAEgASgJEi8KBHR5",
"cGUYAiABKA4yIS5nb29nbGUuYXBpLlByb3BlcnR5LlByb3BlcnR5VHlwZRIT",
"CgtkZXNjcmlwdGlvbhgDIAEoCSJMCgxQcm9wZXJ0eVR5cGUSDwoLVU5TUEVD",
"SUZJRUQQABIJCgVJTlQ2NBABEggKBEJPT0wQAhIKCgZTVFJJTkcQAxIKCgZE",
"T1VCTEUQBEJoCg5jb20uZ29vZ2xlLmFwaUINQ29uc3VtZXJQcm90b1ABWkVn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9zZXJ2",
"aWNlY29uZmlnO3NlcnZpY2Vjb25maWdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.ProjectProperties), global::Google.Api.ProjectProperties.Parser, new[]{ "Properties" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Property), global::Google.Api.Property.Parser, new[]{ "Name", "Type", "Description" }, null, new[]{ typeof(global::Google.Api.Property.Types.PropertyType) }, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// A descriptor for defining project properties for a service. One service may
/// have many consumer projects, and the service may want to behave differently
/// depending on some properties on the project. For example, a project may be
/// associated with a school, or a business, or a government agency, a business
/// type property on the project may affect how a service responds to the client.
/// This descriptor defines which properties are allowed to be set on a project.
///
/// Example:
///
/// project_properties:
/// properties:
/// - name: NO_WATERMARK
/// type: BOOL
/// description: Allows usage of the API without watermarks.
/// - name: EXTENDED_TILE_CACHE_PERIOD
/// type: INT64
/// </summary>
public sealed partial class ProjectProperties : pb::IMessage<ProjectProperties> {
private static readonly pb::MessageParser<ProjectProperties> _parser = new pb::MessageParser<ProjectProperties>(() => new ProjectProperties());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ProjectProperties> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.ConsumerReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties(ProjectProperties other) : this() {
properties_ = other.properties_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProjectProperties Clone() {
return new ProjectProperties(this);
}
/// <summary>Field number for the "properties" field.</summary>
public const int PropertiesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Api.Property> _repeated_properties_codec
= pb::FieldCodec.ForMessage(10, global::Google.Api.Property.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Property> properties_ = new pbc::RepeatedField<global::Google.Api.Property>();
/// <summary>
/// List of per consumer project-specific properties.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.Property> Properties {
get { return properties_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ProjectProperties);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ProjectProperties other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!properties_.Equals(other.properties_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= properties_.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) {
properties_.WriteTo(output, _repeated_properties_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += properties_.CalculateSize(_repeated_properties_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ProjectProperties other) {
if (other == null) {
return;
}
properties_.Add(other.properties_);
}
[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: {
properties_.AddEntriesFrom(input, _repeated_properties_codec);
break;
}
}
}
}
}
/// <summary>
/// Defines project properties.
///
/// API services can define properties that can be assigned to consumer projects
/// so that backends can perform response customization without having to make
/// additional calls or maintain additional storage. For example, Maps API
/// defines properties that controls map tile cache period, or whether to embed a
/// watermark in a result.
///
/// These values can be set via API producer console. Only API providers can
/// define and set these properties.
/// </summary>
public sealed partial class Property : pb::IMessage<Property> {
private static readonly pb::MessageParser<Property> _parser = new pb::MessageParser<Property>(() => new Property());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Property> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.ConsumerReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property(Property other) : this() {
name_ = other.name_;
type_ = other.type_;
description_ = other.description_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Property Clone() {
return new Property(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the property (a.k.a key).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 2;
private global::Google.Api.Property.Types.PropertyType type_ = 0;
/// <summary>
/// The type of this property.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Property.Types.PropertyType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 3;
private string description_ = "";
/// <summary>
/// The description of the property
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Property);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Property other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Type != other.Type) return false;
if (Description != other.Description) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Type != 0) hash ^= Type.GetHashCode();
if (Description.Length != 0) hash ^= Description.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 (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Type != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Type);
}
if (Description.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Description);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Property other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Type != 0) {
Type = other.Type;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
}
[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: {
Name = input.ReadString();
break;
}
case 16: {
type_ = (global::Google.Api.Property.Types.PropertyType) input.ReadEnum();
break;
}
case 26: {
Description = input.ReadString();
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Property message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Supported data type of the property values
/// </summary>
public enum PropertyType {
/// <summary>
/// The type is unspecified, and will result in an error.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The type is `int64`.
/// </summary>
[pbr::OriginalName("INT64")] Int64 = 1,
/// <summary>
/// The type is `bool`.
/// </summary>
[pbr::OriginalName("BOOL")] Bool = 2,
/// <summary>
/// The type is `string`.
/// </summary>
[pbr::OriginalName("STRING")] String = 3,
/// <summary>
/// The type is 'double'.
/// </summary>
[pbr::OriginalName("DOUBLE")] Double = 4,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Linq.Expressions.Compiler;
using System.Reflection;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Linq.Expressions;
namespace System.Linq.Expressions
{
/// <summary>
/// Creates a <see cref="LambdaExpression"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
[DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))]
public abstract class LambdaExpression : Expression
{
private readonly string _name;
private readonly Expression _body;
private readonly ReadOnlyCollection<ParameterExpression> _parameters;
private readonly Type _delegateType;
private readonly bool _tailCall;
internal LambdaExpression(
Type delegateType,
string name,
Expression body,
bool tailCall,
ReadOnlyCollection<ParameterExpression> parameters
)
{
Debug.Assert(delegateType != null);
_name = name;
_body = body;
_parameters = parameters;
_delegateType = delegateType;
_tailCall = tailCall;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _delegateType; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Lambda; }
}
/// <summary>
/// Gets the parameters of the lambda expression.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Parameters
{
get { return _parameters; }
}
/// <summary>
/// Gets the name of the lambda expression.
/// </summary>
/// <remarks>Used for debugging purposes.</remarks>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the body of the lambda expression.
/// </summary>
public Expression Body
{
get { return _body; }
}
/// <summary>
/// Gets the return type of the lambda expression.
/// </summary>
public Type ReturnType
{
get { return Type.GetMethod("Invoke").ReturnType; }
}
/// <summary>
/// Gets the value that indicates if the lambda expression will be compiled with
/// tail call optimization.
/// </summary>
public bool TailCall
{
get { return _tailCall; }
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile()
{
return Compile(preferInterpretation: false);
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="Boolean"/> that indicates if the expression should be compiled to an interpreted form, if available. </param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public Delegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE
#if FEATURE_INTERPRET
if (preferInterpretation)
{
return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return Compiler.LambdaCompiler.Compile(this);
#else
return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
#if FEATURE_COMPILE
internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller);
#endif
}
/// <summary>
/// Defines a <see cref="Expression{TDelegate}"/> node.
/// This captures a block of code that is similar to a .NET method body.
/// </summary>
/// <typeparam name="TDelegate">The type of the delegate.</typeparam>
/// <remarks>
/// Lambda expressions take input through parameters and are expected to be fully bound.
/// </remarks>
public sealed class Expression<TDelegate> : LambdaExpression
{
public Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
: base(typeof(TDelegate), name, body, tailCall, parameters)
{
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile()
{
return Compile(preferInterpretation: false);
}
/// <summary>
/// Produces a delegate that represents the lambda expression.
/// </summary>
/// <param name="preferInterpretation">A <see cref="Boolean"/> that indicates if the expression should be compiled to an interpreted form, if available. </param>
/// <returns>A delegate containing the compiled version of the lambda.</returns>
public new TDelegate Compile(bool preferInterpretation)
{
#if FEATURE_COMPILE
#if FEATURE_INTERPRET
if (preferInterpretation)
{
return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
}
#endif
return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this);
#else
return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate();
#endif
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param>
/// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters)
{
if (body == Body && parameters == Parameters)
{
return this;
}
return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters);
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitLambda(this);
}
#if FEATURE_COMPILE
internal override LambdaExpression Accept(Compiler.StackSpiller spiller)
{
return spiller.Rewrite(this);
}
internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
return new Expression<TDelegate>(body, name, tailCall, parameters);
}
#endif
}
#if !FEATURE_COMPILE
// Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T>
public class ExpressionCreator<TDelegate>
{
public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
return new Expression<TDelegate>(body, name, tailCall, parameters);
}
}
#endif
public partial class Expression
{
/// <summary>
/// Creates an Expression{T} given the delegate type. Caches the
/// factory method to speed up repeated creations for the same T.
/// </summary>
internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters)
{
// Get or create a delegate to the public Expression.Lambda<T>
// method and call that will be used for creating instances of this
// delegate type
Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath;
var factories = s_lambdaFactories;
if (factories == null)
{
s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50);
}
MethodInfo create = null;
if (!factories.TryGetValue(delegateType, out fastPath))
{
#if FEATURE_COMPILE
create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);
#else
create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public);
#endif
if (TypeUtils.CanCache(delegateType))
{
factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>));
}
}
if (fastPath != null)
{
return fastPath(body, name, tailCall, parameters);
}
Debug.Assert(create != null);
return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters });
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, null, tailCall, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters)
{
return Lambda<TDelegate>(body, name, false, parameters);
}
/// <summary>
/// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time.
/// </summary>
/// <typeparam name="TDelegate">The delegate type. </typeparam>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name of the lambda. Used for generating debugging info.</param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
var parameterList = parameters.ToReadOnly();
ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList);
return new Expression<TDelegate>(body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters)
{
return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
return Lambda(delegateType, body, null, tailCall, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
return Lambda(body, name, false, parameters);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
ContractUtils.RequiresNotNull(body, nameof(body));
var parameterList = parameters.ToReadOnly();
int paramCount = parameterList.Count;
Type[] typeArgs = new Type[paramCount + 1];
if (paramCount > 0)
{
var set = new HashSet<ParameterExpression>();
for (int i = 0; i < paramCount; i++)
{
var param = parameterList[i];
ContractUtils.RequiresNotNull(param, "parameter");
typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type;
if (!set.Add(param))
{
throw Error.DuplicateVariable(param, $"parameters[{i}]");
}
}
}
typeArgs[paramCount] = body.Type;
Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
return CreateLambda(delegateType, body, name, tailCall, parameterList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters)
{
var paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList);
return CreateLambda(delegateType, body, name, false, paramList);
}
/// <summary>
/// Creates a LambdaExpression by first constructing a delegate type.
/// </summary>
/// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param>
/// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param>
/// <param name="name">The name for the lambda. Used for emitting debug information.</param>
/// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param>
/// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param>
/// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns>
public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters)
{
var paramList = parameters.ToReadOnly();
ValidateLambdaArgs(delegateType, ref body, paramList);
return CreateLambda(delegateType, body, name, tailCall, paramList);
}
private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters)
{
ContractUtils.RequiresNotNull(delegateType, nameof(delegateType));
RequiresCanRead(body, nameof(body));
if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate))
{
throw Error.LambdaTypeMustBeDerivedFromSystemDelegate();
}
MethodInfo mi;
var ldc = s_lambdaDelegateCache;
if (!ldc.TryGetValue(delegateType, out mi))
{
mi = delegateType.GetMethod("Invoke");
if (TypeUtils.CanCache(delegateType))
{
ldc[delegateType] = mi;
}
}
ParameterInfo[] pis = mi.GetParametersCached();
if (pis.Length > 0)
{
if (pis.Length != parameters.Count)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
var set = new HashSet<ParameterExpression>();
for (int i = 0, n = pis.Length; i < n; i++)
{
ParameterExpression pex = parameters[i];
ParameterInfo pi = pis[i];
RequiresCanRead(pex, nameof(parameters));
Type pType = pi.ParameterType;
if (pex.IsByRef)
{
if (!pType.IsByRef)
{
//We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type.
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType);
}
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pex.Type, pType))
{
throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType);
}
if (!set.Add(pex))
{
throw Error.DuplicateVariable(pex, $"parameters[{i}]");
}
}
}
else if (parameters.Count > 0)
{
throw Error.IncorrectNumberOfLambdaDeclarationParameters();
}
if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type))
{
if (!TryQuote(mi.ReturnType, ref body))
{
throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType);
}
}
}
private static bool ValidateTryGetFuncActionArgs(Type[] typeArgs)
{
if (typeArgs == null)
{
throw new ArgumentNullException(nameof(typeArgs));
}
for (int i = 0, n = typeArgs.Length; i < n; i++)
{
var a = typeArgs[i];
if (a == null)
{
throw new ArgumentNullException(nameof(typeArgs));
}
if (a.IsByRef)
{
return false;
}
}
return true;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
/// <returns>The type of a System.Func delegate that has the specified type arguments.</returns>
public static Type GetFuncType(params Type[] typeArgs)
{
if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(nameof(typeArgs));
Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs));
}
return result;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments.
/// The last type argument specifies the return type of the created delegate.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param>
/// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetFuncType(Type[] typeArgs, out Type funcType)
{
if (ValidateTryGetFuncActionArgs(typeArgs))
{
return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null;
}
funcType = null;
return false;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
/// <returns>The type of a System.Action delegate that has the specified type arguments.</returns>
public static Type GetActionType(params Type[] typeArgs)
{
if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(nameof(typeArgs));
Type result = Compiler.DelegateHelpers.GetActionType(typeArgs);
if (result == null)
{
throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs));
}
return result;
}
/// <summary>
/// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments.
/// </summary>
/// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param>
/// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param>
/// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns>
public static bool TryGetActionType(Type[] typeArgs, out Type actionType)
{
if (ValidateTryGetFuncActionArgs(typeArgs))
{
return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null;
}
actionType = null;
return false;
}
/// <summary>
/// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments.
/// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom
/// delegate type.
/// </summary>
/// <param name="typeArgs">The type arguments of the delegate.</param>
/// <returns>The delegate type.</returns>
/// <remarks>
/// As with Func, the last argument is the return type. It can be set
/// to System.Void to produce an Action.</remarks>
public static Type GetDelegateType(params Type[] typeArgs)
{
ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs));
ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs));
return Compiler.DelegateHelpers.MakeDelegateType(typeArgs);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.Client.Tests;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group4")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientSecurityAuthTestsMU : ThinClientRegionSteps
{
#region Private members
private UnitProcess m_client1;
private UnitProcess m_client2;
private const string CacheXml1 = "cacheserver_notify_subscription.xml";
private const string CacheXml2 = "cacheserver_notify_subscription2.xml";
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
void runValidCredentials()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
Util.Log("ValidCredentials: Using scheme: " + gen.GetClassCode());
Util.Log("ValidCredentials: Using authenticator: " + authenticator);
Util.Log("ValidCredentials: Using authinit: " + authInit);
// Start the server
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start the clients with valid credentials
Properties<string, string> credentials1 = gen.GetValidCredentials(1);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("ValidCredentials: For first client credentials: " +
credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetValidCredentials(2);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("ValidCredentials: For second client credentials: " +
credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, new Properties<string, string>(), true);
m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, new Properties<string, string>(), true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 10, credentials1, true);
// Verify that the puts succeeded
m_client2.Call(DoGetsMU, 10, credentials2, true);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runNoCredentials()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
Util.Log("NoCredentials: Using scheme: " + gen.GetClassCode());
Util.Log("NoCredentials: Using authenticator: " + authenticator);
Util.Log("NoCredentials: Using authinit: " + authInit);
// Start the server
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start the clients with valid credentials
Properties<string, string> credentials1 = gen.GetValidCredentials(3);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("NoCredentials: For first client credentials: " +
credentials1 + " : " + javaProps1);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 4, (Properties<string, string>)null, true, ExpectedResult.AuthFailedException);
m_client1.Call(DoPutsMU, 4, new Properties<string, string>(), true, ExpectedResult.AuthFailedException);
// Creating region on client2 should throw authentication
// required exception
/* m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, (Properties<string, string>)null,
ExpectedResult.AuthRequiredException, true);
*/
m_client1.Call(Close);
//m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runInvalidCredentials()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
Util.Log("InvalidCredentials: Using scheme: " + gen.GetClassCode());
Util.Log("InvalidCredentials: Using authenticator: " + authenticator);
Util.Log("InvalidCredentials: Using authinit: " + authInit);
// Start the server
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start the clients with valid credentials
Properties<string, string> credentials1 = gen.GetValidCredentials(8);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("InvalidCredentials: For first client credentials: " +
credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetInvalidCredentials(7);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("InvalidCredentials: For second client credentials: " +
credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 4, credentials1, true);
// Creating region on client2 should throw authentication
// failure exception
m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client2.Call(DoPutsMU, 4, credentials2, true, ExpectedResult.AuthFailedException);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runInvalidAuthInit()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
Util.Log("InvalidAuthInit: Using scheme: " + gen.GetClassCode());
Util.Log("InvalidAuthInit: Using authenticator: " + authenticator);
// Start the server
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Creating region on client1 with invalid authInit callback should
// throw authentication required exception
Properties<string, string> credentials = gen.GetValidCredentials(5);
javaProps = gen.JavaProperties;
Util.Log("InvalidAuthInit: For first client credentials: " +
credentials + " : " + javaProps);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, "Apache.Geode.Templates.Cache.Security.none",
(Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 20, credentials, true);
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runInvalidAuthenticator()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authInit = gen.AuthInit;
if (authInit == null || authInit.Length == 0)
{
// Skip a scheme which does not have an authInit in the first place
// (e.g. SSL) since that will fail with AuthReqEx before
// authenticator is even invoked
Util.Log("InvalidAuthenticator: Skipping scheme [" +
gen.GetClassCode() + "] which has no authInit");
continue;
}
Util.Log("InvalidAuthenticator: Using scheme: " + gen.GetClassCode());
Util.Log("InvalidAuthenticator: Using authinit: " + authInit);
// Start the server with invalid authenticator
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
"org.apache.geode.none", extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Starting the client with valid credentials should throw
// authentication failed exception
Properties<string, string> credentials1 = gen.GetValidCredentials(1);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("InvalidAuthenticator: For first client valid credentials: " +
credentials1 + " : " + javaProps1);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 20, credentials1, true, ExpectedResult.AuthFailedException);
// Also try with invalid credentials
/*Properties<string, string> credentials2 = gen.GetInvalidCredentials(1);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("InvalidAuthenticator: For first client invalid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, credentials2,
ExpectedResult.AuthFailedException);
*/
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runNoAuthInitWithCredentials()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
if (authInit == null || authInit.Length == 0)
{
// If the scheme does not have an authInit in the first place
// (e.g. SSL) then skip it
Util.Log("NoAuthInitWithCredentials: Skipping scheme [" +
gen.GetClassCode() + "] which has no authInit");
continue;
}
Util.Log("NoAuthInitWithCredentials: Using scheme: " +
gen.GetClassCode());
Util.Log("NoAuthInitWithCredentials: Using authenticator: " +
authenticator);
// Start the server
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start client1 with valid credentials and client2 with invalid
// credentials; both should fail without an authInit
Properties<string, string> credentials1 = gen.GetValidCredentials(6);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("NoAuthInitWithCredentials: For first client valid " +
"credentials: " + credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetInvalidCredentials(2);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("NoAuthInitWithCredentials: For second client invalid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, credentials1,
ExpectedResult.AuthRequiredException);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, credentials2,
ExpectedResult.AuthRequiredException);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runNoAuthenticatorWithCredentials()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
if (authenticator == null || authenticator.Length == 0)
{
// If the scheme does not have an authenticator in the first place
// (e.g. SSL) then skip it since this test is useless
Util.Log("NoAuthenticatorWithCredentials: Skipping scheme [" +
gen.GetClassCode() + "] which has no authenticator");
continue;
}
Util.Log("NoAuthenticatorWithCredentials: Using scheme: " +
gen.GetClassCode());
Util.Log("NoAuthenticatorWithCredentials: Using authinit: " +
authInit);
// Start the servers
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
null, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start client1 with valid credentials and client2 with invalid
// credentials; both should succeed with no authenticator on server
Properties<string, string> credentials1 = gen.GetValidCredentials(3);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("NoAuthenticatorWithCredentials: For first client valid " +
"credentials: " + credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetInvalidCredentials(12);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("NoAuthenticatorWithCredentials: For second client invalid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 4, credentials1, true);
// Verify that the puts succeeded
m_client2.Call(DoGetsMU, 4, credentials2, true);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
void runCredentialsWithFailover()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
Util.Log("CredentialsWithFailover: Using scheme: " +
gen.GetClassCode());
Util.Log("CredentialsWithFailover: Using authenticator: " +
authenticator);
Util.Log("CredentialsWithFailover: Using authinit: " + authInit);
// Start the first server; do not start second server yet to force
// the clients to connect to the first server.
CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
// Start the clients with valid credentials
Properties<string, string> credentials1 = gen.GetValidCredentials(5);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("CredentialsWithFailover: For first client valid " +
"credentials: " + credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetValidCredentials(6);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("CredentialsWithFailover: For second client valid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
m_client2.Call(SecurityTestUtil.CreateClientMU, RegionName,
CacheHelper.Locators, authInit, (Properties<string, string>)null, true);
// Perform some put operations from client1
m_client1.Call(DoPutsMU, 2, credentials1, true);
// Verify that the puts succeeded
m_client2.Call(DoGetsMU, 2, credentials2, true);
// Start the second server and stop the first one to force a failover
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
// Perform some create/update operations from client1
// and verify from client2
m_client1.Call(DoPutsMU, 4, credentials1, true);
m_client2.Call(DoGetsMU, 4, credentials2, true);
// Try to connect client2 with no credentials
// Verify that the creation of region throws security exception
/*m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, (Properties<string, string>)null,
ExpectedResult.AuthRequiredException);
// Now try to connect client1 with invalid credentials
// Verify that the creation of region throws security exception
credentials1 = gen.GetInvalidCredentials(7);
javaProps1 = gen.JavaProperties;
Util.Log("CredentialsWithFailover: For first client invalid " +
"credentials: " + credentials1 + " : " + javaProps1);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, credentials1,
ExpectedResult.AuthFailedException);
*/
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
}
public void registerPdxTypes()
{
Serializable.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
Serializable.RegisterPdxType(PdxTests.PdxTypes1.CreateDeserializable);
}
void runCredentialsForNotifications()
{
foreach (CredentialGenerator gen in SecurityTestUtil.getAllGenerators(true))
{
Properties<string, string> extraProps = gen.SystemProperties;
Properties<string, string> javaProps = gen.JavaProperties;
string authenticator = gen.Authenticator;
string authInit = gen.AuthInit;
Util.Log("CredentialsForNotifications: Using scheme: " +
gen.GetClassCode());
Util.Log("CredentialsForNotifications: Using authenticator: " +
authenticator);
Util.Log("CredentialsForNotifications: Using authinit: " + authInit);
// Start the two servers.
CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 2 started.");
// Start the clients with valid credentials
Properties<string, string> credentials1 = gen.GetValidCredentials(5);
Properties<string, string> javaProps1 = gen.JavaProperties;
Util.Log("CredentialsForNotifications: For first client valid " +
"credentials: " + credentials1 + " : " + javaProps1);
Properties<string, string> credentials2 = gen.GetValidCredentials(6);
Properties<string, string> javaProps2 = gen.JavaProperties;
Util.Log("CredentialsForNotifications: For second client valid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, credentials1);
// Set up zero forward connections to check notification handshake only
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, credentials2,
0, ExpectedResult.Success);
m_client1.Call(registerPdxTypes);
m_client2.Call(registerPdxTypes);
// Register interest for all keys on second client
m_client2.Call(RegisterAllKeys, new string[] { RegionName });
// Wait for secondary server to see second client
Thread.Sleep(1000);
// Perform some put operations from client1
m_client1.Call(DoPuts, 2);
// Verify that the puts succeeded
m_client2.Call(DoLocalGets, 2);
// Stop the first server
CacheHelper.StopJavaServer(1);
// Perform some create/update operations from client1
m_client1.Call(DoPuts, 4, true, ExpectedResult.Success);
// Verify that the creates/updates succeeded
m_client2.Call(DoLocalGets, 4, true);
// Start server1 again and try to connect client1 using zero forward
// connections with no credentials.
// Verify that the creation of region throws authentication
// required exception
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, SecurityTestUtil.GetServerArgs(
authenticator, extraProps, javaProps));
Util.Log("Cacheserver 1 started.");
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, (Properties<string, string>)null,
0, ExpectedResult.AuthRequiredException);
// Now try to connect client2 using zero forward connections
// with invalid credentials.
// Verify that the creation of region throws security exception
credentials2 = gen.GetInvalidCredentials(3);
javaProps2 = gen.JavaProperties;
Util.Log("CredentialsForNotifications: For second client invalid " +
"credentials: " + credentials2 + " : " + javaProps2);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, credentials2,
0, ExpectedResult.AuthFailedException);
// Now try to connect client2 with invalid auth-init method
// Trying to create the region on client with valid credentials should
// throw an authentication failed exception
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, "Apache.Geode.Templates.Cache.Security.none",
credentials1, 0, ExpectedResult.AuthRequiredException);
// Try connection with null auth-init on clients.
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, credentials1,
0, ExpectedResult.AuthRequiredException);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, (string)null, credentials2,
0, ExpectedResult.AuthRequiredException);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaServer(2);
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearLocators();
CacheHelper.ClearEndpoints();
}
}
[Test]
public void ValidCredentials()
{
runValidCredentials();
}
[Test]
public void NoCredentials()
{
runNoCredentials();
}
[Test]
public void InvalidCredentials()
{
runInvalidCredentials();
}
[Test]
public void InvalidAuthInit()
{
runInvalidAuthInit();
}
[Test]
public void InvalidAuthenticator()
{
runInvalidAuthenticator();
}
[Test]
public void NoAuthInitWithCredentials()
{
runNoAuthInitWithCredentials();
}
[Test]
public void NoAuthenticatorWithCredentials()
{
runNoAuthenticatorWithCredentials();
}
[Test]
public void CredentialsWithFailover()
{
runCredentialsWithFailover();
}
[Test]
public void CredentialsForNotifications()
{
runCredentialsForNotifications();
}
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
namespace Fungus.EditorUtils
{
[CustomEditor (typeof(Say))]
public class SayEditor : CommandEditor
{
public static bool showTagHelp;
public Texture2D blackTex;
public static void DrawTagHelpLabel()
{
string tagsText = TextTagParser.GetTagHelp();
if (CustomTag.activeCustomTags.Count > 0)
{
tagsText += "\n\n\t-------- CUSTOM TAGS --------";
List<Transform> activeCustomTagGroup = new List<Transform>();
foreach (CustomTag ct in CustomTag.activeCustomTags)
{
if(ct.transform.parent != null)
{
if (!activeCustomTagGroup.Contains(ct.transform.parent.transform))
{
activeCustomTagGroup.Add(ct.transform.parent.transform);
}
}
else
{
activeCustomTagGroup.Add(ct.transform);
}
}
foreach(Transform parent in activeCustomTagGroup)
{
string tagName = parent.name;
string tagStartSymbol = "";
string tagEndSymbol = "";
CustomTag parentTag = parent.GetComponent<CustomTag>();
if (parentTag != null)
{
tagName = parentTag.name;
tagStartSymbol = parentTag.TagStartSymbol;
tagEndSymbol = parentTag.TagEndSymbol;
}
tagsText += "\n\n\t" + tagStartSymbol + " " + tagName + " " + tagEndSymbol;
foreach(Transform child in parent)
{
tagName = child.name;
tagStartSymbol = "";
tagEndSymbol = "";
CustomTag childTag = child.GetComponent<CustomTag>();
if (childTag != null)
{
tagName = childTag.name;
tagStartSymbol = childTag.TagStartSymbol;
tagEndSymbol = childTag.TagEndSymbol;
}
tagsText += "\n\t " + tagStartSymbol + " " + tagName + " " + tagEndSymbol;
}
}
}
tagsText += "\n";
float pixelHeight = EditorStyles.miniLabel.CalcHeight(new GUIContent(tagsText), EditorGUIUtility.currentViewWidth);
EditorGUILayout.SelectableLabel(tagsText, GUI.skin.GetStyle("HelpBox"), GUILayout.MinHeight(pixelHeight));
}
protected SerializedProperty characterProp;
protected SerializedProperty portraitProp;
protected SerializedProperty storyTextProp;
protected SerializedProperty descriptionProp;
protected SerializedProperty voiceOverClipProp;
protected SerializedProperty showAlwaysProp;
protected SerializedProperty showCountProp;
protected SerializedProperty extendPreviousProp;
protected SerializedProperty fadeWhenDoneProp;
protected SerializedProperty waitForClickProp;
protected SerializedProperty stopVoiceoverProp;
protected SerializedProperty setSayDialogProp;
protected SerializedProperty waitForVOProp;
public override void OnEnable()
{
base.OnEnable();
characterProp = serializedObject.FindProperty("character");
portraitProp = serializedObject.FindProperty("portrait");
storyTextProp = serializedObject.FindProperty("storyText");
descriptionProp = serializedObject.FindProperty("description");
voiceOverClipProp = serializedObject.FindProperty("voiceOverClip");
showAlwaysProp = serializedObject.FindProperty("showAlways");
showCountProp = serializedObject.FindProperty("showCount");
extendPreviousProp = serializedObject.FindProperty("extendPrevious");
fadeWhenDoneProp = serializedObject.FindProperty("fadeWhenDone");
waitForClickProp = serializedObject.FindProperty("waitForClick");
stopVoiceoverProp = serializedObject.FindProperty("stopVoiceover");
setSayDialogProp = serializedObject.FindProperty("setSayDialog");
waitForVOProp = serializedObject.FindProperty("waitForVO");
if (blackTex == null)
{
blackTex = CustomGUI.CreateBlackTexture();
}
}
protected virtual void OnDisable()
{
DestroyImmediate(blackTex);
}
public override void DrawCommandGUI()
{
serializedObject.Update();
bool showPortraits = false;
CommandEditor.ObjectField<Character>(characterProp,
new GUIContent("Character", "Character that is speaking"),
new GUIContent("<None>"),
Character.ActiveCharacters);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(" ");
characterProp.objectReferenceValue = (Character) EditorGUILayout.ObjectField(characterProp.objectReferenceValue, typeof(Character), true);
EditorGUILayout.EndHorizontal();
Say t = target as Say;
// Only show portrait selection if...
if (t._Character != null && // Character is selected
t._Character.Portraits != null && // Character has a portraits field
t._Character.Portraits.Count > 0 ) // Selected Character has at least 1 portrait
{
showPortraits = true;
}
if (showPortraits)
{
CommandEditor.ObjectField<Sprite>(portraitProp,
new GUIContent("Portrait", "Portrait representing speaking character"),
new GUIContent("<None>"),
t._Character.Portraits);
}
else
{
if (!t.ExtendPrevious)
{
t.Portrait = null;
}
}
EditorGUILayout.PropertyField(storyTextProp);
EditorGUILayout.PropertyField(descriptionProp);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(extendPreviousProp);
GUILayout.FlexibleSpace();
if (GUILayout.Button(new GUIContent("Tag Help", "View available tags"), new GUIStyle(EditorStyles.miniButton)))
{
showTagHelp = !showTagHelp;
}
EditorGUILayout.EndHorizontal();
if (showTagHelp)
{
DrawTagHelpLabel();
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(voiceOverClipProp,
new GUIContent("Voice Over Clip", "Voice over audio to play when the text is displayed"));
EditorGUILayout.PropertyField(showAlwaysProp);
if (showAlwaysProp.boolValue == false)
{
EditorGUILayout.PropertyField(showCountProp);
}
GUIStyle centeredLabel = new GUIStyle(EditorStyles.label);
centeredLabel.alignment = TextAnchor.MiddleCenter;
GUIStyle leftButton = new GUIStyle(EditorStyles.miniButtonLeft);
leftButton.fontSize = 10;
leftButton.font = EditorStyles.toolbarButton.font;
GUIStyle rightButton = new GUIStyle(EditorStyles.miniButtonRight);
rightButton.fontSize = 10;
rightButton.font = EditorStyles.toolbarButton.font;
EditorGUILayout.PropertyField(fadeWhenDoneProp);
EditorGUILayout.PropertyField(waitForClickProp);
EditorGUILayout.PropertyField(stopVoiceoverProp);
EditorGUILayout.PropertyField(setSayDialogProp);
EditorGUILayout.PropertyField(waitForVOProp);
if (showPortraits && t.Portrait != null)
{
Texture2D characterTexture = t.Portrait.texture;
float aspect = (float)characterTexture.width / (float)characterTexture.height;
Rect previewRect = GUILayoutUtility.GetAspectRect(aspect, GUILayout.Width(100), GUILayout.ExpandWidth(true));
if (characterTexture != null)
{
GUI.DrawTexture(previewRect,characterTexture,ScaleMode.ScaleToFit,true,aspect);
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
| |
namespace android.media
{
[global::MonoJavaBridge.JavaClass()]
public partial class AudioManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected AudioManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.AudioManager.OnAudioFocusChangeListener_))]
public partial interface OnAudioFocusChangeListener : global::MonoJavaBridge.IJavaObject
{
void onAudioFocusChange(int arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.AudioManager.OnAudioFocusChangeListener))]
internal sealed partial class OnAudioFocusChangeListener_ : java.lang.Object, OnAudioFocusChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal OnAudioFocusChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.media.AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.OnAudioFocusChangeListener_.staticClass, "onAudioFocusChange", "(I)V", ref global::android.media.AudioManager.OnAudioFocusChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
static OnAudioFocusChangeListener_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioManager.OnAudioFocusChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioManager$OnAudioFocusChangeListener"));
}
}
public delegate void OnAudioFocusChangeListenerDelegate(int arg0);
internal partial class OnAudioFocusChangeListenerDelegateWrapper : java.lang.Object, OnAudioFocusChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected OnAudioFocusChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public OnAudioFocusChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero)
global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper.staticClass, global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper._m0);
Init(@__env, handle);
}
static OnAudioFocusChangeListenerDelegateWrapper()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioManager_OnAudioFocusChangeListenerDelegateWrapper"));
}
}
internal partial class OnAudioFocusChangeListenerDelegateWrapper
{
private OnAudioFocusChangeListenerDelegate myDelegate;
public void onAudioFocusChange(int arg0)
{
myDelegate(arg0);
}
public static implicit operator OnAudioFocusChangeListenerDelegateWrapper(OnAudioFocusChangeListenerDelegate d)
{
global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper ret = new global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper();
ret.myDelegate = d;
global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret);
return ret;
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::java.lang.String getParameters(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.media.AudioManager.staticClass, "getParameters", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.media.AudioManager._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void setMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setMode", "(I)V", ref global::android.media.AudioManager._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Mode
{
get
{
return getMode();
}
set
{
setMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual int getMode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getMode", "()I", ref global::android.media.AudioManager._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void playSoundEffect(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "playSoundEffect", "(I)V", ref global::android.media.AudioManager._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void playSoundEffect(int arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "playSoundEffect", "(IF)V", ref global::android.media.AudioManager._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new global::java.lang.String Parameters
{
set
{
setParameters(value);
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void setParameters(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setParameters", "(Ljava/lang/String;)V", ref global::android.media.AudioManager._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void adjustStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "adjustStreamVolume", "(III)V", ref global::android.media.AudioManager._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void adjustVolume(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "adjustVolume", "(II)V", ref global::android.media.AudioManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void adjustSuggestedStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "adjustSuggestedStreamVolume", "(III)V", ref global::android.media.AudioManager._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public new int RingerMode
{
get
{
return getRingerMode();
}
set
{
setRingerMode(value);
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual int getRingerMode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getRingerMode", "()I", ref global::android.media.AudioManager._m9);
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual int getStreamMaxVolume(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getStreamMaxVolume", "(I)I", ref global::android.media.AudioManager._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual int getStreamVolume(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getStreamVolume", "(I)I", ref global::android.media.AudioManager._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void setRingerMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setRingerMode", "(I)V", ref global::android.media.AudioManager._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setStreamVolume(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setStreamVolume", "(III)V", ref global::android.media.AudioManager._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual void setStreamSolo(int arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setStreamSolo", "(IZ)V", ref global::android.media.AudioManager._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setStreamMute(int arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setStreamMute", "(IZ)V", ref global::android.media.AudioManager._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual bool shouldVibrate(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "shouldVibrate", "(I)Z", ref global::android.media.AudioManager._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual int getVibrateSetting(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getVibrateSetting", "(I)I", ref global::android.media.AudioManager._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setVibrateSetting(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setVibrateSetting", "(II)V", ref global::android.media.AudioManager._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new bool SpeakerphoneOn
{
set
{
setSpeakerphoneOn(value);
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void setSpeakerphoneOn(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setSpeakerphoneOn", "(Z)V", ref global::android.media.AudioManager._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual bool isSpeakerphoneOn()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isSpeakerphoneOn", "()Z", ref global::android.media.AudioManager._m20);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual bool isBluetoothScoAvailableOffCall()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isBluetoothScoAvailableOffCall", "()Z", ref global::android.media.AudioManager._m21);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void startBluetoothSco()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "startBluetoothSco", "()V", ref global::android.media.AudioManager._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void stopBluetoothSco()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "stopBluetoothSco", "()V", ref global::android.media.AudioManager._m23);
}
public new bool BluetoothScoOn
{
set
{
setBluetoothScoOn(value);
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void setBluetoothScoOn(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setBluetoothScoOn", "(Z)V", ref global::android.media.AudioManager._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual bool isBluetoothScoOn()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isBluetoothScoOn", "()Z", ref global::android.media.AudioManager._m25);
}
public new bool BluetoothA2dpOn
{
set
{
setBluetoothA2dpOn(value);
}
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void setBluetoothA2dpOn(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setBluetoothA2dpOn", "(Z)V", ref global::android.media.AudioManager._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual bool isBluetoothA2dpOn()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isBluetoothA2dpOn", "()Z", ref global::android.media.AudioManager._m27);
}
public new bool WiredHeadsetOn
{
set
{
setWiredHeadsetOn(value);
}
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual void setWiredHeadsetOn(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setWiredHeadsetOn", "(Z)V", ref global::android.media.AudioManager._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual bool isWiredHeadsetOn()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isWiredHeadsetOn", "()Z", ref global::android.media.AudioManager._m29);
}
public new bool MicrophoneMute
{
set
{
setMicrophoneMute(value);
}
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual void setMicrophoneMute(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setMicrophoneMute", "(Z)V", ref global::android.media.AudioManager._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual bool isMicrophoneMute()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isMicrophoneMute", "()Z", ref global::android.media.AudioManager._m31);
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual void setRouting(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "setRouting", "(III)V", ref global::android.media.AudioManager._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual int getRouting(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "getRouting", "(I)I", ref global::android.media.AudioManager._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual bool isMusicActive()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.media.AudioManager.staticClass, "isMusicActive", "()Z", ref global::android.media.AudioManager._m34);
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void loadSoundEffects()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "loadSoundEffects", "()V", ref global::android.media.AudioManager._m35);
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual void unloadSoundEffects()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "unloadSoundEffects", "()V", ref global::android.media.AudioManager._m36);
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "requestAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;II)I", ref global::android.media.AudioManager._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public int requestAudioFocus(global::android.media.AudioManager.OnAudioFocusChangeListenerDelegate arg0, int arg1, int arg2)
{
return requestAudioFocus((global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper)arg0, arg1, arg2);
}
private static global::MonoJavaBridge.MethodId _m38;
public virtual int abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioManager.staticClass, "abandonAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;)I", ref global::android.media.AudioManager._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public int abandonAudioFocus(global::android.media.AudioManager.OnAudioFocusChangeListenerDelegate arg0)
{
return abandonAudioFocus((global::android.media.AudioManager.OnAudioFocusChangeListenerDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m39;
public virtual void registerMediaButtonEventReceiver(android.content.ComponentName arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "registerMediaButtonEventReceiver", "(Landroid/content/ComponentName;)V", ref global::android.media.AudioManager._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual void unregisterMediaButtonEventReceiver(android.content.ComponentName arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioManager.staticClass, "unregisterMediaButtonEventReceiver", "(Landroid/content/ComponentName;)V", ref global::android.media.AudioManager._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public static global::java.lang.String ACTION_AUDIO_BECOMING_NOISY
{
get
{
return "android.media.AUDIO_BECOMING_NOISY";
}
}
public static global::java.lang.String RINGER_MODE_CHANGED_ACTION
{
get
{
return "android.media.RINGER_MODE_CHANGED";
}
}
public static global::java.lang.String EXTRA_RINGER_MODE
{
get
{
return "android.media.EXTRA_RINGER_MODE";
}
}
public static global::java.lang.String VIBRATE_SETTING_CHANGED_ACTION
{
get
{
return "android.media.VIBRATE_SETTING_CHANGED";
}
}
public static global::java.lang.String EXTRA_VIBRATE_SETTING
{
get
{
return "android.media.EXTRA_VIBRATE_SETTING";
}
}
public static global::java.lang.String EXTRA_VIBRATE_TYPE
{
get
{
return "android.media.EXTRA_VIBRATE_TYPE";
}
}
public static int STREAM_VOICE_CALL
{
get
{
return 0;
}
}
public static int STREAM_SYSTEM
{
get
{
return 1;
}
}
public static int STREAM_RING
{
get
{
return 2;
}
}
public static int STREAM_MUSIC
{
get
{
return 3;
}
}
public static int STREAM_ALARM
{
get
{
return 4;
}
}
public static int STREAM_NOTIFICATION
{
get
{
return 5;
}
}
public static int STREAM_DTMF
{
get
{
return 8;
}
}
public static int NUM_STREAMS
{
get
{
return 5;
}
}
public static int ADJUST_RAISE
{
get
{
return 1;
}
}
public static int ADJUST_LOWER
{
get
{
return -1;
}
}
public static int ADJUST_SAME
{
get
{
return 0;
}
}
public static int FLAG_SHOW_UI
{
get
{
return 1;
}
}
public static int FLAG_ALLOW_RINGER_MODES
{
get
{
return 2;
}
}
public static int FLAG_PLAY_SOUND
{
get
{
return 4;
}
}
public static int FLAG_REMOVE_SOUND_AND_VIBRATE
{
get
{
return 8;
}
}
public static int FLAG_VIBRATE
{
get
{
return 16;
}
}
public static int RINGER_MODE_SILENT
{
get
{
return 0;
}
}
public static int RINGER_MODE_VIBRATE
{
get
{
return 1;
}
}
public static int RINGER_MODE_NORMAL
{
get
{
return 2;
}
}
public static int VIBRATE_TYPE_RINGER
{
get
{
return 0;
}
}
public static int VIBRATE_TYPE_NOTIFICATION
{
get
{
return 1;
}
}
public static int VIBRATE_SETTING_OFF
{
get
{
return 0;
}
}
public static int VIBRATE_SETTING_ON
{
get
{
return 1;
}
}
public static int VIBRATE_SETTING_ONLY_SILENT
{
get
{
return 2;
}
}
public static int USE_DEFAULT_STREAM_TYPE
{
get
{
return -2147483648;
}
}
public static global::java.lang.String ACTION_SCO_AUDIO_STATE_CHANGED
{
get
{
return "android.media.SCO_AUDIO_STATE_CHANGED";
}
}
public static global::java.lang.String EXTRA_SCO_AUDIO_STATE
{
get
{
return "android.media.extra.SCO_AUDIO_STATE";
}
}
public static int SCO_AUDIO_STATE_DISCONNECTED
{
get
{
return 0;
}
}
public static int SCO_AUDIO_STATE_CONNECTED
{
get
{
return 1;
}
}
public static int SCO_AUDIO_STATE_ERROR
{
get
{
return -1;
}
}
public static int MODE_INVALID
{
get
{
return -2;
}
}
public static int MODE_CURRENT
{
get
{
return -1;
}
}
public static int MODE_NORMAL
{
get
{
return 0;
}
}
public static int MODE_RINGTONE
{
get
{
return 1;
}
}
public static int MODE_IN_CALL
{
get
{
return 2;
}
}
public static int ROUTE_EARPIECE
{
get
{
return 1;
}
}
public static int ROUTE_SPEAKER
{
get
{
return 2;
}
}
public static int ROUTE_BLUETOOTH
{
get
{
return 4;
}
}
public static int ROUTE_BLUETOOTH_SCO
{
get
{
return 4;
}
}
public static int ROUTE_HEADSET
{
get
{
return 8;
}
}
public static int ROUTE_BLUETOOTH_A2DP
{
get
{
return 16;
}
}
public static int ROUTE_ALL
{
get
{
return -1;
}
}
public static int FX_KEY_CLICK
{
get
{
return 0;
}
}
public static int FX_FOCUS_NAVIGATION_UP
{
get
{
return 1;
}
}
public static int FX_FOCUS_NAVIGATION_DOWN
{
get
{
return 2;
}
}
public static int FX_FOCUS_NAVIGATION_LEFT
{
get
{
return 3;
}
}
public static int FX_FOCUS_NAVIGATION_RIGHT
{
get
{
return 4;
}
}
public static int FX_KEYPRESS_STANDARD
{
get
{
return 5;
}
}
public static int FX_KEYPRESS_SPACEBAR
{
get
{
return 6;
}
}
public static int FX_KEYPRESS_DELETE
{
get
{
return 7;
}
}
public static int FX_KEYPRESS_RETURN
{
get
{
return 8;
}
}
public static int AUDIOFOCUS_GAIN
{
get
{
return 1;
}
}
public static int AUDIOFOCUS_GAIN_TRANSIENT
{
get
{
return 2;
}
}
public static int AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
{
get
{
return 3;
}
}
public static int AUDIOFOCUS_LOSS
{
get
{
return -1;
}
}
public static int AUDIOFOCUS_LOSS_TRANSIENT
{
get
{
return -2;
}
}
public static int AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
{
get
{
return -3;
}
}
public static int AUDIOFOCUS_REQUEST_FAILED
{
get
{
return 0;
}
}
public static int AUDIOFOCUS_REQUEST_GRANTED
{
get
{
return 1;
}
}
static AudioManager()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioManager"));
}
}
}
| |
//
// Copyright (C) 2008 Jordi Mas i Hernandez, jmas@softcatala.org
// Copyright (C) 2006 John Luke
//
// 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 Gtk;
using System.IO;
using Mono.Unix;
using Mistelix.Core;
namespace Mistelix.Widgets
{
public delegate void ChangeDirectoryEventHandler (object sender, ChangeDirectoryEventArgs e);
public class ChangeDirectoryEventArgs: EventArgs
{
string directory;
public ChangeDirectoryEventArgs (string directory)
{
this.directory = directory;
}
public string Directory {
get { return directory; }
}
}
class ToolbarEntry : ToolItem
{
Entry entry;
public event EventHandler Activated;
public ToolbarEntry () : base ()
{
entry = new Entry ();
entry.Activated += new EventHandler (OnActivated);
this.Add (entry);
entry.Show ();
this.ShowAll ();
}
void OnActivated (object sender, EventArgs a)
{
if (Activated != null)
Activated (this, EventArgs.Empty);
}
public string Text {
get { return entry.Text; }
set { entry.Text = value; }
}
}
//
// Displays directories into a treeview
//
public class DirectoryView
{
const int COL_DISPLAY_NAME = 0;
const int COL_PIXBUF = 1;
const int COL_PATH = 2;
DirectoryInfo current;
TreeStore tree_store;
public ChangeDirectoryEventHandler DirectoryChanged;
Gtk.ScrolledWindow scrolledwindow;
ToolbarEntry entry;
Gtk.CellRendererText text_render;
Gtk.TreeView tv;
Gtk.ToolButton goUp, goHome;
Gdk.Pixbuf dir_icon;
public DirectoryView (VBox parent, ChangeDirectoryEventHandler ev, string directory)
{
parent.Spacing = 2;
scrolledwindow = new ScrolledWindow ();
scrolledwindow.VscrollbarPolicy = PolicyType.Automatic;
scrolledwindow.HscrollbarPolicy = PolicyType.Automatic;
dir_icon = Gtk.IconTheme.Default.LoadIcon ("gtk-directory", 16, (Gtk.IconLookupFlags) 0);
Toolbar toolbar = new Toolbar ();
toolbar.IconSize = IconSize.Menu;
toolbar.ToolbarStyle = Gtk.ToolbarStyle.Icons;
goUp = new ToolButton (Gtk.Stock.GoUp);
goUp.Clicked += new EventHandler (OnGoUpClicked);
goUp.TooltipText = Catalog.GetString ("Go up one level");
toolbar.Insert (goUp, -1);
goHome = new ToolButton (Gtk.Stock.Home);
goHome.Clicked += new EventHandler (OnGoHomeClicked);
goHome.TooltipText = Catalog.GetString ("Home");
toolbar.Insert (goHome, -1);
entry = new ToolbarEntry ();
entry.Expand = true;
entry.Activated += new EventHandler (OnEntryActivated);
entry.TooltipText = Catalog.GetString ("Location");
toolbar.Insert (entry, -1);
toolbar.ShowAll ();
parent.PackStart (toolbar, false, true, 0);
tv = new Gtk.TreeView ();
tv.RulesHint = true;
TreeViewColumn directorycolumn = new TreeViewColumn ();
directorycolumn.Title = Catalog.GetString ("Directories");
CellRendererPixbuf pix_render = new CellRendererPixbuf ();
directorycolumn.PackStart (pix_render, false);
directorycolumn.AddAttribute (pix_render, "pixbuf", COL_PIXBUF);
text_render = new CellRendererText ();
directorycolumn.PackStart (text_render, false);
directorycolumn.AddAttribute (text_render, "text", COL_DISPLAY_NAME);
tv.AppendColumn (directorycolumn);
scrolledwindow.Add (tv);
parent.Homogeneous = false;
parent.PackEnd (new HSeparator (), false, false, 0);
parent.PackEnd (scrolledwindow);
parent.ShowAll ();
tv.Model = tree_store = CreateTreeStore ();
DirectoryChanged = ev;
tv.RowActivated += OnRowActivate;
current = new DirectoryInfo (directory);
ProcessNewDirectory (current.FullName);
}
public string Current {
get { return current.FullName; }
}
TreeStore CreateTreeStore ()
{
// name, path, pixbuf, is_dir
TreeStore store = new TreeStore (typeof (string), typeof (Gdk.Pixbuf), typeof (string));
return store;
}
void FillTreeStore ()
{
// first clear the store
tree_store.Clear ();
if (!current.Exists)
current = new DirectoryInfo ("/");
foreach (DirectoryInfo di in current.GetDirectories ())
{
if (di.Name.StartsWith ("."))
continue;
tree_store.AppendValues (di.Name, dir_icon, di.FullName);
}
}
void OnRowActivate (object o, RowActivatedArgs args)
{
TreeIter iter;
tree_store.GetIter (out iter, args.Path);
string path = (string) tree_store.GetValue (iter, COL_PATH);
ProcessNewDirectory (path);
}
void OnGoHomeClicked (object o, EventArgs args)
{
ProcessNewDirectory (Environment.GetFolderPath (Environment.SpecialFolder.Personal));
}
void OnGoUpClicked (object o, EventArgs args)
{
ProcessNewDirectory (current.Parent.FullName);
}
void ProcessNewDirectory (string path)
{
current = new DirectoryInfo (path);
FillTreeStore ();
if (DirectoryChanged != null)
DirectoryChanged (this, new ChangeDirectoryEventArgs (path));
goUp.Sensitive = (current.Parent != null);
entry.Text = current.FullName;
}
void OnEntryActivated (object sender, EventArgs args)
{
try {
string text = entry.Text.Trim ();
if (Directory.Exists (text)) {
ProcessNewDirectory (text);
return;
}
} catch (Exception) {}
}
}
}
| |
namespace SmartFighter {
partial class ConfigDialog {
/// <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.layout = new System.Windows.Forms.TableLayoutPanel();
this.apiLabel = new System.Windows.Forms.Label();
this.apiText = new System.Windows.Forms.TextBox();
this.player2Panel = new System.Windows.Forms.FlowLayoutPanel();
this.player2Button = new System.Windows.Forms.Button();
this.player2ButtonLabel = new System.Windows.Forms.Label();
this.actionLayout = new System.Windows.Forms.FlowLayoutPanel();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.nfcLabel = new System.Windows.Forms.Label();
this.nfcCombo = new System.Windows.Forms.ComboBox();
this.player1Label = new System.Windows.Forms.Label();
this.player1Panel = new System.Windows.Forms.FlowLayoutPanel();
this.player1Button = new System.Windows.Forms.Button();
this.player1ButtonLabel = new System.Windows.Forms.Label();
this.player2Label = new System.Windows.Forms.Label();
this.layout.SuspendLayout();
this.player2Panel.SuspendLayout();
this.actionLayout.SuspendLayout();
this.player1Panel.SuspendLayout();
this.SuspendLayout();
//
// layout
//
this.layout.ColumnCount = 2;
this.layout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.layout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.layout.Controls.Add(this.apiLabel, 0, 0);
this.layout.Controls.Add(this.apiText, 1, 0);
this.layout.Controls.Add(this.player2Panel, 1, 3);
this.layout.Controls.Add(this.actionLayout, 0, 5);
this.layout.Controls.Add(this.nfcLabel, 0, 1);
this.layout.Controls.Add(this.nfcCombo, 1, 1);
this.layout.Controls.Add(this.player1Label, 0, 2);
this.layout.Controls.Add(this.player1Panel, 1, 2);
this.layout.Controls.Add(this.player2Label, 0, 3);
this.layout.Dock = System.Windows.Forms.DockStyle.Fill;
this.layout.Location = new System.Drawing.Point(0, 0);
this.layout.Name = "layout";
this.layout.RowCount = 6;
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.layout.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.layout.Size = new System.Drawing.Size(425, 174);
this.layout.TabIndex = 0;
//
// apiLabel
//
this.apiLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.apiLabel.AutoSize = true;
this.apiLabel.Location = new System.Drawing.Point(3, 6);
this.apiLabel.Name = "apiLabel";
this.apiLabel.Size = new System.Drawing.Size(52, 13);
this.apiLabel.TabIndex = 0;
this.apiLabel.Text = "API URL:";
//
// apiText
//
this.apiText.Dock = System.Windows.Forms.DockStyle.Fill;
this.apiText.Location = new System.Drawing.Point(75, 3);
this.apiText.Name = "apiText";
this.apiText.Size = new System.Drawing.Size(347, 20);
this.apiText.TabIndex = 2;
//
// player2Panel
//
this.player2Panel.AutoSize = true;
this.player2Panel.Controls.Add(this.player2Button);
this.player2Panel.Controls.Add(this.player2ButtonLabel);
this.player2Panel.Dock = System.Windows.Forms.DockStyle.Fill;
this.player2Panel.Location = new System.Drawing.Point(75, 91);
this.player2Panel.Name = "player2Panel";
this.player2Panel.Size = new System.Drawing.Size(347, 29);
this.player2Panel.TabIndex = 8;
//
// player2Button
//
this.player2Button.Location = new System.Drawing.Point(3, 3);
this.player2Button.Name = "player2Button";
this.player2Button.Size = new System.Drawing.Size(75, 23);
this.player2Button.TabIndex = 0;
this.player2Button.Text = "Select";
this.player2Button.UseVisualStyleBackColor = true;
this.player2Button.Click += new System.EventHandler(this.player2Button_Click);
//
// player2ButtonLabel
//
this.player2ButtonLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.player2ButtonLabel.AutoSize = true;
this.player2ButtonLabel.Location = new System.Drawing.Point(84, 8);
this.player2ButtonLabel.Name = "player2ButtonLabel";
this.player2ButtonLabel.Size = new System.Drawing.Size(0, 13);
this.player2ButtonLabel.TabIndex = 1;
//
// actionLayout
//
this.actionLayout.AutoSize = true;
this.layout.SetColumnSpan(this.actionLayout, 2);
this.actionLayout.Controls.Add(this.okButton);
this.actionLayout.Controls.Add(this.cancelButton);
this.actionLayout.Dock = System.Windows.Forms.DockStyle.Right;
this.actionLayout.Location = new System.Drawing.Point(260, 142);
this.actionLayout.Name = "actionLayout";
this.actionLayout.Size = new System.Drawing.Size(162, 29);
this.actionLayout.TabIndex = 3;
//
// okButton
//
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Location = new System.Drawing.Point(3, 3);
this.okButton.Name = "okButton";
this.okButton.Size = new System.Drawing.Size(75, 23);
this.okButton.TabIndex = 0;
this.okButton.Text = "OK";
this.okButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(84, 3);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 1;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// nfcLabel
//
this.nfcLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.nfcLabel.AutoSize = true;
this.nfcLabel.Location = new System.Drawing.Point(3, 33);
this.nfcLabel.Name = "nfcLabel";
this.nfcLabel.Size = new System.Drawing.Size(66, 13);
this.nfcLabel.TabIndex = 4;
this.nfcLabel.Text = "NFC Reader";
//
// nfcCombo
//
this.nfcCombo.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.nfcCombo.FormattingEnabled = true;
this.nfcCombo.Location = new System.Drawing.Point(75, 29);
this.nfcCombo.Name = "nfcCombo";
this.nfcCombo.Size = new System.Drawing.Size(121, 21);
this.nfcCombo.TabIndex = 5;
//
// player1Label
//
this.player1Label.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.player1Label.AutoSize = true;
this.player1Label.Location = new System.Drawing.Point(3, 64);
this.player1Label.Name = "player1Label";
this.player1Label.Size = new System.Drawing.Size(45, 13);
this.player1Label.TabIndex = 6;
this.player1Label.Text = "Player 1";
//
// player1Panel
//
this.player1Panel.AutoSize = true;
this.player1Panel.Controls.Add(this.player1Button);
this.player1Panel.Controls.Add(this.player1ButtonLabel);
this.player1Panel.Dock = System.Windows.Forms.DockStyle.Fill;
this.player1Panel.Location = new System.Drawing.Point(75, 56);
this.player1Panel.Name = "player1Panel";
this.player1Panel.Size = new System.Drawing.Size(347, 29);
this.player1Panel.TabIndex = 7;
//
// player1Button
//
this.player1Button.Location = new System.Drawing.Point(3, 3);
this.player1Button.Name = "player1Button";
this.player1Button.Size = new System.Drawing.Size(75, 23);
this.player1Button.TabIndex = 0;
this.player1Button.Text = "Select";
this.player1Button.UseVisualStyleBackColor = true;
this.player1Button.Click += new System.EventHandler(this.Player1Button_Click);
//
// player1ButtonLabel
//
this.player1ButtonLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.player1ButtonLabel.AutoSize = true;
this.player1ButtonLabel.Location = new System.Drawing.Point(84, 8);
this.player1ButtonLabel.Name = "player1ButtonLabel";
this.player1ButtonLabel.Size = new System.Drawing.Size(0, 13);
this.player1ButtonLabel.TabIndex = 1;
//
// player2Label
//
this.player2Label.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.player2Label.AutoSize = true;
this.player2Label.Location = new System.Drawing.Point(3, 99);
this.player2Label.Name = "player2Label";
this.player2Label.Size = new System.Drawing.Size(45, 13);
this.player2Label.TabIndex = 8;
this.player2Label.Text = "Player 2";
//
// ConfigDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(425, 174);
this.Controls.Add(this.layout);
this.Name = "ConfigDialog";
this.Text = "ConfigDialog";
this.layout.ResumeLayout(false);
this.layout.PerformLayout();
this.player2Panel.ResumeLayout(false);
this.player2Panel.PerformLayout();
this.actionLayout.ResumeLayout(false);
this.player1Panel.ResumeLayout(false);
this.player1Panel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel layout;
private System.Windows.Forms.Label apiLabel;
private System.Windows.Forms.FlowLayoutPanel actionLayout;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
public System.Windows.Forms.TextBox apiText;
private System.Windows.Forms.Label nfcLabel;
public System.Windows.Forms.ComboBox nfcCombo;
private System.Windows.Forms.Label player1Label;
private System.Windows.Forms.FlowLayoutPanel player1Panel;
private System.Windows.Forms.Button player1Button;
private System.Windows.Forms.Label player1ButtonLabel;
private System.Windows.Forms.FlowLayoutPanel player2Panel;
private System.Windows.Forms.Button player2Button;
private System.Windows.Forms.Label player2ButtonLabel;
private System.Windows.Forms.Label player2Label;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str : FileSystemTest
{
#region Utilities
public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files
protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories
public virtual string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName);
}
#endregion
#region UniversalTests
[Fact]
public void NullFileName()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(null));
}
[Fact]
public void EmptyFileName()
{
Assert.Throws<ArgumentException>(() => GetEntries(string.Empty));
}
[Fact]
public void InvalidFileNames()
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist"));
Assert.Throws<ArgumentException>(() => GetEntries("\0"));
}
[Fact]
public void EmptyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Empty(GetEntries(testDir.FullName));
}
[Fact]
public void GetEntriesThenDelete()
{
string testDirPath = GetTestFilePath();
DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath);
testDirInfo.Create();
string testDir1 = GetTestFileName();
string testDir2 = GetTestFileName();
string testFile1 = GetTestFileName();
string testFile2 = GetTestFileName();
string testFile3 = GetTestFileName();
string testFile4 = GetTestFileName();
string testFile5 = GetTestFileName();
testDirInfo.CreateSubdirectory(testDir1);
testDirInfo.CreateSubdirectory(testDir2);
using (File.Create(Path.Combine(testDirPath, testFile1)))
using (File.Create(Path.Combine(testDirPath, testFile2)))
using (File.Create(Path.Combine(testDirPath, testFile3)))
{
string[] results;
using (File.Create(Path.Combine(testDirPath, testFile4)))
using (File.Create(Path.Combine(testDirPath, testFile5)))
{
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
Assert.Contains(Path.Combine(testDirPath, testFile4), results);
Assert.Contains(Path.Combine(testDirPath, testFile5), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir1), results);
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
File.Delete(Path.Combine(testDirPath, testFile4));
File.Delete(Path.Combine(testDirPath, testFile5));
FailSafeDirectoryOperations.DeleteDirectory(testDir1, true);
results = GetEntries(testDirPath);
Assert.NotNull(results);
Assert.NotEmpty(results);
if (TestFiles)
{
Assert.Contains(Path.Combine(testDirPath, testFile1), results);
Assert.Contains(Path.Combine(testDirPath, testFile2), results);
Assert.Contains(Path.Combine(testDirPath, testFile3), results);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDirPath, testDir2), results);
}
}
}
[Fact]
public void IgnoreSubDirectoryFiles()
{
string subDir = GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, subDir));
string testFile = Path.Combine(TestDirectory, GetTestFileName());
string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
string testDir = Path.Combine(TestDirectory, GetTestFileName());
string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName());
Directory.CreateDirectory(testDir);
Directory.CreateDirectory(testDirInSub);
using (File.Create(testFile))
using (File.Create(testFileInSub))
{
string[] results = GetEntries(TestDirectory);
if (TestFiles)
Assert.Contains(testFile, results);
if (TestDirectories)
Assert.Contains(testDir, results);
Assert.DoesNotContain(testFileInSub, results);
Assert.DoesNotContain(testDirInSub, results);
}
}
[Fact]
public void NonexistentPath()
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(GetTestFilePath()));
}
[Fact]
public void TrailingSlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5));
Assert.NotNull(strArr);
Assert.NotEmpty(strArr);
}
}
[Fact]
public void CurrentDirectory()
{
Assert.NotNull(GetEntries(Directory.GetCurrentDirectory()));
}
#endregion
#region PlatformSpecific
[Fact]
public void InvalidPath()
{
foreach (char invalid in Path.GetInvalidFileNameChars())
{
if (invalid == '/' || invalid == '\\')
{
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else if (invalid == ':')
{
if (FileSystemDebugInfo.IsCurrentDriveNTFS())
Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
else
{
Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString()))));
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsInvalidCharsPath()
{
Assert.All(WindowsInvalidUnixValid, invalid =>
Assert.Throws<ArgumentException>(() => GetEntries(invalid)));
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixValidCharsFilePath()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
string[] results = GetEntries(testDir.FullName);
Assert.All(WindowsInvalidUnixValid, valid =>
Assert.Contains(Path.Combine(testDir.FullName, valid), results));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixValidCharsDirectoryPath()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
string[] results = GetEntries(testDir.FullName);
Assert.All(WindowsInvalidUnixValid, valid =>
Assert.Contains(Path.Combine(testDir.FullName, valid), results));
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2010-2021, Achim Friedland <achim.friedland@graphdefined.com>
* This file is part of Vanaheimr Hermod <https://www.github.com/Vanaheimr/Hermod>
*
* 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.
*/
#region Usings
using System;
using System.IO;
#endregion
namespace org.GraphDefined.Vanaheimr.Hermod.DNS
{
/// <summary>
/// Start of Authority Resource Record
/// </summary>
public class SOA : ADNSResourceRecord
{
#region Data
public const UInt16 TypeId = 6;
#endregion
#region Properties
#region Server
private readonly String _Server;
public String Server
{
get
{
return _Server;
}
}
#endregion
#region Email
private readonly String _Email;
public String Email
{
get
{
return _Email;
}
}
#endregion
#region Serial
private readonly Int64 _Serial;
public Int64 Serial
{
get
{
return _Serial;
}
}
#endregion
#region Refresh
private readonly Int64 _Refresh;
public Int64 Refresh
{
get
{
return _Refresh;
}
}
#endregion
#region Retry
private readonly Int64 _Retry;
public Int64 Retry
{
get
{
return _Retry;
}
}
#endregion
#region Expire
private readonly Int64 _Expire;
public Int64 Expire
{
get
{
return _Expire;
}
}
#endregion
#region Minimum
private readonly Int64 _Minimum;
public Int64 Minimum
{
get
{
return _Minimum;
}
}
#endregion
#endregion
#region Constructor
#region SOA(Stream)
public SOA(Stream Stream)
: base(Stream, TypeId)
{
this._Server = DNSTools.ExtractName(Stream);
this._Email = DNSTools.ExtractName(Stream);
this._Serial = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Refresh = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Retry = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Expire = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Minimum = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
}
#endregion
#region SOA(Name, Stream)
public SOA(String Name,
Stream Stream)
: base(Name, TypeId, Stream)
{
this._Server = DNSTools.ExtractName(Stream);
this._Email = DNSTools.ExtractName(Stream);
this._Serial = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Refresh = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Retry = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Expire = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
this._Minimum = (Stream.ReadByte() & Byte.MaxValue) << 24 | (Stream.ReadByte() & Byte.MaxValue) << 16 | (Stream.ReadByte() & Byte.MaxValue) << 8 | Stream.ReadByte() & Byte.MaxValue;
}
#endregion
#region SOA(Name, Class, TimeToLive, ...)
public SOA(String Name,
DNSQueryClasses Class,
TimeSpan TimeToLive,
String Server,
String Email,
Int64 Serial,
Int64 Refresh,
Int64 Retry,
Int64 Expire,
Int64 Minimum)
: base(Name, TypeId, Class, TimeToLive)
{
this._Server = Server;
this._Email = Email;
this._Serial = Serial;
this._Refresh = Refresh;
this._Retry = Retry;
this._Expire = Expire;
this._Minimum = Minimum;
}
#endregion
#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.Diagnostics;
using System.Drawing.Drawing2D;
using System.Drawing.Internal;
using System.Globalization;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public sealed partial class Region : MarshalByRefObject, IDisposable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
internal IntPtr NativeRegion { get; private set; }
public Region()
{
Gdip.CheckStatus(Gdip.GdipCreateRegion(out IntPtr region));
SetNativeRegion(region);
}
public Region(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCreateRegionRect(ref rect, out IntPtr region));
SetNativeRegion(region);
}
public Region(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCreateRegionRectI(ref rect, out IntPtr region));
SetNativeRegion(region);
}
public Region(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCreateRegionPath(new HandleRef(path, path._nativePath), out IntPtr region));
SetNativeRegion(region);
}
public Region(RegionData rgnData)
{
if (rgnData == null)
throw new ArgumentNullException(nameof(rgnData));
Gdip.CheckStatus(Gdip.GdipCreateRegionRgnData(
rgnData.Data,
rgnData.Data.Length,
out IntPtr region));
SetNativeRegion(region);
}
internal Region(IntPtr nativeRegion) => SetNativeRegion(nativeRegion);
public static Region FromHrgn(IntPtr hrgn)
{
Gdip.CheckStatus(Gdip.GdipCreateRegionHrgn(hrgn, out IntPtr region));
return new Region(region);
}
private void SetNativeRegion(IntPtr nativeRegion)
{
if (nativeRegion == IntPtr.Zero)
throw new ArgumentNullException(nameof(nativeRegion));
NativeRegion = nativeRegion;
}
public Region Clone()
{
Gdip.CheckStatus(Gdip.GdipCloneRegion(new HandleRef(this, NativeRegion), out IntPtr region));
return new Region(region);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeRegion != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (NativeRegion != IntPtr.Zero)
{
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDeleteRegion(new HandleRef(this, NativeRegion));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex))
{
}
finally
{
NativeRegion = IntPtr.Zero;
}
}
}
~Region() => Dispose(false);
public void MakeInfinite()
{
Gdip.CheckStatus(Gdip.GdipSetInfinite(new HandleRef(this, NativeRegion)));
}
public void MakeEmpty()
{
Gdip.CheckStatus(Gdip.GdipSetEmpty(new HandleRef(this, NativeRegion)));
}
public void Intersect(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRect(new HandleRef(this, NativeRegion), ref rect, CombineMode.Intersect));
}
public void Intersect(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Intersect));
}
public void Intersect(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Intersect));
}
public void Intersect(Region region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Intersect));
}
public void Union(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRect(new HandleRef(this, NativeRegion), ref rect, CombineMode.Union));
}
public void Union(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Union));
}
public void Union(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Union));
}
public void Union(Region region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Union));
}
public void Xor(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRect(new HandleRef(this, NativeRegion), ref rect, CombineMode.Xor));
}
public void Xor(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Xor));
}
public void Xor(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Xor));
}
public void Xor(Region region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Xor));
}
public void Exclude(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRect(new HandleRef(this, NativeRegion), ref rect, CombineMode.Exclude));
}
public void Exclude(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Exclude));
}
public void Exclude(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCombineRegionPath(
new HandleRef(this, NativeRegion),
new HandleRef(path, path._nativePath),
CombineMode.Exclude));
}
public void Exclude(Region region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(
new HandleRef(this, NativeRegion),
new HandleRef(region, region.NativeRegion),
CombineMode.Exclude));
}
public void Complement(RectangleF rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRect(new HandleRef(this, NativeRegion), ref rect, CombineMode.Complement));
}
public void Complement(Rectangle rect)
{
Gdip.CheckStatus(Gdip.GdipCombineRegionRectI(new HandleRef(this, NativeRegion), ref rect, CombineMode.Complement));
}
public void Complement(GraphicsPath path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Gdip.CheckStatus(Gdip.GdipCombineRegionPath(new HandleRef(this, NativeRegion), new HandleRef(path, path._nativePath), CombineMode.Complement));
}
public void Complement(Region region)
{
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipCombineRegionRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), CombineMode.Complement));
}
public void Translate(float dx, float dy)
{
Gdip.CheckStatus(Gdip.GdipTranslateRegion(new HandleRef(this, NativeRegion), dx, dy));
}
public void Translate(int dx, int dy)
{
Gdip.CheckStatus(Gdip.GdipTranslateRegionI(new HandleRef(this, NativeRegion), dx, dy));
}
public void Transform(Matrix matrix)
{
if (matrix == null)
throw new ArgumentNullException(nameof(matrix));
Gdip.CheckStatus(Gdip.GdipTransformRegion(
new HandleRef(this, NativeRegion),
new HandleRef(matrix, matrix.NativeMatrix)));
}
public RectangleF GetBounds(Graphics g)
{
if (g == null)
throw new ArgumentNullException(nameof(g));
Gdip.CheckStatus(Gdip.GdipGetRegionBounds(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out RectangleF bounds));
return bounds;
}
public IntPtr GetHrgn(Graphics g)
{
if (g == null)
throw new ArgumentNullException(nameof(g));
Gdip.CheckStatus(Gdip.GdipGetRegionHRgn(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out IntPtr hrgn));
return hrgn;
}
public bool IsEmpty(Graphics g)
{
if (g == null)
throw new ArgumentNullException(nameof(g));
Gdip.CheckStatus(Gdip.GdipIsEmptyRegion(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out int isEmpty));
return isEmpty != 0;
}
public bool IsInfinite(Graphics g)
{
if (g == null)
throw new ArgumentNullException(nameof(g));
Gdip.CheckStatus(Gdip.GdipIsInfiniteRegion(new HandleRef(this, NativeRegion), new HandleRef(g, g.NativeGraphics), out int isInfinite));
return isInfinite != 0;
}
public bool Equals(Region region, Graphics g)
{
if (g == null)
throw new ArgumentNullException(nameof(g));
if (region == null)
throw new ArgumentNullException(nameof(region));
Gdip.CheckStatus(Gdip.GdipIsEqualRegion(new HandleRef(this, NativeRegion), new HandleRef(region, region.NativeRegion), new HandleRef(g, g.NativeGraphics), out int isEqual));
return isEqual != 0;
}
public RegionData GetRegionData()
{
Gdip.CheckStatus(Gdip.GdipGetRegionDataSize(new HandleRef(this, NativeRegion), out int regionSize));
if (regionSize == 0)
return null;
byte[] regionData = new byte[regionSize];
Gdip.CheckStatus(Gdip.GdipGetRegionData(new HandleRef(this, NativeRegion), regionData, regionSize, out regionSize));
return new RegionData(regionData);
}
public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y), null);
public bool IsVisible(PointF point) => IsVisible(point, null);
public bool IsVisible(float x, float y, Graphics g) => IsVisible(new PointF(x, y), g);
public bool IsVisible(PointF point, Graphics g)
{
Gdip.CheckStatus(Gdip.GdipIsVisibleRegionPoint(
new HandleRef(this, NativeRegion),
point.X, point.Y,
new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
out int isVisible));
return isVisible != 0;
}
public bool IsVisible(float x, float y, float width, float height) => IsVisible(new RectangleF(x, y, width, height), null);
public bool IsVisible(RectangleF rect) => IsVisible(rect, null);
public bool IsVisible(float x, float y, float width, float height, Graphics g) => IsVisible(new RectangleF(x, y, width, height), g);
public bool IsVisible(RectangleF rect, Graphics g)
{
Gdip.CheckStatus(Gdip.GdipIsVisibleRegionRect(
new HandleRef(this, NativeRegion),
rect.X, rect.Y, rect.Width, rect.Height,
new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
out int isVisible));
return isVisible != 0;
}
public bool IsVisible(int x, int y, Graphics g) => IsVisible(new Point(x, y), g);
public bool IsVisible(Point point) => IsVisible(point, null);
public bool IsVisible(Point point, Graphics g)
{
Gdip.CheckStatus(Gdip.GdipIsVisibleRegionPointI(
new HandleRef(this, NativeRegion),
point.X, point.Y,
new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
out int isVisible));
return isVisible != 0;
}
public bool IsVisible(int x, int y, int width, int height) => IsVisible(new Rectangle(x, y, width, height), null);
public bool IsVisible(Rectangle rect) => IsVisible(rect, null);
public bool IsVisible(int x, int y, int width, int height, Graphics g) => IsVisible(new Rectangle(x, y, width, height), g);
public bool IsVisible(Rectangle rect, Graphics g)
{
Gdip.CheckStatus(Gdip.GdipIsVisibleRegionRectI(
new HandleRef(this, NativeRegion),
rect.X, rect.Y, rect.Width, rect.Height,
new HandleRef(g, g?.NativeGraphics ?? IntPtr.Zero),
out int isVisible));
return isVisible != 0;
}
public unsafe RectangleF[] GetRegionScans(Matrix matrix)
{
if (matrix == null)
throw new ArgumentNullException(nameof(matrix));
Gdip.CheckStatus(Gdip.GdipGetRegionScansCount(
new HandleRef(this, NativeRegion),
out int count,
new HandleRef(matrix, matrix.NativeMatrix)));
RectangleF[] rectangles = new RectangleF[count];
// Pinning an empty array gives null, libgdiplus doesn't like this.
// As invoking isn't necessary, just return the empty array.
if (count == 0)
return rectangles;
fixed (RectangleF* r = rectangles)
{
Gdip.CheckStatus(Gdip.GdipGetRegionScans
(new HandleRef(this, NativeRegion),
r,
out count,
new HandleRef(matrix, matrix.NativeMatrix)));
}
return rectangles;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.Interoperability;
namespace SpatialAnalysis.Geometry
{
/// <summary>
/// A two dimensional point or vector
/// </summary>
public class UV : IComparable<UV>
{
/// <summary>
/// Gets or sets the u value.
/// </summary>
/// <value>The u.</value>
public double U { get; set; }
/// <summary>
/// Gets or sets the v value.
/// </summary>
/// <value>The v.</value>
public double V { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="UV"/> class.
/// </summary>
public UV()
{
this.U = 0;
this.V = 0;
}
public UV(UV uv)
{
this.U = uv.U;
this.V = uv.V;
}
/// <summary>
/// Initializes a new instance of the <see cref="UV"/> class.
/// </summary>
/// <param name="u">The u value.</param>
/// <param name="v">The v value.</param>
public UV(double u, double v)
{
this.U = u;
this.V = v;
}
#region Utility functions
/// <summary>
/// returns yje cross product value.
/// </summary>
/// <param name="vector2D">The vector2 d.</param>
/// <returns>System.Double.</returns>
public double CrossProductValue(UV vector2D)
{
return this.U * vector2D.V - this.V * vector2D.U;
}
/// <summary>
/// Rotates the this vector and returns the new UV.
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns>UV.</returns>
public UV RotateNew(double angle)
{
double x = Math.Cos(angle) * this.U - Math.Sin(angle) * this.V;
double y = Math.Sin(angle) * this.U + Math.Cos(angle) * this.V;
return new UV(x, y);
}
/// <summary>
/// Rotates this UV at the specified angle.
/// </summary>
/// <param name="angle">The angle.</param>
public void Rotate(double angle)
{
double x = Math.Cos(angle) * this.U - Math.Sin(angle) * this.V;
double y = Math.Sin(angle) * this.U + Math.Cos(angle) * this.V;
this.U = x;
this.V = y;
}
/// <summary>
/// Gets the length of the UV as a vector.
/// </summary>
/// <returns>System.Double.</returns>
public double GetLength()
{
return Math.Sqrt(this.U * this.U + this.V * this.V);
}
/// <summary>
/// Gets the length squared of this UV as a vector.
/// </summary>
/// <returns>System.Double.</returns>
public double GetLengthSquared()
{
return this.U * this.U + this.V * this.V;
}
/// <summary>
/// Gets the length squared between two UVs as points.
/// </summary>
/// <param name="a">Point a.</param>
/// <param name="b">Point b.</param>
/// <returns>System.Double.</returns>
public static double GetLengthSquared(UV a, UV b)
{
double _x = a.U - b.U, _y = a.V - b.V;
return _x*_x+_y*_y;
}
/// <summary>
/// Gets the distance between two UVs as points.
/// </summary>
/// <param name="a">Point a.</param>
/// <param name="b">Point b.</param>
/// <returns>System.Double.</returns>
public static double GetDistanceBetween(UV a, UV b)
{
return Math.Sqrt((a.U - b.U) * (a.U - b.U) + (a.V - b.V) * (a.V - b.V));
}
/// <summary>
/// Unitizes this instance.
/// </summary>
public void Unitize()
{
double length = this.GetLength();
if (length != 0)
{
this.U /= length;
this.V /= length;
}
}
/// <summary>
/// Almost the equals to.
/// </summary>
/// <param name="p">The p.</param>
/// <param name="DistTolerance">The dist tolerance.</param>
/// <returns><c>true</c> if almost equal, <c>false</c> otherwise.</returns>
public bool AlmostEqualsTo(object p, double DistTolerance = OSMDocument.AbsoluteTolerance)
{
UV xy = p as UV;
if (xy != null)
{
if (this.DistanceTo(xy) < DistTolerance)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the angle with the U axis on clockwise direction.
/// </summary>
/// <returns>System.Double.</returns>
public double Angle()
{
return this.AngleTo(UV.UBase);
}
/// <summary>
/// Returns the angle with another vector on clockwise direction.
/// </summary>
/// <param name="xy">The xy.</param>
/// <returns>System.Double.</returns>
public double AngleTo(UV xy)
{
if (this.Equals(UV.ZeroBase) || xy.Equals(UV.ZeroBase))
{
return 0.0d;
}
double dot = this.DotProduct(xy) / (this.GetLength() * xy.GetLength());
if (dot >= 1)
{
return 0;
}
if (dot <= -1)
{
return Math.PI;
}
double angle = Math.Acos(dot);
if (angle < 0)
{
angle = Math.PI - angle;
}
double cross = this.CrossProductValue(xy);
if (cross > 0)
{
angle *= -1;
}
return angle;
}
/// <summary>
/// Retrns the distance between this UV as a point from another UV point.
/// </summary>
/// <param name="p">P as a point.</param>
/// <returns>System.Double.</returns>
public double DistanceTo(UV p)
{
return Math.Sqrt((this.U - p.U) * (this.U - p.U) + (this.V - p.V) * (this.V - p.V));
}
/// <summary>
/// Returns the dot product of this UV as a vector with another UV
/// </summary>
/// <param name="v">V as a vector.</param>
/// <returns>System.Double.</returns>
public double DotProduct(UV v)
{
return this.U * v.U + this.V * v.V;
}
#endregion
#region Defining operators
/// <summary>
/// Implements the == operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="b">UV b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(UV a, UV b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null || (object)b == null)
{
return false;
}
return a.U == b.U && a.V == b.V;
}
/// <summary>
/// Implements the != operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="b">UV b.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(UV a, UV b)
{
return !(a == b);
}
/// <summary>
/// Implements the + operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="b">UV b.</param>
/// <returns>The result of the operator.</returns>
public static UV operator +(UV a, UV b)
{
return new UV(a.U + b.U, a.V + b.V);
}
/// <summary>
/// Implements the - operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="b">UV b.</param>
/// <returns>The result of the operator.</returns>
public static UV operator -(UV a, UV b)
{
return new UV(a.U - b.U, a.V - b.V);
}
/// <summary>
/// Implements the / operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="k">The scalar k.</param>
/// <returns>The result of the operator.</returns>
public static UV operator /(UV a, double k)
{
return new UV(a.U / k, a.V / k);
}
/// <summary>
/// Implements the * operator.
/// </summary>
/// <param name="a">UV a.</param>
/// <param name="k">The scalar k.</param>
/// <returns>The result of the operator.</returns>
public static UV operator *(UV a, double k)
{
return new UV(a.U * k, a.V * k);
}
/// <summary>
/// Implements the * operator.
/// </summary>
/// <param name="k">The scalar k.</param>
/// <param name="a">UV a.</param>
/// <returns>The result of the operator.</returns>
public static UV operator *(double k, UV a)
{
return new UV(a.U * k, a.V * k);
}
/// <summary>
/// The u base
/// </summary>
public static readonly UV UBase = new UV(1, 0);
/// <summary>
/// The v base
/// </summary>
public static readonly UV VBase = new UV(0, 1);
/// <summary>
/// The zero base
/// </summary>
public static readonly UV ZeroBase = new UV(0, 0);
#endregion
public override bool Equals(object p)
{
UV xy = p as UV;
if (xy != null)
{
if (this.U == xy.U && this.V == xy.V)
{
return true;
}
}
return false;
}
public override int GetHashCode()
{
int hash = 7;
hash = 71 * hash + this.U.GetHashCode();
hash = 71 * hash + this.V.GetHashCode();
return hash;
}
public override string ToString()
{
return string.Format("[{0}, {1}]", this.U.ToString(), this.V.ToString());
}
/// <summary>
/// Return ths distance of the UV as a point from a line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>System.Double.</returns>
public double DistanceTo(UVLine line)
{
double area = (line.Start - line.End).CrossProductValue(line.Start - this);
area = Math.Abs(area);
return area / line.GetLength();
}
/// <summary>
/// Returns the projection of this UV as a point from a specified line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>UV.</returns>
public UV Projection(UVLine line)
{
double u = (line.End - line.Start).DotProduct(this - line.Start);
u /= line.GetLength();
return line.FindPoint(u);
}
/// <summary>
/// Returns the closest distance of this UV as a point from a line .
/// </summary>
/// <param name="line">The line.</param>
/// <returns>System.Double.</returns>
public double ClosestDistance(UVLine line)
{
UV p = new UV();
double length = line.GetLength();
double u = (line.End - line.Start).DotProduct(this - line.Start);
u /= length;
if (u < 0)
{
p = line.Start;
}
else if (u > length)
{
p = line.End;
}
else
{
p = this.GetClosestPoint(line);
}
return p.DistanceTo(this);
}
/// <summary>
/// Gets the distance squared of this UV as a point from another UV as a point.
/// </summary>
/// <param name="point">The point.</param>
/// <returns>System.Double.</returns>
public double GetDistanceSquared(UV point)
{
return UV.GetLengthSquared(this, point);
}
/// <summary>
/// Gets the distance squared of this UV as a point from a line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>System.Double.</returns>
public double GetDistanceSquared(UVLine line)
{
UV vs = this - line.Start;
double vs2 = vs.GetLengthSquared();
UV ve = this - line.End;
double ve2 = ve.GetLengthSquared();
double area = vs.CrossProductValue(ve);
area *= area;
double d = UV.GetLengthSquared(line.Start, line.End);
double distSquared = area / d;
if (distSquared < vs2 - d || distSquared < ve2 - d)
{
distSquared = Math.Min(vs2, ve2);
}
return distSquared;
}
/// <summary>
/// Gets the closest point of this UV as a point from a line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>UV.</returns>
public UV GetClosestPoint(UVLine line)
{
double length = line.GetLength();
double u = (line.End - line.Start).DotProduct(this - line.Start);
u /= length;
if (u < 0)
{
return line.Start;
}
if (u > length)
{
return line.End;
}
return line.FindPoint(u);
}
/// <summary>
/// Gets the closest point of this UV as a point from a line.
/// </summary>
/// <param name="line">The line.</param>
/// <param name="isEndPoint">if set to <c>true</c> the closest point is the end point of the line.</param>
/// <returns>UV.</returns>
public UV GetClosestPoint(UVLine line, ref bool isEndPoint)
{
double length = line.GetLength();
double u = (line.End - line.Start).DotProduct(this - line.Start);
u /= length;
if (u < 0)
{
isEndPoint = true;
return line.Start;
}
if (u > length)
{
isEndPoint = true;
return line.End;
}
isEndPoint = false;
return line.FindPoint(u);
}
/// <summary>
/// Shows the point in the BIM environment.
/// </summary>
/// <param name="visualizer">The visualizer.</param>
/// <param name="size">The size of the cross.</param>
/// <param name="elevation">The elevation.</param>
public void ShowPoint(I_OSM_To_BIM visualizer, double size, double elevation = 0.0d)
{
visualizer.VisualizePoint(this, size, elevation);
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This object is equal to <paramref name="other" />. Greater than zero This object is greater than <paramref name="other" />.</returns>
public int CompareTo(UV other)
{
int uCompared = this.U.CompareTo(other.U);
if (uCompared != 0)
{
return uCompared;
}
return this.V.CompareTo(other.V);
}
/// <summary>
/// Gets the reflection of this UV as a vector from another UV as a vector.
/// </summary>
/// <param name="vector">The vector.</param>
/// <returns>UV.</returns>
public UV GetReflection(UV vector)
{
if (vector.GetLengthSquared() != 1)
{
vector.Unitize();
}
double dotPro = this.DotProduct(vector);
UV horizontal_Component = vector * dotPro;
UV normal_Component = this - horizontal_Component;
var result = horizontal_Component - normal_Component;
return result;
}
/// <summary>
/// Gets the reflection of this UV as a vector from a line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns>UV.</returns>
public UV GetReflection(UVLine line)
{
var vector = line.GetDirection();
vector.Unitize();
double dotPro = this.DotProduct(vector);
UV horizontal_Component = vector * dotPro;
UV normal_Component = this - horizontal_Component;
var result = horizontal_Component - normal_Component;
return result;
}
/// <summary>
/// Copies this instance deeply.
/// </summary>
/// <returns>UV.</returns>
public UV Copy()
{
return new UV(this.U, this.V);
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Access to the Field Info file that describes document fields and whether or
/// not they are indexed. Each segment has a separate Field Info file. Objects
/// of this class are thread-safe for multiple readers, but only one thread can
/// be adding documents at a time, with no other reader or writer threads
/// accessing this object.
///
/// </summary>
public sealed class FieldInfo
{
/// <summary>
/// Field's name </summary>
public readonly string Name;
/// <summary>
/// Internal field number </summary>
public readonly int Number;
private bool indexed;
private DocValuesType_e? docValueType;
// True if any document indexed term vectors
private bool StoreTermVector;
private DocValuesType_e? NormTypeValue;
private bool OmitNorms; // omit norms associated with indexed fields
private IndexOptions? IndexOptionsValue;
private bool StorePayloads; // whether this field stores payloads together with term positions
private IDictionary<string, string> Attributes_Renamed;
private long DvGen = -1; // the DocValues generation of this field
/// <summary>
/// Controls how much information is stored in the postings lists.
/// @lucene.experimental
/// </summary>
public enum IndexOptions
{
// NOTE: order is important here; FieldInfo uses this
// order to merge two conflicting IndexOptions (always
// "downgrades" by picking the lowest).
/// <summary>
/// Only documents are indexed: term frequencies and positions are omitted.
/// Phrase and other positional queries on the field will throw an exception, and scoring
/// will behave as if any term in the document appears only once.
/// </summary>
// TODO: maybe rename to just DOCS?
DOCS_ONLY,
/// <summary>
/// Only documents and term frequencies are indexed: positions are omitted.
/// this enables normal scoring, except Phrase and other positional queries
/// will throw an exception.
/// </summary>
DOCS_AND_FREQS,
/// <summary>
/// Indexes documents, frequencies and positions.
/// this is a typical default for full-text search: full scoring is enabled
/// and positional queries are supported.
/// </summary>
DOCS_AND_FREQS_AND_POSITIONS,
/// <summary>
/// Indexes documents, frequencies, positions and offsets.
/// Character offsets are encoded alongside the positions.
/// </summary>
DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS
}
/// <summary>
/// DocValues types.
/// Note that DocValues is strongly typed, so a field cannot have different types
/// across different documents.
/// </summary>
public enum DocValuesType_e
{
/// <summary>
/// A per-document Number
/// </summary>
NUMERIC,
/// <summary>
/// A per-document byte[]. Values may be larger than
/// 32766 bytes, but different codecs may enforce their own limits.
/// </summary>
BINARY,
/// <summary>
/// A pre-sorted byte[]. Fields with this type only store distinct byte values
/// and store an additional offset pointer per document to dereference the shared
/// byte[]. The stored byte[] is presorted and allows access via document id,
/// ordinal and by-value. Values must be <= 32766 bytes.
/// </summary>
SORTED,
/// <summary>
/// A pre-sorted Set<byte[]>. Fields with this type only store distinct byte values
/// and store additional offset pointers per document to dereference the shared
/// byte[]s. The stored byte[] is presorted and allows access via document id,
/// ordinal and by-value. Values must be <= 32766 bytes.
/// </summary>
SORTED_SET
}
/// <summary>
/// Sole Constructor.
///
/// @lucene.experimental
/// </summary>
public FieldInfo(string name, bool indexed, int number, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions? indexOptions, DocValuesType_e? docValues, DocValuesType_e? normsType, IDictionary<string, string> attributes)
{
this.Name = name;
this.indexed = indexed;
this.Number = number;
this.docValueType = docValues;
if (indexed)
{
this.StoreTermVector = storeTermVector;
this.StorePayloads = storePayloads;
this.OmitNorms = omitNorms;
this.IndexOptionsValue = indexOptions;
this.NormTypeValue = !omitNorms ? normsType : null;
} // for non-indexed fields, leave defaults
else
{
this.StoreTermVector = false;
this.StorePayloads = false;
this.OmitNorms = false;
this.IndexOptionsValue = null;
this.NormTypeValue = null;
}
this.Attributes_Renamed = attributes;
Debug.Assert(CheckConsistency());
}
private bool CheckConsistency()
{
if (!indexed)
{
Debug.Assert(!StoreTermVector);
Debug.Assert(!StorePayloads);
Debug.Assert(!OmitNorms);
Debug.Assert(NormTypeValue == null);
Debug.Assert(IndexOptionsValue == null);
}
else
{
Debug.Assert(IndexOptionsValue != null);
if (OmitNorms)
{
Debug.Assert(NormTypeValue == null);
}
// Cannot store payloads unless positions are indexed:
Debug.Assert(((int)IndexOptionsValue.GetValueOrDefault() >= (int)IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) || !this.StorePayloads);
}
return true;
}
internal void Update(IndexableFieldType ft)
{
Update(ft.Indexed, false, ft.OmitNorms, false, ft.IndexOptions);
}
// should only be called by FieldInfos#addOrUpdate
internal void Update(bool indexed, bool storeTermVector, bool omitNorms, bool storePayloads, IndexOptions? indexOptions)
{
//System.out.println("FI.update field=" + name + " indexed=" + indexed + " omitNorms=" + omitNorms + " this.omitNorms=" + this.omitNorms);
if (this.indexed != indexed)
{
this.indexed = true; // once indexed, always index
}
if (indexed) // if updated field data is not for indexing, leave the updates out
{
if (this.StoreTermVector != storeTermVector)
{
this.StoreTermVector = true; // once vector, always vector
}
if (this.StorePayloads != storePayloads)
{
this.StorePayloads = true;
}
if (this.OmitNorms != omitNorms)
{
this.OmitNorms = true; // if one require omitNorms at least once, it remains off for life
this.NormTypeValue = null;
}
if (this.IndexOptionsValue != indexOptions)
{
if (this.IndexOptionsValue == null)
{
this.IndexOptionsValue = indexOptions;
}
else
{
// downgrade
IndexOptionsValue = (int)IndexOptionsValue.GetValueOrDefault() < (int)indexOptions ? IndexOptionsValue : indexOptions;
}
if ((int)IndexOptionsValue.GetValueOrDefault() < (int)FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
// cannot store payloads if we don't store positions:
this.StorePayloads = false;
}
}
}
Debug.Assert(CheckConsistency());
}
public DocValuesType_e? DocValuesType
{
set
{
if (docValueType != null && docValueType != value)
{
throw new System.ArgumentException("cannot change DocValues type from " + docValueType + " to " + value + " for field \"" + Name + "\"");
}
docValueType = value;
Debug.Assert(CheckConsistency());
}
get
{
return docValueType;
}
}
/// <summary>
/// Returns IndexOptions for the field, or null if the field is not indexed </summary>
public IndexOptions? FieldIndexOptions
{
get
{
return IndexOptionsValue;
}
}
/// <summary>
/// Returns true if this field has any docValues.
/// </summary>
public bool HasDocValues()
{
return docValueType != null;
}
/// <summary>
/// Sets the docValues generation of this field. </summary>
public long DocValuesGen
{
set
{
this.DvGen = value;
}
get
{
return DvGen;
}
}
/// <summary>
/// Returns <seealso cref="DocValuesType_e"/> of the norm. this may be null if the field has no norms.
/// </summary>
public DocValuesType_e? NormType
{
get
{
return NormTypeValue;
}
set
{
if (NormTypeValue != null && NormTypeValue != value)
{
throw new System.ArgumentException("cannot change Norm type from " + NormTypeValue + " to " + value + " for field \"" + Name + "\"");
}
NormTypeValue = value;
Debug.Assert(CheckConsistency());
}
}
internal void SetStoreTermVectors()
{
StoreTermVector = true;
Debug.Assert(CheckConsistency());
}
public void SetStorePayloads()
{
if (indexed && (int)IndexOptionsValue.GetValueOrDefault() >= (int)FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
StorePayloads = true;
}
Debug.Assert(CheckConsistency());
}
/// <summary>
/// Returns true if norms are explicitly omitted for this field
/// </summary>
public bool OmitsNorms()
{
return OmitNorms;
}
/// <summary>
/// Returns true if this field actually has any norms.
/// </summary>
public bool HasNorms()
{
return NormTypeValue != null;
}
/// <summary>
/// Returns true if this field is indexed.
/// </summary>
public bool Indexed
{
get
{
return indexed;
}
}
/// <summary>
/// Returns true if any payloads exist for this field.
/// </summary>
public bool HasPayloads()
{
return StorePayloads;
}
/// <summary>
/// Returns true if any term vectors exist for this field.
/// </summary>
public bool HasVectors()
{
return StoreTermVector;
}
/// <summary>
/// Get a codec attribute value, or null if it does not exist
/// </summary>
public string GetAttribute(string key)
{
if (Attributes_Renamed == null)
{
return null;
}
else
{
string ret;
Attributes_Renamed.TryGetValue(key, out ret);
return ret;
}
}
/// <summary>
/// Puts a codec attribute value.
/// <p>
/// this is a key-value mapping for the field that the codec can use
/// to store additional metadata, and will be available to the codec
/// when reading the segment via <seealso cref="#getAttribute(String)"/>
/// <p>
/// If a value already exists for the field, it will be replaced with
/// the new value.
/// </summary>
public string PutAttribute(string key, string value)
{
if (Attributes_Renamed == null)
{
Attributes_Renamed = new Dictionary<string, string>();
}
string ret;
// The key was not previously assigned, null will be returned
if (!Attributes_Renamed.TryGetValue(key, out ret))
{
ret = null;
}
Attributes_Renamed[key] = value;
return ret;
}
/// <summary>
/// Returns internal codec attributes map. May be null if no mappings exist.
/// </summary>
public IDictionary<string, string> Attributes()
{
return Attributes_Renamed;
}
}
}
| |
// 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.CompilerServices;
using Microsoft.Xunit.Performance;
using System.Collections.Generic;
using System.Linq;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public decimal UnitPrice { get; set; }
public int UnitsInStock { get; set; }
private static List<Product> s_productList;
public static List<Product> GetProductList()
{
if (s_productList == null)
CreateLists();
return s_productList;
}
private static void CreateLists()
{
s_productList =
new List<Product> {
new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 },
new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 },
new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 },
new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 },
new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 },
new Product { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120 },
new Product { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15 },
new Product { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6 },
new Product { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29 },
new Product { ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31 },
new Product { ProductID = 11, ProductName = "Queso Cabrales", Category = "Dairy Products", UnitPrice = 21.0000M, UnitsInStock = 22 },
new Product { ProductID = 12, ProductName = "Queso Manchego La Pastora", Category = "Dairy Products", UnitPrice = 38.0000M, UnitsInStock = 86 },
new Product { ProductID = 13, ProductName = "Konbu", Category = "Seafood", UnitPrice = 6.0000M, UnitsInStock = 24 },
new Product { ProductID = 14, ProductName = "Tofu", Category = "Produce", UnitPrice = 23.2500M, UnitsInStock = 35 },
new Product { ProductID = 15, ProductName = "Genen Shouyu", Category = "Condiments", UnitPrice = 15.5000M, UnitsInStock = 39 },
new Product { ProductID = 16, ProductName = "Pavlova", Category = "Confections", UnitPrice = 17.4500M, UnitsInStock = 29 },
new Product { ProductID = 17, ProductName = "Alice Mutton", Category = "Meat/Poultry", UnitPrice = 39.0000M, UnitsInStock = 0 },
new Product { ProductID = 18, ProductName = "Carnarvon Tigers", Category = "Seafood", UnitPrice = 62.5000M, UnitsInStock = 42 },
new Product { ProductID = 19, ProductName = "Teatime Chocolate Biscuits", Category = "Confections", UnitPrice = 9.2000M, UnitsInStock = 25 },
new Product { ProductID = 20, ProductName = "Sir Rodney's Marmalade", Category = "Confections", UnitPrice = 81.0000M, UnitsInStock = 40 },
new Product { ProductID = 21, ProductName = "Sir Rodney's Scones", Category = "Confections", UnitPrice = 10.0000M, UnitsInStock = 3 },
new Product { ProductID = 22, ProductName = "Gustaf's Kn\u00E4ckebr\u00F6d", Category = "Grains/Cereals", UnitPrice = 21.0000M, UnitsInStock = 104 },
new Product { ProductID = 23, ProductName = "Tunnbr\u00F6d", Category = "Grains/Cereals", UnitPrice = 9.0000M, UnitsInStock = 61 },
new Product { ProductID = 24, ProductName = "Guaran\u00E1 Fant\u00E1stica", Category = "Beverages", UnitPrice = 4.5000M, UnitsInStock = 20 },
new Product { ProductID = 25, ProductName = "NuNuCa Nu\u00DF-Nougat-Creme", Category = "Confections", UnitPrice = 14.0000M, UnitsInStock = 76 },
new Product { ProductID = 26, ProductName = "Gumb\u00E4r Gummib\u00E4rchen", Category = "Confections", UnitPrice = 31.2300M, UnitsInStock = 15 },
new Product { ProductID = 27, ProductName = "Schoggi Schokolade", Category = "Confections", UnitPrice = 43.9000M, UnitsInStock = 49 },
new Product { ProductID = 28, ProductName = "R\u00F6ssle Sauerkraut", Category = "Produce", UnitPrice = 45.6000M, UnitsInStock = 26 },
new Product { ProductID = 29, ProductName = "Th\u00FCringer Rostbratwurst", Category = "Meat/Poultry", UnitPrice = 123.7900M, UnitsInStock = 0 },
new Product { ProductID = 30, ProductName = "Nord-Ost Matjeshering", Category = "Seafood", UnitPrice = 25.8900M, UnitsInStock = 10 },
new Product { ProductID = 31, ProductName = "Gorgonzola Telino", Category = "Dairy Products", UnitPrice = 12.5000M, UnitsInStock = 0 },
new Product { ProductID = 32, ProductName = "Mascarpone Fabioli", Category = "Dairy Products", UnitPrice = 32.0000M, UnitsInStock = 9 },
new Product { ProductID = 33, ProductName = "Geitost", Category = "Dairy Products", UnitPrice = 2.5000M, UnitsInStock = 112 },
new Product { ProductID = 34, ProductName = "Sasquatch Ale", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 111 },
new Product { ProductID = 35, ProductName = "Steeleye Stout", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 20 },
new Product { ProductID = 36, ProductName = "Inlagd Sill", Category = "Seafood", UnitPrice = 19.0000M, UnitsInStock = 112 },
new Product { ProductID = 37, ProductName = "Gravad lax", Category = "Seafood", UnitPrice = 26.0000M, UnitsInStock = 11 },
new Product { ProductID = 38, ProductName = "C\u00F4te de Blaye", Category = "Beverages", UnitPrice = 263.5000M, UnitsInStock = 17 },
new Product { ProductID = 39, ProductName = "Chartreuse verte", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 69 },
new Product { ProductID = 40, ProductName = "Boston Crab Meat", Category = "Seafood", UnitPrice = 18.4000M, UnitsInStock = 123 },
new Product { ProductID = 41, ProductName = "Jack's New England Clam Chowder", Category = "Seafood", UnitPrice = 9.6500M, UnitsInStock = 85 },
new Product { ProductID = 42, ProductName = "Singaporean Hokkien Fried Mee", Category = "Grains/Cereals", UnitPrice = 14.0000M, UnitsInStock = 26 },
new Product { ProductID = 43, ProductName = "Ipoh Coffee", Category = "Beverages", UnitPrice = 46.0000M, UnitsInStock = 17 },
new Product { ProductID = 44, ProductName = "Gula Malacca", Category = "Condiments", UnitPrice = 19.4500M, UnitsInStock = 27 },
new Product { ProductID = 45, ProductName = "Rogede sild", Category = "Seafood", UnitPrice = 9.5000M, UnitsInStock = 5 },
new Product { ProductID = 46, ProductName = "Spegesild", Category = "Seafood", UnitPrice = 12.0000M, UnitsInStock = 95 },
new Product { ProductID = 47, ProductName = "Zaanse koeken", Category = "Confections", UnitPrice = 9.5000M, UnitsInStock = 36 },
new Product { ProductID = 48, ProductName = "Chocolade", Category = "Confections", UnitPrice = 12.7500M, UnitsInStock = 15 },
new Product { ProductID = 49, ProductName = "Maxilaku", Category = "Confections", UnitPrice = 20.0000M, UnitsInStock = 10 },
new Product { ProductID = 50, ProductName = "Valkoinen suklaa", Category = "Confections", UnitPrice = 16.2500M, UnitsInStock = 65 },
new Product { ProductID = 51, ProductName = "Manjimup Dried Apples", Category = "Produce", UnitPrice = 53.0000M, UnitsInStock = 20 },
new Product { ProductID = 52, ProductName = "Filo Mix", Category = "Grains/Cereals", UnitPrice = 7.0000M, UnitsInStock = 38 },
new Product { ProductID = 53, ProductName = "Perth Pasties", Category = "Meat/Poultry", UnitPrice = 32.8000M, UnitsInStock = 0 },
new Product { ProductID = 54, ProductName = "Tourti\u00E8re", Category = "Meat/Poultry", UnitPrice = 7.4500M, UnitsInStock = 21 },
new Product { ProductID = 55, ProductName = "P\u00E2t\u00E9 chinois", Category = "Meat/Poultry", UnitPrice = 24.0000M, UnitsInStock = 115 },
new Product { ProductID = 56, ProductName = "Gnocchi di nonna Alice", Category = "Grains/Cereals", UnitPrice = 38.0000M, UnitsInStock = 21 },
new Product { ProductID = 57, ProductName = "Ravioli Angelo", Category = "Grains/Cereals", UnitPrice = 19.5000M, UnitsInStock = 36 },
new Product { ProductID = 58, ProductName = "Escargots de Bourgogne", Category = "Seafood", UnitPrice = 13.2500M, UnitsInStock = 62 },
new Product { ProductID = 59, ProductName = "Raclette Courdavault", Category = "Dairy Products", UnitPrice = 55.0000M, UnitsInStock = 79 },
new Product { ProductID = 60, ProductName = "Camembert Pierrot", Category = "Dairy Products", UnitPrice = 34.0000M, UnitsInStock = 19 },
new Product { ProductID = 61, ProductName = "Sirop d'\u00E9rable", Category = "Condiments", UnitPrice = 28.5000M, UnitsInStock = 113 },
new Product { ProductID = 62, ProductName = "Tarte au sucre", Category = "Confections", UnitPrice = 49.3000M, UnitsInStock = 17 },
new Product { ProductID = 63, ProductName = "Vegie-spread", Category = "Condiments", UnitPrice = 43.9000M, UnitsInStock = 24 },
new Product { ProductID = 64, ProductName = "Wimmers gute Semmelkn\u00F6del", Category = "Grains/Cereals", UnitPrice = 33.2500M, UnitsInStock = 22 },
new Product { ProductID = 65, ProductName = "Louisiana Fiery Hot Pepper Sauce", Category = "Condiments", UnitPrice = 21.0500M, UnitsInStock = 76 },
new Product { ProductID = 66, ProductName = "Louisiana Hot Spiced Okra", Category = "Condiments", UnitPrice = 17.0000M, UnitsInStock = 4 },
new Product { ProductID = 67, ProductName = "Laughing Lumberjack Lager", Category = "Beverages", UnitPrice = 14.0000M, UnitsInStock = 52 },
new Product { ProductID = 68, ProductName = "Scottish Longbreads", Category = "Confections", UnitPrice = 12.5000M, UnitsInStock = 6 },
new Product { ProductID = 69, ProductName = "Gudbrandsdalsost", Category = "Dairy Products", UnitPrice = 36.0000M, UnitsInStock = 26 },
new Product { ProductID = 70, ProductName = "Outback Lager", Category = "Beverages", UnitPrice = 15.0000M, UnitsInStock = 15 },
new Product { ProductID = 71, ProductName = "Flotemysost", Category = "Dairy Products", UnitPrice = 21.5000M, UnitsInStock = 26 },
new Product { ProductID = 72, ProductName = "Mozzarella di Giovanni", Category = "Dairy Products", UnitPrice = 34.8000M, UnitsInStock = 14 },
new Product { ProductID = 73, ProductName = "R\u00F6d Kaviar", Category = "Seafood", UnitPrice = 15.0000M, UnitsInStock = 101 },
new Product { ProductID = 74, ProductName = "Longlife Tofu", Category = "Produce", UnitPrice = 10.0000M, UnitsInStock = 4 },
new Product { ProductID = 75, ProductName = "Rh\u00F6nbr\u00E4u Klosterbier", Category = "Beverages", UnitPrice = 7.7500M, UnitsInStock = 125 },
new Product { ProductID = 76, ProductName = "Lakkalik\u00F6\u00F6ri", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 57 },
new Product { ProductID = 77, ProductName = "Original Frankfurter gr\u00FCne So\u00DFe", Category = "Condiments", UnitPrice = 13.0000M, UnitsInStock = 32 }
};
}
}
public class LinqBenchmarks
{
#if DEBUG
public const int IterationsWhere00 = 1;
public const int IterationsWhere01 = 1;
public const int IterationsCount00 = 1;
public const int IterationsOrder00 = 1;
#else
public const int IterationsWhere00 = 1000000;
public const int IterationsWhere01 = 250000;
public const int IterationsCount00 = 1000000;
public const int IterationsOrder00 = 25000;
#endif
private static volatile object s_volatileObject;
private static void Escape(object obj)
{
s_volatileObject = obj;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool Bench()
{
bool result = true;
result &= Where00();
result &= Where01();
result &= Count00();
result &= Order00();
return result;
}
#region Where00
private bool Where00()
{
bool result = true;
result &= Where00For();
result &= Where00LinqMethod();
result &= Where00LinqQuery();
return result;
}
[Benchmark]
private bool Where00LinqQueryX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where00LinqQuery();
}
}
return result;
}
private bool Where00LinqQuery()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere00; i++)
{
var soldOutProducts =
from prod in products
where prod.UnitsInStock == 0
select prod;
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 5 * IterationsWhere00);
}
[Benchmark]
private bool Where00LinqMethodX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where00LinqMethod();
}
}
return result;
}
private bool Where00LinqMethod()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere00; i++)
{
var soldOutProducts = products.Where(p => p.UnitsInStock == 0);
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 5 * IterationsWhere00);
}
[Benchmark]
private bool Where00ForX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where00For();
}
}
return result;
}
private bool Where00For()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere00; i++)
{
List<Product> soldOutProducts = new List<Product>();
foreach (Product p in products)
{
if (p.UnitsInStock == 0)
{
soldOutProducts.Add(p);
}
}
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 5 * IterationsWhere00);
}
#endregion
#region Where01
private bool Where01()
{
bool result = true;
result &= Where01For();
result &= Where01LinqMethod();
result &= Where01LinqQuery();
return result;
}
[Benchmark]
private bool Where01LinqQueryX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where01LinqQuery();
}
}
return result;
}
private bool Where01LinqQuery()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere01; i++)
{
var expensiveInStockProducts =
from prod in products
where prod.UnitsInStock > 0 && prod.UnitPrice > 60.00M
select prod;
foreach (var product in expensiveInStockProducts)
{
count++;
}
}
return (count == 4 * IterationsWhere01);
}
[Benchmark]
private bool Where01LinqMethodX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where01LinqMethod();
}
}
return result;
}
private bool Where01LinqMethod()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere01; i++)
{
var soldOutProducts = products.Where(p => p.UnitsInStock > 0 && p.UnitPrice > 60.00M);
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 4 * IterationsWhere01);
}
[Benchmark]
private bool Where01LinqMethodNestedX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where01LinqMethodNested();
}
}
return result;
}
private bool Where01LinqMethodNested()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere01; i++)
{
var soldOutProducts = products.Where(p => p.UnitsInStock > 0).Where(p => p.UnitPrice > 60.00M);
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 4 * IterationsWhere01);
}
[Benchmark]
private bool Where01ForX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Where01For();
}
}
return result;
}
private bool Where01For()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsWhere01; i++)
{
List<Product> soldOutProducts = new List<Product>();
foreach (Product p in products)
{
if (p.UnitsInStock > 0 && p.UnitPrice > 60.00M)
{
soldOutProducts.Add(p);
}
}
foreach (var product in soldOutProducts)
{
count++;
}
}
return (count == 4 * IterationsWhere01);
}
#endregion
#region Count00
private bool Count00()
{
bool result = true;
result &= Count00For();
result &= Count00LinqMethod();
return result;
}
[Benchmark]
private bool Count00LinqMethodX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Count00LinqMethod();
}
}
return result;
}
private bool Count00LinqMethod()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsCount00; i++)
{
count += products.Count(p => p.UnitsInStock == 0);
}
return (count == 5 * IterationsCount00);
}
[Benchmark]
private bool Count00ForX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Count00For();
}
}
return result;
}
private bool Count00For()
{
List<Product> products = Product.GetProductList();
int count = 0;
for (int i = 0; i < IterationsCount00; i++)
{
foreach (Product p in products)
{
if (p.UnitsInStock == 0)
{
count++;
}
}
}
return (count == 5 * IterationsCount00);
}
#endregion
#region Order00
private bool Order00()
{
bool result = true;
result &= Order00Manual();
result &= Order00LinqMethod();
result &= Order00LinqQuery();
return result;
}
[Benchmark]
private bool Order00LinqQueryX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Order00LinqQuery();
}
}
return result;
}
private bool Order00LinqQuery()
{
List<Product> products = Product.GetProductList();
Product medianPricedProduct = null;
for (int i = 0; i < IterationsOrder00; i++)
{
var productsInPriceOrder = from prod in products orderby prod.UnitPrice descending select prod;
int count = productsInPriceOrder.Count();
medianPricedProduct = productsInPriceOrder.ElementAt<Product>(count / 2);
Escape(medianPricedProduct);
}
return (medianPricedProduct.ProductID == 57);
}
[Benchmark]
private bool Order00LinqMethodX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Order00LinqMethod();
}
}
return result;
}
private bool Order00LinqMethod()
{
List<Product> products = Product.GetProductList();
Product medianPricedProduct = null;
for (int i = 0; i < IterationsOrder00; i++)
{
var productsInPriceOrder = products.OrderByDescending(p => p.UnitPrice);
int count = productsInPriceOrder.Count();
medianPricedProduct = productsInPriceOrder.ElementAt<Product>(count / 2);
Escape(medianPricedProduct);
}
return (medianPricedProduct.ProductID == 57);
}
[Benchmark]
private bool Order00ManualX()
{
bool result = true;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
result &= Order00Manual();
}
}
return result;
}
private bool Order00Manual()
{
List<Product> products = Product.GetProductList();
Product medianPricedProduct = null;
for (int i = 0; i < IterationsOrder00; i++)
{
Product[] productsInPriceOrder = products.ToArray<Product>();
Array.Sort<Product>(productsInPriceOrder, delegate (Product x, Product y) { return -x.UnitPrice.CompareTo(y.UnitPrice); });
int count = productsInPriceOrder.Count();
medianPricedProduct = productsInPriceOrder[count / 2];
Escape(medianPricedProduct);
}
return (medianPricedProduct.ProductID == 57);
}
#endregion
public static int Main()
{
var tests = new LinqBenchmarks();
bool result = tests.Bench();
return result ? 100 : -1;
}
}
| |
using Gedcomx.Model.Rt;
using Gedcomx.Model.Util;
using Gx.Common;
using Gx.Records;
using Gx.Types;
// <auto-generated>
//
//
// Generated by <a href="http://enunciate.codehaus.org">Enunciate</a>.
// </auto-generated>
using System;
using System.Collections.Generic;
namespace Gx.Conclusion
{
/// <remarks>
/// A part of a name.
/// </remarks>
/// <summary>
/// A part of a name.
/// </summary>
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://gedcomx.org/v1/", TypeName = "NamePart")]
public sealed partial class NamePart : Gx.Common.ExtensibleData
{
private string _value;
private string _type;
private System.Collections.Generic.List<Gx.Records.Field> _fields;
private System.Collections.Generic.List<Gx.Common.Qualifier> _qualifiers;
public NamePart()
: this(default(NamePartType), null)
{
}
public NamePart(NamePartType type, String text)
{
if (type != NamePartType.NULL)
{
KnownType = type;
}
Value = text;
}
/// <summary>
/// The value of the name part.
/// </summary>
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "value")]
[Newtonsoft.Json.JsonProperty("value")]
public string Value
{
get
{
return this._value;
}
set
{
this._value = value;
}
}
/// <summary>
/// The type of the name part.
/// </summary>
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "type")]
[Newtonsoft.Json.JsonProperty("type")]
public string Type
{
get
{
return this._type;
}
set
{
this._type = value;
}
}
/// <summary>
/// Convenience property for treating Type as an enum. See Gx.Types.NamePartTypeQNameUtil for details on getter/setter functionality.
/// </summary>
[System.Xml.Serialization.XmlIgnoreAttribute]
[Newtonsoft.Json.JsonIgnore]
public Gx.Types.NamePartType KnownType
{
get
{
return XmlQNameEnumUtil.GetEnumValue<NamePartType>(this._type);
}
set
{
this._type = XmlQNameEnumUtil.GetNameValue(value);
}
}
/// <summary>
/// The references to the record fields being used as evidence.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "field", Namespace = "http://gedcomx.org/v1/")]
[Newtonsoft.Json.JsonProperty("fields")]
public System.Collections.Generic.List<Gx.Records.Field> Fields
{
get
{
return this._fields;
}
set
{
this._fields = value;
}
}
/// <summary>
/// The qualifiers associated with this name part.
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "qualifier", Namespace = "http://gedcomx.org/v1/")]
[Newtonsoft.Json.JsonProperty("qualifiers")]
public System.Collections.Generic.List<Gx.Common.Qualifier> Qualifiers
{
get
{
return this._qualifiers;
}
set
{
this._qualifiers = value;
}
}
/**
* Accept a visitor.
*
* @param visitor The visitor.
*/
public void Accept(IGedcomxModelVisitor visitor)
{
visitor.VisitNamePart(this);
}
/**
* Build out this name part with a type.
*
* @param type The type.
* @return this.
*/
public NamePart SetType(String type)
{
Type = type;
return this;
}
/**
* Build out this name part with a type.
*
* @param type The type.
* @return this.
*/
public NamePart SetType(NamePartType type)
{
KnownType = type;
return this;
}
/**
* Build out this name part with a value.
*
* @param value The value.
* @return this.
*/
public NamePart SetValue(String value)
{
Value = value;
return this;
}
/**
* Build out this name part with a qualifier.
*
* @param qualifier The qualifier.
* @return this.
*/
public NamePart SetQualifier(Qualifier qualifier)
{
AddQualifier(qualifier);
return this;
}
/**
* Build out this name part with a field.
* @param field The field.
* @return this.
*/
public NamePart SetField(Field field)
{
AddField(field);
return this;
}
/**
* Add a qualifier associated with this name part.
*
* @param qualifier The qualifier to be added.
*/
public void AddQualifier(Qualifier qualifier)
{
if (qualifier != null)
{
if (_qualifiers == null)
{
_qualifiers = new List<Qualifier>();
}
_qualifiers.Add(qualifier);
}
}
/**
* Add a reference to the record field values being used as evidence.
*
* @param field The field to be added.
*/
public void AddField(Field field)
{
if (field != null)
{
if (_fields == null)
{
_fields = new List<Field>();
}
_fields.Add(field);
}
}
}
}
| |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the inspector-2015-08-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Inspector.Model
{
/// <summary>
/// Contains information about an Inspector finding.
///
///
/// <para>
/// This data type is used as the response element in the <a>DescribeFinding</a> action.
/// </para>
/// </summary>
public partial class Finding
{
private string _agentId;
private List<Attribute> _attributes = new List<Attribute>();
private string _autoScalingGroup;
private LocalizedText _description;
private string _findingArn;
private LocalizedText _recommendation;
private string _ruleName;
private string _rulesPackageArn;
private string _runArn;
private string _severity;
private LocalizedText _title;
private List<Attribute> _userAttributes = new List<Attribute>();
/// <summary>
/// Gets and sets the property AgentId.
/// <para>
/// The EC2 instance ID where the agent is installed that is used during the assessment
/// that generates the finding.
/// </para>
/// </summary>
public string AgentId
{
get { return this._agentId; }
set { this._agentId = value; }
}
// Check to see if AgentId property is set
internal bool IsSetAgentId()
{
return this._agentId != null;
}
/// <summary>
/// Gets and sets the property Attributes.
/// <para>
/// The system-defined attributes for the finding.
/// </para>
/// </summary>
public List<Attribute> Attributes
{
get { return this._attributes; }
set { this._attributes = value; }
}
// Check to see if Attributes property is set
internal bool IsSetAttributes()
{
return this._attributes != null && this._attributes.Count > 0;
}
/// <summary>
/// Gets and sets the property AutoScalingGroup.
/// <para>
/// The autoscaling group of the EC2 instance where the agent is installed that is used
/// during the assessment that generates the finding.
/// </para>
/// </summary>
public string AutoScalingGroup
{
get { return this._autoScalingGroup; }
set { this._autoScalingGroup = value; }
}
// Check to see if AutoScalingGroup property is set
internal bool IsSetAutoScalingGroup()
{
return this._autoScalingGroup != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the finding.
/// </para>
/// </summary>
public LocalizedText Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property FindingArn.
/// <para>
/// The ARN specifying the finding.
/// </para>
/// </summary>
public string FindingArn
{
get { return this._findingArn; }
set { this._findingArn = value; }
}
// Check to see if FindingArn property is set
internal bool IsSetFindingArn()
{
return this._findingArn != null;
}
/// <summary>
/// Gets and sets the property Recommendation.
/// <para>
/// The recommendation for the finding.
/// </para>
/// </summary>
public LocalizedText Recommendation
{
get { return this._recommendation; }
set { this._recommendation = value; }
}
// Check to see if Recommendation property is set
internal bool IsSetRecommendation()
{
return this._recommendation != null;
}
/// <summary>
/// Gets and sets the property RuleName.
/// <para>
/// The rule name that is used to generate the finding.
/// </para>
/// </summary>
public string RuleName
{
get { return this._ruleName; }
set { this._ruleName = value; }
}
// Check to see if RuleName property is set
internal bool IsSetRuleName()
{
return this._ruleName != null;
}
/// <summary>
/// Gets and sets the property RulesPackageArn.
/// <para>
/// The ARN of the rules package that is used to generate the finding.
/// </para>
/// </summary>
public string RulesPackageArn
{
get { return this._rulesPackageArn; }
set { this._rulesPackageArn = value; }
}
// Check to see if RulesPackageArn property is set
internal bool IsSetRulesPackageArn()
{
return this._rulesPackageArn != null;
}
/// <summary>
/// Gets and sets the property RunArn.
/// <para>
/// The ARN of the assessment run that generated the finding.
/// </para>
/// </summary>
public string RunArn
{
get { return this._runArn; }
set { this._runArn = value; }
}
// Check to see if RunArn property is set
internal bool IsSetRunArn()
{
return this._runArn != null;
}
/// <summary>
/// Gets and sets the property Severity.
/// <para>
/// The finding severity. Values can be set to <i>High</i>, <i>Medium</i>, <i>Low</i>,
/// and <i>Informational</i>.
/// </para>
/// </summary>
public string Severity
{
get { return this._severity; }
set { this._severity = value; }
}
// Check to see if Severity property is set
internal bool IsSetSeverity()
{
return this._severity != null;
}
/// <summary>
/// Gets and sets the property Title.
/// <para>
/// A short description that identifies the finding.
/// </para>
/// </summary>
public LocalizedText Title
{
get { return this._title; }
set { this._title = value; }
}
// Check to see if Title property is set
internal bool IsSetTitle()
{
return this._title != null;
}
/// <summary>
/// Gets and sets the property UserAttributes.
/// <para>
/// The user-defined attributes that are assigned to the finding.
/// </para>
/// </summary>
public List<Attribute> UserAttributes
{
get { return this._userAttributes; }
set { this._userAttributes = value; }
}
// Check to see if UserAttributes property is set
internal bool IsSetUserAttributes()
{
return this._userAttributes != null && this._userAttributes.Count > 0;
}
}
}
| |
/*****************************************************************************
* SkeletonBaker added by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using Spine;
/// <summary>
/// [SUPPORTS]
/// Linear, Constant, and Bezier Curves*
/// Inverse Kinematics*
/// Inherit Rotation
/// Translate Timeline
/// Rotate Timeline
/// Scale Timeline**
/// Event Timeline***
/// Attachment Timeline
///
/// RegionAttachment
/// MeshAttachment
/// SkinnedMeshAttachment
///
/// [LIMITATIONS]
/// *Inverse Kinematics & Bezier Curves are baked into the animation at 60fps and are not realtime. Use bakeIncrement constant to adjust key density if desired.
/// **Non-uniform Scale Keys (ie: if ScaleX and ScaleY are not equal to eachother, it will not be accurate to Spine source)
/// ***Events may only fire 1 type of data per event in Unity safely so priority to String data if present in Spine key, otherwise a Float is sent whether the Spine key was Int or Float with priority given to Int.
///
/// [DOES NOT SUPPORT]
/// FlipX or FlipY (Maybe one day)
/// FFD (Unity does not provide access to BlendShapes with code)
/// Color Keys (Maybe one day when Unity supports full FBX standard and provides access with code)
/// InheritScale (Never. Unity and Spine do scaling very differently)
/// Draw Order Keyframes
/// </summary>
public static class SkeletonBaker {
/// <summary>
/// Interval between key sampling for Bezier curves, IK controlled bones, and Inherit Rotation effected bones.
/// </summary>
const float bakeIncrement = 1 / 60f;
public static void BakeToPrefab (SkeletonDataAsset skeletonDataAsset, ExposedList<Skin> skins, string outputPath = "", bool bakeAnimations = true, bool bakeIK = true, SendMessageOptions eventOptions = SendMessageOptions.DontRequireReceiver) {
if (skeletonDataAsset == null || skeletonDataAsset.GetSkeletonData(true) == null) {
Debug.LogError("Could not export Spine Skeleton because SkeletonDataAsset is null or invalid!");
return;
}
if (outputPath == "") {
outputPath = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(skeletonDataAsset)) + "/Baked";
System.IO.Directory.CreateDirectory(outputPath);
}
var skeletonData = skeletonDataAsset.GetSkeletonData(true);
bool hasAnimations = bakeAnimations && skeletonData.Animations.Count > 0;
#if UNITY_5
UnityEditor.Animations.AnimatorController controller = null;
#else
UnityEditorInternal.AnimatorController controller = null;
#endif
if (hasAnimations) {
string controllerPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " Controller.controller";
bool newAnimContainer = false;
var runtimeController = AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController));
#if UNITY_5
if (runtimeController != null) {
controller = (UnityEditor.Animations.AnimatorController)runtimeController;
} else {
controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
newAnimContainer = true;
}
#else
if (runtimeController != null) {
controller = (UnityEditorInternal.AnimatorController)runtimeController;
} else {
controller = UnityEditorInternal.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
newAnimContainer = true;
}
#endif
Dictionary<string, AnimationClip> existingClipTable = new Dictionary<string, AnimationClip>();
List<string> unusedClipNames = new List<string>();
Object[] animObjs = AssetDatabase.LoadAllAssetsAtPath(controllerPath);
foreach (Object o in animObjs) {
if (o is AnimationClip) {
var clip = (AnimationClip)o;
existingClipTable.Add(clip.name, clip);
unusedClipNames.Add(clip.name);
}
}
Dictionary<int, List<string>> slotLookup = new Dictionary<int, List<string>>();
int skinCount = skins.Count;
for (int s = 0; s < skeletonData.Slots.Count; s++) {
List<string> attachmentNames = new List<string>();
for (int i = 0; i < skinCount; i++) {
var skin = skins.Items[i];
List<string> temp = new List<string>();
skin.FindNamesForSlot(s, temp);
foreach (string str in temp) {
if (!attachmentNames.Contains(str))
attachmentNames.Add(str);
}
}
slotLookup.Add(s, attachmentNames);
}
foreach (var anim in skeletonData.Animations) {
AnimationClip clip = null;
if (existingClipTable.ContainsKey(anim.Name)) {
clip = existingClipTable[anim.Name];
}
clip = ExtractAnimation(anim.Name, skeletonData, slotLookup, bakeIK, eventOptions, clip);
if (unusedClipNames.Contains(clip.name)) {
unusedClipNames.Remove(clip.name);
} else {
AssetDatabase.AddObjectToAsset(clip, controller);
#if UNITY_5
controller.AddMotion(clip);
#else
UnityEditorInternal.AnimatorController.AddAnimationClipToController(controller, clip);
#endif
}
}
if (newAnimContainer) {
EditorUtility.SetDirty(controller);
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
} else {
foreach (string str in unusedClipNames) {
AnimationClip.DestroyImmediate(existingClipTable[str], true);
}
EditorUtility.SetDirty(controller);
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(controllerPath, ImportAssetOptions.ForceUpdate);
AssetDatabase.Refresh();
}
}
foreach (var skin in skins) {
bool newPrefab = false;
string prefabPath = outputPath + "/" + skeletonDataAsset.skeletonJSON.name + " (" + skin.Name + ").prefab";
Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
if (prefab == null) {
prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
newPrefab = true;
}
Dictionary<string, Mesh> meshTable = new Dictionary<string, Mesh>();
List<string> unusedMeshNames = new List<string>();
Object[] assets = AssetDatabase.LoadAllAssetsAtPath(prefabPath);
foreach (var obj in assets) {
if (obj is Mesh) {
meshTable.Add(obj.name, (Mesh)obj);
unusedMeshNames.Add(obj.name);
}
}
GameObject prefabRoot = new GameObject("root");
Dictionary<string, Transform> slotTable = new Dictionary<string, Transform>();
Dictionary<string, Transform> boneTable = new Dictionary<string, Transform>();
List<Transform> boneList = new List<Transform>();
//create bones
for (int i = 0; i < skeletonData.Bones.Count; i++) {
var boneData = skeletonData.Bones.Items[i];
Transform boneTransform = new GameObject(boneData.Name).transform;
boneTransform.parent = prefabRoot.transform;
boneTable.Add(boneTransform.name, boneTransform);
boneList.Add(boneTransform);
}
for (int i = 0; i < skeletonData.Bones.Count; i++) {
var boneData = skeletonData.Bones.Items[i];
Transform boneTransform = boneTable[boneData.Name];
Transform parentTransform = null;
if (i > 0)
parentTransform = boneTable[boneData.Parent.Name];
else
parentTransform = boneTransform.parent;
boneTransform.parent = parentTransform;
boneTransform.localPosition = new Vector3(boneData.X, boneData.Y, 0);
if (boneData.InheritRotation)
boneTransform.localRotation = Quaternion.Euler(0, 0, boneData.Rotation);
else
boneTransform.rotation = Quaternion.Euler(0, 0, boneData.Rotation);
if (boneData.InheritScale)
boneTransform.localScale = new Vector3(boneData.ScaleX, boneData.ScaleY, 1);
}
//create slots and attachments
for (int i = 0; i < skeletonData.Slots.Count; i++) {
var slotData = skeletonData.Slots.Items[i];
Transform slotTransform = new GameObject(slotData.Name).transform;
slotTransform.parent = prefabRoot.transform;
slotTable.Add(slotData.Name, slotTransform);
List<Attachment> attachments = new List<Attachment>();
List<string> attachmentNames = new List<string>();
skin.FindAttachmentsForSlot(i, attachments);
skin.FindNamesForSlot(i, attachmentNames);
if (skin != skeletonData.DefaultSkin) {
skeletonData.DefaultSkin.FindAttachmentsForSlot(i, attachments);
skeletonData.DefaultSkin.FindNamesForSlot(i, attachmentNames);
}
for (int a = 0; a < attachments.Count; a++) {
var attachment = attachments[a];
var attachmentName = attachmentNames[a];
var attachmentMeshName = "[" + slotData.Name + "] " + attachmentName;
Vector3 offset = Vector3.zero;
float rotation = 0;
Mesh mesh = null;
Material material = null;
if (meshTable.ContainsKey(attachmentMeshName))
mesh = meshTable[attachmentMeshName];
if (attachment is RegionAttachment) {
var regionAttachment = (RegionAttachment)attachment;
offset.x = regionAttachment.X;
offset.y = regionAttachment.Y;
rotation = regionAttachment.Rotation;
mesh = ExtractRegionAttachment(attachmentMeshName, regionAttachment, mesh);
material = ExtractMaterial((RegionAttachment)attachment);
unusedMeshNames.Remove(attachmentMeshName);
if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false)
AssetDatabase.AddObjectToAsset(mesh, prefab);
} else if (attachment is MeshAttachment) {
var meshAttachment = (MeshAttachment)attachment;
offset.x = 0;
offset.y = 0;
rotation = 0;
mesh = ExtractMeshAttachment(attachmentMeshName, meshAttachment, mesh);
material = ExtractMaterial((MeshAttachment)attachment);
unusedMeshNames.Remove(attachmentMeshName);
if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false)
AssetDatabase.AddObjectToAsset(mesh, prefab);
} else if (attachment is WeightedMeshAttachment) {
var meshAttachment = (WeightedMeshAttachment)attachment;
offset.x = 0;
offset.y = 0;
rotation = 0;
mesh = ExtractSkinnedMeshAttachment(attachmentMeshName, meshAttachment, i, skeletonData, boneList, mesh);
material = ExtractMaterial((WeightedMeshAttachment)attachment);
unusedMeshNames.Remove(attachmentMeshName);
if (newPrefab || meshTable.ContainsKey(attachmentMeshName) == false)
AssetDatabase.AddObjectToAsset(mesh, prefab);
} else
continue; //disregard unsupported types for now
Transform attachmentTransform = new GameObject(attachmentName).transform;
attachmentTransform.parent = slotTransform;
attachmentTransform.localPosition = offset;
attachmentTransform.localRotation = Quaternion.Euler(0, 0, rotation);
if (attachment is WeightedMeshAttachment) {
attachmentTransform.position = Vector3.zero;
attachmentTransform.rotation = Quaternion.identity;
var skinnedMeshRenderer = attachmentTransform.gameObject.AddComponent<SkinnedMeshRenderer>();
skinnedMeshRenderer.rootBone = boneList[0];
skinnedMeshRenderer.bones = boneList.ToArray();
skinnedMeshRenderer.sharedMesh = mesh;
} else {
attachmentTransform.gameObject.AddComponent<MeshFilter>().sharedMesh = mesh;
attachmentTransform.gameObject.AddComponent<MeshRenderer>();
}
attachmentTransform.GetComponent<Renderer>().sharedMaterial = material;
attachmentTransform.GetComponent<Renderer>().sortingOrder = i;
if (attachmentName != slotData.AttachmentName)
attachmentTransform.gameObject.SetActive(false);
}
}
foreach (var slotData in skeletonData.Slots) {
Transform slotTransform = slotTable[slotData.Name];
slotTransform.parent = boneTable[slotData.BoneData.Name];
slotTransform.localPosition = Vector3.zero;
slotTransform.localRotation = Quaternion.identity;
slotTransform.localScale = Vector3.one;
}
if (hasAnimations) {
var animator = prefabRoot.AddComponent<Animator>();
animator.applyRootMotion = false;
animator.runtimeAnimatorController = (RuntimeAnimatorController)controller;
EditorGUIUtility.PingObject(controller);
}
if (newPrefab) {
PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ConnectToPrefab);
} else {
foreach (string str in unusedMeshNames) {
Mesh.DestroyImmediate(meshTable[str], true);
}
PrefabUtility.ReplacePrefab(prefabRoot, prefab, ReplacePrefabOptions.ReplaceNameBased);
}
EditorGUIUtility.PingObject(prefab);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
GameObject.DestroyImmediate(prefabRoot);
}
}
public static void GenerateMecanimAnimationClips (SkeletonDataAsset skeletonDataAsset) {
var data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
Debug.LogError("SkeletonData failed!", skeletonDataAsset);
return;
}
string dataPath = AssetDatabase.GetAssetPath(skeletonDataAsset);
string controllerPath = dataPath.Replace("_SkeletonData", "_Controller").Replace(".asset", ".controller");
#if UNITY_5
UnityEditor.Animations.AnimatorController controller;
if (skeletonDataAsset.controller != null) {
controller = (UnityEditor.Animations.AnimatorController)skeletonDataAsset.controller;
controllerPath = AssetDatabase.GetAssetPath(controller);
} else {
if (File.Exists(controllerPath)) {
if (EditorUtility.DisplayDialog("Controller Overwrite Warning", "Unknown Controller already exists at: " + controllerPath, "Update", "Overwrite")) {
controller = (UnityEditor.Animations.AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController));
} else {
controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
} else {
controller = (UnityEditor.Animations.AnimatorController)UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
}
#else
UnityEditorInternal.AnimatorController controller;
if (skeletonDataAsset.controller != null) {
controller = (UnityEditorInternal.AnimatorController)skeletonDataAsset.controller;
controllerPath = AssetDatabase.GetAssetPath(controller);
} else {
if (File.Exists(controllerPath)) {
if (EditorUtility.DisplayDialog("Controller Overwrite Warning", "Unknown Controller already exists at: " + controllerPath, "Update", "Overwrite")) {
controller = (UnityEditorInternal.AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(RuntimeAnimatorController));
} else {
controller = (UnityEditorInternal.AnimatorController)UnityEditorInternal.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
} else {
controller = (UnityEditorInternal.AnimatorController)UnityEditorInternal.AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
}
}
#endif
skeletonDataAsset.controller = controller;
EditorUtility.SetDirty(skeletonDataAsset);
Object[] objs = AssetDatabase.LoadAllAssetsAtPath(controllerPath);
Dictionary<string, AnimationClip> clipTable = new Dictionary<string, AnimationClip>();
Dictionary<string, Spine.Animation> animTable = new Dictionary<string, Spine.Animation>();
foreach (var o in objs) {
if (o is AnimationClip) {
clipTable.Add(o.name, (AnimationClip)o);
}
}
foreach (var anim in data.Animations) {
string name = anim.Name;
animTable.Add(name, anim);
if (clipTable.ContainsKey(name) == false) {
//generate new dummy clip
AnimationClip newClip = new AnimationClip();
newClip.name = name;
#if UNITY_5
#else
AnimationUtility.SetAnimationType(newClip, ModelImporterAnimationType.Generic);
#endif
AssetDatabase.AddObjectToAsset(newClip, controller);
clipTable.Add(name, newClip);
}
AnimationClip clip = clipTable[name];
clip.SetCurve("", typeof(GameObject), "dummy", AnimationCurve.Linear(0, 0, anim.Duration, 0));
var settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.stopTime = anim.Duration;
SetAnimationSettings(clip, settings);
AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]);
foreach (Timeline t in anim.Timelines) {
if (t is EventTimeline) {
ParseEventTimeline((EventTimeline)t, clip, SendMessageOptions.DontRequireReceiver);
}
}
EditorUtility.SetDirty(clip);
clipTable.Remove(name);
}
//clear no longer used animations
foreach (var clip in clipTable.Values) {
AnimationClip.DestroyImmediate(clip, true);
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
static Bone extractionBone;
static Slot extractionSlot;
static Bone GetExtractionBone () {
if (extractionBone != null)
return extractionBone;
SkeletonData skelData = new SkeletonData();
BoneData data = new BoneData("temp", null);
data.ScaleX = 1;
data.ScaleY = 1;
data.Length = 100;
skelData.Bones.Add(data);
Skeleton skeleton = new Skeleton(skelData);
Bone bone = new Bone(data, skeleton, null);
bone.UpdateWorldTransform();
extractionBone = bone;
return extractionBone;
}
static Slot GetExtractionSlot () {
if (extractionSlot != null)
return extractionSlot;
Bone bone = GetExtractionBone();
SlotData data = new SlotData("temp", bone.Data);
Slot slot = new Slot(data, bone);
extractionSlot = slot;
return extractionSlot;
}
static Material ExtractMaterial (Attachment attachment) {
if (attachment == null || attachment is BoundingBoxAttachment)
return null;
if (attachment is RegionAttachment) {
var att = (RegionAttachment)attachment;
return (Material)((AtlasRegion)att.RendererObject).page.rendererObject;
} else if (attachment is MeshAttachment) {
var att = (MeshAttachment)attachment;
return (Material)((AtlasRegion)att.RendererObject).page.rendererObject;
} else if (attachment is WeightedMeshAttachment) {
var att = (WeightedMeshAttachment)attachment;
return (Material)((AtlasRegion)att.RendererObject).page.rendererObject;
} else {
return null;
}
}
static Mesh ExtractRegionAttachment (string name, RegionAttachment attachment, Mesh mesh = null) {
var bone = GetExtractionBone();
bone.X = -attachment.X;
bone.Y = -attachment.Y;
bone.UpdateWorldTransform();
Vector2[] uvs = ExtractUV(attachment.UVs);
float[] floatVerts = new float[8];
attachment.ComputeWorldVertices(bone, floatVerts);
Vector3[] verts = ExtractVerts(floatVerts);
//unrotate verts now that they're centered
for (int i = 0; i < verts.Length; i++) {
verts[i] = Quaternion.Euler(0, 0, -attachment.Rotation) * verts[i];
}
int[] triangles = new int[6] { 1, 3, 0, 2, 3, 1 };
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
if (mesh == null)
mesh = new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.colors = new Color[] { color, color, color, color };
mesh.RecalculateBounds();
mesh.RecalculateNormals();
mesh.name = name;
return mesh;
}
static Mesh ExtractMeshAttachment (string name, MeshAttachment attachment, Mesh mesh = null) {
var slot = GetExtractionSlot();
slot.Bone.X = 0;
slot.Bone.Y = 0;
slot.Bone.UpdateWorldTransform();
Vector2[] uvs = ExtractUV(attachment.UVs);
float[] floatVerts = new float[attachment.Vertices.Length];
attachment.ComputeWorldVertices(slot, floatVerts);
Vector3[] verts = ExtractVerts(floatVerts);
int[] triangles = attachment.Triangles;
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
if (mesh == null)
mesh = new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
Color[] colors = new Color[verts.Length];
for (int i = 0; i < verts.Length; i++)
colors[i] = color;
mesh.colors = colors;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
mesh.name = name;
return mesh;
}
public class BoneWeightContainer {
public struct Pair {
public Transform bone;
public float weight;
public Pair (Transform bone, float weight) {
this.bone = bone;
this.weight = weight;
}
}
public List<Transform> bones;
public List<float> weights;
public List<Pair> pairs;
public BoneWeightContainer () {
this.bones = new List<Transform>();
this.weights = new List<float>();
this.pairs = new List<Pair>();
}
public void Add (Transform transform, float weight) {
bones.Add(transform);
weights.Add(weight);
pairs.Add(new Pair(transform, weight));
}
}
static Mesh ExtractSkinnedMeshAttachment (string name, WeightedMeshAttachment attachment, int slotIndex, SkeletonData skeletonData, List<Transform> boneList, Mesh mesh = null) {
Skeleton skeleton = new Skeleton(skeletonData);
skeleton.UpdateWorldTransform();
float[] floatVerts = new float[attachment.UVs.Length];
attachment.ComputeWorldVertices(skeleton.Slots.Items[slotIndex], floatVerts);
Vector2[] uvs = ExtractUV(attachment.UVs);
Vector3[] verts = ExtractVerts(floatVerts);
int[] triangles = attachment.Triangles;
Color color = new Color(attachment.R, attachment.G, attachment.B, attachment.A);
if (mesh == null)
mesh = new Mesh();
mesh.triangles = new int[0];
mesh.vertices = verts;
mesh.uv = uvs;
mesh.triangles = triangles;
Color[] colors = new Color[verts.Length];
for (int i = 0; i < verts.Length; i++)
colors[i] = color;
mesh.colors = colors;
mesh.name = name;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
//Handle weights and binding
Dictionary<int, BoneWeightContainer> weightTable = new Dictionary<int, BoneWeightContainer>();
System.Text.StringBuilder warningBuilder = new System.Text.StringBuilder();
int[] bones = attachment.Bones;
float[] weights = attachment.Weights;
for (int w = 0, v = 0, b = 0, n = bones.Length; v < n; w += 2) {
int nn = bones[v++] + v;
for (; v < nn; v++, b += 3) {
Transform boneTransform = boneList[bones[v]];
int vIndex = w / 2;
float weight = weights[b + 2];
BoneWeightContainer container;
if (weightTable.ContainsKey(vIndex))
container = weightTable[vIndex];
else {
container = new BoneWeightContainer();
weightTable.Add(vIndex, container);
}
container.Add(boneTransform, weight);
}
}
BoneWeight[] boneWeights = new BoneWeight[weightTable.Count];
for (int i = 0; i < weightTable.Count; i++) {
BoneWeight bw = new BoneWeight();
var container = weightTable[i];
var pairs = container.pairs.OrderByDescending(pair => pair.weight).ToList();
for (int b = 0; b < pairs.Count; b++) {
if (b > 3) {
if (warningBuilder.Length == 0)
warningBuilder.Insert(0, "[SkinnedMeshAttachment " + name + "]\r\nUnity only supports 4 weight influences per vertex! The 4 strongest influences will be used.\r\n");
warningBuilder.AppendFormat("{0} ignored on vertex {1}!\r\n", pairs[b].bone.name, i);
continue;
}
int boneIndex = boneList.IndexOf(pairs[b].bone);
float weight = pairs[b].weight;
switch (b) {
case 0:
bw.boneIndex0 = boneIndex;
bw.weight0 = weight;
break;
case 1:
bw.boneIndex1 = boneIndex;
bw.weight1 = weight;
break;
case 2:
bw.boneIndex2 = boneIndex;
bw.weight2 = weight;
break;
case 3:
bw.boneIndex3 = boneIndex;
bw.weight3 = weight;
break;
}
}
boneWeights[i] = bw;
}
Matrix4x4[] bindPoses = new Matrix4x4[boneList.Count];
for (int i = 0; i < boneList.Count; i++) {
bindPoses[i] = boneList[i].worldToLocalMatrix;
}
mesh.boneWeights = boneWeights;
mesh.bindposes = bindPoses;
string warningString = warningBuilder.ToString();
if (warningString.Length > 0)
Debug.LogWarning(warningString);
return mesh;
}
static Vector2[] ExtractUV (float[] floats) {
Vector2[] arr = new Vector2[floats.Length / 2];
for (int i = 0; i < floats.Length; i += 2) {
arr[i / 2] = new Vector2(floats[i], floats[i + 1]);
}
return arr;
}
static Vector3[] ExtractVerts (float[] floats) {
Vector3[] arr = new Vector3[floats.Length / 2];
for (int i = 0; i < floats.Length; i += 2) {
arr[i / 2] = new Vector3(floats[i], floats[i + 1], 0);// *scale;
}
return arr;
}
static void SetAnimationSettings (AnimationClip clip, AnimationClipSettings settings) {
#if UNITY_5
AnimationUtility.SetAnimationClipSettings(clip, settings);
#else
MethodInfo methodInfo = typeof(AnimationUtility).GetMethod("SetAnimationClipSettings", BindingFlags.Static | BindingFlags.NonPublic);
methodInfo.Invoke(null, new object[] { clip, settings });
EditorUtility.SetDirty(clip);
#endif
}
static AnimationClip ExtractAnimation (string name, SkeletonData skeletonData, Dictionary<int, List<string>> slotLookup, bool bakeIK, SendMessageOptions eventOptions, AnimationClip clip = null) {
var animation = skeletonData.FindAnimation(name);
var timelines = animation.Timelines;
if (clip == null) {
clip = new AnimationClip();
} else {
clip.ClearCurves();
AnimationUtility.SetAnimationEvents(clip, new AnimationEvent[0]);
}
#if UNITY_5
#else
AnimationUtility.SetAnimationType(clip, ModelImporterAnimationType.Generic);
#endif
clip.name = name;
Skeleton skeleton = new Skeleton(skeletonData);
List<int> ignoreRotateTimelineIndexes = new List<int>();
if (bakeIK) {
foreach (IkConstraint i in skeleton.IkConstraints) {
foreach (Bone b in i.Bones) {
int index = skeleton.FindBoneIndex(b.Data.Name);
ignoreRotateTimelineIndexes.Add(index);
BakeBone(b, animation, clip);
}
}
}
foreach (Bone b in skeleton.Bones) {
if (b.Data.InheritRotation == false) {
int index = skeleton.FindBoneIndex(b.Data.Name);
if (ignoreRotateTimelineIndexes.Contains(index) == false) {
ignoreRotateTimelineIndexes.Add(index);
BakeBone(b, animation, clip);
}
}
}
foreach (Timeline t in timelines) {
skeleton.SetToSetupPose();
if (t is ScaleTimeline) {
ParseScaleTimeline(skeleton, (ScaleTimeline)t, clip);
} else if (t is TranslateTimeline) {
ParseTranslateTimeline(skeleton, (TranslateTimeline)t, clip);
} else if (t is RotateTimeline) {
//bypass any rotation keys if they're going to get baked anyway to prevent localEulerAngles vs Baked collision
if (ignoreRotateTimelineIndexes.Contains(((RotateTimeline)t).BoneIndex) == false)
ParseRotateTimeline(skeleton, (RotateTimeline)t, clip);
} else if (t is AttachmentTimeline) {
ParseAttachmentTimeline(skeleton, (AttachmentTimeline)t, slotLookup, clip);
} else if (t is EventTimeline) {
ParseEventTimeline((EventTimeline)t, clip, eventOptions);
}
}
var settings = AnimationUtility.GetAnimationClipSettings(clip);
settings.loopTime = true;
settings.stopTime = Mathf.Max(clip.length, 0.001f);
SetAnimationSettings(clip, settings);
clip.EnsureQuaternionContinuity();
EditorUtility.SetDirty(clip);
return clip;
}
static int BinarySearch (float[] values, float target) {
int low = 0;
int high = values.Length - 2;
if (high == 0) return 1;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1)] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1);
current = (int)((uint)(low + high) >> 1);
}
}
static void ParseEventTimeline (EventTimeline timeline, AnimationClip clip, SendMessageOptions eventOptions) {
float[] frames = timeline.Frames;
var events = timeline.Events;
List<AnimationEvent> animEvents = new List<AnimationEvent>();
for (int i = 0; i < frames.Length; i++) {
var ev = events[i];
AnimationEvent ae = new AnimationEvent();
//TODO: Deal with Mecanim's zero-time missed event
ae.time = frames[i];
ae.functionName = ev.Data.Name;
ae.messageOptions = eventOptions;
if (ev.String != "" && ev.String != null) {
ae.stringParameter = ev.String;
} else {
if (ev.Int == 0 && ev.Float == 0) {
//do nothing, raw function
} else {
if (ev.Int != 0)
ae.floatParameter = (float)ev.Int;
else
ae.floatParameter = ev.Float;
}
}
animEvents.Add(ae);
}
AnimationUtility.SetAnimationEvents(clip, animEvents.ToArray());
}
static void ParseAttachmentTimeline (Skeleton skeleton, AttachmentTimeline timeline, Dictionary<int, List<string>> slotLookup, AnimationClip clip) {
var attachmentNames = slotLookup[timeline.SlotIndex];
string bonePath = GetPath(skeleton.Slots.Items[timeline.SlotIndex].Bone.Data);
string slotPath = bonePath + "/" + skeleton.Slots.Items[timeline.SlotIndex].Data.Name;
Dictionary<string, AnimationCurve> curveTable = new Dictionary<string, AnimationCurve>();
foreach (string str in attachmentNames) {
curveTable.Add(str, new AnimationCurve());
}
float[] frames = timeline.Frames;
if (frames[0] != 0) {
string startingName = skeleton.Slots.Items[timeline.SlotIndex].Data.AttachmentName;
foreach (var pair in curveTable) {
if (startingName == "" || startingName == null) {
pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity));
} else {
if (pair.Key == startingName) {
pair.Value.AddKey(new Keyframe(0, 1, float.PositiveInfinity, float.PositiveInfinity));
} else {
pair.Value.AddKey(new Keyframe(0, 0, float.PositiveInfinity, float.PositiveInfinity));
}
}
}
}
float currentTime = timeline.Frames[0];
float endTime = frames[frames.Length - 1];
int f = 0;
while (currentTime < endTime) {
float time = frames[f];
int frameIndex = (time >= frames[frames.Length - 1] ? frames.Length : BinarySearch(frames, time)) - 1;
string name = timeline.AttachmentNames[frameIndex];
foreach (var pair in curveTable) {
if (name == "") {
pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity));
} else {
if (pair.Key == name) {
pair.Value.AddKey(new Keyframe(time, 1, float.PositiveInfinity, float.PositiveInfinity));
} else {
pair.Value.AddKey(new Keyframe(time, 0, float.PositiveInfinity, float.PositiveInfinity));
}
}
}
currentTime = time;
f += 1;
}
foreach (var pair in curveTable) {
string path = slotPath + "/" + pair.Key;
string prop = "m_IsActive";
clip.SetCurve(path, typeof(GameObject), prop, pair.Value);
}
}
static float GetUninheritedRotation (Bone b) {
Bone parent = b.Parent;
float angle = b.AppliedRotation;
while (parent != null) {
angle -= parent.AppliedRotation;
parent = parent.Parent;
}
return angle;
}
static void BakeBone (Bone bone, Spine.Animation animation, AnimationClip clip) {
Skeleton skeleton = bone.Skeleton;
bool inheritRotation = bone.Data.InheritRotation;
skeleton.SetToSetupPose();
animation.Apply(skeleton, 0, 0, true, null);
skeleton.UpdateWorldTransform();
float duration = animation.Duration;
AnimationCurve curve = new AnimationCurve();
List<Keyframe> keys = new List<Keyframe>();
float rotation = bone.AppliedRotation;
if (!inheritRotation)
rotation = GetUninheritedRotation(bone);
keys.Add(new Keyframe(0, rotation, 0, 0));
int listIndex = 1;
float r = rotation;
int steps = Mathf.CeilToInt(duration / bakeIncrement);
float currentTime = 0;
float lastTime = 0;
float angle = rotation;
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = duration;
animation.Apply(skeleton, lastTime, currentTime, true, null);
skeleton.UpdateWorldTransform();
int pIndex = listIndex - 1;
Keyframe pk = keys[pIndex];
pk = keys[pIndex];
if (inheritRotation)
rotation = bone.AppliedRotation;
else {
rotation = GetUninheritedRotation(bone);
}
angle += Mathf.DeltaAngle(angle, rotation);
r = angle;
float rOut = (r - pk.value) / (currentTime - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(currentTime, r, rOut, 0));
keys[pIndex] = pk;
listIndex++;
lastTime = currentTime;
}
curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray()));
string path = GetPath(bone.Data);
string propertyName = "localEulerAnglesBaked";
EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x");
AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve());
EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y");
AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve());
EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z");
AnimationUtility.SetEditorCurve(clip, zBind, curve);
}
static void ParseTranslateTimeline (Skeleton skeleton, TranslateTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve xCurve = new AnimationCurve();
AnimationCurve yCurve = new AnimationCurve();
AnimationCurve zCurve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3];
float currentTime = timeline.Frames[0];
List<Keyframe> xKeys = new List<Keyframe>();
List<Keyframe> yKeys = new List<Keyframe>();
xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] + boneData.X, 0, 0));
yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] + boneData.Y, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 3;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] + boneData.X;
float y = frames[f + 2] + boneData.Y;
float xOut = (x - px.value) / (time - px.time);
float yOut = (y - py.value) / (time - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] + boneData.X;
float y = frames[f + 2] + boneData.Y;
float xOut = float.PositiveInfinity;
float yOut = float.PositiveInfinity;
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
int steps = Mathf.FloorToInt((time - px.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
px = xKeys[listIndex - 1];
py = yKeys[listIndex - 1];
float xOut = (bone.X - px.value) / (currentTime - px.time);
float yOut = (bone.Y - py.value) / (currentTime - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(currentTime, bone.X, xOut, 0));
yKeys.Add(new Keyframe(currentTime, bone.Y, yOut, 0));
xKeys[listIndex - 1] = px;
yKeys[listIndex - 1] = py;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 3;
}
xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray()));
yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray()));
string path = GetPath(boneData);
string propertyName = "localPosition";
clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve);
}
static AnimationCurve EnsureCurveKeyCount (AnimationCurve curve) {
if (curve.length == 1)
curve.AddKey(curve.keys[0].time + 0.25f, curve.keys[0].value);
return curve;
}
static void ParseScaleTimeline (Skeleton skeleton, ScaleTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve xCurve = new AnimationCurve();
AnimationCurve yCurve = new AnimationCurve();
AnimationCurve zCurve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 3) - 3];
float currentTime = timeline.Frames[0];
List<Keyframe> xKeys = new List<Keyframe>();
List<Keyframe> yKeys = new List<Keyframe>();
xKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[1] * boneData.ScaleX, 0, 0));
yKeys.Add(new Keyframe(timeline.Frames[0], timeline.Frames[2] * boneData.ScaleY, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 3;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] * boneData.ScaleX;
float y = frames[f + 2] * boneData.ScaleY;
float xOut = (x - px.value) / (time - px.time);
float yOut = (y - py.value) / (time - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
float x = frames[f + 1] * boneData.ScaleX;
float y = frames[f + 2] * boneData.ScaleY;
float xOut = float.PositiveInfinity;
float yOut = float.PositiveInfinity;
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(time, x, xOut, 0));
yKeys.Add(new Keyframe(time, y, yOut, 0));
xKeys[pIndex] = px;
yKeys[pIndex] = py;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe px = xKeys[pIndex];
Keyframe py = yKeys[pIndex];
float time = frames[f];
int steps = Mathf.FloorToInt((time - px.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
px = xKeys[listIndex - 1];
py = yKeys[listIndex - 1];
float xOut = (bone.ScaleX - px.value) / (currentTime - px.time);
float yOut = (bone.ScaleY - py.value) / (currentTime - py.time);
px.outTangent = xOut;
py.outTangent = yOut;
xKeys.Add(new Keyframe(currentTime, bone.ScaleX, xOut, 0));
yKeys.Add(new Keyframe(currentTime, bone.ScaleY, yOut, 0));
xKeys[listIndex - 1] = px;
yKeys[listIndex - 1] = py;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 3;
}
xCurve = EnsureCurveKeyCount(new AnimationCurve(xKeys.ToArray()));
yCurve = EnsureCurveKeyCount(new AnimationCurve(yKeys.ToArray()));
string path = GetPath(boneData);
string propertyName = "localScale";
clip.SetCurve(path, typeof(Transform), propertyName + ".x", xCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".y", yCurve);
clip.SetCurve(path, typeof(Transform), propertyName + ".z", zCurve);
}
static void ParseRotateTimeline (Skeleton skeleton, RotateTimeline timeline, AnimationClip clip) {
var boneData = skeleton.Data.Bones.Items[timeline.BoneIndex];
var bone = skeleton.Bones.Items[timeline.BoneIndex];
AnimationCurve curve = new AnimationCurve();
float endTime = timeline.Frames[(timeline.FrameCount * 2) - 2];
float currentTime = timeline.Frames[0];
List<Keyframe> keys = new List<Keyframe>();
float rotation = timeline.Frames[1] + boneData.Rotation;
keys.Add(new Keyframe(timeline.Frames[0], rotation, 0, 0));
int listIndex = 1;
int frameIndex = 1;
int f = 2;
float[] frames = timeline.Frames;
skeleton.SetToSetupPose();
float lastTime = 0;
float angle = rotation;
while (currentTime < endTime) {
int pIndex = listIndex - 1;
float curveType = timeline.GetCurveType(frameIndex - 1);
if (curveType == 0) {
//linear
Keyframe pk = keys[pIndex];
float time = frames[f];
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
float rOut = (r - pk.value) / (time - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(time, r, rOut, 0));
keys[pIndex] = pk;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 1) {
//stepped
Keyframe pk = keys[pIndex];
float time = frames[f];
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
float rOut = float.PositiveInfinity;
pk.outTangent = rOut;
keys.Add(new Keyframe(time, r, rOut, 0));
keys[pIndex] = pk;
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
lastTime = time;
listIndex++;
} else if (curveType == 2) {
//bezier
Keyframe pk = keys[pIndex];
float time = frames[f];
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
skeleton.UpdateWorldTransform();
rotation = frames[f + 1] + boneData.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
float r = angle;
int steps = Mathf.FloorToInt((time - pk.time) / bakeIncrement);
for (int i = 1; i <= steps; i++) {
currentTime += bakeIncrement;
if (i == steps)
currentTime = time;
timeline.Apply(skeleton, lastTime, currentTime, null, 1);
skeleton.UpdateWorldTransform();
pk = keys[listIndex - 1];
rotation = bone.Rotation;
angle += Mathf.DeltaAngle(angle, rotation);
r = angle;
float rOut = (r - pk.value) / (currentTime - pk.time);
pk.outTangent = rOut;
keys.Add(new Keyframe(currentTime, r, rOut, 0));
keys[listIndex - 1] = pk;
listIndex++;
lastTime = currentTime;
}
}
frameIndex++;
f += 2;
}
curve = EnsureCurveKeyCount(new AnimationCurve(keys.ToArray()));
string path = GetPath(boneData);
string propertyName = "localEulerAnglesBaked";
EditorCurveBinding xBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".x");
AnimationUtility.SetEditorCurve(clip, xBind, new AnimationCurve());
EditorCurveBinding yBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".y");
AnimationUtility.SetEditorCurve(clip, yBind, new AnimationCurve());
EditorCurveBinding zBind = EditorCurveBinding.FloatCurve(path, typeof(Transform), propertyName + ".z");
AnimationUtility.SetEditorCurve(clip, zBind, curve);
}
static string GetPath (BoneData b) {
return GetPathRecurse(b).Substring(1);
}
static string GetPathRecurse (BoneData b) {
if (b == null) {
return "";
}
return GetPathRecurse(b.Parent) + "/" + b.Name;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Counters;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("OrleansTaskScheduler RunQueue={RunQueue.Length}")]
internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant
{
private readonly Logger logger;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger taskWorkItemLogger;
private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; // work group directory
private bool applicationTurnsStopped;
internal WorkQueue RunQueue { get; private set; }
internal WorkerPool Pool { get; private set; }
internal static TimeSpan TurnWarningLengthThreshold { get; set; }
// This is the maximum number of pending work items for a single activation before we write a warning log.
internal LimitValue MaxPendingItemsLimit { get; private set; }
internal TimeSpan DelayWarningThreshold { get; private set; }
public int RunQueueLength { get { return RunQueue.Length; } }
public static OrleansTaskScheduler CreateTestInstance(int maxActiveThreads, ICorePerformanceMetrics performanceMetrics, ILoggerFactory loggerFactory)
{
return new OrleansTaskScheduler(
maxActiveThreads,
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(100),
NodeConfiguration.ENABLE_WORKER_THREAD_INJECTION,
LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS),
performanceMetrics,
loggerFactory);
}
public OrleansTaskScheduler(NodeConfiguration config, ICorePerformanceMetrics performanceMetrics, ILoggerFactory loggerFactory)
: this(config.MaxActiveThreads, config.DelayWarningThreshold, config.ActivationSchedulingQuantum,
config.TurnWarningLengthThreshold, config.EnableWorkerThreadInjection, config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS),
performanceMetrics, loggerFactory)
{
}
private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum,
TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads, LimitValue maxPendingItemsLimit, ICorePerformanceMetrics performanceMetrics, ILoggerFactory loggerFactory)
{
this.logger = new LoggerWrapper<OrleansTaskScheduler>(loggerFactory);
this.loggerFactory = loggerFactory;
DelayWarningThreshold = delayWarningThreshold;
WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum;
TurnWarningLengthThreshold = turnWarningLengthThreshold;
applicationTurnsStopped = false;
MaxPendingItemsLimit = maxPendingItemsLimit;
workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>();
RunQueue = new WorkQueue();
this.taskWorkItemLogger = loggerFactory.CreateLogger<TaskWorkItem>();
logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads);
Pool = new WorkerPool(this, performanceMetrics, loggerFactory, maxActiveThreads, injectMoreWorkerThreads);
IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount);
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength);
if (!StatisticsCollector.CollectShedulerQueuesStats) return;
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo);
}
public int WorkItemGroupCount { get { return workgroupDirectory.Count; } }
private float AverageRunQueueLengthLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageEnqueuedLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageArrivalRateLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count;
}
}
private float SumRunQueueLengthLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght);
}
}
private float SumEnqueuedLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests);
}
}
private float SumArrivalRateLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate);
}
}
public void Start()
{
Pool.Start();
}
public void StopApplicationTurns()
{
#if DEBUG
if (logger.IsVerbose) logger.Verbose("StopApplicationTurns");
#endif
// Do not RunDown the application run queue, since it is still used by low priority system targets.
applicationTurnsStopped = true;
foreach (var group in workgroupDirectory.Values)
{
if (!group.IsSystemGroup)
group.Stop();
}
}
public void Stop()
{
RunQueue.RunDown();
Pool.Stop();
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return new Task[0];
}
protected override void QueueTask(Task task)
{
var contextObj = task.AsyncState;
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = contextObj as ISchedulingContext;
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
logger.Warn(ErrorCode.SchedulerAppTurnsStopped_2, string.Format("Dropping Task {0} because application turns are stopped", task));
return;
}
if (workItemGroup == null)
{
var todo = new TaskWorkItem(this, task, context, this.taskWorkItemLogger);
RunQueue.Add(todo);
}
else
{
var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error);
throw new InvalidOperationException(error);
}
}
// Enqueue a work item to a given context
public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueWorkItem " + context);
#endif
if (workItem is TaskWorkItem)
{
var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.",
workItem.ToString(), context);
logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error);
throw new InvalidOperationException(error);
}
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem);
logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg);
return;
}
workItem.SchedulingContext = context;
// We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start.
// This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem.
if (workItemGroup == null)
{
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, this);
t.Start(this);
}
else
{
// Create Task wrapper for this work item
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, workItemGroup.TaskRunner);
t.Start(workItemGroup.TaskRunner);
}
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public WorkItemGroup RegisterWorkContext(ISchedulingContext context)
{
if (context == null) return null;
var wg = new WorkItemGroup(this, context, this.loggerFactory);
workgroupDirectory.TryAdd(context, wg);
return wg;
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public void UnregisterWorkContext(ISchedulingContext context)
{
if (context == null) return;
WorkItemGroup workGroup;
if (workgroupDirectory.TryRemove(context, out workGroup))
workGroup.Stop();
}
// public for testing only -- should be private, otherwise
public WorkItemGroup GetWorkItemGroup(ISchedulingContext context)
{
if (context == null)
return null;
WorkItemGroup workGroup;
if(workgroupDirectory.TryGetValue(context, out workGroup))
return workGroup;
var error = String.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context);
logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error);
throw new InvalidSchedulingContextException(error);
}
internal void CheckSchedulingContextValidity(ISchedulingContext context)
{
if (context == null)
{
throw new InvalidSchedulingContextException(
"CheckSchedulingContextValidity was called on a null SchedulingContext."
+ "Please make sure you are not trying to create a Timer from outside Orleans Task Scheduler, "
+ "which will be the case if you create it inside Task.Run.");
}
GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context
}
public TaskScheduler GetTaskScheduler(ISchedulingContext context)
{
if (context == null)
return this;
WorkItemGroup workGroup;
return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this;
}
public override int MaximumConcurrencyLevel { get { return Pool.MaxActiveThreads; } }
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
//bool canExecuteInline = WorkerPoolThread.CurrentContext != null;
var ctx = RuntimeContext.Current;
bool canExecuteInline = ctx == null || ctx.ActivationContext==null;
#if DEBUG
if (logger.IsVerbose2)
{
logger.Verbose2("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}",
task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline);
}
#endif
if (!canExecuteInline) return false;
if (taskWasPreviouslyQueued)
canExecuteInline = TryDequeue(task);
if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads
// We are on a worker pool thread, so can execute this task
bool done = TryExecuteTask(task);
if (!done)
{
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
return done;
}
/// <summary>
/// Run the specified task synchronously on the current thread
/// </summary>
/// <param name="task"><c>Task</c> to be executed</param>
public void RunTask(Task task)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = RuntimeContext.CurrentActivationContext;
var workItemGroup = GetWorkItemGroup(context);
if (workItemGroup == null)
{
RuntimeContext.SetExecutionContext(null, this);
bool done = TryExecuteTask(task);
if (!done)
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
else
{
var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error);
throw new InvalidOperationException(error);
}
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
}
// Returns true if healthy, false if not
public bool CheckHealth(DateTime lastCheckTime)
{
return Pool.DoHealthCheck();
}
internal void PrintStatistics()
{
if (!logger.IsInfo) return;
var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine);
if (stats.Length > 0)
logger.Info(ErrorCode.SchedulerStatistics,
"OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:" + Environment.NewLine + "{2}",
RunQueue.Length, WorkItemGroupCount, stats);
}
internal void DumpSchedulerStatus(bool alwaysOutput = true)
{
if (!logger.IsVerbose && !alwaysOutput) return;
PrintStatistics();
var sb = new StringBuilder();
sb.AppendLine("Dump of current OrleansTaskScheduler status:");
sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}",
Environment.ProcessorCount,
RunQueue.Length,
workgroupDirectory.Count,
applicationTurnsStopped ? "STOPPING" : "").AppendLine();
sb.AppendLine("RunQueue:");
RunQueue.DumpStatus(sb);
Pool.DumpStatus(sb);
foreach (var workgroup in workgroupDirectory.Values)
sb.AppendLine(workgroup.DumpStatus());
logger.Info(ErrorCode.SchedulerStatus, sb.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Devices;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using rhodes;
using rhoruntime;
using Windows.Graphics.Display;
using Windows.Phone.Media.Capture;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Pickers;
namespace rho
{
namespace CameraImpl
{
public class Camera : CameraBase
{
#region UIElements Required for creating Camera region
PhotoCamera Rho_StillCamera;
MediaLibrary Rho_Store_Picturelibrary = new MediaLibrary();
VideoBrush Rho_PhotoCameraBrush;
Canvas Rho_PhotoCameraCanvas;
Grid Store_PreviousGridElements = new Grid();
// Holds current flash mode.
PhotoChooserTask Rho_photoChooserTask;
PhoneApplicationFrame rootFrame;
#endregion
#region Variable Declartion region
int Rho_Camera_selected = 0;
MainPage Rho_MainPage;
Grid LayoutGrid;
FlashMode Rho_FlashMode;
Dictionary<double, Size> Rho_Supported_Resolutions = new Dictionary<double, Size>();
List<double> Rho_Screen_Resolution_Width = new List<double>();
List<double> Rho_Screen_Resolution_Height = new List<double>();
Dictionary<string, double> Rho_Paramenters = new Dictionary<string, double>();
Dictionary<string, string> Rho_StringParameters = new Dictionary<string, string>();
Dictionary<string, int> Rho_Flash_Types = new Dictionary<string, int>();
Dictionary<string, string> Rho_AliasParametersName = new Dictionary<string, string>();
Dictionary<string, string> Rho_Flashmodes = new Dictionary<string, string>();
Dictionary<string, string> Rho_OutputType = new Dictionary<string, string>();
Dictionary<string, string> Rho_OutPutFormat = new Dictionary<string, string>();
IMethodResult m_StoreTakePictureResult;
Dictionary<string, string> m_Take_Picture_Output = new Dictionary<string, string>();
Dictionary<string, int> m_CameraTypes = new Dictionary<string, int>();
string strbase64;
IReadOnlyDictionary<string, string> Store_TakePicture_Arguments;
CompositeTransform Rho_Camera_Rotation;
Dictionary<PageOrientation, Dictionary<string, double>> CameraRotation;
bool ApplicationBarPresentStatus = true;
Dictionary<bool, bool> ApplciationBarPresentStatus;
BitmapImage Rho_ToReduceResolution = new BitmapImage();
Dictionary<CameraType, string> m_CameratypeMapping = new Dictionary<CameraType, string>();
string Rho_FilePath = "C:\\Data\\Users\\Public\\Pictures\\Camera Roll\\";
IReadOnlyList<StorageFolder> subfolders;
IReadOnlyList<StorageFolder> subfoldersfolders;
IReadOnlyList<StorageFolder> subfolders_App;
#endregion
/// <summary>
/// Constructor
/// </summary>
public Camera()
{
CRhoRuntime.getInstance().logEvent("Camera class -->Constructor");
}
#region CameraBase abstract class implimentation
/// <summary>
/// This is an overloaded method,We set the type of camera type.
/// </summary>
/// <param name="strID"></param>
/// <param name="native"></param>
public override void setNativeImpl(string strID, long native)
{
try
{
CRhoRuntime.getInstance().logEvent(" Camera class--> setNativeImpl" + strID);
base.setNativeImpl(strID, native);
InitializeCameraProperties(_strID);
}
catch (Exception ex)
{
}
}
/// <summary>
/// Set Basic Camera style like type of camera.
/// </summary>
/// <param name="strId"> Front or Back camera</param>
public void InitializeCameraProperties(string strId)
{
double WidthofScreen = 0;
double HeightofScreen = 0;
CRhoRuntime.getInstance().logEvent("Camera class-->Entered InitializeCameraProperties ");
try
{
// initialize class instance in C# here
ApplciationBarPresentStatus = new Dictionary<bool, bool>();
ApplciationBarPresentStatus.Add(true, true);
ApplciationBarPresentStatus.Add(false, false);
try
{
m_CameraTypes.Clear();
m_CameraTypes.Add("back", 0);
m_CameraTypes.Add("front", 1);
m_CameratypeMapping.Clear();
m_CameratypeMapping.Add(CameraType.Primary, "back");
m_CameratypeMapping.Add(CameraType.FrontFacing, "front");
// if strid is blank select the primary //Simha
Rho_Camera_selected = m_CameraTypes[strId];
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class->Invalid Camera type Specified, So setting to default camera(back)");
Rho_Camera_selected = m_CameraTypes["back"];
}
using (PhotoCamera Temp_camera = new PhotoCamera((CameraType)Rho_Camera_selected))
{
Rho_Paramenters.Add("desired_height", Temp_camera.Resolution.Height);
Rho_Paramenters.Add("desired_width", Temp_camera.Resolution.Width);
Rho_AliasParametersName.Add("desiredheight", "desired_height");
Rho_AliasParametersName.Add("desiredwidth", "desired_width");
Rho_AliasParametersName.Add("flashmode", "flash_mode");
Rho_Paramenters.Add("camera_type", (int)Temp_camera.CameraType);
Rho_StringParameters.Add("filename", "Img");
Rho_StringParameters.Add("imageformat", "jpg");
Rho_StringParameters.Add("captureSound", string.Empty);
Rho_OutputType.Add("image", OUTPUT_FORMAT_IMAGE);
Rho_OutputType.Add("datauri", OUTPUT_FORMAT_DATAURI);
Rho_OutPutFormat.Add("outputformat", "image");
//CameraResolutionhsize what is hsize meaning in this //Simha
IEnumerable<Size> CameraResolutionsize = Temp_camera.AvailableResolutions;
// change the variable name x,y to meaning ful name
Rho_Paramenters.Add("getmaxwidth", CameraResolutionsize.Max(x => x.Width));
Rho_Paramenters.Add("getmaxheight", CameraResolutionsize.Max(Y => Y.Height));
int Counter = 0;
foreach (Size ResolutionStyle in CameraResolutionsize)
{
Rho_Screen_Resolution_Height.Add(ResolutionStyle.Height);
Rho_Screen_Resolution_Width.Add(ResolutionStyle.Width);
Rho_Supported_Resolutions.Add(Counter, ResolutionStyle);
Counter++;
}
Rho_MainPage = MainPage.getInstance();
try
{
ApplicationBarPresentStatus = ApplciationBarPresentStatus[Rho_MainPage.ApplicationBarStatus()];
}
catch (Exception ex)
{
ApplicationBarPresentStatus = true;
}
Rho_Flash_Types.Add(FLASH_ON, 1);
Rho_Flash_Types.Add(FLASH_OFF, 2);
Rho_Flash_Types.Add(FLASH_AUTO, 3);
Rho_Flash_Types.Add(FLASH_RED_EYE, 4);
Rho_FlashMode = (FlashMode)(Rho_Flash_Types[FLASH_AUTO]);
Rho_Flashmodes.Add("flash_mode", FLASH_AUTO);
LayoutGrid = MainPage.LayoutGrid();
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-> InitializeCameraProperties, Setting up Camera Related Variables-->Exception" + ex.Message);
}
CameraRotation = new Dictionary<PageOrientation, Dictionary<string, double>>();
try
{
WidthofScreen = Application.Current.Host.Content.ActualWidth;
HeightofScreen = Application.Current.Host.Content.ActualHeight;
}
catch (Exception ex)
{
MainPage.LayoutGrid().Dispatcher.BeginInvoke(delegate()
{
WidthofScreen = Application.Current.Host.Content.ActualWidth;
HeightofScreen = Application.Current.Host.Content.ActualHeight;
});
while (WidthofScreen == 0)
{
Thread.Sleep(1000);
}
}
Dictionary<string, double> LandscapeLeft = new Dictionary<string, double>();
LandscapeLeft.Add("rotation", -90);
LandscapeLeft.Add("Height", WidthofScreen);
LandscapeLeft.Add("Width", HeightofScreen);
LandscapeLeft.Add("CameraType", 0);
CameraRotation.Add(PageOrientation.LandscapeLeft, LandscapeLeft);
Dictionary<string, double> LandscapeRight = new Dictionary<string, double>();
LandscapeRight.Add("rotation", 90);
LandscapeRight.Add("Height", WidthofScreen);
LandscapeRight.Add("Width", HeightofScreen);
CameraRotation.Add(PageOrientation.LandscapeRight, LandscapeRight);
Dictionary<string, double> PortraitDown = new Dictionary<string, double>();
PortraitDown.Add("rotation", 0);
PortraitDown.Add("Height", HeightofScreen);
PortraitDown.Add("Width", WidthofScreen);
PortraitDown.Add("front", -180);
CameraRotation.Add(PageOrientation.PortraitDown, PortraitDown);
Dictionary<string, double> PortraitUp = new Dictionary<string, double>();
PortraitUp.Add("rotation", 0);
PortraitUp.Add("Height", HeightofScreen);
PortraitUp.Add("Width", WidthofScreen);
PortraitUp.Add("front", 180);
CameraRotation.Add(PageOrientation.PortraitUp, PortraitUp);
CRhoRuntime.getInstance().logEvent("Camera class-->End InitializeCameraProperties");
}
/// <summary>
/// Get the kind of Camera (front or Back) facing.
/// </summary>
/// <param name="oResult"></param>
IMethodResult StoregetCameratypeResult = null;
public override void getCameraType(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class-> getCameraType");
using (PhotoCamera TempCamera = new PhotoCamera((CameraType)Rho_Paramenters["camera_type"]))
{
try
{
oResult.set(m_CameratypeMapping[TempCamera.CameraType]);
}
catch (Exception ex)
{
string strmessage = ex.Message;
}
}
}
/// <summary>
/// Get Maximum Width of the Resolution.
/// </summary>
/// <param name="oResult"></param>
public override void getMaxWidth(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> getMaxWidth");
try
{
oResult.set(Rho_Paramenters["getmaxwidth"]);
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-> getMaxWidth" + ex.Message);
}
}
/// <summary>
/// Get Maximum Height of the Resolution
/// </summary>
/// <param name="oResult"></param>
public override void getMaxHeight(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> getMaxHeight");
try
{
oResult.set(Rho_Paramenters["getmaxheight"]);
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class->getMaxHeight" + ex.Message);
}
}
/// <summary>
/// Get all the Supported Resolution of the specified Camera type.
/// </summary>
/// <param name="oResult"></param>
public override void getSupportedSizeList(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> Entered getSupportedSizeList");
using (PhotoCamera TempCamera = new PhotoCamera((CameraType)Rho_Paramenters["camera_type"]))
{
List<Dictionary<string, string>> RTypes = new List<Dictionary<string, string>>();
try
{
IEnumerable<Size> objsize = TempCamera.AvailableResolutions;
foreach (Size size in objsize)
{
Dictionary<string, string> Store_Resolution = new Dictionary<string, string>();
Store_Resolution.Add("width", size.Width.ToString());
Store_Resolution.Add("height", size.Height.ToString());
RTypes.Add(Store_Resolution);
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class->" + ex.Message);
}
oResult.set(RTypes);
}
CRhoRuntime.getInstance().logEvent("Camera class--> End getSupportedSizeList");
}
/// <summary>
/// Get the setted Resolution Width of the Camera Type (Back/Front).
/// </summary>
/// <param name="oResult"></param>
public override void getDesiredWidth(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> getDesiredWidth");
oResult.set(Rho_Paramenters["desired_width"].ToString());
}
/// <summary>
/// Sets the Width from the avaialble Resolution,if not available then sets to the nearest available Resolution.
/// </summary>
/// <param name="desiredWidth">Width to be setted </param>
/// <param name="oResult"></param>
public override void setDesiredWidth(int desiredWidth, IMethodResult oResult)
{
try
{
CRhoRuntime.getInstance().logEvent("Camera class--> setDesiredWidth " + desiredWidth);
double closestWidth = Rho_Screen_Resolution_Width.Aggregate((x, y) => Math.Abs(x - desiredWidth) < Math.Abs(y - desiredWidth) ? x : y);
Rho_Paramenters["desired_width"] = closestWidth;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->setDesiredWidth--> Exception" + ex.ToString());
}
}
/// <summary>
/// Get the setted Resolution Height of the Camera Type (Back/Front).
/// </summary>
/// <param name="oResult"></param>
public override void getDesiredHeight(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> getDesiredHeight");
oResult.set(Rho_Paramenters["desired_height"].ToString());
}
/// <summary>
/// Sets the Height from the avaialble Resolution,if not available then sets to the nearest available Resolution.
/// </summary>
/// <param name="desiredWidth">Height from the Resolution </param>
/// <param name="oResult"></param>
public override void setDesiredHeight(int desiredHeight, IMethodResult oResult)
{
try
{
CRhoRuntime.getInstance().logEvent("Camera class--> setDesiredHeight" + desiredHeight);
double closestHeight = Rho_Screen_Resolution_Height.Aggregate((x, y) => Math.Abs(x - desiredHeight) < Math.Abs(y - desiredHeight) ? x : y);
Rho_Paramenters["desired_height"] = closestHeight;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->setDesiredHeight--> Exception" + ex.ToString());
}
}
/// <summary>
/// Gets the File Name to be used when picture to be saved under CameraRoll.
/// </summary>
/// <param name="oResult"></param>
public override void getFileName(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> getFileName" + Rho_StringParameters["filename"]);
oResult.set(Rho_StringParameters["filename"]);
}
/// <summary>
/// Sets the File Name to be used when picture to be saved under CameraRoll.
/// </summary>
/// <param name="fileName"></param>
/// <param name="oResult"></param>
public override void setFileName(string fileName, IMethodResult oResult)
{
Dictionary<bool, bool> stringnullorempty = new Dictionary<bool, bool>();
stringnullorempty.Add(false, false);
try
{
bool filenameemptyornull = stringnullorempty[String.IsNullOrEmpty(fileName)];
CRhoRuntime.getInstance().logEvent("Camera class--> setFileName " + fileName);
Rho_StringParameters["filename"] = fileName;
}
catch (Exception ex)
{
Rho_StringParameters["filename"] = "Img";
}
}
/// <summary>
/// Gets the Compression Format in WP8 we support only Jpeg
/// </summary>
/// <param name="oResult"></param>
public override void getCompressionFormat(IMethodResult oResult)
{
oResult.set(Rho_StringParameters["imageformat"]);
}
/// <summary>
/// Not Supported in WP8
/// </summary>
/// <param name="compressionFormat"></param>
/// <param name="oResult"></param>
public override void setCompressionFormat(string compressionFormat, IMethodResult oResult)
{
//AS WP8 does not support any other format apart from jpeg, need to check in 8.1
// Rho_StringParameters["ImageFormat"] = compressionFormat;
}
/// <summary>
/// get either dataURI(Base64 shall be sent) or image(path of the captured jpeg file).
/// </summary>
/// <param name="oResult"></param>
public override void getOutputFormat(IMethodResult oResult)
{
oResult.set(Rho_OutputType[Rho_OutPutFormat["outputformat"]]);
}
/// <summary>
/// get either dataURI or image.
/// </summary>
/// <param name="outputFormat">dataURI(Base64 shall be sent) or image(path of the captured jpeg file) </param>
/// <param name="oResult"></param>
public override void setOutputFormat(string outputFormat, IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class->setOutputFormat type");
try
{
string DataURI = Rho_OutputType[outputFormat.ToLower().Trim()];
Rho_OutPutFormat.Clear();
Rho_OutPutFormat.Add("outputformat", outputFormat.ToLower().Trim());
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class->invalid setOutputFormat " + outputFormat + " Exception " + ex.ToString());
}
;
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getColorModel(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="colorModel"></param>
/// <param name="oResult"></param>
public override void setColorModel(string colorModel, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getEnableEditing(IMethodResult oResult)
{
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="enableEditing"></param>
/// <param name="oResult"></param>
public override void setEnableEditing(bool enableEditing, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Get the kind of flash mode setted (On,Off, Auto)
/// </summary>
/// <param name="oResult"></param>
public override void getFlashMode(IMethodResult oResult)
{
string FlashModeType = FlashMode.Auto.ToString();
try
{
CRhoRuntime.getInstance().logEvent("Camera class--> getFlashMode");
IEnumerable<KeyValuePair<string, int>> Flashmode = Rho_Flash_Types.Select(x => x).Where(k => k.Value == (int)Rho_FlashMode).ToList();
FlashModeType = string.Empty; //give proper varible name for returnablevalue //Simha
foreach (KeyValuePair<string, int> obj in Flashmode)
{
FlashModeType = obj.Key;
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class->invalid getFlashMode " + ex.ToString());
}
oResult.set(FlashModeType);
}
/// <summary>
/// Set the kind of flash mode (On,Off,Auto).
/// </summary>
/// <param name="flashMode"></param>
/// <param name="oResult"></param>
public override void setFlashMode(string flashMode, IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class--> setFlashMode");
try
{
Rho_FlashMode = (FlashMode)(Rho_Flash_Types[flashMode.ToLower().Trim()]);
Rho_Flashmodes["flash_mode"] = flashMode.ToLower().Trim();
}
catch (Exception ex)
{
Rho_FlashMode = (FlashMode)(Rho_Flash_Types[FLASH_AUTO]);
CRhoRuntime.getInstance().logEvent("Camera class->invalid setFlashMode " + ex.ToString());
}
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getSaveToDeviceGallery(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="saveToDeviceGallery"></param>
/// <param name="oResult"></param>
public override void setSaveToDeviceGallery(bool saveToDeviceGallery, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getCaptureSound(IMethodResult oResult)
{
oResult.set(Rho_StringParameters["captureSound"]);
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="captureSound"></param>
/// <param name="oResult"></param>
public override void setCaptureSound(string captureSound, IMethodResult oResult)
{
Rho_StringParameters["captureSound"] = captureSound;
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getPreviewLeft(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="previewLeft"></param>
/// <param name="oResult"></param>
public override void setPreviewLeft(int previewLeft, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getPreviewTop(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="previewTop"></param>
/// <param name="oResult"></param>
public override void setPreviewTop(int previewTop, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getPreviewWidth(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="previewWidth"></param>
/// <param name="oResult"></param>
public override void setPreviewWidth(int previewWidth, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getPreviewHeight(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="previewHeight"></param>
/// <param name="oResult"></param>
public override void setPreviewHeight(int previewHeight, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getUseSystemViewfinder(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="useSystemViewfinder"></param>
/// <param name="oResult"></param>
public override void setUseSystemViewfinder(bool useSystemViewfinder, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void getAimMode(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="aimMode"></param>
/// <param name="oResult"></param>
public override void setAimMode(string aimMode, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="propertyMap"></param>
/// <param name="oResult"></param>
public override void showPreview(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void hidePreview(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Not supported in WP8.
/// </summary>
/// <param name="oResult"></param>
public override void capture(IMethodResult oResult)
{
// implement this method in C# here
}
/// <summary>
/// Set the Configuration as per parameters of camera of take Image
/// </summary>
/// <param name="propertyMap">Contains the details of paramenters sent by user to takepicture</param>
private void SetCameraConfiguration(IReadOnlyDictionary<string, string> propertyMap)
{
CRhoRuntime.getInstance().logEvent("Camera class--> SetCameraConfiguration");
foreach (KeyValuePair<string, string> Parameters in propertyMap)
{
string ParametersKeyName = Parameters.Key.Trim().ToLower();
try
{
ParametersKeyName = Rho_AliasParametersName[ParametersKeyName];
}
catch (Exception ex)
{
}
try
{
Rho_Paramenters[ParametersKeyName] = Convert.ToDouble(Parameters.Value);
}
catch (Exception ex)
{
}
try
{
Rho_Flashmodes[ParametersKeyName] = Parameters.Value.ToString().Trim();
Rho_FlashMode = (FlashMode)(Rho_Flash_Types[Rho_Flashmodes[ParametersKeyName]]);
}
catch (Exception ex)
{
}
try
{
Rho_StringParameters[ParametersKeyName] = Parameters.Value.ToString().Trim();
}
catch (Exception ex)
{
}
try
{
string value = Rho_OutPutFormat[ParametersKeyName];
string tempnumber = Rho_OutputType[Parameters.Value.Trim().ToLower()];
Rho_OutPutFormat.Clear();
Rho_OutPutFormat.Add(ParametersKeyName, Parameters.Value.Trim().ToLower());
}
catch (Exception ex)
{
}
}
}
/// <summary>
/// To show Still Camera, on taking the picture we shall move to previous screen.
/// </summary>
/// <param name="propertyMap">Contains the arguments set by user.</param>
/// <param name="oResult"></param>
public override void takePicture(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
MainPage.LayoutGrid().Dispatcher.BeginInvoke(delegate()
{
CRhoRuntime.getInstance().logEvent("Camera class--> takePicture");
try
{
//Rho_MainPage.toolbarHide();
Rho_MainPage.ApplicationBarEnable(false);
Store_TakePicture_Arguments = propertyMap;
SetCameraConfiguration(propertyMap);
Initialize_TakePictureCallBack();
RemovePreviousControls();
Rho_Create_Camera_Layout();
InitializeEventsRelatedtoCamera();
m_StoreTakePictureResult = oResult;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class--> takePicture exception" + ex.ToString());
m_Take_Picture_Output["status"] = "error";
m_Take_Picture_Output["message"] = ex.Message;
m_Take_Picture_Output["image_format"] = string.Empty;
m_Take_Picture_Output["imageFormat"] = string.Empty;
oResult.set(m_Take_Picture_Output);
}
CRhoRuntime.getInstance().logEvent("Camera class--> End takePicture");
});
}
/// <summary>
/// Remove Previous Controls before adding/Loading Camera Controls
/// </summary>
void RemovePreviousControls()
{
UIElement[] UiElementCollection = new UIElement[LayoutGrid.Children.Count];
LayoutGrid.Children.CopyTo(UiElementCollection, 0);
LayoutGrid.Children.Clear();
foreach (UIElement UIElement in UiElementCollection)
{
Store_PreviousGridElements.Children.Add(UIElement);
}
}
/// <summary>
/// Add Previous Control as user has finished his action.
/// </summary>
void AddPreviousControls()
{
UIElement[] UiElementCollection = new UIElement[Store_PreviousGridElements.Children.Count];
Store_PreviousGridElements.Children.CopyTo(UiElementCollection, 0);
Store_PreviousGridElements.Children.Clear();
foreach (UIElement UIElement in UiElementCollection)
{
LayoutGrid.Children.Add(UIElement);
}
}
#endregion
# region takeImage call the below methods.
/// <summary>
/// On Unlock of Phone this event is fired.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void rootFrame_Unobscured(object sender, EventArgs e)
{
CRhoRuntime.getInstance().logEvent("Camera class--> rootFrame_Unobscured");
UninitializeRegisteredEvents();
takePicture(Store_TakePicture_Arguments, m_StoreTakePictureResult);
}
/// <summary>
/// Initialize Camera Related Events
/// </summary>
private void InitializeEventsRelatedtoCamera()
{
rootFrame.Unobscured += rootFrame_Unobscured;
//On Clicking the Camera Canvas Lets consider it as a camera click.
Rho_PhotoCameraCanvas.Tap += Rho_PhotoCameraCanvas_Tap;
CameraButtons.ShutterKeyPressed += CameraButtons_ShutterKeyPressed;
Rho_MainPage.OrientationChanged += Rho_MainPage_OrientationChanged;
Rho_StillCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
// Event is fired when the capture sequence is complete and an image is available.
Rho_StillCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
Rho_MainPage.BackKeyPress += Rho_MainPage_BackKeyPress;
}
/// <summary>
/// Uninitialize all events which are registered in TakePicture
/// </summary>
private void UninitializeRegisteredEvents()
{
CRhoRuntime.getInstance().logEvent("Camera class--> UninitializeRegisteredEvents");
Rho_MainPage.OrientationChanged -= Rho_MainPage_OrientationChanged;
rootFrame.Unobscured -= rootFrame_Unobscured;
Rho_MainPage.BackKeyPress -= Rho_MainPage_BackKeyPress;
Rho_StillCamera.CaptureImageAvailable -= new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
Rho_StillCamera.Initialized -= new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);
Rho_StillCamera.CaptureImageAvailable -= new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);
CameraButtons.ShutterKeyPressed -= CameraButtons_ShutterKeyPressed;
}
/// <summary>
/// Return to the previous screen.
/// </summary>
void Return_To_Previous_Screen()
{
CRhoRuntime.getInstance().logEvent("Camera class--> Return_To_Previous_Screen");
try
{
Rho_MainPage.ApplicationBarEnable(ApplicationBarPresentStatus);
UninitializeRegisteredEvents();
LayoutGrid.Children.Remove(Rho_PhotoCameraCanvas);
AddPreviousControls();
Rho_StillCamera.Dispose();
Rho_StillCamera = null;
Rho_PhotoCameraCanvas = null;
Rho_PhotoCameraBrush = null;
GC.Collect();
Rho_MainPage.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
Rho_MainPage.Orientation = PageOrientation.Portrait;
}
catch (AccessViolationException et)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Return_To_Previous_Screen--> AccessViolationException" + et.ToString());
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Return_To_Previous_Screen-->Exception" + ex.ToString());
}
}
/// <summary>
/// Set the default value for the call back parameters
/// </summary>
private void Initialize_TakePictureCallBack()
{
CRhoRuntime.getInstance().logEvent("Camera class-->Initialize_TakePictureCallBack");
m_Take_Picture_Output.Clear();
m_Take_Picture_Output.Add("status", "cancel");
m_Take_Picture_Output.Add("imageUri", string.Empty);
m_Take_Picture_Output.Add("imageHeight", string.Empty);
m_Take_Picture_Output.Add("imageWidth", string.Empty);
m_Take_Picture_Output.Add("imageFormat", "jpg");
m_Take_Picture_Output.Add("message", string.Empty);
m_Take_Picture_Output.Add("image_uri", string.Empty);
m_Take_Picture_Output.Add("image_height", string.Empty);
m_Take_Picture_Output.Add("image_width", string.Empty);
m_Take_Picture_Output.Add("image_format", "jpg");
}
/// <summary>
/// on clicking of BackPress on Mobile.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Rho_MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Rho_MainPage_BackKeyPress");
try
{
Return_To_Previous_Screen();
e.Cancel = true;
m_Take_Picture_Output["image_format"] = string.Empty;
m_Take_Picture_Output["imageFormat"] = string.Empty;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Rho_MainPage_BackKeyPress -->Error" + ex.ToString());
m_Take_Picture_Output["status"] = "error";
m_Take_Picture_Output["message"] = ex.Message;
m_Take_Picture_Output["image_format"] = string.Empty;
m_Take_Picture_Output["imageFormat"] = string.Empty;
}
m_StoreTakePictureResult.set(m_Take_Picture_Output);
}
protected AudioVideoCaptureDevice Device { get; set; }
/// <summary>
/// When camera is up.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_Initialized");
if (e.Succeeded)
{
Rho_PhotoCameraCanvas.Dispatcher.BeginInvoke(delegate()
{
// Write message.
Rho_StillCamera.FlashMode = Rho_FlashMode;
try
{
KeyValuePair<double, Size> CameraResolution = Rho_Supported_Resolutions.Aggregate((x, y) => Math.Abs(x.Value.Height - Rho_Paramenters["desired_height"]) < Math.Abs(y.Value.Height - Rho_Paramenters["desired_height"]) ? x : y);
Rho_StillCamera.Resolution = CameraResolution.Value;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_Initialized-->Exception" + ex.ToString());
}
});
}
else
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_Initialized-->Exception" + e.Exception.ToString());
m_Take_Picture_Output["status"] = "error";
m_Take_Picture_Output["message"] = e.Exception.Message;
m_Take_Picture_Output["image_format"] = string.Empty;
m_Take_Picture_Output["imageFormat"] = string.Empty;
m_StoreTakePictureResult.set(m_Take_Picture_Output);
}
}
/// <summary>
/// For Rotating the captured Image
/// </summary>
/// <param name="stream">Input Stream For Rotation</param>
/// <param name="angle">Rotation angle, to which the 'stream' has to be rotated</param>
/// <param name="FixedLength">IF flase maintain the Resolution, if true, reduce the resolution</param>
/// <returns></returns>
public MemoryStream RotateStream(MemoryStream stream, int angle)
{
Dictionary<int, int> Angle0 = new Dictionary<int, int>();
Angle0.Add(0, 0);
stream.Position = 0;
Rho_ToReduceResolution.SetSource(stream);
try
{
int result = Angle0[angle % 360];
return stream;
}
catch (Exception ex)
{
}
var wbSource = new WriteableBitmap(Rho_ToReduceResolution);
WriteableBitmap wbTarget;
try
{
int result = Angle0[angle % 180];
wbTarget = new WriteableBitmap(wbSource.PixelWidth, wbSource.PixelHeight);
}
catch (Exception ex)
{
wbTarget = new WriteableBitmap(wbSource.PixelHeight, wbSource.PixelWidth);
}
for (int xIndex = 0; xIndex < wbSource.PixelWidth; xIndex++)
{
for (int yIndex = 0; yIndex < wbSource.PixelHeight; yIndex++)
{
//Maintaining This switch because, if i replace this with Dictionary Mapping, was getting an Performance issue.
switch (angle % 360)
{
case 90:
wbTarget.Pixels[(wbSource.PixelHeight - yIndex - 1) + xIndex * wbTarget.PixelWidth] = wbSource.Pixels[xIndex + yIndex * wbSource.PixelWidth];
break;
case 180:
wbTarget.Pixels[(wbSource.PixelWidth - xIndex - 1) + (wbSource.PixelHeight - yIndex - 1) * wbSource.PixelWidth] = wbSource.Pixels[xIndex + yIndex * wbSource.PixelWidth];
break;
case 270:
wbTarget.Pixels[yIndex + (wbSource.PixelWidth - xIndex - 1) * wbTarget.PixelWidth] = wbSource.Pixels[xIndex + yIndex * wbSource.PixelWidth];
break;
}
}
}
var targetStream = new MemoryStream();
wbTarget.SaveJpeg(targetStream, (int)(Math.Abs(wbTarget.PixelWidth)), (int)(Math.Abs(wbTarget.PixelHeight)), 0, 100);
return targetStream;
}
/// <summary>
/// Stores file in its own virtual drive rho\apps\app
/// </summary>
/// <param name="file">Stream of file that needs to be saved in the Location.</param>
/// <param name="fileName">Name i n which the file needs to be saved</param>
/// <param name="StorechoosePictureResult">Callback event</param>
/// <param name="choosePicture_output">The path of the image needs to be stored</param>
/// <returns>Successll or error</returns>
public async Task SaveToLocalFolderAsync(Stream file, string fileName, IMethodResult StoreTakePictureResult, Dictionary<string, string> TakePicture_output)
{
string FileNameSuffix = "__DTF__";
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string strLocalFolder = CRhoRuntime.getInstance().getRootPath(ApplicationData.Current.LocalFolder.Path.ToString());
string[] strFolders = strLocalFolder.Split(new string[] { ApplicationData.Current.LocalFolder.Path.ToString() }, StringSplitOptions.None);
Dictionary<bool, bool> Rho_SubFolder_Pass = new Dictionary<bool, bool>();
Rho_SubFolder_Pass.Add(true, true);
try
{
//bool FIleExists= Rho_SubFolder_Pass[strFolders[1].Contains(localFolder.Path.ToString())];
string[] StrSubFolders = strFolders[0].Split('/');
foreach (string Path in StrSubFolders)
{
try
{
bool BlankFolder = Rho_SubFolder_Pass[!string.IsNullOrEmpty(Path)];
subfolders = await localFolder.GetFoldersAsync();
foreach (StorageFolder appFolder in subfolders)
{
try
{
bool status = Rho_SubFolder_Pass[appFolder.Name.Contains(Path)];
localFolder = appFolder;
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
string[] picList = Directory.GetFiles(localFolder.Path);
try
{
bool image = Rho_SubFolder_Pass[fileName.Contains(".jpg")];
fileName = fileName.Replace(".jpg", FileNameSuffix + ".jpg");
}
catch (Exception ex)
{
fileName = fileName + FileNameSuffix;
}
foreach (string DeleteFile in picList)
{
try
{
bool fileexist = Rho_SubFolder_Pass[DeleteFile.Contains(FileNameSuffix)];
File.Delete(DeleteFile);
}
catch (Exception ex)
{
}
}
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
Task<Stream> outputStreamTask = storageFile.OpenStreamForWriteAsync();
Stream outputStream = outputStreamTask.Result;
var bitmap = new BitmapImage();
bitmap.SetSource(file);
var wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(outputStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
outputStream.Close();
TakePicture_output["imageUri"] = "\\" + storageFile.Name;
TakePicture_output["image_uri"] = "\\" + storageFile.Name;
StoreTakePictureResult.set(TakePicture_output);
}
/// <summary>
/// After clicking image this event is fired.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_CaptureImageAvailable");
Dictionary<bool, bool> stringnullorempty = new Dictionary<bool, bool>();
stringnullorempty.Add(false, false);
try
{
bool strstringnullorempty = stringnullorempty[String.IsNullOrEmpty(Rho_StringParameters["filename"])];
}
catch (Exception ex)
{
Rho_StringParameters["filename"] = "Img";
}
string fileName = Rho_StringParameters["filename"] + "_" + DateTime.Now.ToLongDateString() + "_" + DateTime.Now.ToLongTimeString().Replace(':', '_');
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
try
{ // Write message to the UI thread.
LayoutGrid.Children.Remove(Rho_PhotoCameraCanvas);
MemoryStream ms = new MemoryStream();
e.ImageStream.CopyTo(ms);
MemoryStream oms = RotateStream(ms, (int)Rho_Camera_Rotation.Rotation);
byte[] imagebytes = oms.ToArray();
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save photo to the media library camera roll.
Picture PictDetails = Rho_Store_Picturelibrary.SavePictureToCameraRoll(fileName, imagebytes);
MemoryStream ms1 = new MemoryStream();
PictDetails.GetThumbnail().CopyTo(ms1);
strbase64 = System.Convert.ToBase64String(ms1.ToArray());
// Write message to the UI thread.
Return_To_Previous_Screen();
string returnablevalue = "";
m_Take_Picture_Output["status"] = "ok";
m_Take_Picture_Output["imageHeight"] = PictDetails.Height.ToString();
m_Take_Picture_Output["imageWidth"] = PictDetails.Width.ToString();
m_Take_Picture_Output["image_height"] = PictDetails.Height.ToString();
m_Take_Picture_Output["image_width"] = PictDetails.Width.ToString();
try
{
IEnumerable<KeyValuePair<string, string>> OutPutFormat = Rho_OutPutFormat.Select(x => x).Where(k => k.Value == "image").ToList();
foreach (KeyValuePair<string, string> format in OutPutFormat)
{
returnablevalue = Rho_FilePath + fileName + ".jpg";
e.ImageStream.Close();
Task Storetask = SaveToLocalFolderAsync(PictDetails.GetImage(), fileName, m_StoreTakePictureResult, m_Take_Picture_Output);
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_CaptureImageAvailable-->Dispatcher-->exception" + ex.ToString());
}
try
{
IEnumerable<KeyValuePair<string, string>> OutPutFormat = Rho_OutPutFormat.Select(x => x).Where(k => k.Value == "datauri").ToList();
foreach (KeyValuePair<string, string> format in OutPutFormat)
{
returnablevalue = "data:image/jpeg;base64," + strbase64;
m_Take_Picture_Output["image_uri"] = returnablevalue;
m_Take_Picture_Output["imageUri"] = returnablevalue;
e.ImageStream.Close();
m_StoreTakePictureResult.set(m_Take_Picture_Output);
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_CaptureImageAvailable-->OutPutFormat-->exception" + ex.ToString());
}
GC.Collect();
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->cam_CaptureImageAvailable-->exception" + ex.ToString());
m_Take_Picture_Output["status"] = "error";
m_Take_Picture_Output["message"] = ex.Message;
m_Take_Picture_Output["image_format"] = string.Empty;
m_Take_Picture_Output["imageFormat"] = string.Empty;
e.ImageStream.Close();
m_StoreTakePictureResult.set(m_Take_Picture_Output);
}
});
}
/// <summary>
/// On pressing Camera Hardware button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CameraButtons_ShutterKeyPressed(object sender, System.EventArgs e)
{
CaptureImage();
}
/// <summary>
/// on clicking on Screen.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Rho_PhotoCameraCanvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
CaptureImage();
}
/// <summary>
/// Capture the Image.
/// </summary>
void CaptureImage()
{
CRhoRuntime.getInstance().logEvent("Camera class-->CaptureImage");
if (Rho_StillCamera != null)
{
try
{
// Start image capture.
rootFrame.Unobscured -= rootFrame_Unobscured;
Rho_StillCamera.CaptureImage();
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->CaptureImage-->exception" + ex.ToString());
}
}
}
#endregion
/// <summary>
/// On changing the screen Orientation.
/// </summary>
/// <param name="sender">MainPage</param>
/// <param name="e">Type of Orienation</param>
void Rho_MainPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Rho_MainPage_OrientationChange");
//rhodes.MainPage.LayoutGrid().Dispatcher.BeginInvoke(delegate()
//{
SetCameraRotation(e.Orientation);
//});
}
/// <summary>
/// Initialize/Set the camera as per the Screen Rotation
/// </summary>
/// <param name="OrientationStyle"> Type of Orientation</param>
void SetCameraRotation(PageOrientation OrientationStyle)
{
try
{
CRhoRuntime.getInstance().logEvent("Camera class-->SetCameraRotation");
double rotation = Rho_StillCamera.Orientation;
// double strvalue = CameraRotation[OrientationStyle]["rotation"];
rotation = Rho_StillCamera.Orientation + CameraRotation[OrientationStyle]["rotation"];
Rho_PhotoCameraCanvas.Height = CameraRotation[OrientationStyle]["Height"];
Rho_PhotoCameraCanvas.Width = CameraRotation[OrientationStyle]["Width"];
try
{
rotation = Rho_StillCamera.Orientation + CameraRotation[OrientationStyle][_strID];
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->SetCameraRotation-->LandScapeMode" + ex.ToString());
}
Rho_Camera_Rotation.Rotation = rotation;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->SetCameraRotation-->Exception" + ex.ToString());
}
}
# region Set the camera layout
/// <summary>
/// Create a camera Layout.
/// </summary>
private void Rho_Create_Camera_Layout()
{
CRhoRuntime.getInstance().logEvent("Camera class-->Rho_Create_Camera_Layout");
try
{
rootFrame = Rho_MainPage.RootVisual() as PhoneApplicationFrame;
//Create a desired Camera Object.
Rho_StillCamera = new Microsoft.Devices.PhotoCamera((CameraType)Rho_Camera_selected);
//Create a Video Brush for painting in Canvas.
Rho_PhotoCameraBrush = new VideoBrush();
//Create a Camera Rotaion Object.
Rho_Camera_Rotation = new CompositeTransform();
//Initialize CenterX and CenterY for Rho Camera Roation
Rho_Camera_Rotation.CenterX = 0.5;
Rho_Camera_Rotation.CenterY = 0.5;
//Add the Screen rotation to Composite Transformation object as this object takes care of rotating the camera.
Rho_Camera_Rotation.Rotation = Rho_StillCamera.Orientation;
Rho_PhotoCameraBrush.Stretch = Stretch.Fill;
//Set Composite transform object to PhotoBrush.
Rho_PhotoCameraBrush.RelativeTransform = Rho_Camera_Rotation;
// Create a Canvas for painting the image.
Rho_PhotoCameraCanvas = new Canvas();
//Create Canvas for the whole screen.
ColumnDefinition Rho_Camera_Columncollection = new ColumnDefinition();
//check if the set orienation is required, if it is front camera then we may have to do some extra calculation. else it appears upside down.
SetCameraRotation(Rho_MainPage.Orientation);
//Set Desired camera as a child for Camera Brush.
Rho_PhotoCameraBrush.SetSource(Rho_StillCamera);
//Add Camera Brush as background to the Canvas.
Rho_PhotoCameraCanvas.Background = Rho_PhotoCameraBrush;
//Add canvas to the Main screen object.
LayoutGrid.Children.Add(Rho_PhotoCameraCanvas);
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Rho_Create_Camera_Layout-->Exception " + ex.ToString());
}
}
#endregion
}
#region Singleton class
/// <summary>
/// Singleton class
/// </summary>
public class CameraSingleton : CameraSingletonBase
{
object _rhoruntime;
PhotoChooserTask photoChooserTask;
Dictionary<string, int> Rho_CameraTypes = new Dictionary<string, int>();
IMethodResult m_StorechoosePictureResult;
Dictionary<string, string> m_choosePicture_output = new Dictionary<string, string>();
string Store_CaptureImage_outputformat = "image";
Dictionary<string, string> Data_Uri = new Dictionary<string, string>();
Dictionary<string, string> Imageoutputformat = new Dictionary<string, string>();
IReadOnlyList<StorageFolder> subfolders;
IReadOnlyList<StorageFolder> subfoldersfolders;
IReadOnlyList<StorageFolder> subfolders_App;
/// <summary>
/// Initialize DataURI and Image types.
/// </summary>
public CameraSingleton()
{
CRhoRuntime.getInstance().logEvent("Camera class-->CameraSingleton");
Data_Uri.Add("datauri", "outputformat");
Imageoutputformat.Add("image", "outputformat");
// initialize singleton instance in C# here
}
/// <summary>
/// Get the list of supported Camera
/// </summary>
/// <param name="oResult"></param>
public override void enumerate(IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class-->enumerate");
List<string> AvailabeCameras = new List<string>();
try
{
PhotoCamera Primary = new PhotoCamera(CameraType.Primary);
AvailabeCameras.Add("back");
}
catch (Exception ex)
{
}
try
{
PhotoCamera FrontCamera = new PhotoCamera(CameraType.FrontFacing);
AvailabeCameras.Add("front");
}
catch (Exception ex)
{
//Throw the Exception //Simha
}
oResult.set(AvailabeCameras);
}
/// <summary>
/// Get whether the supplied camera type is supported or not.
/// </summary>
/// <param name="cameraType">type of camera supported (back or front)</param>
/// <param name="oResult"></param>
public override void getCameraByType(string cameraType, IMethodResult oResult)
{
string CameraByTypeReturnType = null;
CRhoRuntime.getInstance().logEvent("Camera class-->getCameraByType");
try
{
Rho_CameraTypes.Clear();
Rho_CameraTypes.Add("back", 0);
Rho_CameraTypes.Add("front", 1);
List<string> AvailabeCameras = new List<string>();
PhotoCamera CameraCheck = new PhotoCamera((CameraType)Rho_CameraTypes[cameraType.Trim().ToLower()]);
CameraByTypeReturnType = cameraType;
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->getCameraByType-->Exception" + ex.ToString());
}
oResult.set(CameraByTypeReturnType);
}
/// <summary>
/// Choose the Pictures from the shown list.
/// </summary>
/// <param name="propertyMap">supports only outputformat.</param>
/// <param name="oResult"></param>
public override void choosePicture(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
CRhoRuntime.getInstance().logEvent("Camera class-->choosePicture");
try
{
m_StorechoosePictureResult = oResult;
Initialize_choosePicture();
try
{
Store_CaptureImage_outputformat = propertyMap["outputFormat"].ToLower().Trim();
}
catch (Exception ex)
{
}
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += photoChooserTask_Completed;
photoChooserTask.Show();
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->choosePicture-->Exception" + ex.ToString());
m_choosePicture_output["status"] = "error";
m_choosePicture_output["message"] = ex.Message;
m_choosePicture_output["image_format"] = string.Empty;
m_StorechoosePictureResult.set(m_choosePicture_output);
}
}
/// <summary>
/// Initialize the callback with the default values.
/// </summary>
private void Initialize_choosePicture()
{
CRhoRuntime.getInstance().logEvent("Camera class-->Initialize_choosePicture");
m_choosePicture_output.Clear();
m_choosePicture_output.Add("status", "cancel");
m_choosePicture_output.Add("imageUri", string.Empty);
m_choosePicture_output.Add("imageHeight", string.Empty);
m_choosePicture_output.Add("imageWidth", string.Empty);
m_choosePicture_output.Add("imageFormat", "jpg");
m_choosePicture_output.Add("message", string.Empty);
m_choosePicture_output.Add("image_uri", string.Empty);
m_choosePicture_output.Add("image_height", string.Empty);
m_choosePicture_output.Add("image_width", string.Empty);
m_choosePicture_output.Add("image_format", "jpg");
}
/// <summary>
/// After selecting the Picture this event is raised.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void photoChooserTask_Completed(object sender, PhotoResult e)
{
CRhoRuntime.getInstance().logEvent("Camera class-->photoChooserTask_Completed");
try
{
if (e.TaskResult == TaskResult.OK)
{
string ReturnValue = e.OriginalFileName;
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
m_choosePicture_output["imageHeight"] = bmp.PixelHeight.ToString();
m_choosePicture_output["imageWidth"] = bmp.PixelWidth.ToString();
m_choosePicture_output["image_height"] = bmp.PixelHeight.ToString();
m_choosePicture_output["image_width"] = bmp.PixelWidth.ToString();
m_choosePicture_output["status"] = "ok";
try
{
string Data = Data_Uri[Store_CaptureImage_outputformat];
double TargetScreenDivisor = 1;
Dictionary<bool, bool> ReducedResolutionforbase64 = new Dictionary<bool, bool>();
ReducedResolutionforbase64.Add(true, true);
for (int Divider = 70; Divider > 0; Divider -= 2)
{
try
{
int val = (int)Math.Abs(bmp.PixelHeight / Divider);
bool FirstCondition = ReducedResolutionforbase64[val > (int)Math.Abs(Application.Current.Host.Content.ActualHeight / 6) && val < (int)Math.Abs(Application.Current.Host.Content.ActualHeight / 5)];
// implement non hardcoded logic for scaled down images/thumbnail.
TargetScreenDivisor = Divider;
}
catch (Exception ex)
{
}
}
MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(bmp);
int imageWidth = (int)Math.Abs(bmp.PixelWidth / TargetScreenDivisor);
int imageHeight = (int)Math.Abs(bmp.PixelHeight / TargetScreenDivisor);
wb.SaveJpeg(ms, imageWidth, imageHeight, 0, 100);
byte[] imagebytes = ms.ToArray();
ReturnValue = "data:image/jpeg;base64," + System.Convert.ToBase64String(imagebytes);
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Not an Data URI");
}
try
{
string Data = Imageoutputformat[Store_CaptureImage_outputformat];
Task Storetask = SaveToLocalFolderAsync(e.ChosenPhoto, e.OriginalFileName.Split('\\')[e.OriginalFileName.Split('\\').Length - 1], m_StorechoosePictureResult, m_choosePicture_output);
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->Not an Image");
m_choosePicture_output["imageUri"] = ReturnValue;
m_choosePicture_output["image_uri"] = ReturnValue;
m_StorechoosePictureResult.set(m_choosePicture_output);
}
}
else
{
m_choosePicture_output["status"] = "cancel";
m_choosePicture_output["image_format"] = string.Empty;
m_choosePicture_output["imageFormat"] = string.Empty;
m_StorechoosePictureResult.set(m_choosePicture_output);
}
}
catch (Exception ex)
{
CRhoRuntime.getInstance().logEvent("Camera class-->photoChooserTask_Completed--> Exception" + ex.ToString());
m_choosePicture_output["status"] = "error";
m_choosePicture_output["message"] = ex.Message;
m_choosePicture_output["image_format"] = string.Empty;
m_StorechoosePictureResult.set(m_choosePicture_output);
}
}
/// <summary>
/// Stores file in its own virtual drive rho\apps\app
/// </summary>
/// <param name="file">Stream of file that needs to be saved in the Location.</param>
/// <param name="fileName">Name i n which the file needs to be saved</param>
/// <param name="StorechoosePictureResult">Callback event</param>
/// <param name="choosePicture_output">The path of the image needs to be stored</param>
/// <returns>Successll or error</returns>
public async Task SaveToLocalFolderAsync(Stream file, string fileName, IMethodResult StorechoosePictureResult, Dictionary<string, string> choosePicture_output)
{
string FileNameSuffix = "__DTF__";
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string strLocalFolder = CRhoRuntime.getInstance().getRootPath(ApplicationData.Current.LocalFolder.Path.ToString());
string[] strFolders = strLocalFolder.Split(new string[] { ApplicationData.Current.LocalFolder.Path.ToString() }, StringSplitOptions.None);
Dictionary<bool, bool> Rho_SubFolder_Pass = new Dictionary<bool, bool>();
Rho_SubFolder_Pass.Add(true, true);
try
{
//bool FIleExists= Rho_SubFolder_Pass[strFolders[1].Contains(localFolder.Path.ToString())];
string[] StrSubFolders = strFolders[0].Split('/');
foreach (string Path in StrSubFolders)
{
try
{
bool BlankFolder = Rho_SubFolder_Pass[!string.IsNullOrEmpty(Path)];
subfolders = await localFolder.GetFoldersAsync();
foreach (StorageFolder appFolder in subfolders)
{
try
{
bool status = Rho_SubFolder_Pass[appFolder.Name.Contains(Path)];
localFolder = appFolder;
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
string[] picList = Directory.GetFiles(localFolder.Path);
fileName = fileName.Replace(".jpg", FileNameSuffix + ".jpg");
foreach (string DeleteFile in picList)
{
try
{
bool fileexist = Rho_SubFolder_Pass[DeleteFile.Contains(FileNameSuffix)];
File.Delete(DeleteFile);
}
catch (Exception ex)
{
}
}
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
Task<Stream> outputStreamTask = storageFile.OpenStreamForWriteAsync();
Stream outputStream = outputStreamTask.Result;
var bitmap = new BitmapImage();
bitmap.SetSource(file);
var wb = new WriteableBitmap(bitmap);
wb.SaveJpeg(outputStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
outputStream.Close();
choosePicture_output["imageUri"] = "\\" + storageFile.Name;
choosePicture_output["image_uri"] = "\\" + storageFile.Name;
StorechoosePictureResult.set(choosePicture_output);
}
/// <summary>
/// Not supported by WP8.
/// </summary>
/// <param name="pathToImage"></param>
/// <param name="oResult"></param>
public override void copyImageToDeviceGallery(string pathToImage, IMethodResult oResult)
{
// implement this method in C# here
}
}
public class CameraFactory : CameraFactoryBase
{
public override ICameraImpl getImpl()
{
Camera storecamera = null; ;
try
{
return new Camera();
}
catch (Exception ex)
{
rhodes.MainPage.LayoutGrid().Dispatcher.BeginInvoke(delegate()
{
storecamera = new Camera();
});
while (storecamera == null)
{
Thread.Sleep(1000);
}
return storecamera;
}
}
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Core;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Extension methods for grains.
/// </summary>
public static class GrainExtensions
{
private const string WRONG_GRAIN_ERROR_MSG = "Passing a half baked grain as an argument. It is possible that you instantiated a grain class explicitly, as a regular object and not via Orleans runtime or via proper test mocking";
internal static GrainReference AsWeaklyTypedReference(this IAddressable grain)
{
ThrowIfNullGrain(grain);
// When called against an instance of a grain reference class, do nothing
var reference = grain as GrainReference;
if (reference != null) return reference;
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Data?.GrainReference == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, nameof(grain));
}
return grainBase.Data.GrainReference;
}
var systemTarget = grain as ISystemTargetBase;
if (systemTarget != null) return GrainReference.FromGrainId(systemTarget.GrainId, systemTarget.RuntimeClient.GrainReferenceRuntime, null, systemTarget.Silo);
throw new ArgumentException(
$"AsWeaklyTypedReference has been called on an unexpected type: {grain.GetType().FullName}.",
nameof(grain));
}
/// <summary>
/// Converts this grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to convert.</param>
/// <returns>A strongly typed <c>GrainReference</c> of grain interface type TGrainInterface.</returns>
public static TGrainInterface AsReference<TGrainInterface>(this IAddressable grain)
{
ThrowIfNullGrain(grain);
var grainReference = grain.AsWeaklyTypedReference();
return grainReference.Runtime.Convert<TGrainInterface>(grainReference);
}
/// <summary>
/// Casts a grain to a specific grain interface.
/// </summary>
/// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
/// <param name="grain">The grain to cast.</param>
public static TGrainInterface Cast<TGrainInterface>(this IAddressable grain)
{
return grain.AsReference<TGrainInterface>();
}
/// <summary>
/// Binds the grain reference to the provided <see cref="IGrainFactory"/>.
/// </summary>
/// <param name="grain">The grain reference.</param>
/// <param name="grainFactory">The grain factory.</param>
public static void BindGrainReference(this IAddressable grain, IGrainFactory grainFactory)
{
grainFactory.BindGrainReference(grain);
}
internal static GrainId GetGrainId(IAddressable grain)
{
var reference = grain as GrainReference;
if (reference != null)
{
if (reference.GrainId == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return reference.GrainId;
}
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Data == null || grainBase.Data.Identity == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainBase.Data.Identity;
}
throw new ArgumentException(String.Format("GetGrainId has been called on an unexpected type: {0}.", grain.GetType().FullName), "grain");
}
public static IGrainIdentity GetGrainIdentity(this IGrain grain)
{
var grainBase = grain as Grain;
if (grainBase != null)
{
if (grainBase.Identity == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainBase.Identity;
}
var grainReference = grain as GrainReference;
if (grainReference != null)
{
if (grainReference.GrainId == null)
{
throw new ArgumentException(WRONG_GRAIN_ERROR_MSG, "grain");
}
return grainReference.GrainId;
}
throw new ArgumentException(String.Format("GetGrainIdentity has been called on an unexpected type: {0}.", grain.GetType().FullName), "grain");
}
/// <summary>
/// Returns whether part of the primary key is of type long.
/// </summary>
/// <param name="grain">The target grain.</param>
public static bool IsPrimaryKeyBasedOnLong(this IAddressable grain)
{
return GetGrainId(grain).IsLongKey;
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output paramater to return the extended key part of the grain primary key, if extened primary key was provided for that grain.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain, out string keyExt)
{
return GetGrainId(grain).GetPrimaryKeyLong(out keyExt);
}
/// <summary>
/// Returns the long representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A long representing the primary key for this grain.</returns>
public static long GetPrimaryKeyLong(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKeyLong();
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <param name="keyExt">The output paramater to return the extended key part of the grain primary key, if extened primary key was provided for that grain.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain, out string keyExt)
{
return GetGrainId(grain).GetPrimaryKey(out keyExt);
}
/// <summary>
/// Returns the Guid representation of a grain primary key.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A Guid representing the primary key for this grain.</returns>
public static Guid GetPrimaryKey(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKey();
}
/// <summary>
/// Returns the string primary key of the grain.
/// </summary>
/// <param name="grain">The grain to find the primary key for.</param>
/// <returns>A string representing the primary key for this grain.</returns>
public static string GetPrimaryKeyString(this IAddressable grain)
{
return GetGrainId(grain).GetPrimaryKeyString();
}
public static long GetPrimaryKeyLong(this IGrain grain, out string keyExt)
{
return GetGrainIdentity(grain).GetPrimaryKeyLong(out keyExt);
}
public static long GetPrimaryKeyLong(this IGrain grain)
{
return GetGrainIdentity(grain).PrimaryKeyLong;
}
public static Guid GetPrimaryKey(this IGrain grain, out string keyExt)
{
return GetGrainIdentity(grain).GetPrimaryKey(out keyExt);
}
public static Guid GetPrimaryKey(this IGrain grain)
{
return GetGrainIdentity(grain).PrimaryKey;
}
public static string GetPrimaryKeyString(this IGrainWithStringKey grain)
{
return GetGrainIdentity(grain).PrimaryKeyString;
}
/// <summary>
/// Invokes a method of a grain interface is one-way fashion so that no response message will be sent to the caller.
/// </summary>
/// <typeparam name="T">Grain interface</typeparam>
/// <param name="grainReference">Grain reference which will be copied and then a call executed on it</param>
/// <param name="grainMethodInvocation">Function that should invoke grain method and return resulting task</param>
public static void InvokeOneWay<T>(this T grainReference, Func<T, Task> grainMethodInvocation) where T : class, IAddressable
{
var oneWayGrainReferenceCopy = new GrainReference(grainReference.AsWeaklyTypedReference(), InvokeMethodOptions.OneWay).Cast<T>();
// Task is always completed at this point. Should also help to catch situations of mistakenly calling the method on original grain reference
var invokationResult = grainMethodInvocation(oneWayGrainReferenceCopy);
if (!invokationResult.IsCompleted)
{
throw new InvalidOperationException("Invoking of methods with one way flag must result in completed task");
}
}
private static void ThrowIfNullGrain(IAddressable grain)
{
if (grain == null)
{
throw new ArgumentNullException(nameof(grain));
}
}
}
}
| |
//
// BlobStoreWriter.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// 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.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Util;
using Sharpen;
using System.Collections.Generic;
using System.Linq;
using Couchbase.Lite.Store;
using System.Security.Cryptography;
namespace Couchbase.Lite
{
/// <summary>Lets you stream a large attachment to a BlobStore asynchronously, e.g.</summary>
/// <remarks>Lets you stream a large attachment to a BlobStore asynchronously, e.g. from a network download.
/// </remarks>
internal class BlobStoreWriter
{
/// <summary>The underlying blob store where it should be stored.</summary>
/// <remarks>The underlying blob store where it should be stored.</remarks>
private BlobStore store;
/// <summary>The number of bytes in the blob.</summary>
/// <remarks>The number of bytes in the blob.</remarks>
private long length;
/// <summary>After finishing, this is the key for looking up the blob through the CBL_BlobStore.
/// </summary>
/// <remarks>After finishing, this is the key for looking up the blob through the CBL_BlobStore.
/// </remarks>
private BlobKey blobKey;
/// <summary>After finishing, store md5 digest result here</summary>
private byte[] md5DigestResult;
/// <summary>Message digest for sha1 that is updated as data is appended</summary>
private MessageDigest sha1Digest;
private MessageDigest md5Digest;
private Stream outStream;
private FilePath tempFile;
public string FilePath
{
get { return tempFile.GetPath(); }
}
public BlobStoreWriter(BlobStore store)
{
this.store = store;
try
{
sha1Digest = MessageDigest.GetInstance("SHA-1");
sha1Digest.Reset();
md5Digest = MessageDigest.GetInstance("MD5");
md5Digest.Reset();
}
catch (NoSuchAlgorithmException e)
{
throw new InvalidOperationException("Could not get an instance of SHA-1 or MD5." , e);
}
try
{
OpenTempFile();
}
catch (FileNotFoundException e)
{
throw new InvalidOperationException("Unable to open temporary file.", e);
}
}
/// <exception cref="System.IO.FileNotFoundException"></exception>
private void OpenTempFile()
{
string uuid = Misc.CreateGUID();
string filename = string.Format("{0}.blobtmp", uuid);
FilePath tempDir = store.TempDir();
tempFile = new FilePath(tempDir, filename);
if (store.EncryptionKey == null) {
outStream = new BufferedStream(File.Open (tempFile.GetAbsolutePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
} else {
outStream = store.EncryptionKey.CreateStream(
new BufferedStream(File.Open(tempFile.GetAbsolutePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)));
}
}
/// <summary>Appends data to the blob.</summary>
/// <remarks>Appends data to the blob. Call this when new data is available.</remarks>
public void AppendData(IEnumerable<Byte> data)
{
var dataVector = data.ToArray();
length += dataVector.LongLength;
sha1Digest.Update(dataVector);
md5Digest.Update(dataVector);
try {
outStream.Write(dataVector, 0, dataVector.Length);
} catch (IOException e) {
throw new CouchbaseLiteException("Unable to write to stream.", e) { Code = StatusCode.Exception };
}
}
internal void Read(InputStream inputStream)
{
byte[] buffer = new byte[16384];
int len;
length = 0;
try
{
while ((len = inputStream.Read(buffer)) != -1)
{
var dataToWrite = buffer;
outStream.Write(dataToWrite, 0, len);
sha1Digest.Update(buffer, 0, len);
md5Digest.Update(buffer, 0, len);
length += len;
}
}
catch (IOException e)
{
throw new RuntimeException("Unable to read from stream.", e);
}
finally
{
try
{
inputStream.Close();
}
catch (IOException e)
{
Log.W(Database.TAG, "Exception closing input stream", e);
}
}
}
/// <summary>Call this after all the data has been added.</summary>
public void Finish()
{
try {
outStream.Flush();
outStream.Close();
} catch (IOException e) {
Log.W(Database.TAG, "Exception closing output stream", e);
}
blobKey = new BlobKey(sha1Digest.Digest());
md5DigestResult = md5Digest.Digest();
}
/// <summary>Call this to cancel before finishing the data.</summary>
public void Cancel()
{
try {
outStream.Close();
} catch (IOException e) {
Log.W(Database.TAG, "Exception closing output stream", e);
}
tempFile.Delete();
}
/// <summary>Installs a finished blob into the store.</summary>
public void Install()
{
if (tempFile == null)
{
return;
}
// already installed
// Move temp file to correct location in blob store:
string destPath = store.PathForKey(blobKey);
FilePath destPathFile = new FilePath(destPath);
bool result = tempFile.RenameTo(destPathFile);
// If the move fails, assume it means a file with the same name already exists; in that
// case it must have the identical contents, so we're still OK.
if (result == false)
{
Cancel();
}
tempFile = null;
}
public string MD5DigestString()
{
string base64Md5Digest = Convert.ToBase64String(md5DigestResult);
return string.Format("md5-{0}", base64Md5Digest);
}
public string SHA1DigestString()
{
string base64Sha1Digest = Convert.ToBase64String(blobKey.Bytes);
return string.Format("sha1-{0}", base64Sha1Digest);
}
public long GetLength()
{
return length;
}
public BlobKey GetBlobKey()
{
return blobKey;
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents accessing a field or property.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.MemberExpressionProxy))]
public class MemberExpression : Expression
{
private readonly Expression _expression;
/// <summary>
/// Gets the field or property to be accessed.
/// </summary>
public MemberInfo Member
{
get { return GetMember(); }
}
/// <summary>
/// Gets the containing object of the field or property.
/// </summary>
public Expression Expression
{
get { return _expression; }
}
// param order: factories args in order, then other args
internal MemberExpression(Expression expression)
{
_expression = expression;
}
internal static PropertyExpression Make(Expression expression, PropertyInfo property)
{
Debug.Assert(property != null);
return new PropertyExpression(expression, property);
}
internal static FieldExpression Make(Expression expression, FieldInfo field)
{
Debug.Assert(field != null);
return new FieldExpression(expression, field);
}
internal static MemberExpression Make(Expression expression, MemberInfo member)
{
FieldInfo fi = member as FieldInfo;
return fi == null ? (MemberExpression)Make(expression, (PropertyInfo)member) : Make(expression, fi);
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.MemberAccess; }
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual MemberInfo GetMember()
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitMember(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expression">The <see cref="Expression" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public MemberExpression Update(Expression expression)
{
if (expression == Expression)
{
return this;
}
return Expression.MakeMemberAccess(expression, Member);
}
}
internal class FieldExpression : MemberExpression
{
private readonly FieldInfo _field;
public FieldExpression(Expression expression, FieldInfo member)
: base(expression)
{
_field = member;
}
internal override MemberInfo GetMember()
{
return _field;
}
public sealed override Type Type
{
get { return _field.FieldType; }
}
}
internal class PropertyExpression : MemberExpression
{
private readonly PropertyInfo _property;
public PropertyExpression(Expression expression, PropertyInfo member)
: base(expression)
{
_property = member;
}
internal override MemberInfo GetMember()
{
return _property;
}
public sealed override Type Type
{
get { return _property.PropertyType; }
}
}
public partial class Expression
{
#region Field
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="field">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Field(Expression expression, FieldInfo field)
{
ContractUtils.RequiresNotNull(field, nameof(field));
if (field.IsStatic)
{
if (expression != null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(expression));
}
else
{
if (expression == null) throw Error.OnlyStaticFieldsHaveNullInstance(nameof(field));
RequiresCanRead(expression, nameof(expression));
if (!TypeUtils.AreReferenceAssignable(field.DeclaringType, expression.Type))
{
throw Error.FieldInfoNotDefinedForType(field.DeclaringType, field.Name, expression.Type);
}
}
return MemberExpression.Make(expression, field);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="fieldName">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Field(Expression expression, string fieldName)
{
RequiresCanRead(expression, nameof(expression));
ContractUtils.RequiresNotNull(fieldName, nameof(fieldName));
// bind to public names first
FieldInfo fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi == null)
{
fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (fi == null)
{
throw Error.InstanceFieldNotDefinedForType(fieldName, expression.Type);
}
return Expression.Field(expression, fi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a field.
/// </summary>
/// <param name="expression">The containing object of the field. This can be null for static fields.</param>
/// <param name="type">The <see cref="Type"/> containing the field.</param>
/// <param name="fieldName">The field to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Field(Expression expression, Type type, string fieldName)
{
ContractUtils.RequiresNotNull(type, nameof(type));
// bind to public names first
FieldInfo fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi == null)
{
fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (fi == null)
{
throw Error.FieldNotDefinedForType(fieldName, type);
}
return Expression.Field(expression, fi);
}
#endregion
#region Property
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="propertyName">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, string propertyName)
{
RequiresCanRead(expression, nameof(expression));
ContractUtils.RequiresNotNull(propertyName, nameof(propertyName));
// bind to public names first
PropertyInfo pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi == null)
{
pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (pi == null)
{
throw Error.InstancePropertyNotDefinedForType(propertyName, expression.Type, nameof(propertyName));
}
return Property(expression, pi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="type">The <see cref="Type"/> containing the property.</param>
/// <param name="propertyName">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, Type type, string propertyName)
{
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(propertyName, nameof(propertyName));
// bind to public names first
PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi == null)
{
pi = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
}
if (pi == null)
{
throw Error.PropertyNotDefinedForType(propertyName, type, nameof(propertyName));
}
return Property(expression, pi);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="property">The property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")]
public static MemberExpression Property(Expression expression, PropertyInfo property)
{
ContractUtils.RequiresNotNull(property, nameof(property));
MethodInfo mi = property.GetGetMethod(true);
if (mi == null)
{
mi = property.GetSetMethod(true);
if (mi == null)
{
throw Error.PropertyDoesNotHaveAccessor(property, nameof(property));
}
else if (mi.GetParametersCached().Length != 1)
{
throw Error.IncorrectNumberOfMethodCallArguments(mi, nameof(property));
}
}
else if (mi.GetParametersCached().Length != 0)
{
throw Error.IncorrectNumberOfMethodCallArguments(mi, nameof(property));
}
if (mi.IsStatic)
{
if (expression != null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(expression));
}
else
{
if (expression == null) throw Error.OnlyStaticPropertiesHaveNullInstance(nameof(property));
RequiresCanRead(expression, nameof(expression));
if (!TypeUtils.IsValidInstanceType(property, expression.Type))
{
throw Error.PropertyNotDefinedForType(property, expression.Type, nameof(property));
}
}
return MemberExpression.Make(expression, property);
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property.
/// </summary>
/// <param name="expression">The containing object of the property. This can be null for static properties.</param>
/// <param name="propertyAccessor">An accessor method of the property to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression Property(Expression expression, MethodInfo propertyAccessor)
{
ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor));
ValidateMethodInfo(propertyAccessor, nameof(propertyAccessor));
return Property(expression, GetProperty(propertyAccessor, nameof(propertyAccessor)));
}
private static PropertyInfo GetProperty(MethodInfo mi, string paramName, int index = -1)
{
Type type = mi.DeclaringType;
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
flags |= (mi.IsStatic) ? BindingFlags.Static : BindingFlags.Instance;
var props = type.GetProperties(flags);
foreach (PropertyInfo pi in props)
{
if (pi.CanRead && CheckMethod(mi, pi.GetGetMethod(true)))
{
return pi;
}
if (pi.CanWrite && CheckMethod(mi, pi.GetSetMethod(true)))
{
return pi;
}
}
throw Error.MethodNotPropertyAccessor(mi.DeclaringType, mi.Name, paramName, index);
}
private static bool CheckMethod(MethodInfo method, MethodInfo propertyMethod)
{
if (method.Equals(propertyMethod))
{
return true;
}
// If the type is an interface then the handle for the method got by the compiler will not be the
// same as that returned by reflection.
// Check for this condition and try and get the method from reflection.
Type type = method.DeclaringType;
if (type.GetTypeInfo().IsInterface && method.Name == propertyMethod.Name && type.GetMethod(method.Name) == propertyMethod)
{
return true;
}
return false;
}
#endregion
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property or field.
/// </summary>
/// <param name="expression">The containing object of the member. This can be null for static members.</param>
/// <param name="propertyOrFieldName">The member to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
{
RequiresCanRead(expression, nameof(expression));
// bind to public names first
PropertyInfo pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi != null)
return Property(expression, pi);
FieldInfo fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi != null)
return Field(expression, fi);
pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (pi != null)
return Property(expression, pi);
fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy);
if (fi != null)
return Field(expression, fi);
throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type, nameof(propertyOrFieldName));
}
/// <summary>
/// Creates a <see cref="MemberExpression"/> accessing a property or field.
/// </summary>
/// <param name="expression">The containing object of the member. This can be null for static members.</param>
/// <param name="member">The member to be accessed.</param>
/// <returns>The created <see cref="MemberExpression"/>.</returns>
public static MemberExpression MakeMemberAccess(Expression expression, MemberInfo member)
{
ContractUtils.RequiresNotNull(member, nameof(member));
FieldInfo fi = member as FieldInfo;
if (fi != null)
{
return Expression.Field(expression, fi);
}
PropertyInfo pi = member as PropertyInfo;
if (pi != null)
{
return Expression.Property(expression, pi);
}
throw Error.MemberNotFieldOrProperty(member, nameof(member));
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.TrackingAnalyst;
using ESRI.ArcGIS.Geodatabase;
using TemporalStatistics2008;
using ESRI.ArcGIS.GeoDatabaseExtensions;
namespace TemporalStatistics
{
public sealed partial class MainForm : Form
{
#region class private members
private IMapControl3 m_mapControl = null;
private string m_mapDocumentName = string.Empty;
#endregion
IWorkspaceFactory m_amsWorkspaceFactory = null;
bool m_bTAInitialized = false;
private const string TEMPORALLAYERCLSID = "{78C7430C-17CF-11D5-B7CF-00010265ADC5}"; //CLSID for ITemporalLayer
#region class constructor
public MainForm()
{
InitializeComponent();
}
#endregion
private void MainForm_Load(object sender, EventArgs e)
{
//get the MapControl
m_mapControl = (IMapControl3)axMapControl1.Object;
//disable the Save menu (since there is no document yet)
menuSaveDoc.Enabled = false;
timerStats.Start();
}
#region Main Menu event handlers
private void menuNewDoc_Click(object sender, EventArgs e)
{
//execute New Document command
ICommand command = new CreateNewDocument();
command.OnCreate(m_mapControl.Object);
command.OnClick();
}
private void menuOpenDoc_Click(object sender, EventArgs e)
{
//execute Open Document command
ICommand command = new ControlsOpenDocCommandClass();
command.OnCreate(m_mapControl.Object);
command.OnClick();
}
private void menuSaveDoc_Click(object sender, EventArgs e)
{
//execute Save Document command
if (m_mapControl.CheckMxFile(m_mapDocumentName))
{
//create a new instance of a MapDocument
IMapDocument mapDoc = new MapDocumentClass();
mapDoc.Open(m_mapDocumentName, string.Empty);
//Make sure that the MapDocument is not readonly
if (mapDoc.get_IsReadOnly(m_mapDocumentName))
{
MessageBox.Show("Map document is read only!");
mapDoc.Close();
return;
}
//Replace its contents with the current map
mapDoc.ReplaceContents((IMxdContents)m_mapControl.Map);
//save the MapDocument in order to persist it
mapDoc.Save(mapDoc.UsesRelativePaths, false);
//close the MapDocument
mapDoc.Close();
}
}
private void menuSaveAs_Click(object sender, EventArgs e)
{
//execute SaveAs Document command
ICommand command = new ControlsSaveAsDocCommandClass();
command.OnCreate(m_mapControl.Object);
command.OnClick();
}
private void menuExitApp_Click(object sender, EventArgs e)
{
//exit the application
Application.Exit();
}
#endregion
//listen to MapReplaced event in order to update the status bar and the Save menu
private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
{
//get the current document name from the MapControl
m_mapDocumentName = m_mapControl.DocumentFilename;
//if there is no MapDocument, disable the Save menu and clear the status bar
if (m_mapDocumentName == string.Empty)
{
menuSaveDoc.Enabled = false;
statusBarXY.Text = string.Empty;
}
else
{
//enable the Save menu and write the doc name to the status bar
menuSaveDoc.Enabled = true;
statusBarXY.Text = Path.GetFileName(m_mapDocumentName);
}
//Update combo list of tracking services
PopulateTrackingServices();
}
private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
{
statusBarXY.Text = string.Format("{0}, {1} {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), axMapControl1.MapUnits.ToString().Substring(4));
}
//Initialize the Tracking Analyst Environment
private ITrackingEnvironment3 setupTrackingEnv(ref object mapObj)
{
IExtensionManager extentionManager = new ExtensionManagerClass();
UID uid = new UIDClass();
uid.Value = "esriTrackingAnalyst.TrackingEngineUtil";
((IExtensionManagerAdmin)extentionManager).AddExtension(uid, ref mapObj);
ITrackingEnvironment3 trackingEnv = new TrackingEnvironmentClass();
trackingEnv.Initialize(ref mapObj);
trackingEnv.EnableTemporalDisplayManagement = true;
return trackingEnv;
}
//Periodically update the statistics information
private void timerStats_Tick(object sender, EventArgs e)
{
//Initialize TA if there is hasn't been already and there are Tracking layers in the map
if (!m_bTAInitialized &&
GetAllTrackingLayers() != null)
{
object oMapControl = m_mapControl;
ITrackingEnvironment3 taEnv = setupTrackingEnv(ref oMapControl);
//ITrackingEnvironment3 taEnv = setupTrackingEnv(ref oMapControl);
if (taEnv != null)
{
m_bTAInitialized = true;
}
//Need to refresh the map once to get the tracks moving
m_mapControl.Refresh(esriViewDrawPhase.esriViewGeography, null, null);
}
RefreshStatistics();
}
private void RefreshStatistics()
{
try
{
ITemporalLayer temporalLayer = GetSelectedTemporalLayer();
//If a temporal layer is selected in the combo box only update that layer's stats
if (temporalLayer == null)
{
RefreshAllStatistics();
}
else
{
RefreshLayerStatistics(temporalLayer.Name,
(ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass);
}
}
catch (Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
//Refresh the statistics for all tracking layers in the map
//The AMSWorkspaceFactory provides easy access to query the statistics for every layer at once
private void RefreshAllStatistics()
{
try
{
object oNames, oValues;
string[] sNames;
if (m_amsWorkspaceFactory == null)
{
m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass();
}
//Get the AMS Workspace Factory Statistics interface
ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory;
//Get the message rates for all the tracking connections in the map
IPropertySet psMessageRates = temporalWsfStatistics.AllMessageRates;
psMessageRates.GetAllProperties(out oNames, out oValues);
sNames = (string[])oNames;
object[] oaMessageRates = (object[])oValues;
//Get the feature counts for all the tracking connections in the map
IPropertySet psTotalFeatureCounts = temporalWsfStatistics.AllTotalFeatureCounts;
psTotalFeatureCounts.GetAllProperties(out oNames, out oValues);
object[] oaFeatureCounts = (object[])oValues;
//Get the connection status for all the tracking connections in the map
IPropertySet psConnectionStatus = temporalWsfStatistics.ConnectionStatus;
psConnectionStatus.GetAllProperties(out oNames, out oValues);
string[] sConnectionNames = (string[])oNames;
object[] oaConnectionStatus = (object[])oValues;
Hashtable htConnectionStatus = new Hashtable(sConnectionNames.Length);
for (int i = 0; i < sConnectionNames.Length; ++i)
{
htConnectionStatus.Add(sConnectionNames[i], oaConnectionStatus[i]);
}
//Get the track counts for all the tracking connections in the map
IPropertySet psTrackCounts = temporalWsfStatistics.AllTrackCounts;
psTrackCounts.GetAllProperties(out oNames, out oValues);
object[] oaTrackCounts = (object[])oValues;
//Get the sample sizes for all the tracking connections in the map
IPropertySet psSampleSizes = temporalWsfStatistics.AllSampleSizes;
psSampleSizes.GetAllProperties(out oNames, out oValues);
object[] oaSampleSizes = (object[])oValues;
//Clear the existing list view items and repopulate from the collection
lvStatistics.BeginUpdate();
lvStatistics.Items.Clear();
//Create list view items from statistics' IPropertySets
for (int i = 0; i < sNames.Length; ++i)
{
ListViewItem lvItem = new ListViewItem(sNames[i]);
lvItem.SubItems.Add(Convert.ToString(oaMessageRates[i]));
lvItem.SubItems.Add(Convert.ToString(oaFeatureCounts[i]));
string sConnName = sNames[i].Split(new Char[] { '/' })[0];
esriWorkspaceConnectionStatus eWCS = (esriWorkspaceConnectionStatus)Convert.ToInt32(htConnectionStatus[sConnName]);
lvItem.SubItems.Add(eWCS.ToString());
lvItem.SubItems.Add(Convert.ToString(oaTrackCounts[i]));
lvItem.SubItems.Add(Convert.ToString(oaSampleSizes[i]));
lvStatistics.Items.Add(lvItem);
}
lvStatistics.EndUpdate();
}
catch (System.Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
//Refresh the statistics for a single layer using the ITemporalFeatureClassStatistics
private void RefreshLayerStatistics(string sLayerName, ITemporalFeatureClassStatistics temporalFCStats)
{
ListViewItem lvItem = new ListViewItem(sLayerName);
lvItem.SubItems.Add(Convert.ToString(temporalFCStats.MessageRate));
lvItem.SubItems.Add(Convert.ToString(temporalFCStats.TotalFeatureCount));
lvItem.SubItems.Add("Not Available");
lvItem.SubItems.Add(Convert.ToString(temporalFCStats.TrackCount));
lvItem.SubItems.Add(Convert.ToString(temporalFCStats.SampleSize));
lvStatistics.Items.Clear();
lvStatistics.Items.Add(lvItem);
}
//Cause a manual refresh of the statistics, also update the timer interval
private void btnRefresh_Click(object sender, EventArgs e)
{
try
{
timerStats.Stop();
SetSampleSize();
RefreshStatistics();
double dTimerRate = Convert.ToDouble(txtRate.Text);
timerStats.Interval = Convert.ToInt32(dTimerRate * 1000);
timerStats.Start();
}
catch (Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
//Populate the combo box with the tracking services in the map
private void PopulateTrackingServices()
{
ILayer lyr = null;
IEnumLayer temporalLayers = GetAllTrackingLayers();
cbTrackingServices.Items.Clear();
cbTrackingServices.Items.Add("All");
if (temporalLayers != null)
{
while ((lyr = temporalLayers.Next()) != null)
{
cbTrackingServices.Items.Add(lyr.Name);
}
}
cbTrackingServices.SelectedIndex = 0;
}
//Query the map for all the tracking layers in it
private IEnumLayer GetAllTrackingLayers()
{
try
{
IUID uidTemoralLayer = new UIDClass();
uidTemoralLayer.Value = TEMPORALLAYERCLSID;
//This call throws an E_FAIL exception if the map has no layers, caught below
return m_mapControl.ActiveView.FocusMap.get_Layers((UID)uidTemoralLayer, true);
}
catch
{
return null;
}
}
//Get the tracking layer that is selected in the combo box according to its name
private ITemporalLayer GetSelectedTemporalLayer()
{
ITemporalLayer temporalLayer = null;
if (cbTrackingServices.SelectedIndex > 0)
{
ILayer lyr = null;
IEnumLayer temporalLayers = GetAllTrackingLayers();
string selectedLayerName = cbTrackingServices.Text;
while ((lyr = temporalLayers.Next()) != null)
{
if (lyr.Name == selectedLayerName)
{
temporalLayer = (ITemporalLayer)lyr;
}
}
}
return temporalLayer;
}
//Reset the statistic's feature count for one or all of the layers in the map
private void btnResetFC_Click(object sender, EventArgs e)
{
try
{
ITemporalLayer temporalLayer = GetSelectedTemporalLayer();
if (temporalLayer == null)
{
if (m_amsWorkspaceFactory == null)
{
m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass();
}
//Get the AMS Workspace Factory Statistics interface
ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory;
temporalWsfStatistics.ResetAllFeatureCounts();
}
else
{
ITemporalFeatureClassStatistics temporalFCStats =
(ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass;
temporalFCStats.ResetFeatureCount();
}
}
catch (Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
//Reset the statistic's message rate for one or all of the layers in the map
private void btnResetMsgRate_Click(object sender, EventArgs e)
{
try
{
ITemporalLayer temporalLayer = GetSelectedTemporalLayer();
if (temporalLayer == null)
{
if (m_amsWorkspaceFactory == null)
{
m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass();
}
//Get the AMS Workspace Factory Statistics interface
ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory;
temporalWsfStatistics.ResetAllMessageRates();
}
else
{
ITemporalFeatureClassStatistics temporalFCStats =
(ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass;
temporalFCStats.ResetMessageRate();
}
}
catch (Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
//Set the sampling size for one or all of the layers in the map
//The sampling size determines how many messages are factored into the message rate calculation.
//For instance a sampling size of 500 will store the times the last 500 messages were received.
//The message rate is calculated as the (oldest timestamp - current time) / number of messages
private void SetSampleSize()
{
try
{
int samplingSize = Convert.ToInt32(txtSampleSize.Text);
ITemporalLayer temporalLayer = GetSelectedTemporalLayer();
if (temporalLayer == null)
{
if (m_amsWorkspaceFactory == null)
{
m_amsWorkspaceFactory = new AMSWorkspaceFactoryClass();
}
//Get the AMS Workspace Factory Statistics interface
ITemporalWorkspaceStatistics temporalWsfStatistics = (ITemporalWorkspaceStatistics)m_amsWorkspaceFactory;
temporalWsfStatistics.SetAllSampleSizes(samplingSize);
}
else
{
ITemporalFeatureClassStatistics temporalFCStats =
(ITemporalFeatureClassStatistics)((IFeatureLayer)temporalLayer).FeatureClass;
temporalFCStats.SampleSize = samplingSize;
}
}
catch (Exception ex)
{
statusBarXY.Text = ex.Message;
}
}
private void cbTrackingServices_SelectionChangeCommitted(object sender, EventArgs e)
{
RefreshStatistics();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Test resource injections in tasks and jobs.
/// </summary>
public class ResourceTaskTest : AbstractTaskTest
{
/// <summary>
/// Constructor.
/// </summary>
public ResourceTaskTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected ResourceTaskTest(bool fork) : base(fork) { }
/// <summary>
/// Test Ignite injection into the task.
/// </summary>
[Test]
public void TestTaskInjection()
{
int res = Grid1.GetCompute().Execute(new InjectionTask(), 0);
Assert.AreEqual(GetServerCount(), res);
}
/// <summary>
/// Test Ignite injection into the closure.
/// </summary>
[Test]
public void TestClosureInjection()
{
var res = Grid1.GetCompute().Broadcast(new InjectionClosure(), 1);
Assert.AreEqual(GetServerCount(), res.Sum());
}
/// <summary>
/// Test Ignite injection into reducer.
/// </summary>
[Test]
public void TestReducerInjection()
{
int res = Grid1.GetCompute().Apply(new InjectionClosure(), new List<int> { 1, 1, 1 }, new InjectionReducer());
Assert.AreEqual(3, res);
}
/// <summary>
/// Test no-result-cache attribute.
/// </summary>
[Test]
public void TestNoResultCache()
{
int res = Grid1.GetCompute().Execute(new NoResultCacheTask(), 0);
Assert.AreEqual(GetServerCount(), res);
}
/// <summary>
/// Injection task.
/// </summary>
public class InjectionTask : Injectee, IComputeTask<object, int, int>
{
/** <inheritDoc /> */
public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg)
{
CheckInjection();
return subgrid.ToDictionary(x => (IComputeJob<int>) new InjectionJob(), x => x);
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd)
{
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public int Reduce(IList<IComputeJobResult<int>> results)
{
return results.Sum(res => res.Data);
}
}
/// <summary>
/// Injection job.
/// </summary>
[Serializable]
public class InjectionJob : Injectee, IComputeJob<int>
{
/// <summary>
///
/// </summary>
public InjectionJob()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public InjectionJob(SerializationInfo info, StreamingContext context) : base(info, context)
{
// No-op.
}
/** <inheritDoc /> */
public int Execute()
{
CheckInjection();
return 1;
}
public void Cancel()
{
// No-op.
}
}
/// <summary>
/// Injection closure.
/// </summary>
[Serializable]
public class InjectionClosure : IComputeFunc<int, int>
{
/** */
[InstanceResource]
private static IIgnite _staticGrid1;
/** */
[InstanceResource]
public static IIgnite StaticGrid2;
/// <summary>
///
/// </summary>
[InstanceResource]
public static IIgnite StaticPropGrid1
{
get { return _staticGrid1; }
set { _staticGrid1 = value; }
}
/// <summary>
///
/// </summary>
[InstanceResource]
private static IIgnite StaticPropGrid2
{
get { return StaticGrid2; }
set { StaticGrid2 = value; }
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
public static void StaticMethod1(IIgnite grid)
{
_staticGrid1 = grid;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
private static void StaticMethod2(IIgnite grid)
{
StaticGrid2 = grid;
}
/// <summary>
///
/// </summary>
public InjectionClosure()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public InjectionClosure(SerializationInfo info, StreamingContext context)
{
// No-op.
}
/** */
[InstanceResource]
private readonly IIgnite _grid1 = null;
/** */
[InstanceResource]
public IIgnite Grid2;
/** */
private IIgnite _mthdGrid1;
/** */
private IIgnite _mthdGrid2;
/// <summary>
///
/// </summary>
[InstanceResource]
public IIgnite PropGrid1
{
get;
set;
}
/// <summary>
///
/// </summary>
[InstanceResource]
private IIgnite PropGrid2
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
public void Method1(IIgnite grid)
{
_mthdGrid1 = grid;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
private void Method2(IIgnite grid)
{
_mthdGrid2 = grid;
}
/// <summary>
/// Check Ignite injections.
/// </summary>
protected void CheckInjection()
{
Assert.IsTrue(_staticGrid1 == null);
Assert.IsTrue(StaticGrid2 == null);
Assert.IsTrue(_grid1 != null);
Assert.IsTrue(Grid2 == _grid1);
Assert.IsTrue(PropGrid1 == _grid1);
Assert.IsTrue(PropGrid2 == _grid1);
Assert.IsTrue(_mthdGrid1 == _grid1);
Assert.IsTrue(_mthdGrid2 == _grid1);
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// No-op.
}
/** <inheritDoc /> */
public int Invoke(int arg)
{
CheckInjection();
return arg;
}
}
/// <summary>
/// Injection reducer.
/// </summary>
public class InjectionReducer : Injectee, IComputeReducer<int, int>
{
/** Collected results. */
private readonly ICollection<int> _ress = new List<int>();
/** <inheritDoc /> */
public bool Collect(int res)
{
CheckInjection();
lock (_ress)
{
_ress.Add(res);
}
return true;
}
/** <inheritDoc /> */
public int Reduce()
{
CheckInjection();
lock (_ress)
{
return _ress.Sum();
}
}
}
/// <summary>
/// Injectee.
/// </summary>
[Serializable]
public class Injectee : ISerializable
{
/** */
[InstanceResource]
private static IIgnite _staticGrid1;
/** */
[InstanceResource]
public static IIgnite StaticGrid2;
/// <summary>
///
/// </summary>
[InstanceResource]
public static IIgnite StaticPropGrid1
{
get { return _staticGrid1; }
set { _staticGrid1 = value; }
}
/// <summary>
///
/// </summary>
[InstanceResource]
private static IIgnite StaticPropGrid2
{
get { return StaticGrid2; }
set { StaticGrid2 = value; }
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
public static void StaticMethod1(IIgnite grid)
{
_staticGrid1 = grid;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
private static void StaticMethod2(IIgnite grid)
{
StaticGrid2 = grid;
}
/// <summary>
///
/// </summary>
public Injectee()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Injectee(SerializationInfo info, StreamingContext context)
{
// No-op.
}
/** */
[InstanceResource]
private readonly IIgnite _grid1 = null;
/** */
[InstanceResource]
public IIgnite Grid2;
/** */
private IIgnite _mthdGrid1;
/** */
private IIgnite _mthdGrid2;
/// <summary>
///
/// </summary>
[InstanceResource]
public IIgnite PropGrid1
{
get;
set;
}
/// <summary>
///
/// </summary>
[InstanceResource]
private IIgnite PropGrid2
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
public void Method1(IIgnite grid)
{
_mthdGrid1 = grid;
}
/// <summary>
///
/// </summary>
/// <param name="grid"></param>
[InstanceResource]
private void Method2(IIgnite grid)
{
_mthdGrid2 = grid;
}
/// <summary>
/// Check Ignite injections.
/// </summary>
protected void CheckInjection()
{
Assert.IsTrue(_staticGrid1 == null);
Assert.IsTrue(StaticGrid2 == null);
Assert.IsTrue(_grid1 != null);
Assert.IsTrue(Grid2 == _grid1);
Assert.IsTrue(PropGrid1 == _grid1);
Assert.IsTrue(PropGrid2 == _grid1);
Assert.IsTrue(_mthdGrid1 == _grid1);
Assert.IsTrue(_mthdGrid2 == _grid1);
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// No-op.
}
}
/// <summary>
///
/// </summary>
[ComputeTaskNoResultCache]
public class NoResultCacheTask : IComputeTask<int, int, int>
{
/** Sum. */
private int _sum;
/** <inheritDoc /> */
public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, int arg)
{
return subgrid.ToDictionary(x => (IComputeJob<int>) new NoResultCacheJob(), x => x);
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<int> res, IList<IComputeJobResult<int>> rcvd)
{
Assert.IsTrue(rcvd != null);
Assert.IsTrue(rcvd.Count == 0);
_sum += res.Data;
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public int Reduce(IList<IComputeJobResult<int>> results)
{
Assert.IsTrue(results != null);
Assert.IsTrue(results.Count == 0);
return _sum;
}
}
/// <summary>
///
/// </summary>
[Serializable]
public class NoResultCacheJob : IComputeJob<int>
{
/// <summary>
///
/// </summary>
public NoResultCacheJob()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public NoResultCacheJob(SerializationInfo info, StreamingContext context)
{
// No-op.
}
/** <inheritDoc /> */
public int Execute()
{
return 1;
}
public void Cancel()
{
// No-op.
}
}
}
}
| |
/*
* Stack.cs - Implementation of the "System.Collections.Stack" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Collections
{
#if !ECMA_COMPAT
using System;
using System.Private;
public class Stack : ICollection, IEnumerable, ICloneable
{
// Internal state.
private Object[] items;
private int size;
private int generation;
// The default capacity for stacks.
private const int DefaultCapacity = 10;
// The amount to grow the stack by each time.
private const int GrowSize = 10;
// Constructors.
public Stack()
{
items = new Object [DefaultCapacity];
size = 0;
generation = 0;
}
public Stack(int initialCapacity)
{
if(initialCapacity < 0)
{
throw new ArgumentOutOfRangeException
("initialCapacity", _("ArgRange_NonNegative"));
}
items = new Object [initialCapacity];
size = 0;
generation = 0;
}
public Stack(ICollection col)
{
if(col == null)
{
throw new ArgumentNullException("col");
}
items = new Object [col.Count];
col.CopyTo(items, 0);
size = items.Length;
generation = 0;
}
// Implement the ICollection interface.
public virtual void CopyTo(Array array, int index)
{
if(array == null)
{
throw new ArgumentNullException("array");
}
else if(array.Rank != 1)
{
throw new ArgumentException(_("Arg_RankMustBe1"));
}
else if(index < 0)
{
throw new ArgumentOutOfRangeException
("index", _("ArgRange_Array"));
}
else if((array.GetLength(0) - index) < size)
{
throw new ArgumentException(_("Arg_InvalidArrayRange"));
}
else if(size > 0)
{
Array.Copy(ToArray(), 0, array, index, size);
}
}
public virtual int Count
{
get
{
return size;
}
}
public virtual bool IsSynchronized
{
get
{
return false;
}
}
public virtual Object SyncRoot
{
get
{
return this;
}
}
// Implement the ICloneable interface.
public virtual Object Clone()
{
Stack stack = (Stack)MemberwiseClone();
stack.items = (Object[])items.Clone();
return stack;
}
// Implement the IEnumerable interface.
public virtual IEnumerator GetEnumerator()
{
return new StackEnumerator(this);
}
// Clear the contents of this stack.
public virtual void Clear()
{
// brubbel
// set all references to zero, to avoid memory leaks !!!
int iCount = items.Length;
for( int i = 0; i < iCount; i++ ) {
items[i] = null;
}
size = 0;
++generation;
}
// Determine if this stack contains a specific object.
public virtual bool Contains(Object obj)
{
int index;
for(index = 0; index < size; ++index)
{
if(items[index] != null && obj != null)
{
if(obj.Equals(items[index]))
{
return true;
}
}
else if(items[index] == null && obj == null)
{
return true;
}
}
return false;
}
// Pop an item.
public virtual Object Pop()
{
if(size > 0)
{
++generation;
--size;
Object o = items[size];
items[size] = null; // remove reference of object, to avoid memory leaks !!!
return o;
}
else
{
throw new InvalidOperationException
(_("Invalid_EmptyStack"));
}
}
// Push an item.
public virtual void Push(Object obj)
{
if(size < items.Length)
{
// The stack is big enough to hold the new item.
items[size++] = obj;
}
else
{
// We need to increase the size of the stack.
int newCapacity = items.Length + GrowSize;
Object[] newItems = new Object [newCapacity];
if(size > 0)
{
Array.Copy(items, newItems, size);
}
items = newItems;
items[size++] = obj;
}
++generation;
}
// Peek at the top-most item without popping it.
public virtual Object Peek()
{
if(size > 0)
{
return items[size - 1];
}
else
{
throw new InvalidOperationException
(_("Invalid_EmptyStack"));
}
}
// Convert the contents of this stack into an array.
public virtual Object[] ToArray()
{
Object[] array = new Object [size];
int index;
for(index = 0; index < size; ++index)
{
array[index] = items[size - index - 1];
}
return array;
}
// Convert this stack into a synchronized stack.
public static Stack Synchronized(Stack stack)
{
if(stack == null)
{
throw new ArgumentNullException("stack");
}
else if(stack.IsSynchronized)
{
return stack;
}
else
{
return new SynchronizedStack(stack);
}
}
// Private class that implements synchronized stacks.
private class SynchronizedStack : Stack
{
// Internal state.
private Stack stack;
// Constructor.
public SynchronizedStack(Stack stack)
{
this.stack = stack;
}
// Implement the ICollection interface.
public override void CopyTo(Array array, int index)
{
lock(SyncRoot)
{
stack.CopyTo(array, index);
}
}
public override int Count
{
get
{
lock(SyncRoot)
{
return stack.Count;
}
}
}
public override bool IsSynchronized
{
get
{
return true;
}
}
public override Object SyncRoot
{
get
{
return stack.SyncRoot;
}
}
// Implement the ICloneable interface.
public override Object Clone()
{
return new SynchronizedStack((Stack)(stack.Clone()));
}
// Implement the IEnumerable interface.
public override IEnumerator GetEnumerator()
{
lock(SyncRoot)
{
return new SynchronizedEnumerator
(SyncRoot, stack.GetEnumerator());
}
}
// Clear the contents of this stack.
public override void Clear()
{
lock(SyncRoot)
{
stack.Clear();
}
}
// Determine if this stack contains a specific object.
public override bool Contains(Object obj)
{
lock(SyncRoot)
{
return stack.Contains(obj);
}
}
// Pop an item.
public override Object Pop()
{
lock(SyncRoot)
{
return stack.Pop();
}
}
// Push an item.
public override void Push(Object obj)
{
lock(SyncRoot)
{
stack.Push(obj);
}
}
// Peek at the top-most item without popping it.
public override Object Peek()
{
lock(SyncRoot)
{
return stack.Peek();
}
}
// Convert the contents of this stack into an array.
public override Object[] ToArray()
{
lock(SyncRoot)
{
return stack.ToArray();
}
}
}; // class SynchronizedStack
// Private class for implementing stack enumeration.
private class StackEnumerator : IEnumerator
{
// Internal state.
private Stack stack;
private int generation;
private int position;
// Constructor.
public StackEnumerator(Stack stack)
{
this.stack = stack;
generation = stack.generation;
position = -1;
}
// Implement the IEnumerator interface.
public bool MoveNext()
{
if(generation != stack.generation)
{
throw new InvalidOperationException
(_("Invalid_CollectionModified"));
}
++position;
if(position < stack.size)
{
return true;
}
position = stack.size;
return false;
}
public void Reset()
{
if(generation != stack.generation)
{
throw new InvalidOperationException
(_("Invalid_CollectionModified"));
}
position = -1;
}
public Object Current
{
get
{
if(generation != stack.generation)
{
throw new InvalidOperationException
(_("Invalid_CollectionModified"));
}
if(position < 0 || position >= stack.size)
{
throw new InvalidOperationException
(_("Invalid_BadEnumeratorPosition"));
}
return stack.items[stack.size - position - 1];
}
}
}; // class StackEnumerator
}; // class Stack
#endif // !ECMA_COMPAT
}; // namespace System.Collections
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Threading;
namespace Physics2DDotNet
{
/// <summary>
/// The State of a PhysicsTimer
/// </summary>
public enum TimerState
{
NotStarted,
/// <summary>
/// The PhysicsTimer is Paused.
/// </summary>
Paused,
/// <summary>
/// The PhysicsTimer's calls to the Callback are on time.
/// </summary>
Normal,
/// <summary>
/// The PhysicsTimer's calls to the Callback are behind schedule.
/// </summary>
Slow,
/// <summary>
/// The PhysicsTimer's calls to the Callback are delayed to be on time.
/// </summary>
Fast,
/// <summary>
/// The PhysicsTimer is Disposed.
/// </summary>
Disposed,
}
/// <summary>
/// A Callback used by the PhysicsTimer
/// </summary>
/// <param name="dt">The change in time.</param>
public delegate void PhysicsCallback(Scalar dt, Scalar trueDt);
/// <summary>
/// A class to update the PhysicsEngine at regular intervals.
/// </summary>
public sealed class PhysicsTimer : IDisposable
{
#region static
static int threadCount;
#endregion
#region events
public event EventHandler IsRunningChanged;
#endregion
#region fields
bool isBackground;
bool isDisposed;
bool isRunning;
TimerState state;
Scalar targetInterval;
PhysicsCallback callback;
AutoResetEvent waitHandle;
Thread engineThread;
#endregion
#region constructors
/// <summary>
/// Creates a new PhysicsTimer Instance.
/// </summary>
/// <param name="callback">The callback to call.</param>
/// <param name="targetDt">The target change in time. (in seconds)</param>
public PhysicsTimer(PhysicsCallback callback, Scalar targetInterval)
{
if (callback == null) { throw new ArgumentNullException("callback"); }
if (targetInterval <= 0) { throw new ArgumentOutOfRangeException("targetInterval"); }
this.isBackground = true;
this.state = TimerState.NotStarted;
this.targetInterval = targetInterval;
this.callback = callback;
this.waitHandle = new AutoResetEvent(true);
}
#endregion
#region properties
/// <summary>
/// Gets or sets a value indicating whether or not the thread that runs the time is a background thread.
/// </summary>
public bool IsBackground
{
get { return isBackground; }
set
{
if (isDisposed) { throw new ObjectDisposedException(typeof(PhysicsTimer).Name); }
if (isBackground ^ value)
{
isBackground = value;
if (engineThread != null)
{
engineThread.IsBackground = value;
}
}
}
}
/// <summary>
/// Gets and Sets if the PhysicsTimer is currently calling the Callback.
/// </summary>
public bool IsRunning
{
get
{
return isRunning;
}
set
{
if (isDisposed) { throw new ObjectDisposedException(typeof(PhysicsTimer).Name); }
if (this.isRunning ^ value)
{
this.isRunning = value;
if (value)
{
if (this.engineThread == null)
{
this.engineThread = new Thread(EngineProcess);
this.engineThread.IsBackground = isBackground;
this.engineThread.Name = string.Format("PhysicsEngine Thread: {0}", Interlocked.Increment(ref threadCount));
this.engineThread.Start();
}
else
{
waitHandle.Set();
}
}
if (IsRunningChanged != null) { IsRunningChanged(this, EventArgs.Empty); }
}
}
}
/// <summary>
/// Gets and Sets the desired Interval between Callback calls.
/// </summary>
public Scalar TargetInterval
{
get { return targetInterval; }
set
{
if (isDisposed) { throw new ObjectDisposedException(this.ToString()); }
if (value <= 0) { throw new ArgumentOutOfRangeException("value"); }
this.targetInterval = value;
}
}
/// <summary>
/// Gets the current State of the PhysicsTimer.
/// </summary>
public TimerState State
{
get { return state; }
}
/// <summary>
/// Gets and Sets the current Callback that will be called.
/// </summary>
public PhysicsCallback Callback
{
get { return callback; }
set
{
if (isDisposed) { throw new ObjectDisposedException(this.ToString()); }
if (value == null) { throw new ArgumentNullException("value"); }
callback = value;
}
}
#endregion
#region methods
/// <summary>
/// Stops the Timer
/// </summary>
public void Dispose()
{
if (!isDisposed)
{
isDisposed = true;
isRunning = false;
waitHandle.Set();
waitHandle.Close();
state = TimerState.Disposed;
}
}
void EngineProcess()
{
Scalar desiredDt = targetInterval * 1000;
DateTime lastRun = DateTime.Now;
Scalar extraDt = 0;
while (!isDisposed)
{
if (isRunning)
{
DateTime now = DateTime.Now;
Scalar dt = (Scalar)(now.Subtract(lastRun).TotalMilliseconds);
Scalar currentDt = extraDt + dt;
if (currentDt < desiredDt)
{
state = TimerState.Fast;
int sleep = (int)Math.Ceiling(desiredDt - currentDt);
#if SILVERLIGHT
waitHandle.WaitOne(sleep);
#else
waitHandle.WaitOne(sleep, false);
#endif
}
else
{
extraDt = currentDt - desiredDt;
if (extraDt > desiredDt)
{
extraDt = desiredDt;
state = TimerState.Slow;
}
else
{
state = TimerState.Normal;
}
lastRun = now;
callback(targetInterval, dt * (1 / 1000f));
}
}
else
{
state = TimerState.Paused;
waitHandle.WaitOne();
lastRun = DateTime.Now;
extraDt = 0;
}
}
state = TimerState.Disposed;
}
public void RunOnCurrentThread()
{
if (this.engineThread != null) { throw new InvalidOperationException("Timer must be NotStarted"); }
this.engineThread = Thread.CurrentThread;
this.isRunning = true;
EngineProcess();
}
#endregion
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// 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.Diagnostics;
namespace Alachisoft.NCache.Common
{
//This class is to serve as the basis for live upgrades and cross version communication in future
/// <summary>
/// Returns the version of the NCache running on a particular Node.
/// This returns a single instance per installation
/// </summary>
struct ProductVersionType
{
public static int Major, Minor, Build, Revision;
}
public class ProductVersion: IComparable, Runtime.Serialization.ICompactSerializable
{
#region members
private byte _majorVersion1=0;
private byte _majorVersion2=0;
private byte _minorVersion1=0;
private byte _minorVersion2=0;
private string _productName= string.Empty;
private int _editionID=-1;
private static volatile ProductVersion _productInfo;
private static object _syncRoot = new object(); // this object is to serve as locking instance to avoid deadlocks
private byte[] _additionalData;
#endregion
#region Properties
/// <summary>
/// Gets the productInfo
/// </summary>
public static ProductVersion ProductInfo
{
//Double check locking approach is used because of the multi-threaded nature of NCache
get
{
if (_productInfo == null)
{
lock (_syncRoot)
{
if (_productInfo == null)
{
_productInfo = new ProductVersion();
#if SERVER
_productInfo._editionID = 32;
_productInfo._majorVersion1 = 4;
_productInfo._majorVersion2 = 3;
_productInfo._minorVersion1 = 0;
_productInfo._minorVersion2 = 0;
_productInfo._productName = "NCACHE";
_productInfo._additionalData = new byte[0];
#elif CLIENT
_productInfo._editionID = 33;
_productInfo._majorVersion1 = 4;
_productInfo._majorVersion2 = 3;
_productInfo._minorVersion1 = 0;
_productInfo._minorVersion2 = 0;
_productInfo._productName = "NCACHE";
_productInfo._additionalData = new byte[0];
#endif
}
}
}
return _productInfo;
}
}
/// <summary>
/// Gets/Sets the Product Name(JvCache/NCache)
/// </summary>
public string ProductName
{
get { return _productName; }
private set
{
_productName = value;
}
}
/// <summary>
/// Get/Sets the editionID of the product
/// </summary>
public int EditionID
{
get { return _editionID; }
private set
{
_editionID = value;
}
}
/// <summary>
/// Get/Set the edditional data that needs
/// to be send.
/// </summary>
public byte[] AdditionalData
{
get { return _additionalData; }
private set { _additionalData = value; }
}
/// <summary>
/// Get/Set the second minor version of the API
/// </summary>
public byte MinorVersion2
{
get { return _minorVersion2; }
private set { _minorVersion2 = value; }
}
/// <summary>
/// Get/Set the first minor version of the API
/// </summary>
public byte MinorVersion1
{
get { return _minorVersion1; }
private set { _minorVersion1 = value; }
}
/// <summary>
/// Get/Set the second major version of the API
/// </summary>
public byte MajorVersion2
{
get { return _majorVersion2; }
private set { _majorVersion2 = value; }
}
/// <summary>
/// Get/Set the first major version of the API
/// </summary>
public byte MajorVersion1
{
get { return _majorVersion1; }
private set { _majorVersion1 = value; }
}
#endregion
#region methods
/// <summary>
///
/// </summary>
public ProductVersion()
{
}
/// <summary>
/// compares editionIDs to ensure whether the version is correct or not
/// </summary>
/// <param name="id"></param>
/// <returns>
/// true: Incase of same edition
/// False: Incase of incorrect edition
/// </returns>
public bool IsValidVersion(int editionID)
{
if (this.EditionID == editionID)
return true;
else
return false;
}
public static string GetVersion()
{
string version;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
version = fvi.FileVersion;
try
{
string[] components = version.Split('.');
int.TryParse(components[0], out ProductVersionType.Major);
int.TryParse(components[1], out ProductVersionType.Minor);
int.TryParse(components[2], out ProductVersionType.Build);
int.TryParse(components[3], out ProductVersionType.Revision);
//Example: AssemblyFileVersion is 4.9.0.0
// productVersion = 4.8 (Major and Minor together form a product version)
// servicePack = SP-2 (Build tells the service pack number)
// privatePatch = PP-2 (Revision tells the private patch number)
string productVersion = string.Format("{0}.{1}", ProductVersionType.Major, ProductVersionType.Minor);
string servicePack = string.Format("{0}{1}", ProductVersionType.Build > 0 ? "SP" : string.Empty, ProductVersionType.Build > 0 ? ProductVersionType.Build.ToString() : string.Empty);
string privatePatch = string.Format("{0}{1}", ProductVersionType.Revision > 0 ? "PP" : string.Empty, ProductVersionType.Revision > 0 ? ProductVersionType.Revision.ToString() : string.Empty);
version = (string.Format("{0} {1} {2}", productVersion, servicePack, privatePatch)).TrimEnd();
return version;
}
catch (Exception ex)
{
AppUtil.LogEvent("Error occured while reading product info: " + ex.ToString(), EventLogEntryType.Error);
try
{
string spVersion = (string)Alachisoft.NCache.Common.RegHelper.GetRegValue(Alachisoft.NCache.Common.RegHelper.ROOT_KEY, "SPVersion", 0);
return (string.Format("{0} {1} ", version, spVersion));
}
catch
{
return null;
}
}
}
#endregion
#region ICompact Serializable Members
public void Deserialize(Runtime.Serialization.IO.CompactReader reader)
{
_majorVersion1 = reader.ReadByte();
_majorVersion2 = reader.ReadByte();
_minorVersion1 = reader.ReadByte();
_minorVersion2 = reader.ReadByte();
_productName =(string) reader.ReadObject();
_editionID = reader.ReadInt32();
int temp = reader.ReadInt32();
_additionalData = reader.ReadBytes(temp);
}
public void Serialize(Runtime.Serialization.IO.CompactWriter writer)
{
writer.Write(_majorVersion1);
writer.Write(_majorVersion2);
writer.Write(_minorVersion1);
writer.Write(_minorVersion2);
writer.WriteObject(_productName);
writer.Write(_editionID);
writer.Write(_additionalData.Length);// to know the lengt5h of the additional data to be followed; used when deserializing
writer.Write(_additionalData);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
int result = -1;
if (obj != null && obj is ProductVersion)
{
ProductVersion other = (ProductVersion)obj;
if (_editionID == other.EditionID)
{
if (_majorVersion1 == other.MajorVersion1)
{
if (_majorVersion2 == other.MajorVersion2)
{
if (_minorVersion1 == other.MinorVersion1)
{
if (_minorVersion2 == other._minorVersion2)
{
result = 0;
}
else if (_minorVersion2 < other.MinorVersion2)
result = -1;
else
result = 1;
}
else if (_minorVersion1 < other.MinorVersion1)
result = -1;
else
result = 1;
}
else if (_majorVersion2 < other.MajorVersion2)
result = -1;
else
result = 1;
}
else if (_majorVersion1 < other.MajorVersion1)
result = -1;
else
result = 1;
}
else
result = -1;
}
return result;
}
#endregion
}
}
| |
#pragma warning disable 0414
using UnityEngine;
using System.Collections;
using UniRx;
using System.Threading;
using System.Collections.Generic;
using System;
using System.Text;
using UniRx.Triggers;
using UniRx.Diagnostics;
using System.Net;
using System.IO;
using System.Linq;
#if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6)
// Fallback for Unity versions below 4.5
using Hash = System.Collections.Hashtable;
using HashEntry = System.Collections.DictionaryEntry;
#else
using Hash = System.Collections.Generic.Dictionary<string, string>;
using HashEntry = System.Collections.Generic.KeyValuePair<string, string>;
using UniRx.InternalUtil;
#endif
namespace UniRx.ObjectTest
{
public enum Mikan
{
Ringo = 30,
Tako = 40
}
public class LogCallback
{
public string Condition;
public string StackTrace;
public UnityEngine.LogType LogType;
public override string ToString()
{
return Condition + " " + StackTrace;
}
}
static class LogHelper
{
// If static register callback, use Subject for event branching.
#if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6)
static Subject<LogCallback> subject;
public static IObservable<LogCallback> LogCallbackAsObservable()
{
if (subject == null)
{
subject = new Subject<LogCallback>();
// Publish to Subject in callback
UnityEngine.Application.RegisterLogCallback((condition, stackTrace, type) =>
{
subject.OnNext(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type });
});
}
return subject.AsObservable();
}
#else
// If standard evetns, you can use Observable.FromEvent.
public static IObservable<LogCallback> LogCallbackAsObservable()
{
return Observable.FromEvent<Application.LogCallback, LogCallback>(
h => (condition, stackTrace, type) => h(new LogCallback { Condition = condition, StackTrace = stackTrace, LogType = type }),
h => Application.logMessageReceived += h, h => Application.logMessageReceived -= h);
}
#endif
}
[Serializable]
public struct MySuperStruct
{
public int A;
public int B;
public int C;
public int D;
public int E;
public int F;
public int G;
public int X;
public int Y;
public int Z;
public override string ToString()
{
return A + ":" + B + ":" + C + ":" + D + ":" + E + ":" + F + ":" + G + ":" + X + ":" + Y + ":" + Z;
}
}
public enum Fruit
{
Apple, Grape
}
[Serializable]
public class FruitReactiveProperty : ReactiveProperty<Fruit>
{
public FruitReactiveProperty()
{
}
public FruitReactiveProperty(Fruit initialValue)
: base(initialValue)
{
}
}
[Serializable]
public class MikanReactiveProperty : ReactiveProperty<Mikan>
{
public MikanReactiveProperty()
{
}
public MikanReactiveProperty(Mikan mikan)
: base(mikan)
{
}
}
[Serializable]
public class MyContainerClass
{
public int X;
public int Y;
}
[Serializable]
public class MySuperStructReactiveProperty : ReactiveProperty<MySuperStruct>
{
public MySuperStructReactiveProperty()
{
}
}
[Serializable]
public class MyContainerReactiveProperty : ReactiveProperty<MyContainerClass>
{
public MyContainerReactiveProperty()
{
}
}
[Serializable]
public class UShortReactiveProeprty : ReactiveProperty<ushort>
{
}
#if UNITY_EDITOR
[UnityEditor.CustomPropertyDrawer(typeof(UShortReactiveProeprty))]
[UnityEditor.CustomPropertyDrawer(typeof(MikanReactiveProperty))]
[UnityEditor.CustomPropertyDrawer(typeof(MySuperStructReactiveProperty))]
public class ExtendInspectorDisplayDrawer : InspectorDisplayDrawer
{
}
#endif
// test sandbox
[Serializable]
public class UniRxTestSandbox : MonoBehaviour
{
readonly static Logger logger = new Logger("UniRx.Test.NewBehaviour");
// public UnityEvent<int> SimpleEvent;
public Vector2ReactiveProperty V2R;
StringBuilder logtext = new StringBuilder();
GameObject cube;
Clicker clicker;
//[ThreadStatic]
static object threadstaticobj;
public DateTime DateTimeSonomono;
public IntReactiveProperty Intxxx;
public LongReactiveProperty LongxXXX;
public BoolReactiveProperty Booxxx;
public FloatReactiveProperty FloAAX;
public DoubleReactiveProperty DuAAX;
public MikanReactiveProperty MikanRP;
public StringReactiveProperty Strrrrr;
public UShortReactiveProeprty USHHHH;
//[InspectorDisplay]
//public MyContainerReactiveProperty MCCCC;
//public Vector4 V4;
//public Rect REEEECT;
//public AnimationCurve ACCCCCCC;
//public Bounds BOO;
//public Quaternion ZOOOM;
public Vector2ReactiveProperty AAA;
public Vector3ReactiveProperty BBB;
public Vector4ReactiveProperty CCC;
public ColorReactiveProperty DDD;
public RectReactiveProperty EEE;
// public Slider MySlider;
public MySuperStructReactiveProperty SUPER_Rx;
public AnimationCurveReactiveProperty FFF;
public BoundsReactiveProperty GGG;
public QuaternionReactiveProperty HHH;
public void Awake()
{
MainThreadDispatcher.Initialize();
LogHelper.LogCallbackAsObservable()
.ObserveOnMainThread()
.Where(x => x.LogType == LogType.Exception)
.Subscribe(x => logtext.AppendLine(x.ToString()));
ObservableLogger.Listener.LogToUnityDebug();
ObservableLogger.Listener.ObserveOnMainThread().Subscribe(x =>
{
logtext.AppendLine(x.Message);
});
}
CompositeDisposable disposables = new CompositeDisposable();
Subject<int> Source = new Subject<int>();
public void OnGUI()
{
var xpos = 0;
var ypos = 0;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Clear"))
{
logtext.Length = 0;
disposables.Clear();
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "PushSource"))
{
Source.OnNext(UnityEngine.Random.Range(1, 100));
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Select"))
{
Source.Select(x => x * 100).Subscribe(x => logger.Debug(x)).AddTo(disposables);
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "SubscribePerf1"))
{
var list = Enumerable.Range(1, 10000).Select(x => new ReactiveProperty<int>(x)).ToArray();
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (var item in list)
{
item.Subscribe();
}
sw.Stop();
logger.Debug("Direct Subscribe:" + sw.Elapsed.TotalMilliseconds + "ms");
}
{
var r = UnityEngine.Random.Range(1, 100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (var item in list)
{
item.Value = r;
}
sw.Stop();
logger.Debug("Push Direct Perf:" + sw.Elapsed.TotalMilliseconds + "ms");
}
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "SubscribePerf2"))
{
var list = Enumerable.Range(1, 10000).Select(x => new ReactiveProperty<int>(x)).ToArray();
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (var item in list)
{
item.Select(x => x).Subscribe();
}
sw.Stop();
logger.Debug("Select.Subscribe:" + sw.Elapsed.TotalMilliseconds + "ms");
}
{
var r = UnityEngine.Random.Range(1, 100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var sw = System.Diagnostics.Stopwatch.StartNew();
foreach (var item in list)
{
item.Value = r;
}
sw.Stop();
logger.Debug("Push Select Perf:" + sw.Elapsed.TotalMilliseconds + "ms");
}
}
ypos += 100;
//if (GUI.Button(new Rect(xpos, ypos, 100, 100), "CurrentThreadScheduler"))
//{
// try
// {
// Scheduler.CurrentThread.Schedule(() =>
// {
// try
// {
// logtext.AppendLine("test threadscheduler");
// }
// catch (Exception ex)
// {
// logtext.AppendLine("innner ex" + ex.ToString());
// }
// });
// }
// catch (Exception ex)
// {
// logtext.AppendLine("outer ex" + ex.ToString());
// }
//}
//ypos += 100;
//if (GUI.Button(new Rect(xpos, ypos, 100, 100), "EveryUpdate"))
//{
// Observable.EveryUpdate()
// .Subscribe(x => logtext.AppendLine(x.ToString()), ex => logtext.AppendLine("ex:" + ex.ToString()))
// .AddTo(disposables);
//}
//ypos += 100;
//if (GUI.Button(new Rect(xpos, ypos, 100, 100), "FromCoroutinePure"))
//{
// Observable.Create<Unit>(observer =>
// {
// var cancel = new BooleanDisposable();
// MainThreadDispatcher.StartCoroutine(Hoge(observer));
// return cancel;
// })
// .Subscribe(x => logtext.AppendLine(x.ToString()), ex => logtext.AppendLine("ex:" + ex.ToString()));
//}
//ypos += 100;
//if (GUI.Button(new Rect(xpos, ypos, 100, 100), "FromCoroutine"))
//{
// Observable.FromCoroutine<Unit>(Hoge)
// .Subscribe(x => logtext.AppendLine(x.ToString()), ex => logtext.AppendLine("ex:" + ex.ToString()));
//}
/*
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale-1"))
{
Time.timeScale -= 1f;
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale+1"))
{
Time.timeScale += 1f;
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale=0"))
{
Time.timeScale = 0;
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "TimeScale=100"))
{
Time.timeScale = 100;
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler0"))
{
logger.Debug("run");
Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(5000), () =>
{
logger.Debug(DateTime.Now);
});
}
xpos += 100;
ypos = 0;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler1"))
{
logger.Debug("Before Start");
Scheduler.MainThread.Schedule(() => logger.Debug("immediate"));
Scheduler.MainThread.Schedule(TimeSpan.Zero, () => logger.Debug("zero span"));
Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(1), () => logger.Debug("0.1 span"));
logger.Debug("After Start");
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Scheduler2"))
{
logger.Debug("M:Before Start");
Scheduler.MainThread.Schedule(TimeSpan.FromSeconds(5), () => logger.Debug("M:after 5 minutes"));
Scheduler.MainThread.Schedule(TimeSpan.FromMilliseconds(5500), () => logger.Debug("M:after 5.5 minutes"));
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Realtime"))
{
logger.Debug("R:Before Start");
Scheduler.MainThreadIgnoreTimeScale.Schedule(TimeSpan.FromSeconds(5), () => logger.Debug("R:after 5 minutes"));
Scheduler.MainThreadIgnoreTimeScale.Schedule(TimeSpan.FromMilliseconds(5500), () => logger.Debug("R:after 5.5 minutes"));
}
#if !UNITY_METRO
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ManagedThreadId"))
{
logger.Debug("Current:" + Thread.CurrentThread.ManagedThreadId);
new Thread(_ => logger.Debug("NewThread:" + Thread.CurrentThread.ManagedThreadId)).Start();
ThreadPool.QueueUserWorkItem(_ =>
{
logger.Debug("ThraedPool:" + Thread.CurrentThread.ManagedThreadId);
this.transform.position = new Vector3(0, 0, 0); // exception
});
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ThreadStatic"))
{
logger.Debug(threadstaticobj != null);
new Thread(_ => logger.Debug(threadstaticobj != null)).Start();
ThreadPool.QueueUserWorkItem(_ => logger.Debug(threadstaticobj != null));
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Log"))
{
logger.Debug("test", this);
ThreadPool.QueueUserWorkItem(_ => logger.Debug("test2", this));
}
#endif
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "POST"))
{
var form = new WWWForm();
form.AddField("test", "abcdefg");
ObservableWWW.PostWWW("http://localhost:53395/Handler1.ashx", form, new Hash
{
{"aaaa", "bbb"},
{"User-Agent", "HugaHuga"}
})
.Subscribe(x => logger.Debug(x.text));
}
xpos += 100;
ypos = 0;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Yield"))
{
yieldCancel = Observable.FromCoroutineValue<string>(StringYield, false)
.Subscribe(x => logger.Debug(x), ex => logger.Debug("E-x:" + ex));
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "YieldCancel"))
{
yieldCancel.Dispose();
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "ThreadPool"))
{
Observable.Timer(TimeSpan.FromMilliseconds(400), Scheduler.ThreadPool)
.ObserveOnMainThread()
.Subscribe(x => logger.Debug(x));
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Subscribe"))
{
subscriber.InitSubscriptions();
logger.Debug("Subscribe++ : " + subscriber.SubscriptionCount);
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Push"))
{
Publisher.foo();
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "Unsubscriber"))
{
subscriber.RemoveSubscriptions();
logger.Debug("UnsubscribeAll : " + subscriber.SubscriptionCount);
}
ypos += 100;
if (GUI.Button(new Rect(xpos, ypos, 100, 100), "DistinctUntilChanged"))
{
new[] { "hoge", null, null, "huga", "huga", "hoge" }
.ToObservable()
.DistinctUntilChanged()
.Subscribe(x => logger.Debug(x));
}
* */
// Time
var sb = new StringBuilder();
sb.AppendLine("CaptureFramerate:" + Time.captureFramerate);
sb.AppendLine("deltaTime:" + Time.deltaTime);
sb.AppendLine("fixedDeltaTime:" + Time.fixedDeltaTime);
sb.AppendLine("fixedTime:" + Time.fixedTime);
sb.AppendLine("frameCount:" + Time.frameCount);
sb.AppendLine("maximumDeltaTime:" + Time.maximumDeltaTime);
sb.AppendLine("realtimeSinceStartup:" + Time.realtimeSinceStartup);
sb.AppendLine("renderedFrameCount:" + Time.renderedFrameCount);
sb.AppendLine("smoothDeltaTime:" + Time.smoothDeltaTime);
sb.AppendLine("time:" + Time.time);
sb.AppendLine("timeScale:" + Time.timeScale);
sb.AppendLine("timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
sb.AppendLine("unscaledDeltaTime:" + Time.unscaledDeltaTime);
sb.AppendLine("unscaledTime:" + Time.unscaledTime);
//GUI.Box(new Rect(Screen.width - 300, Screen.height - 300, 300, 300), "Time");
//GUI.Label(new Rect(Screen.width - 290, Screen.height - 290, 290, 290), sb.ToString());
// logtext only
GUI.Box(new Rect(Screen.width - 300, Screen.height - 300, 300, 300), "logtext");
GUI.Label(new Rect(Screen.width - 290, Screen.height - 290, 290, 290), logtext.ToString());
// Log
//GUI.Box(new Rect(Screen.width - 300, 0, 300, 300), "Log");
//GUI.Label(new Rect(Screen.width - 290, 10, 290, 290), logtext.ToString());
}
}
}
#pragma warning restore 0414
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
namespace Polybrush
{
[CustomEditor(typeof(z_PrefabPalette))]
public class z_PrefabPaletteEditor : Editor
{
private SerializedProperty prefabs;
private HashSet<int> selected = new HashSet<int>();
public Delegate<IEnumerable<int>> onSelectionChanged = null;
private void OnEnable()
{
prefabs = serializedObject.FindProperty("prefabs");
}
public static z_PrefabPalette AddNew()
{
string path = z_EditorUtility.FindFolder(z_Pref.ProductName + "/" + "Prefab Palettes");
if(string.IsNullOrEmpty(path))
path = "Assets";
path = AssetDatabase.GenerateUniqueAssetPath(path + "/New Prefab Palette.asset");
if(!string.IsNullOrEmpty(path))
{
z_PrefabPalette palette = ScriptableObject.CreateInstance<z_PrefabPalette>();
palette.SetDefaultValues();
AssetDatabase.CreateAsset(palette, path);
AssetDatabase.Refresh();
EditorGUIUtility.PingObject(palette);
return palette;
}
return null;
}
public override void OnInspectorGUI()
{
OnInspectorGUI_Internal(64);
}
private bool IsDeleteKey(Event e)
{
return e.keyCode == KeyCode.Backspace;
}
public void OnInspectorGUI_Internal(int thumbSize)
{
serializedObject.Update();
int count = prefabs != null ? prefabs.arraySize : 0;
const int margin_x = 8; // group pad
const int margin_y = 4; // group pad
const int pad = 2; // texture pad
const int selected_rect_height = 10; // the little green bar and height padding
int actual_width = (int) Mathf.Ceil(thumbSize + pad/2);
int container_width = (int) Mathf.Floor(EditorGUIUtility.currentViewWidth) - (margin_x * 2);
int usable_width = container_width - pad * 2;
int columns = (int) Mathf.Floor(usable_width / actual_width);
int fill = (int) Mathf.Floor(((usable_width % actual_width)) / columns);
int size = thumbSize + fill;
int rows = count / columns + (count % columns == 0 ? 0 : 1);
if(rows < 1) rows = 1;
int height = rows * (size + selected_rect_height);
Rect r = EditorGUILayout.GetControlRect(false, height);
r.x = margin_x + pad;
r.y += margin_y;
r.width = size;
r.height = size;
Rect border = new Rect( margin_x, r.y, container_width, height );
// GUI.color = EditorGUIUtility.isProSkin ? z_GUI.BOX_OUTLINE_DARK : z_GUI.BOX_OUTLINE_LIGHT;
// EditorGUI.DrawPreviewTexture(border, EditorGUIUtility.whiteTexture);
// border.x += 1;
// border.y += 1;
// border.width -= 2;
// border.height -= 2;
// GUI.color = EditorGUIUtility.isProSkin ? z_GUI.BOX_BACKGROUND_DARK : z_GUI.BOX_BACKGROUND_LIGHT;
// EditorGUI.DrawPreviewTexture(border, EditorGUIUtility.whiteTexture);
// GUI.color = Color.white;
GUI.Box(border, "");
bool listNeedsPruning = false;
if(count < 1)
{
if( GUI.skin.name.Contains("polybrush"))
GUI.Label(border, "Drag Prefabs Here!", "dragprefablabel");
else
GUI.Label(border, "Drag Prefabs Here!", EditorStyles.centeredGreyMiniLabel);
}
for(int i = 0; i < count; i++)
{
SerializedProperty it = prefabs.GetArrayElementAtIndex(i);
SerializedProperty prefab = it.FindPropertyRelative("gameObject");
if( prefab == null || prefab.objectReferenceValue == null )
{
listNeedsPruning = true;
continue;
}
if(i > 0 && i % columns == 0)
{
r.x = pad + margin_x;
r.y += r.height + selected_rect_height;
}
if( z_GUILayout.AssetPreviewButton(r, prefab.objectReferenceValue, selected.Contains(i)) )
{
if(Event.current.shift || Event.current.control)
{
if(!selected.Add(i))
selected.Remove(i);
}
else
{
selected.Clear();
selected.Add(i);
}
if(onSelectionChanged != null)
onSelectionChanged( selected );
GUI.changed = true;
}
r.x += r.width + pad;
}
if(listNeedsPruning)
{
DeleteWhere(prefabs, (index, prop) =>
{
if(prop == null) return true;
SerializedProperty g = prop.FindPropertyRelative("gameObject");
return g == null || g.objectReferenceValue == null;
});
}
Event e = Event.current;
if( border.Contains(e.mousePosition) &&
(e.type == EventType.DragUpdated || e.type == EventType.DragPerform) &&
DragAndDrop.objectReferences.Length > 0 )
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if(e.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
IEnumerable<GameObject> dragAndDropReferences = DragAndDrop.objectReferences.Where(x => x is GameObject).Cast<GameObject>();
foreach(GameObject go in dragAndDropReferences)
{
prefabs.InsertArrayElementAtIndex(prefabs.arraySize);
SerializedProperty last = prefabs.GetArrayElementAtIndex(prefabs.arraySize - 1);
SerializedProperty gameObject = last.FindPropertyRelative("gameObject");
gameObject.objectReferenceValue = go;
}
}
}
if(e.type == EventType.KeyUp)
{
if( IsDeleteKey(e) )
{
DeleteWhere(prefabs, (i, v) => { return selected.Contains(i); } );
selected.Clear();
if(onSelectionChanged != null)
onSelectionChanged(null);
z_Editor.DoRepaint();
}
}
serializedObject.ApplyModifiedProperties();
}
private void DeleteWhere(SerializedProperty array, System.Func<int, SerializedProperty, bool> lamdba)
{
int arraySize = array.arraySize;
for(int i = arraySize - 1; i > -1; i--)
{
if( lamdba(i, array.GetArrayElementAtIndex(i)) )
array.DeleteArrayElementAtIndex(i);
}
}
}
}
| |
// 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.Xml;
#if NET_NATIVE
namespace System.Runtime.Serialization.Json
{
public delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames);
public delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
public delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
}
#else
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Security;
using System.Xml;
internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames);
internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract);
internal sealed class JsonFormatReaderGenerator
{
private CriticalHelper _helper;
public JsonFormatReaderGenerator()
{
_helper = new CriticalHelper();
}
public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
return _helper.GenerateClassReader(classContract);
}
public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionReader(collectionContract);
}
public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateGetOnlyCollectionReader(collectionContract);
}
private class CriticalHelper
{
private CodeGenerator _ilg;
private LocalBuilder _objectLocal;
private Type _objectType;
private ArgBuilder _xmlReaderArg;
private ArgBuilder _contextArg;
private ArgBuilder _memberNamesArg;
private ArgBuilder _collectionContractArg;
private ArgBuilder _emptyDictionaryStringArg;
public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null);
try
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
CreateObject(classContract);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
InvokeOnDeserializing(classContract);
if (classContract.IsISerializable)
ReadISerializable(classContract);
else
ReadClass(classContract);
if (Globals.TypeOfIDeserializationCallback.IsAssignableFrom(classContract.UnderlyingType))
{
_ilg.Call(_objectLocal, JsonFormatGeneratorStatics.OnDeserializationMethod, null);
}
InvokeOnDeserialized(classContract);
if (!InvokeFactoryMethod(classContract))
{
_ilg.Load(_objectLocal);
// Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
// DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod);
_ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType);
}
//Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>.
else if (classContract.IsKeyValuePairAdapter)
{
_ilg.Call(classContract.GetKeyValuePairMethodInfo);
_ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType);
}
else
{
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
}
}
return (JsonFormatClassReaderDelegate)_ilg.EndMethod();
}
public JsonFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/);
ReadCollection(collectionContract);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
return (JsonFormatCollectionReaderDelegate)_ilg.EndMethod();
}
public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/);
ReadGetOnlyCollection(collectionContract);
return (JsonFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod();
}
private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null);
try
{
if (isGetOnlyCollection)
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson" + "IsGetOnly", typeof(JsonFormatGetOnlyCollectionReaderDelegate), memberAccessFlag);
}
else
{
BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "FromJson", typeof(JsonFormatCollectionReaderDelegate), memberAccessFlag);
}
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
_collectionContractArg = _ilg.GetArg(4);
return _ilg;
}
private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
#else
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatReaderGenerator).Module, allowPrivateMemberAccess);
ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess);
#endif
}
private void InitArgs()
{
_xmlReaderArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(1);
_emptyDictionaryStringArg = _ilg.GetArg(2);
_memberNamesArg = _ilg.GetArg(3);
}
private void CreateObject(ClassDataContract classContract)
{
_objectType = classContract.UnderlyingType;
Type type = classContract.ObjectType;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (classContract.UnderlyingType == Globals.TypeOfDBNull)
{
_ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
_ilg.Stloc(_objectLocal);
}
else if (classContract.IsNonAttributedType)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(classContract.GetNonAttributedTypeConstructor());
_ilg.Stloc(_objectLocal);
}
}
else
{
_ilg.Call(null, JsonFormatGeneratorStatics.GetUninitializedObjectMethod, classContract.TypeForInitialization);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
}
}
private void InvokeOnDeserializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserializing(classContract.BaseContract);
if (classContract.OnDeserializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserializing);
}
}
private void InvokeOnDeserialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserialized(classContract.BaseContract);
if (classContract.OnDeserialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserialized);
}
}
private bool InvokeFactoryMethod(ClassDataContract classContract)
{
return false;
}
private void ReadClass(ClassDataContract classContract)
{
if (classContract.HasExtensionData)
{
LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData");
_ilg.New(JsonFormatGeneratorStatics.ExtensionDataObjectCtor);
_ilg.Store(extensionDataLocal);
ReadMembers(classContract, extensionDataLocal);
ClassDataContract currentContract = classContract;
while (currentContract != null)
{
MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod;
if (extensionDataSetMethod != null)
_ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal);
currentContract = currentContract.BaseContract;
}
}
else
{
ReadMembers(classContract, null /*extensionDataLocal*/);
}
}
private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
{
int memberCount = classContract.MemberNames.Length;
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements");
byte[] requiredElements = new byte[expectedElements.GetLocalCount()];
SetRequiredElements(classContract, requiredElements);
SetExpectedElements(expectedElements, 0 /*startIndex*/);
LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1);
Label throwDuplicateMemberLabel = _ilg.DefineLabel();
Label throwMissingRequiredMembersLabel = _ilg.DefineLabel();
object forReadElements = _ilg.For(null, null, null);
_ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg);
_ilg.IfFalseBreak(forReadElements);
_ilg.Call(_contextArg, JsonFormatGeneratorStatics.GetJsonMemberIndexMethod, _xmlReaderArg, _memberNamesArg, memberIndexLocal, extensionDataLocal);
if (memberCount > 0)
{
Label[] memberLabels = _ilg.Switch(memberCount);
ReadMembers(classContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal);
_ilg.EndSwitch();
}
else
{
_ilg.Pop();
}
_ilg.EndFor();
CheckRequiredElements(expectedElements, requiredElements, throwMissingRequiredMembersLabel);
Label endOfTypeLabel = _ilg.DefineLabel();
_ilg.Br(endOfTypeLabel);
_ilg.MarkLabel(throwDuplicateMemberLabel);
_ilg.Call(null, JsonFormatGeneratorStatics.ThrowDuplicateMemberExceptionMethod, _objectLocal, _memberNamesArg, memberIndexLocal);
_ilg.MarkLabel(throwMissingRequiredMembersLabel);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfObject);
_ilg.Load(_memberNamesArg);
expectedElements.LoadArray();
LoadArray(requiredElements, "requiredElements");
_ilg.Call(JsonFormatGeneratorStatics.ThrowMissingRequiredMembersMethod);
_ilg.MarkLabel(endOfTypeLabel);
}
private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expectedElements,
Label[] memberLabels, Label throwDuplicateMemberLabel, LocalBuilder memberIndexLocal)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember dataMember = classContract.Members[i];
Type memberType = dataMember.MemberType;
_ilg.Case(memberLabels[memberCount], dataMember.Name);
_ilg.Set(memberIndexLocal, memberCount);
expectedElements.Load(memberCount);
_ilg.Brfalse(throwDuplicateMemberLabel);
LocalBuilder value = null;
if (dataMember.IsGetOnlyCollection)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(dataMember.MemberInfo);
value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value");
_ilg.Stloc(value);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value);
ReadValue(memberType, dataMember.Name);
}
else
{
value = ReadValue(memberType, dataMember.Name);
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Ldloc(value);
_ilg.StoreMember(dataMember.MemberInfo);
}
ResetExpectedElements(expectedElements, memberCount);
_ilg.EndCase();
}
return memberCount;
}
private void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] requiredElements, Label throwMissingRequiredMembersLabel)
{
for (int i = 0; i < requiredElements.Length; i++)
{
_ilg.Load(expectedElements.GetLocal(i));
_ilg.Load(requiredElements[i]);
_ilg.And();
_ilg.Load(0);
_ilg.Ceq();
_ilg.Brfalse(throwMissingRequiredMembersLabel);
}
}
private void LoadArray(byte[] array, string name)
{
LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray, name);
_ilg.NewArray(typeof(byte), array.Length);
_ilg.Store(localArray);
for (int i = 0; i < array.Length; i++)
{
_ilg.StoreArrayElement(localArray, i, array[i]);
}
_ilg.Load(localArray);
}
private int SetRequiredElements(ClassDataContract contract, byte[] requiredElements)
{
int memberCount = (contract.BaseContract == null) ? 0 :
SetRequiredElements(contract.BaseContract, requiredElements);
List<DataMember> members = contract.Members;
for (int i = 0; i < members.Count; i++, memberCount++)
{
if (members[i].IsRequired)
{
BitFlagsGenerator.SetBit(requiredElements, memberCount);
}
}
return memberCount;
}
private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex)
{
int memberCount = expectedElements.GetBitCount();
for (int i = startIndex; i < memberCount; i++)
{
expectedElements.Store(i, true);
}
}
private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index)
{
expectedElements.Store(index, false);
}
private void ReadISerializable(ClassDataContract classContract)
{
ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null);
if (ctor == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType))));
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(ctor);
}
private LocalBuilder ReadValue(Type type, string name)
{
LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
LocalBuilder nullableValue = null;
int nullables = 0;
while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
nullables++;
type = type.GetGenericArguments()[0];
}
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType)
{
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type));
_ilg.Stloc(objectId);
// Deserialize null
_ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId);
if (nullables != 0)
{
_ilg.LoadAddress(value);
_ilg.InitObj(value.LocalType);
}
else if (type.IsValueType)
ThrowSerializationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Load(null);
_ilg.Stloc(value);
}
// Deserialize value
// Compare against Globals.NewObjectId, which is set to string.Empty
_ilg.ElseIfIsEmptyString(objectId);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
if (type.IsValueType)
{
_ilg.IfNotIsEmptyString(objectId);
ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
_ilg.EndIf();
}
if (nullables != 0)
{
nullableValue = value;
value = _ilg.DeclareLocal(type, "innerValueRead");
}
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
_ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod);
_ilg.Stloc(value);
if (!type.IsValueType)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value);
}
else
{
InternalDeserialize(value, type, name);
}
// Deserialize ref
_ilg.Else();
if (type.IsValueType)
ThrowSerializationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, string.Empty);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
_ilg.EndIf();
if (nullableValue != null)
{
_ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId);
WrapNullableObject(value, nullableValue, nullables);
_ilg.EndIf();
value = nullableValue;
}
}
else
{
InternalDeserialize(value, type, name);
}
return value;
}
private void InternalDeserialize(LocalBuilder value, Type type, string name)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlReaderArg);
Type declaredType = type;
_ilg.Load(DataContract.GetId(declaredType.TypeHandle));
_ilg.Ldtoken(declaredType);
_ilg.Load(name);
// Empty namespace
_ilg.Load(string.Empty);
_ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables)
{
Type innerType = innerValue.LocalType, outerType = outerValue.LocalType;
_ilg.LoadAddress(outerValue);
_ilg.Load(innerValue);
for (int i = 1; i < nullables; i++)
{
Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
_ilg.New(type.GetConstructor(new Type[] { innerType }));
innerType = type;
}
_ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
}
private void ReadCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
ConstructorInfo constructor = collectionContract.Constructor;
if (type.IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.GenericDictionary:
type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
break;
case CollectionKind.Dictionary:
type = Globals.TypeOfHashtable;
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
break;
case CollectionKind.Collection:
case CollectionKind.GenericCollection:
case CollectionKind.Enumerable:
case CollectionKind.GenericEnumerable:
case CollectionKind.List:
case CollectionKind.GenericList:
type = itemType.MakeArrayType();
isArray = true;
break;
}
}
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (!isArray)
{
if (type.IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(constructor);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
}
bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary ||
collectionContract.Kind == CollectionKind.GenericDictionary;
if (canReadSimpleDictionary)
{
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty);
_ilg.If();
ReadSimpleDictionary(collectionContract, itemType);
_ilg.Else();
}
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
bool canReadPrimitiveArray = false;
if (isArray && TryReadPrimitiveArray(itemType))
{
canReadPrimitiveArray = true;
_ilg.IfNot();
}
LocalBuilder growingCollection = null;
if (isArray)
{
growingCollection = _ilg.DeclareLocal(type, "growingCollection");
_ilg.NewArray(itemType, 32);
_ilg.Stloc(growingCollection);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
// Empty namespace
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType);
if (isArray)
{
MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
_ilg.Stloc(growingCollection);
_ilg.StoreArrayElement(growingCollection, i, value);
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
if (isArray)
{
MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, trimArraySizeMethod, growingCollection, i);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
}
if (canReadPrimitiveArray)
{
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
_ilg.EndIf();
}
if (canReadSimpleDictionary)
{
_ilg.EndIf();
}
}
private void ReadSimpleDictionary(CollectionDataContract collectionContract, Type keyValueType)
{
Type[] keyValueTypes = keyValueType.GetGenericArguments();
Type keyType = keyValueTypes[0];
Type valueType = keyValueTypes[1];
int keyTypeNullableDepth = 0;
Type keyTypeOriginal = keyType;
while (keyType.IsGenericType && keyType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
keyTypeNullableDepth++;
keyType = keyType.GetGenericArguments()[0];
}
ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract;
DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract;
KeyParseMode keyParseMode = KeyParseMode.Fail;
if (keyType == Globals.TypeOfString || keyType == Globals.TypeOfObject)
{
keyParseMode = KeyParseMode.AsString;
}
else if (keyType.IsEnum)
{
keyParseMode = KeyParseMode.UsingParseEnum;
}
else if (keyDataContract.ParseMethod != null)
{
keyParseMode = KeyParseMode.UsingCustomParse;
}
if (keyParseMode == KeyParseMode.Fail)
{
ThrowSerializationException(
SR.Format(
SR.KeyTypeCannotBeParsedInSimpleDictionary,
DataContract.GetClrTypeFullName(collectionContract.UnderlyingType),
DataContract.GetClrTypeFullName(keyType)));
}
else
{
LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType), "nodeType");
_ilg.BeginWhileCondition();
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod);
_ilg.Stloc(nodeType);
_ilg.Load(nodeType);
_ilg.Load(XmlNodeType.EndElement);
_ilg.BeginWhileBody(Cmp.NotEqualTo);
_ilg.Load(nodeType);
_ilg.Load(XmlNodeType.Element);
_ilg.If(Cmp.NotEqualTo);
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
if (keyParseMode == KeyParseMode.UsingParseEnum)
{
_ilg.Load(keyType);
}
_ilg.Load(_xmlReaderArg);
_ilg.Call(JsonFormatGeneratorStatics.GetJsonMemberNameMethod);
if (keyParseMode == KeyParseMode.UsingParseEnum)
{
_ilg.Call(JsonFormatGeneratorStatics.ParseEnumMethod);
_ilg.ConvertValue(Globals.TypeOfObject, keyType);
}
else if (keyParseMode == KeyParseMode.UsingCustomParse)
{
_ilg.Call(keyDataContract.ParseMethod);
}
LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key");
_ilg.Stloc(pairKey);
if (keyTypeNullableDepth > 0)
{
LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal, "keyOriginal");
WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth);
pairKey = pairKeyNullable;
}
LocalBuilder pairValue = ReadValue(valueType, String.Empty);
StoreKeyValuePair(_objectLocal, collectionContract, pairKey, pairValue);
_ilg.EndWhile();
}
}
private void ReadGetOnlyCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
bool canReadSimpleDictionary = collectionContract.Kind == CollectionKind.Dictionary ||
collectionContract.Kind == CollectionKind.GenericDictionary;
if (canReadSimpleDictionary)
{
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatReadProperty);
_ilg.If();
if (!type.IsValueType)
{
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.EndIf();
}
ReadSimpleDictionary(collectionContract, itemType);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg);
_ilg.Else();
}
//check that items are actually going to be deserialized into the collection
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
if (!type.IsValueType)
{
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.EndIf();
}
if (isArray)
{
_ilg.Load(_objectLocal);
_ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod);
_ilg.Stloc(size);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
IsStartElement(_memberNamesArg, _emptyDictionaryStringArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType);
if (isArray)
{
_ilg.If(size, Cmp.EqualTo, i);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type);
_ilg.Else();
_ilg.StoreArrayElement(_objectLocal, i, value);
_ilg.EndIf();
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _emptyDictionaryStringArg);
_ilg.EndIf();
if (canReadSimpleDictionary)
{
_ilg.EndIf();
}
}
private bool TryReadPrimitiveArray(Type itemType)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string readArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
readArrayMethod = "TryReadBooleanArray";
break;
case TypeCode.Decimal:
readArrayMethod = "TryReadDecimalArray";
break;
case TypeCode.Int32:
readArrayMethod = "TryReadInt32Array";
break;
case TypeCode.Int64:
readArrayMethod = "TryReadInt64Array";
break;
case TypeCode.Single:
readArrayMethod = "TryReadSingleArray";
break;
case TypeCode.Double:
readArrayMethod = "TryReadDoubleArray";
break;
case TypeCode.DateTime:
readArrayMethod = "TryReadJsonDateTimeArray";
break;
default:
break;
}
if (readArrayMethod != null)
{
_ilg.Load(_xmlReaderArg);
_ilg.ConvertValue(typeof(XmlReaderDelegator), typeof(JsonReaderDelegator));
_ilg.Load(_contextArg);
_ilg.Load(_memberNamesArg);
// Empty namespace
_ilg.Load(_emptyDictionaryStringArg);
// -1 Array Size
_ilg.Load(-1);
_ilg.Ldloca(_objectLocal);
_ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
return true;
}
return false;
}
private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType)
{
if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod);
LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead");
_ilg.Load(_collectionContractArg);
_ilg.Call(JsonFormatGeneratorStatics.GetItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod);
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Call(JsonFormatGeneratorStatics.ReadJsonValueMethod);
_ilg.ConvertValue(Globals.TypeOfObject, itemType);
_ilg.Stloc(value);
return value;
}
else
{
return ReadValue(itemType, JsonGlobals.itemString);
}
}
private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract)
{
if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
{
ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
if (keyValuePairContract == null)
{
Fx.Assert("Failed to create contract for KeyValuePair type");
}
DataMember keyMember = keyValuePairContract.Members[0];
DataMember valueMember = keyValuePairContract.Members[1];
LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
_ilg.LoadAddress(value);
_ilg.LoadMember(keyMember.MemberInfo);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(value);
_ilg.LoadMember(valueMember.MemberInfo);
_ilg.Stloc(pairValue);
StoreKeyValuePair(collection, collectionContract, pairKey, pairValue);
}
else
{
_ilg.Call(collection, collectionContract.AddMethod, value);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
}
private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue)
{
_ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
private void HandleUnexpectedItemInCollection(LocalBuilder iterator)
{
IsStartElement();
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg);
_ilg.Dec(iterator);
_ilg.Else();
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
}
private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg)
{
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg);
}
private void IsStartElement()
{
_ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.IsStartElementMethod0);
}
private void IsEndElement()
{
_ilg.Load(_xmlReaderArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.NodeTypeProperty);
_ilg.Load(XmlNodeType.EndElement);
_ilg.Ceq();
}
private void ThrowUnexpectedStateException(XmlNodeType expectedState)
{
_ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg);
_ilg.Throw();
}
private void ThrowSerializationException(string msg, params object[] values)
{
if (values != null && values.Length > 0)
_ilg.CallStringFormat(msg, values);
else
_ilg.Load(msg);
ThrowSerializationException();
}
private void ThrowSerializationException()
{
_ilg.New(JsonFormatGeneratorStatics.SerializationExceptionCtor);
_ilg.Throw();
}
private enum KeyParseMode
{
Fail,
AsString,
UsingParseEnum,
UsingCustomParse
}
}
}
}
#endif
| |
//
// 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.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IAuditingPolicyOperations _auditingPolicy;
/// <summary>
/// Represents all the operations to manage Azure SQL Database and
/// Database Server Audit policy. Contains operations to: Create,
/// Retrieve and Update audit policy.
/// </summary>
public virtual IAuditingPolicyOperations AuditingPolicy
{
get { return this._auditingPolicy; }
}
private IDatabaseOperations _databases;
/// <summary>
/// Represents all the operations for operating on Azure SQL Databases.
/// Contains operations to: Create, Retrieve, Update, and Delete
/// databases, and also includes the ability to get the event logs for
/// a database.
/// </summary>
public virtual IDatabaseOperations Databases
{
get { return this._databases; }
}
private IDataMaskingOperations _dataMasking;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// data masking. Contains operations to: Create, Retrieve, Update,
/// and Delete data masking rules, as well as Create, Retreive and
/// Update data masking policy.
/// </summary>
public virtual IDataMaskingOperations DataMasking
{
get { return this._dataMasking; }
}
private IElasticPoolOperations _elasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Elastic Pools. Contains operations to: Create, Retrieve, Update,
/// and Delete.
/// </summary>
public virtual IElasticPoolOperations ElasticPools
{
get { return this._elasticPools; }
}
private IFirewallRuleOperations _firewallRules;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Server Firewall Rules. Contains operations to: Create, Retrieve,
/// Update, and Delete firewall rules.
/// </summary>
public virtual IFirewallRuleOperations FirewallRules
{
get { return this._firewallRules; }
}
private IRecommendedElasticPoolOperations _recommendedElasticPools;
/// <summary>
/// Represents all the operations for operating on Azure SQL
/// Recommended Elastic Pools. Contains operations to: Retrieve.
/// </summary>
public virtual IRecommendedElasticPoolOperations RecommendedElasticPools
{
get { return this._recommendedElasticPools; }
}
private ISecureConnectionPolicyOperations _secureConnection;
/// <summary>
/// Represents all the operations for managing Azure SQL Database
/// secure connection. Contains operations to: Create, Retrieve and
/// Update secure connection policy .
/// </summary>
public virtual ISecureConnectionPolicyOperations SecureConnection
{
get { return this._secureConnection; }
}
private IServerOperations _servers;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Servers. Contains operations to: Create, Retrieve, Update, and
/// Delete servers.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
private IServerUpgradeOperations _serverUpgrades;
/// <summary>
/// Represents all the operations for Azure SQL Database Server Upgrade
/// </summary>
public virtual IServerUpgradeOperations ServerUpgrades
{
get { return this._serverUpgrades; }
}
private IServiceObjectiveOperations _serviceObjectives;
/// <summary>
/// Represents all the operations for operating on Azure SQL Database
/// Service Objectives. Contains operations to: Retrieve service
/// objectives.
/// </summary>
public virtual IServiceObjectiveOperations ServiceObjectives
{
get { return this._serviceObjectives; }
}
private IServiceTierAdvisorOperations _serviceTierAdvisors;
/// <summary>
/// Represents all the operations for operating on service tier
/// advisors. Contains operations to: Retrieve.
/// </summary>
public virtual IServiceTierAdvisorOperations ServiceTierAdvisors
{
get { return this._serviceTierAdvisors; }
}
private ITransparentDataEncryptionOperations _transparentDataEncryption;
/// <summary>
/// Represents all the operations of Azure SQL Database Transparent
/// Data Encryption. Contains operations to: Retrieve, and Update
/// Transparent Data Encryption.
/// </summary>
public virtual ITransparentDataEncryptionOperations TransparentDataEncryption
{
get { return this._transparentDataEncryption; }
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
public SqlManagementClient()
: base()
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._auditingPolicy = new AuditingPolicyOperations(this);
this._databases = new DatabaseOperations(this);
this._dataMasking = new DataMaskingOperations(this);
this._elasticPools = new ElasticPoolOperations(this);
this._firewallRules = new FirewallRuleOperations(this);
this._recommendedElasticPools = new RecommendedElasticPoolOperations(this);
this._secureConnection = new SecureConnectionPolicyOperations(this);
this._servers = new ServerOperations(this);
this._serverUpgrades = new ServerUpgradeOperations(this);
this._serviceObjectives = new ServiceObjectiveOperations(this);
this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this);
this._transparentDataEncryption = new TransparentDataEncryptionOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SqlManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SqlManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SqlManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SqlManagementClient> client)
{
base.Clone(client);
if (client is SqlManagementClient)
{
SqlManagementClient clonedClient = ((SqlManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
/*
Copyright (c) 2013 Christoph Fabritz
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.Linq;
using FileStream = System.IO.FileStream;
using BinaryReader = System.IO.BinaryReader;
using BitConverter = System.BitConverter;
using HeaderChunk = Midi.Chunks.HeaderChunk;
using TrackChunk = Midi.Chunks.TrackChunk;
using StringEncoder = System.Text.UTF7Encoding;
using TrackEventsIEnumerable = System.Collections.Generic.IEnumerable<Midi.Events.MidiEvent>;
using ByteList = System.Collections.Generic.List<byte>;
using ByteEnumerable = System.Collections.Generic.IEnumerable<byte>;
using MidiEvent = Midi.Events.MidiEvent;
using MIDIEvent_Length_Tuple = System.Tuple<Midi.Util.Option.Option<Midi.Events.MidiEvent>, int, byte>;
using SomeMidiEvent = Midi.Util.Option.Some<Midi.Events.MidiEvent>;
using NoMidiEvent = Midi.Util.Option.None<Midi.Events.MidiEvent>;
using VariableLengthUtil = Midi.Util.VariableLengthUtil;
using Midi.Events.MetaEvents;
using SysexEvent = Midi.Events.SysexEvent;
using Midi.Events.ChannelEvents;
using System;
namespace Midi
{
public class FileParser
{
private readonly static StringEncoder stringEncoder = new StringEncoder();
public static MidiData parse(FileStream input_file_stream)
{
var input_binary_reader = new BinaryReader(input_file_stream);
HeaderChunk header_chunk;
ushort number_of_tracks;
{
var header_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4));
var header_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0);
var header_chunk_data = input_binary_reader.ReadBytes(header_chunk_size);
var format_type = BitConverter.ToUInt16(header_chunk_data.Take(2).Reverse().ToArray<byte>(), 0);
number_of_tracks = BitConverter.ToUInt16(header_chunk_data.Skip(2).Take(2).Reverse().ToArray<byte>(), 0);
var time_division = BitConverter.ToUInt16(header_chunk_data.Skip(4).Take(2).Reverse().ToArray<byte>(), 0);
header_chunk = new HeaderChunk(format_type, time_division);
}
var tracks =
Enumerable.Range(0, number_of_tracks)
.Select(track_number =>
{
var track_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4));
var track_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0);
var track_chunk_data = input_binary_reader.ReadBytes(track_chunk_size);
return Tuple.Create(track_chunk_size, track_chunk_data);
}).ToList()
.Select(raw_track => new TrackChunk(parse_events(raw_track.Item2, raw_track.Item1)));
return new MidiData(header_chunk, tracks);
}
private static TrackEventsIEnumerable parse_events(ByteEnumerable track_data, int chunk_size)
{
var i = 0;
var last_midi_channel = (byte)0x00;
while (i < chunk_size)
{
var tuple = next_event(track_data, i, last_midi_channel);
i += tuple.Item2;
last_midi_channel = tuple.Item3;
switch (tuple.Item1.GetType() == typeof(SomeMidiEvent))
{
case true:
yield return (tuple.Item1 as SomeMidiEvent).value;
break;
}
}
yield break;
}
private static MIDIEvent_Length_Tuple next_event(ByteEnumerable track_data, int start_index, byte last_midi_channel)
{
var i = start_index - 1;
MidiEvent midi_event = null;
{
var delta_time = 0;
{
var length_temp = new ByteList();
do
{
i += 1;
length_temp.Add(track_data.ElementAt(i));
} while (track_data.ElementAt(i) > 0x7F);
delta_time = VariableLengthUtil.decode_to_int(length_temp);
}
i += 1;
var event_type_value = track_data.ElementAt(i);
// MIDI Channel Events
if ((event_type_value & 0xF0) < 0xF0)
{
var midi_channel_event_type = (byte)(event_type_value & 0xF0);
var midi_channel = (byte)(event_type_value & 0x0F);
i += 1;
var parameter_1 = track_data.ElementAt(i);
var parameter_2 = (byte)0x00;
// One or two parameter type
switch (midi_channel_event_type)
{
// One parameter types
case 0xC0:
midi_event = new ProgramChangeEvent(delta_time, midi_channel, parameter_1);
last_midi_channel = midi_channel;
break;
case 0xD0:
midi_event = new ChannelAftertouchEvent(delta_time, midi_channel, parameter_1);
last_midi_channel = midi_channel;
break;
// Two parameter types
case 0x80:
i += 1;
parameter_2 = track_data.ElementAt(i);
midi_event = new NoteOffEvent(delta_time, midi_channel, parameter_1, parameter_2);
last_midi_channel = midi_channel;
break;
case 0x90:
i += 1;
parameter_2 = track_data.ElementAt(i);
midi_event = new NoteOnEvent(delta_time, midi_channel, parameter_1, parameter_2);
last_midi_channel = midi_channel;
break;
case 0xA0:
i += 1;
parameter_2 = track_data.ElementAt(i);
midi_event = new NoteAftertouchEvent(delta_time, midi_channel, parameter_1, parameter_2);
last_midi_channel = midi_channel;
break;
case 0xB0:
i += 1;
parameter_2 = track_data.ElementAt(i);
midi_event = new ControllerEvent(delta_time, midi_channel, parameter_1, parameter_2);
last_midi_channel = midi_channel;
break;
case 0xE0:
i += 1;
parameter_2 = track_data.ElementAt(i);
midi_event = new PitchBendEvent(delta_time, midi_channel, parameter_1, parameter_2);
last_midi_channel = midi_channel;
break;
// Might be a Control Change Messages LSB
default:
midi_event = new ControllerEvent(delta_time, last_midi_channel, event_type_value, parameter_1);
break;
}
i += 1;
}
// Meta Events
else if (event_type_value == 0xFF)
{
i += 1;
var meta_event_type = track_data.ElementAt(i);
i += 1;
var meta_event_length = track_data.ElementAt(i);
i += 1;
var meta_event_data = Enumerable.Range(i, meta_event_length).Select(b => track_data.ElementAt(b)).ToArray();
switch (meta_event_type)
{
case 0x00:
midi_event = new SequenceNumberEvent(BitConverter.ToUInt16(meta_event_data.Reverse().ToArray<byte>(), 0));
break;
case 0x01:
midi_event = new TextEvent(delta_time, stringEncoder.GetString(meta_event_data));
break;
case 0x02:
midi_event = new CopyrightNoticeEvent(stringEncoder.GetString(meta_event_data));
break;
case 0x03:
midi_event = new SequenceOrTrackNameEvent(stringEncoder.GetString(meta_event_data));
break;
case 0x04:
midi_event = new InstrumentNameEvent(delta_time, stringEncoder.GetString(meta_event_data));
break;
case 0x05:
midi_event = new LyricsEvent(delta_time, stringEncoder.GetString(meta_event_data));
break;
case 0x06:
midi_event = new MarkerEvent(delta_time, stringEncoder.GetString(meta_event_data));
break;
case 0x07:
midi_event = new CuePointEvent(delta_time, stringEncoder.GetString(meta_event_data));
break;
case 0x20:
midi_event = new MIDIChannelPrefixEvent(delta_time, meta_event_data[0]);
break;
case 0x2F:
midi_event = new EndOfTrackEvent(delta_time);
break;
case 0x51:
var tempo =
(meta_event_data[2] & 0x0F) +
((meta_event_data[2] & 0xF0) * 16) +
((meta_event_data[1] & 0x0F) * 256) +
((meta_event_data[1] & 0xF0) * 4096) +
((meta_event_data[0] & 0x0F) * 65536) +
((meta_event_data[0] & 0xF0) * 1048576);
midi_event = new SetTempoEvent(delta_time, tempo);
break;
case 0x54:
midi_event = new SMPTEOffsetEvent(delta_time, meta_event_data[0], meta_event_data[1], meta_event_data[2], meta_event_data[3], meta_event_data[4]);
break;
case 0x58:
midi_event = new TimeSignatureEvent(delta_time, meta_event_data[0], meta_event_data[1], meta_event_data[2], meta_event_data[3]);
break;
case 0x59:
midi_event = new KeySignatureEvent(delta_time, meta_event_data[0], meta_event_data[1]);
break;
case 0x7F:
midi_event = new SequencerSpecificEvent(delta_time, meta_event_data);
break;
}
i += meta_event_length;
}
// System Exclusive Events
else if (event_type_value == 0xF0 || event_type_value == 0xF7)
{
var event_length = 0;
{
var length_temp = new ByteList();
do
{
i += 1;
length_temp.Add(track_data.ElementAt(i));
} while (track_data.ElementAt(i) > 0x7F);
event_length = VariableLengthUtil.decode_to_int(length_temp);
}
i += 1;
var event_data = Enumerable.Range(i, event_length).Select(b => track_data.ElementAt(b));
midi_event = new SysexEvent(delta_time, event_type_value, event_data);
i += event_length;
}
}
switch (midi_event != null)
{
case true:
return new MIDIEvent_Length_Tuple(new SomeMidiEvent(midi_event), i - start_index, last_midi_channel);
}
return new MIDIEvent_Length_Tuple(new NoMidiEvent(), i - start_index, last_midi_channel);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace SIL.Data
{
public sealed class ResultSet<T>: IEnumerable<RecordToken<T>>, IEnumerable<RepositoryId>
where T : class, new()
{
private readonly List<RecordToken<T>> _results;
private readonly IDataMapper<T> _dataMapper;
public ResultSet(IDataMapper<T> dataMapper, params IEnumerable<RecordToken<T>>[] results)
{
if (dataMapper == null)
{
throw new ArgumentNullException("dataMapper");
}
if (results == null)
{
throw new ArgumentNullException("results");
}
_results = new List<RecordToken<T>>();
foreach (IEnumerable<RecordToken<T>> result in results)
{
_results.AddRange(result);
}
_dataMapper = dataMapper;
}
[Obsolete]
private static List<RecordToken<T>> CreateResultsWithNoDuplicates(IEnumerable<IEnumerable<RecordToken<T>>> initialResults)
{
Dictionary<RecordToken<T>, object> alreadyUsedTokens = new Dictionary<RecordToken<T>, object>();
List<RecordToken<T>> results = new List<RecordToken<T>>();
foreach (IEnumerable<RecordToken<T>> resultSet in initialResults)
{
foreach (RecordToken<T> token in resultSet)
{
if (alreadyUsedTokens.ContainsKey(token))
{
continue;
}
alreadyUsedTokens.Add(token, null);
results.Add(token);
}
}
return results;
}
public RecordToken<T> this[int index]
{
get { return _results[index]; }
}
public void RemoveAll(Predicate<RecordToken<T>> match)
{
_results.RemoveAll(match);
}
public int Count
{
get { return _results.Count; }
}
private RecordToken<T> GetItemFromIndex(int index)
{
if (index < 0)
{
return null;
}
return this[index];
}
#region FindFirst(Index) Of DisplayString
public RecordToken<T> FindFirst(Predicate<RecordToken<T>> match)
{
int index = FindFirstIndex(match);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(int startIndex, Predicate<RecordToken<T>> match)
{
int index = FindFirstIndex(startIndex, match);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(int startIndex, int count, Predicate<RecordToken<T>> match)
{
int index = FindFirstIndex(startIndex, count, match);
return GetItemFromIndex(index);
}
public int FindFirstIndex(Predicate<RecordToken<T>> match)
{
return _results.FindIndex(match);
}
public int FindFirstIndex(int startIndex, int count, Predicate<RecordToken<T>> match)
{
return _results.FindIndex(startIndex, count, match);
}
public int FindFirstIndex(int startIndex, Predicate<RecordToken<T>> match)
{
return _results.FindIndex(startIndex, match);
}
#endregion
#region FindFirst(Index) of RepositoryId
public RecordToken<T> FindFirst(RepositoryId id)
{
int index = FindFirstIndex(id);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(RepositoryId id, int startIndex)
{
int index = FindFirstIndex(id, startIndex);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(RepositoryId id, int startIndex, int count)
{
int index = FindFirstIndex(id, startIndex, count);
return GetItemFromIndex(index);
}
public int FindFirstIndex(RepositoryId id, int startIndex, int count)
{
return _results.FindIndex(startIndex,
count,
delegate(RecordToken<T> r) { return (r.Id == id); });
}
public int FindFirstIndex(RepositoryId id)
{
return _results.FindIndex(delegate(RecordToken<T> r) { return (r.Id == id); });
}
public int FindFirstIndex(RepositoryId id, int startIndex)
{
return _results.FindIndex(startIndex,
delegate(RecordToken<T> r) { return (r.Id == id); });
}
#endregion
#region FindFirst(Index) of T
public RecordToken<T> FindFirst(T item)
{
int index = FindFirstIndex(item);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(T item, int startIndex)
{
int index = FindFirstIndex(item, startIndex);
return GetItemFromIndex(index);
}
public RecordToken<T> FindFirst(T item, int startIndex, int count)
{
int index = FindFirstIndex(item, startIndex, count);
return GetItemFromIndex(index);
}
public int FindFirstIndex(T item)
{
RepositoryId id = _dataMapper.GetId(item);
return FindFirstIndex(id);
}
public int FindFirstIndex(T item, int startIndex)
{
RepositoryId id = _dataMapper.GetId(item);
return FindFirstIndex(id, startIndex);
}
public int FindFirstIndex(T item, int startIndex, int count)
{
RepositoryId id = _dataMapper.GetId(item);
return FindFirstIndex(id, startIndex, count);
}
#endregion
#region FindFirstIndex of RecordToken<T>
public int FindFirstIndex(RecordToken<T> token, int startIndex, int count)
{
return _results.FindIndex(startIndex,
count,
delegate(RecordToken<T> r) { return (r == token); });
}
public int FindFirstIndex(RecordToken<T> token)
{
return _results.FindIndex(delegate(RecordToken<T> r) { return (r == token); });
}
public int FindFirstIndex(RecordToken<T> token, int startIndex)
{
return _results.FindIndex(startIndex,
delegate(RecordToken<T> r) { return (r == token); });
}
#endregion
public static explicit operator BindingList<RecordToken<T>>(ResultSet<T> results)
{
return new BindingList<RecordToken<T>>(results._results);
}
#region IEnumerable<RecordToken<T>> Members
IEnumerator<RecordToken<T>> IEnumerable<RecordToken<T>>.GetEnumerator()
{
return _results.GetEnumerator();
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return ((IEnumerable<RecordToken<T>>) this).GetEnumerator();
}
#endregion
#region IEnumerable<RepositoryId> Members
IEnumerator<RepositoryId> IEnumerable<RepositoryId>.GetEnumerator()
{
foreach (RecordToken<T> recordToken in this)
{
yield return (recordToken.Id);
}
}
#endregion
public void Sort(params SortDefinition[] sortDefinitions)
{
_results.Sort(new RecordTokenComparer<T>(sortDefinitions));
}
public void SortByRepositoryId()
{
SortByRepositoryId(_results);
}
private static void SortByRepositoryId(List<RecordToken<T>> list)
{
list.Sort(new RecordTokenComparer<T>(new SortDefinition("RepositoryId", Comparer<RepositoryId>.Default)));
}
/// <summary>
/// Removes any entries for which the predicate canBeRemoved is true
/// and another record token with the same repository Id exists
/// </summary>
/// <param name="fieldName"></param>
/// <param name="canBeRemoved"></param>
public void Coalesce(string fieldName, Predicate<object> canBeRemoved)
{
List<RecordToken<T>> results = new List<RecordToken<T>>(_results);
SortByRepositoryId(results);
bool hasValidEntry = false;
List<RecordToken<T>> removeable = new List<RecordToken<T>>();
RecordToken<T> previousToken = null;
foreach (RecordToken<T> token in results)
{
if ((previousToken != null) && (token.Id != previousToken.Id))
{
if(hasValidEntry)
{
RemoveTokens(removeable);
}
removeable.Clear();
hasValidEntry = false;
}
if (canBeRemoved(token[fieldName]))
{
removeable.Add(token);
}
else
{
hasValidEntry = true;
}
previousToken = token;
}
if (hasValidEntry)
{
RemoveTokens(removeable);
}
}
private void RemoveTokens(IEnumerable<RecordToken<T>> removeable)
{
foreach (RecordToken<T> recordToken in removeable)
{
_results.Remove(recordToken);
}
}
}
public class SortDefinition
{
private readonly string _field;
private readonly IComparer _comparer;
public SortDefinition(string field, IComparer comparer)
{
_field = field;
_comparer = comparer;
}
public string Field
{
get { return _field; }
}
public IComparer Comparer
{
get { return _comparer; }
}
}
}
| |
/*
* 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
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.DataStructures;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Plugin;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Interop;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Native Ignite wrapper.
/// </summary>
internal class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite
{
/// <summary>
/// Operation codes for PlatformProcessorImpl calls.
/// </summary>
private enum Op
{
GetCache = 1,
CreateCache = 2,
GetOrCreateCache = 3,
CreateCacheFromConfig = 4,
GetOrCreateCacheFromConfig = 5,
DestroyCache = 6,
GetAffinity = 7,
GetDataStreamer = 8,
GetTransactions = 9,
GetClusterGroup = 10,
GetExtension = 11,
GetAtomicLong = 12,
GetAtomicReference = 13,
GetAtomicSequence = 14,
GetIgniteConfiguration = 15,
GetCacheNames = 16,
CreateNearCache = 17,
GetOrCreateNearCache = 18,
LoggerIsLevelEnabled = 19,
LoggerLog = 20,
GetBinaryProcessor = 21,
ReleaseStart = 22,
AddCacheConfiguration = 23,
SetBaselineTopologyVersion = 24,
SetBaselineTopologyNodes = 25,
GetBaselineTopology = 26,
DisableWal = 27,
EnableWal = 28,
IsWalEnabled = 29,
SetTxTimeoutOnPartitionMapExchange = 30
}
/** */
private readonly IgniteConfiguration _cfg;
/** Grid name. */
private readonly string _name;
/** Unmanaged node. */
private readonly IPlatformTargetInternal _proc;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Initial projection. */
private readonly ClusterGroupImpl _prj;
/** Binary. */
private readonly Binary.Binary _binary;
/** Binary processor. */
private readonly BinaryProcessor _binaryProc;
/** Lifecycle handlers. */
private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers;
/** Local node. */
private IClusterNode _locNode;
/** Callbacks */
private readonly UnmanagedCallbacks _cbs;
/** Node info cache. */
private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes =
new ConcurrentDictionary<Guid, ClusterNodeImpl>();
/** Client reconnect task completion source. */
private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource =
new TaskCompletionSource<bool>();
/** Plugin processor. */
private readonly PluginProcessor _pluginProcessor;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="name">Grid name.</param>
/// <param name="proc">Interop processor.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="lifecycleHandlers">Lifecycle beans.</param>
/// <param name="cbs">Callbacks.</param>
public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh,
IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc)
{
Debug.Assert(cfg != null);
Debug.Assert(proc != null);
Debug.Assert(marsh != null);
Debug.Assert(lifecycleHandlers != null);
Debug.Assert(cbs != null);
_cfg = cfg;
_name = name;
_proc = proc;
_marsh = marsh;
_lifecycleHandlers = lifecycleHandlers;
_cbs = cbs;
marsh.Ignite = this;
_prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null);
_binary = new Binary.Binary(marsh);
_binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor));
cbs.Initialize(this);
// Set reconnected task to completed state for convenience.
_clientReconnectTaskCompletionSource.SetResult(false);
SetCompactFooter();
_pluginProcessor = new PluginProcessor(this);
}
/// <summary>
/// Sets the compact footer setting.
/// </summary>
private void SetCompactFooter()
{
if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl))
{
// If there is a Spring config, use setting from Spring,
// since we ignore .NET config in legacy mode.
var cfg0 = GetConfiguration().BinaryConfiguration;
if (cfg0 != null)
_marsh.CompactFooter = cfg0.CompactFooter;
}
}
/// <summary>
/// On-start routine.
/// </summary>
internal void OnStart()
{
PluginProcessor.OnIgniteStart();
foreach (var lifecycleBean in _lifecycleHandlers)
lifecycleBean.OnStart(this);
}
/** <inheritdoc /> */
public string Name
{
get { return _name; }
}
/** <inheritdoc /> */
public ICluster GetCluster()
{
return this;
}
/** <inheritdoc /> */
IIgnite IClusterGroup.Ignite
{
get { return this; }
}
/** <inheritdoc /> */
public IClusterGroup ForLocal()
{
return _prj.ForNodes(GetLocalNode());
}
/** <inheritdoc /> */
public ICompute GetCompute()
{
return _prj.ForServers().GetCompute();
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
IgniteArgumentCheck.NotNull(p, "p");
return _prj.ForPredicate(p);
}
/** <inheritdoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
return _prj.ForAttribute(name, val);
}
/** <inheritdoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return _prj.ForCacheNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForDataNodes(string name)
{
return _prj.ForDataNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForClientNodes(string name)
{
return _prj.ForClientNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForRemotes()
{
return _prj.ForRemotes();
}
/** <inheritdoc /> */
public IClusterGroup ForDaemons()
{
return _prj.ForDaemons();
}
/** <inheritdoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
IgniteArgumentCheck.NotNull(node, "node");
return _prj.ForHost(node);
}
/** <inheritdoc /> */
public IClusterGroup ForRandom()
{
return _prj.ForRandom();
}
/** <inheritdoc /> */
public IClusterGroup ForOldest()
{
return _prj.ForOldest();
}
/** <inheritdoc /> */
public IClusterGroup ForYoungest()
{
return _prj.ForYoungest();
}
/** <inheritdoc /> */
public IClusterGroup ForDotNet()
{
return _prj.ForDotNet();
}
/** <inheritdoc /> */
public IClusterGroup ForServers()
{
return _prj.ForServers();
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetNodes()
{
return _prj.GetNodes();
}
/** <inheritdoc /> */
public IClusterNode GetNode(Guid id)
{
return _prj.GetNode(id);
}
/** <inheritdoc /> */
public IClusterNode GetNode()
{
return _prj.GetNode();
}
/** <inheritdoc /> */
public IClusterMetrics GetMetrics()
{
return _prj.GetMetrics();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy",
Justification = "Proxy does not need to be disposed.")]
public void Dispose()
{
Ignition.Stop(Name, true);
}
/// <summary>
/// Internal stop routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
internal void Stop(bool cancel)
{
var jniTarget = _proc as PlatformJniTarget;
if (jniTarget == null)
{
throw new IgniteException("Ignition.Stop is not supported in thin client.");
}
UU.IgnitionStop(Name, cancel);
_cbs.Cleanup();
}
/// <summary>
/// Called before node has stopped.
/// </summary>
internal void BeforeNodeStop()
{
var handler = Stopping;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called after node has stopped.
/// </summary>
internal void AfterNodeStop()
{
foreach (var bean in _lifecycleHandlers)
bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop);
var handler = Stopped;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration)
{
return GetOrCreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.GetOrCreateCacheFromConfig);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name));
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration)
{
return CreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.CreateCacheFromConfig);
}
/// <summary>
/// Gets or creates the cache.
/// </summary>
private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration, Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name");
configuration.Validate(Logger);
var cacheTarget = DoOutOpObject((int) op, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
configuration.Write(w, ClientSocket.CurrentProtocolVersion);
if (nearConfiguration != null)
{
w.WriteBoolean(true);
nearConfiguration.Write(w);
}
else
{
w.WriteBoolean(false);
}
});
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public void DestroyCache(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
DoOutOp((int) Op.DestroyCache, w => w.WriteString(name));
}
/// <summary>
/// Gets cache from specified native cache object.
/// </summary>
/// <param name="nativeCache">Native cache.</param>
/// <param name="keepBinary">Keep binary flag.</param>
/// <returns>
/// New instance of cache wrapping specified native cache.
/// </returns>
public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false)
{
return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false, false);
}
/** <inheritdoc /> */
public IClusterNode GetLocalNode()
{
return _locNode ?? (_locNode =
GetNodes().FirstOrDefault(x => x.IsLocal) ??
ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal));
}
/** <inheritdoc /> */
public bool PingNode(Guid nodeId)
{
return _prj.PingNode(nodeId);
}
/** <inheritdoc /> */
public long TopologyVersion
{
get { return _prj.TopologyVersion; }
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetTopology(long ver)
{
return _prj.Topology(ver);
}
/** <inheritdoc /> */
public void ResetMetrics()
{
_prj.ResetMetrics();
}
/** <inheritdoc /> */
public Task<bool> ClientReconnectTask
{
get { return _clientReconnectTaskCompletionSource.Task; }
}
/** <inheritdoc /> */
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetDataStreamer<TK, TV>(cacheName, false);
}
/// <summary>
/// Gets the data streamer.
/// </summary>
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary)
{
var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w =>
{
w.WriteString(cacheName);
w.WriteBoolean(keepBinary);
});
return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary);
}
/// <summary>
/// Gets the public Ignite interface.
/// </summary>
public IIgnite GetIgnite()
{
return this;
}
/** <inheritdoc /> */
public IBinary GetBinary()
{
return _binary;
}
/** <inheritdoc /> */
public ICacheAffinity GetAffinity(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName));
return new CacheAffinityImpl(aff, false);
}
/** <inheritdoc /> */
public ITransactions GetTransactions()
{
return new TransactionsImpl(this, DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id);
}
/** <inheritdoc /> */
public IMessaging GetMessaging()
{
return _prj.GetMessaging();
}
/** <inheritdoc /> */
public IEvents GetEvents()
{
return _prj.GetEvents();
}
/** <inheritdoc /> */
public IServices GetServices()
{
return _prj.ForServers().GetServices();
}
/** <inheritdoc /> */
public IAtomicLong GetAtomicLong(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeLong == null)
return null;
return new AtomicLong(nativeLong, name);
}
/** <inheritdoc /> */
public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeSeq == null)
return null;
return new AtomicSequence(nativeSeq, name);
}
/** <inheritdoc /> */
public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w =>
{
w.WriteString(name);
w.WriteObject(initialValue);
w.WriteBoolean(create);
});
return refTarget == null ? null : new AtomicReference<T>(refTarget, name);
}
/** <inheritdoc /> */
public IgniteConfiguration GetConfiguration()
{
return DoInOp((int) Op.GetIgniteConfiguration,
s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg,
ClientSocket.CurrentProtocolVersion));
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.CreateNearCache);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.GetOrCreateNearCache);
}
/** <inheritdoc /> */
public ICollection<string> GetCacheNames()
{
return Target.OutStream((int) Op.GetCacheNames, r =>
{
var res = new string[r.ReadInt()];
for (var i = 0; i < res.Length; i++)
res[i] = r.ReadString();
return (ICollection<string>) res;
});
}
/** <inheritdoc /> */
public ILogger Logger
{
get { return _cbs.Log; }
}
/** <inheritdoc /> */
public event EventHandler Stopping;
/** <inheritdoc /> */
public event EventHandler Stopped;
/** <inheritdoc /> */
public event EventHandler ClientDisconnected;
/** <inheritdoc /> */
public event EventHandler<ClientReconnectEventArgs> ClientReconnected;
/** <inheritdoc /> */
public T GetPlugin<T>(string name) where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return PluginProcessor.GetProvider(name).GetPlugin<T>();
}
/** <inheritdoc /> */
public void ResetLostPartitions(IEnumerable<string> cacheNames)
{
IgniteArgumentCheck.NotNull(cacheNames, "cacheNames");
_prj.ResetLostPartitions(cacheNames);
}
/** <inheritdoc /> */
public void ResetLostPartitions(params string[] cacheNames)
{
ResetLostPartitions((IEnumerable<string>) cacheNames);
}
/** <inheritdoc /> */
#pragma warning disable 618
public ICollection<IMemoryMetrics> GetMemoryMetrics()
{
return _prj.GetMemoryMetrics();
}
/** <inheritdoc /> */
public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName)
{
IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName");
return _prj.GetMemoryMetrics(memoryPolicyName);
}
#pragma warning restore 618
/** <inheritdoc /> */
public void SetActive(bool isActive)
{
_prj.SetActive(isActive);
}
/** <inheritdoc /> */
public bool IsActive()
{
return _prj.IsActive();
}
/** <inheritdoc /> */
public void SetBaselineTopology(long topologyVersion)
{
DoOutInOp((int) Op.SetBaselineTopologyVersion, topologyVersion);
}
/** <inheritdoc /> */
public void SetBaselineTopology(IEnumerable<IBaselineNode> nodes)
{
IgniteArgumentCheck.NotNull(nodes, "nodes");
DoOutOp((int) Op.SetBaselineTopologyNodes, w =>
{
var pos = w.Stream.Position;
w.WriteInt(0);
var cnt = 0;
foreach (var node in nodes)
{
cnt++;
BaselineNode.Write(w, node);
}
w.Stream.WriteInt(pos, cnt);
});
}
/** <inheritdoc /> */
public ICollection<IBaselineNode> GetBaselineTopology()
{
return DoInOp((int) Op.GetBaselineTopology,
s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r)));
}
/** <inheritdoc /> */
public void DisableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.DisableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public void EnableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.EnableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public bool IsWalEnabled(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return DoOutOp((int) Op.IsWalEnabled, w => w.WriteString(cacheName)) == True;
}
public void SetTxTimeoutOnPartitionMapExchange(TimeSpan timeout)
{
DoOutOp((int) Op.SetTxTimeoutOnPartitionMapExchange,
(BinaryWriter w) => w.WriteLong((long) timeout.TotalMilliseconds));
}
/** <inheritdoc /> */
#pragma warning disable 618
public IPersistentStoreMetrics GetPersistentStoreMetrics()
{
return _prj.GetPersistentStoreMetrics();
}
#pragma warning restore 618
/** <inheritdoc /> */
public ICollection<IDataRegionMetrics> GetDataRegionMetrics()
{
return _prj.GetDataRegionMetrics();
}
/** <inheritdoc /> */
public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName)
{
return _prj.GetDataRegionMetrics(memoryPolicyName);
}
/** <inheritdoc /> */
public IDataStorageMetrics GetDataStorageMetrics()
{
return _prj.GetDataStorageMetrics();
}
/** <inheritdoc /> */
public void AddCacheConfiguration(CacheConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
DoOutOp((int) Op.AddCacheConfiguration,
s => configuration.Write(BinaryUtils.Marshaller.StartMarshal(s), ClientSocket.CurrentProtocolVersion));
}
/// <summary>
/// Gets or creates near cache.
/// </summary>
private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration,
Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
var cacheTarget = DoOutOpObject((int) op, w =>
{
w.WriteString(name);
configuration.Write(w);
});
return GetCache<TK, TV>(cacheTarget);
}
/// <summary>
/// Gets internal projection.
/// </summary>
/// <returns>Projection.</returns>
public ClusterGroupImpl ClusterGroup
{
get { return _prj; }
}
/// <summary>
/// Gets the binary processor.
/// </summary>
public IBinaryProcessor BinaryProcessor
{
get { return _binaryProc; }
}
/// <summary>
/// Configuration.
/// </summary>
public IgniteConfiguration Configuration
{
get { return _cfg; }
}
/// <summary>
/// Handle registry.
/// </summary>
public HandleRegistry HandleRegistry
{
get { return _cbs.HandleRegistry; }
}
/// <summary>
/// Updates the node information from stream.
/// </summary>
/// <param name="memPtr">Stream ptr.</param>
public void UpdateNodeInfo(long memPtr)
{
var stream = IgniteManager.Memory.Get(memPtr).GetStream();
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
var node = new ClusterNodeImpl(reader);
node.Init(this);
_nodes[node.Id] = node;
}
/// <summary>
/// Returns instance of Ignite Transactions to mark a transaction with a special label.
/// </summary>
/// <param name="label"></param>
/// <returns><see cref="ITransactions"/></returns>
internal ITransactions GetTransactionsWithLabel(string label)
{
Debug.Assert(label != null);
var platformTargetInternal = DoOutOpObject((int) Op.GetTransactions, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
w.WriteString(label);
});
return new TransactionsImpl(this, platformTargetInternal, GetLocalNode().Id, label);
}
/// <summary>
/// Gets the node from cache.
/// </summary>
/// <param name="id">Node id.</param>
/// <returns>Cached node.</returns>
public ClusterNodeImpl GetNode(Guid? id)
{
return id == null ? null : _nodes[id.Value];
}
/// <summary>
/// Gets the interop processor.
/// </summary>
internal IPlatformTargetInternal InteropProcessor
{
get { return _proc; }
}
/// <summary>
/// Called when local client node has been disconnected from the cluster.
/// </summary>
internal void OnClientDisconnected()
{
_clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>();
var handler = ClientDisconnected;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called when local client node has been reconnected to the cluster.
/// </summary>
/// <param name="clusterRestarted">Cluster restarted flag.</param>
internal void OnClientReconnected(bool clusterRestarted)
{
_marsh.OnClientReconnected(clusterRestarted);
_clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted);
var handler = ClientReconnected;
if (handler != null)
handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted));
}
/// <summary>
/// Gets the plugin processor.
/// </summary>
public PluginProcessor PluginProcessor
{
get { return _pluginProcessor; }
}
/// <summary>
/// Notify processor that it is safe to use.
/// </summary>
internal void ProcessorReleaseStart()
{
Target.InLongOutLong((int) Op.ReleaseStart, 0);
}
/// <summary>
/// Checks whether log level is enabled in Java logger.
/// </summary>
internal bool LoggerIsLevelEnabled(LogLevel logLevel)
{
return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True;
}
/// <summary>
/// Logs to the Java logger.
/// </summary>
internal void LoggerLog(LogLevel level, string msg, string category, string err)
{
Target.InStreamOutLong((int) Op.LoggerLog, w =>
{
w.WriteInt((int) level);
w.WriteString(msg);
w.WriteString(category);
w.WriteString(err);
});
}
/// <summary>
/// Gets the platform plugin extension.
/// </summary>
internal IPlatformTarget GetExtension(int id)
{
return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id));
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorLogPageFactory.cs 923 2011-12-23 22:02:10Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using Encoding = System.Text.Encoding;
#endregion
/// <summary>
/// HTTP handler factory that dispenses handlers for rendering views and
/// resources needed to display the error log.
/// </summary>
public class ErrorLogPageFactory : IHttpHandlerFactory
{
private static readonly object _authorizationHandlersKey = new object();
IHttpHandler IHttpHandlerFactory.GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
return GetHandler(new HttpContextWrapper(context), requestType, url, pathTranslated);
}
/// <summary>
/// Returns an object that implements the <see cref="IHttpHandler"/>
/// interface and which is responsible for serving the request.
/// </summary>
/// <returns>
/// A new <see cref="IHttpHandler"/> object that processes the request.
/// </returns>
public virtual IHttpHandler GetHandler(HttpContextBase context, string requestType, string url, string pathTranslated)
{
//
// The request resource is determined by the looking up the
// value of the PATH_INFO server variable.
//
var request = context.Request;
var resource = request.PathInfo.Length == 0
? string.Empty
: request.PathInfo.Substring(1).ToLowerInvariant();
var handler = FindHandler(resource);
if (handler == null)
throw new HttpException(404, "Resource not found.");
//
// Check if authorized then grant or deny request.
//
var authorized = IsAuthorized(context);
if (authorized == false
|| (authorized == null // Compatibility case...
&& !request.IsLocal
&& !SecurityConfiguration.Default.AllowRemoteAccess))
{
ManifestResourceHandler.Create("RemoteAccessError.htm", "text/html")(context);
var response = context.Response;
response.Status = "403 Forbidden";
response.End();
//
// HttpResponse.End docs say that it throws
// ThreadAbortException and so should never end up here but
// that's not been the observation in the debugger. So as a
// precautionary measure, bail out anyway.
//
return null;
}
return handler;
}
private static IHttpHandler FindHandler(string name)
{
Debug.Assert(name != null);
switch (name)
{
case "detail":
return CreateTemplateHandler<ErrorDetailPage>();
case "html":
return new ErrorHtmlPage();
case "xml":
return new DelegatingHttpHandler(ErrorXmlHandler.ProcessRequest);
case "json":
return new DelegatingHttpHandler(ErrorJsonHandler.ProcessRequest);
case "rss":
return new DelegatingHttpHandler(ErrorRssHandler.ProcessRequest);
case "digestrss":
return new DelegatingHttpHandler(ErrorDigestRssHandler.ProcessRequest);
case "download":
#if NET_3_5 || NET_4_0
return new HttpAsyncHandler((context, getAsyncCallback) => HttpTextAsyncHandler.Create(ErrorLogDownloadHandler.ProcessRequest)(context, getAsyncCallback));
#else
return new DelegatingHttpTaskAsyncHandler(ErrorLogDownloadHandler.ProcessRequestAsync);
#endif
case "stylesheet":
return new DelegatingHttpHandler(ManifestResourceHandler.Create(StyleSheetHelper.StyleSheetResourceNames, "text/css", Encoding.GetEncoding("Windows-1252"), true));
case "test":
throw new TestException();
case "about":
return CreateTemplateHandler<AboutPage>();
default:
return name.Length == 0 ? CreateTemplateHandler<ErrorLogPage>() : null;
}
}
static IHttpHandler CreateTemplateHandler<T>() where T : WebTemplateBase, new()
{
return new DelegatingHttpHandler(context =>
{
var template = new T { Context = context };
context.Response.Write(template.TransformText());
});
}
/// <summary>
/// Enables the factory to reuse an existing handler instance.
/// </summary>
public virtual void ReleaseHandler(IHttpHandler handler) {}
/// <summary>
/// Determines if the request is authorized by objects implementing
/// <see cref="IRequestAuthorizationHandler" />.
/// </summary>
/// <returns>
/// Returns <c>false</c> if unauthorized, <c>true</c> if authorized
/// otherwise <c>null</c> if no handlers were available to answer.
/// </returns>
private static bool? IsAuthorized(HttpContextBase context)
{
Debug.Assert(context != null);
var handlers = GetAuthorizationHandlers(context).ToArray();
return handlers.Length != 0
? handlers.All(h => h.Authorize(context))
: (bool?) null;
}
private static IEnumerable<IRequestAuthorizationHandler> GetAuthorizationHandlers(HttpContextBase context)
{
Debug.Assert(context != null);
var key = _authorizationHandlersKey;
var handlers = (IEnumerable<IRequestAuthorizationHandler>) context.Items[key];
if (handlers == null)
{
handlers =
from app in new[] { context.ApplicationInstance }
let mods = HttpModuleRegistry.GetModules(app)
select new[] { app }.Concat(from object m in mods select m) into objs
from obj in objs
select obj as IRequestAuthorizationHandler into handler
where handler != null
select handler;
context.Items[key] = handlers = Array.AsReadOnly(handlers.ToArray());
}
return handlers;
}
internal static Uri GetRequestUrl(HttpContextBase context)
{
if (context == null) throw new ArgumentNullException("context");
var url = context.Items["ELMAH_REQUEST_URL"] as Uri;
return url ?? context.Request.Url;
}
}
public interface IRequestAuthorizationHandler
{
bool Authorize(HttpContextBase context);
}
}
| |
using System;
using System.Globalization;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms.Design;
[assembly:CLSCompliant(true)]
namespace gView.Framework.UI.Controls
{
[Browsable(false)]
[Designer(typeof(AdvancedTextBox.Designer))]
public abstract class AdvancedTextBox : System.Windows.Forms.TextBox
{
/// <summary> The Behavior object associated with this TextBox. </summary>
protected Behavior m_behavior = null; // must be initialized by derived classes
/// <summary>
/// Initializes a new instance of the TextBox class. </summary>
/// <remarks>
/// This constructor is just for convenience for derived classes. It does nothing. </remarks>
protected AdvancedTextBox()
{
}
/// <summary>
/// Initializes a new instance of the TextBox class by explicitly assigning its Behavior field. </summary>
/// <param name="behavior">
/// The <see cref="Behavior" /> object to associate the textbox with. </param>
/// <remarks>
/// This constructor provides a way for derived classes to set the internal Behavior object
/// to something other than the default value (such as <c>null</c>). </remarks>
protected AdvancedTextBox(Behavior behavior)
{
m_behavior = behavior;
}
/// <summary>
/// Checks if the textbox's text is valid and if not updates it with a valid value. </summary>
/// <returns>
/// If the textbox's text is updated (because it wasn't valid), the return value is true; otherwise it is false. </returns>
/// <remarks>
/// This method delegates to <see cref="Behavior.UpdateText">Behavior.UpdateText</see>. </remarks>
public bool UpdateText()
{
return m_behavior.UpdateText();
}
/// <summary>
/// Gets or sets the flags associated with self's Behavior. </summary>
/// <remarks>
/// This property delegates to <see cref="Behavior.Flags">Behavior.Flags</see>. </remarks>
/// <seealso cref="ModifyFlags" />
[Category("Behavior")]
[Description("The flags (on/off attributes) associated with the Behavior.")]
public int Flags
{
get
{
return m_behavior.Flags;
}
set
{
m_behavior.Flags = value;
}
}
/// <summary>
/// Adds or removes flags from self's Behavior. </summary>
/// <param name="flags">
/// The bits to be turned on (ORed) or turned off in the internal flags member. </param>
/// <param name="addOrRemove">
/// If true the flags are added, otherwise they're removed. </param>
/// <remarks>
/// This method delegates to <see cref="Behavior.ModifyFlags">Behavior.ModifyFlags</see>. </remarks>
/// <seealso cref="Flags" />
public void ModifyFlags(int flags, bool addOrRemove)
{
m_behavior.ModifyFlags(flags, addOrRemove);
}
/// <summary>
/// Checks if the textbox's value is valid and if not proceeds according to the behavior's <see cref="Flags" />. </summary>
/// <returns>
/// If the validation succeeds, the return value is true; otherwise it is false. </returns>
/// <remarks>
/// This method delegates to <see cref="Behavior.Validate">Behavior.Validate</see>. </remarks>
/// <seealso cref="IsValid" />
public bool Validate()
{
return m_behavior.Validate();
}
/// <summary>
/// Checks if the textbox contains a valid value. </summary>
/// <returns>
/// If the value is valid, the return value is true; otherwise it is false. </returns>
/// <remarks>
/// This method delegates to <see cref="Behavior.IsValid">Behavior.IsValid</see>. </remarks>
/// <seealso cref="Validate" />
public bool IsValid()
{
return m_behavior.IsValid();
}
/// <summary>
/// Show an error message box. </summary>
/// <param name="message">
/// The message to show. </param>
/// <remarks>
/// This property delegates to <see cref="Behavior.ShowErrorMessageBox">Behavior.ShowErrorMessageBox</see>. </remarks>
/// <seealso cref="ShowErrorIcon" />
/// <seealso cref="ErrorMessage" />
public void ShowErrorMessageBox(string message)
{
m_behavior.ShowErrorMessageBox(message);
}
/// <summary>
/// Show a blinking icon next to the textbox with an error message. </summary>
/// <param name="message">
/// The message to show when the cursor is placed over the icon. </param>
/// <remarks>
/// This property delegates to <see cref="Behavior.ShowErrorIcon">Behavior.ShowErrorIcon</see>. </remarks>
/// <seealso cref="ShowErrorMessageBox" />
/// <seealso cref="ErrorMessage" />
public void ShowErrorIcon(string message)
{
m_behavior.ShowErrorIcon(message);
}
/// <summary>
/// Gets the error message used to notify the user to enter a valid value. </summary>
/// <remarks>
/// This property delegates to <see cref="Behavior.ErrorMessage">Behavior.ErrorMessage</see>. </remarks>
/// <seealso cref="Validate" />
/// <seealso cref="IsValid" />
[Browsable(false)]
public string ErrorMessage
{
get
{
return m_behavior.ErrorMessage;
}
}
/// <summary>
/// Designer class used to prevent the Text property from being set to
/// some default value (ie. textBox1) and to remove any properties the designer
/// should not generate code for. </summary>
internal class Designer : ControlDesigner
{
/// <summary>
/// This typically sets the control's Text property.
/// Here it does nothing so the Text is left blank. </summary>
public override void OnSetComponentDefaults()
{
}
}
}
public class AlphanumericTextBox : AdvancedTextBox
{
public AlphanumericTextBox()
{
m_behavior = new AlphanumericBehavior(this);
}
public AlphanumericTextBox(char[] invalidChars)
{
m_behavior = new AlphanumericBehavior(this, invalidChars);
}
public AlphanumericTextBox(string invalidChars)
{
m_behavior = new AlphanumericBehavior(this, invalidChars);
}
public AlphanumericTextBox(AlphanumericBehavior behavior) :
base(behavior)
{
}
[Browsable(false)]
public AlphanumericBehavior Behavior
{
get
{
return (AlphanumericBehavior)m_behavior;
}
}
[Category("Behavior")]
public char[] InvalidChars
{
get
{
return Behavior.InvalidChars;
}
set
{
Behavior.InvalidChars = value;
}
}
}
public class MaskedTextBox : AdvancedTextBox
{
public MaskedTextBox()
{
m_behavior = new MaskedBehavior(this);
}
public MaskedTextBox(string mask)
{
m_behavior = new MaskedBehavior(this, mask);
}
public MaskedTextBox(MaskedBehavior behavior) :
base(behavior)
{
}
[Browsable(false)]
public MaskedBehavior Behavior
{
get
{
return (MaskedBehavior)m_behavior;
}
}
[Category("Behavior")]
[Description("The string used for formatting the characters entered into the textbox. (# = digit)")]
public string Mask
{
get
{
return Behavior.Mask;
}
set
{
Behavior.Mask = value;
}
}
[Browsable(false)]
public ArrayList Symbols
{
get
{
return Behavior.Symbols;
}
}
[Browsable(false)]
public string NumericText
{
get
{
return Behavior.NumericText;
}
}
}
[Designer(typeof(NumericTextBox.Designer))]
public class NumericTextBox : AdvancedTextBox
{
public NumericTextBox()
{
m_behavior = new NumericBehavior(this);
}
public NumericTextBox(int maxWholeDigits, int maxDecimalPlaces)
{
m_behavior = new NumericBehavior(this, maxWholeDigits, maxDecimalPlaces);
}
public NumericTextBox(NumericBehavior behavior)
:
base(behavior)
{
}
[Browsable(false)]
public NumericBehavior Behavior
{
get
{
return (NumericBehavior)m_behavior;
}
}
[Browsable(false)]
public double Double
{
get
{
try
{
return Convert.ToDouble(Behavior.NumericText);
}
catch
{
return 0;
}
}
set
{
Text = value.ToString();
}
}
[Browsable(false)]
public int Int
{
get
{
try
{
return Convert.ToInt32(Behavior.NumericText);
}
catch
{
return 0;
}
}
set
{
Text = value.ToString();
}
}
[Browsable(false)]
public long Long
{
get
{
try
{
return Convert.ToInt64(Behavior.NumericText);
}
catch
{
return 0;
}
}
set
{
Text = value.ToString();
}
}
[Browsable(false)]
public string NumericText
{
get
{
return Behavior.NumericText;
}
}
[Browsable(false)]
public string RealNumericText
{
get
{
return Behavior.RealNumericText;
}
}
[Category("Behavior")]
public int MaxWholeDigits
{
get
{
return Behavior.MaxWholeDigits;
}
set
{
Behavior.MaxWholeDigits = value;
}
}
[Category("Behavior")]
public int MaxDecimalPlaces
{
get
{
return Behavior.MaxDecimalPlaces;
}
set
{
Behavior.MaxDecimalPlaces = value;
}
}
[Category("Behavior")]
public bool AllowNegative
{
get
{
return Behavior.AllowNegative;
}
set
{
Behavior.AllowNegative = value;
}
}
[Category("Behavior")]
public int DigitsInGroup
{
get
{
return Behavior.DigitsInGroup;
}
set
{
Behavior.DigitsInGroup = value;
}
}
[Browsable(false)]
public char DecimalPoint
{
get
{
return Behavior.DecimalPoint;
}
set
{
Behavior.DecimalPoint = value;
}
}
[Browsable(false)]
public char GroupSeparator
{
get
{
return Behavior.GroupSeparator;
}
set
{
Behavior.GroupSeparator = value;
}
}
[Browsable(false)]
public char NegativeSign
{
get
{
return Behavior.NegativeSign;
}
set
{
Behavior.NegativeSign = value;
}
}
[Category("Behavior")]
public String Prefix
{
get
{
return Behavior.Prefix;
}
set
{
Behavior.Prefix = value;
}
}
[Category("Behavior")]
public double RangeMin
{
get
{
return Behavior.RangeMin;
}
set
{
Behavior.RangeMin = value;
}
}
[Category("Behavior")]
public double RangeMax
{
get
{
return Behavior.RangeMax;
}
set
{
Behavior.RangeMax = value;
}
}
private NumericDataType _dataType=NumericDataType.doubleType;
[Category("Behavior")]
public NumericDataType DataType
{
get { return _dataType; }
set
{
switch (value)
{
case NumericDataType.byteType:
this.RangeMax = byte.MaxValue;
this.RangeMin = byte.MinValue;
this.MaxWholeDigits = 3;
this.MaxDecimalPlaces = 0;
break;
case NumericDataType.shortType:
this.RangeMax = short.MaxValue;
this.RangeMin = short.MinValue;
this.MaxWholeDigits = 5;
this.MaxDecimalPlaces = 0;
break;
case NumericDataType.intType:
this.RangeMax = int.MaxValue;
this.RangeMin = int.MinValue;
this.MaxWholeDigits = 10;
this.MaxDecimalPlaces = 0;
break;
case NumericDataType.longType:
this.RangeMax = long.MaxValue;
this.RangeMin = long.MinValue;
this.MaxWholeDigits = 20;
this.MaxDecimalPlaces = 0;
break;
case NumericDataType.floatType:
this.RangeMax = float.MaxValue;
this.RangeMin = float.MinValue;
this.MaxWholeDigits = 20;
this.MaxDecimalPlaces = 5;
break;
case NumericDataType.doubleType:
this.RangeMax = double.MaxValue;
this.RangeMin = double.MinValue;
this.MaxWholeDigits = 20;
this.MaxDecimalPlaces = 5;
break;
}
_dataType = value;
}
}
internal new class Designer : AdvancedTextBox.Designer
{
protected override void PostFilterProperties(IDictionary properties)
{
properties.Remove("DecimalPoint");
properties.Remove("GroupSeparator");
properties.Remove("NegativeSign");
properties.Remove("Double");
properties.Remove("Int");
properties.Remove("Long");
base.PostFilterProperties(properties);
}
}
public enum NumericDataType { byteType = 0, shortType = 1, intType = 2, longType = 3, floatType = 4, doubleType = 5 }
}
public class IntegerTextBox : NumericTextBox
{
public IntegerTextBox() :
base(null)
{
m_behavior = new IntegerBehavior(this);
}
public IntegerTextBox(int maxWholeDigits) :
base(null)
{
m_behavior = new IntegerBehavior(this, maxWholeDigits);
}
public IntegerTextBox(IntegerBehavior behavior) :
base(behavior)
{
}
}
[Designer(typeof(CurrencyTextBox.Designer))]
public class CurrencyTextBox : NumericTextBox
{
public CurrencyTextBox() :
base(null)
{
m_behavior = new CurrencyBehavior(this);
}
public CurrencyTextBox(CurrencyBehavior behavior) :
base(behavior)
{
}
internal new class Designer : NumericTextBox.Designer
{
protected override void PostFilterProperties(IDictionary properties)
{
properties.Remove("DigitsInGroup");
properties.Remove("Prefix");
properties.Remove("MaxDecimalPlaces");
base.PostFilterProperties(properties);
}
}
}
[Designer(typeof(DateTextBox.Designer))]
public class DateTextBox : AdvancedTextBox
{
public DateTextBox()
{
m_behavior = new DateBehavior(this);
}
public DateTextBox(DateBehavior behavior) :
base(behavior)
{
}
[Browsable(false)]
public DateBehavior Behavior
{
get
{
return (DateBehavior)m_behavior;
}
}
[Browsable(false)]
public int Month
{
get
{
return Behavior.Month;
}
set
{
Behavior.Month = value;
}
}
[Browsable(false)]
public int Day
{
get
{
return Behavior.Day;
}
set
{
Behavior.Day = value;
}
}
[Browsable(false)]
public int Year
{
get
{
return Behavior.Year;
}
set
{
Behavior.Year = value;
}
}
[Browsable(false)]
public object Value
{
get
{
return Behavior.Value;
}
set
{
Behavior.Value = value;
}
}
[Category("Behavior")]
public DateTime RangeMin
{
get
{
return Behavior.RangeMin;
}
set
{
Behavior.RangeMin = value;
}
}
[Category("Behavior")]
public DateTime RangeMax
{
get
{
return Behavior.RangeMax;
}
set
{
Behavior.RangeMax = value;
}
}
[Browsable(false)]
public char Separator
{
get
{
return Behavior.Separator;
}
set
{
Behavior.Separator = value;
}
}
[Browsable(false)]
public bool ShowDayBeforeMonth
{
get
{
return Behavior.ShowDayBeforeMonth;
}
set
{
Behavior.ShowDayBeforeMonth = value;
}
}
public void SetDate(int year, int month, int day)
{
Behavior.SetDate(year, month, day);
}
internal new class Designer : AdvancedTextBox.Designer
{
protected override void PostFilterProperties(IDictionary properties)
{
properties.Remove("Month");
properties.Remove("Day");
properties.Remove("Year");
properties.Remove("Value");
properties.Remove("Separator");
properties.Remove("ShowDayBeforeMonth");
base.PostFilterProperties(properties);
}
}
}
[Designer(typeof(TimeTextBox.Designer))]
public class TimeTextBox : AdvancedTextBox
{
public TimeTextBox()
{
m_behavior = new TimeBehavior(this);
}
public TimeTextBox(TimeBehavior behavior) :
base(behavior)
{
}
[Browsable(false)]
public TimeBehavior Behavior
{
get
{
return (TimeBehavior)m_behavior;
}
}
[Browsable(false)]
public int Hour
{
get
{
return Behavior.Hour;
}
set
{
Behavior.Hour = value;
}
}
[Browsable(false)]
public int Minute
{
get
{
return Behavior.Minute;
}
set
{
Behavior.Minute = value;
}
}
[Browsable(false)]
public int Second
{
get
{
return Behavior.Second;
}
set
{
Behavior.Second = value;
}
}
[Browsable(false)]
public string AMPM
{
get
{
return Behavior.AMPM;
}
}
[Browsable(false)]
public object Value
{
get
{
return Behavior.Value;
}
set
{
Behavior.Value = value;
}
}
[Category("Behavior")]
public DateTime RangeMin
{
get
{
return Behavior.RangeMin;
}
set
{
Behavior.RangeMin = value;
}
}
[Category("Behavior")]
public DateTime RangeMax
{
get
{
return Behavior.RangeMax;
}
set
{
Behavior.RangeMax = value;
}
}
[Browsable(false)]
public char Separator
{
get
{
return Behavior.Separator;
}
set
{
Behavior.Separator = value;
}
}
[Browsable(false)]
public bool Show24HourFormat
{
get
{
return Behavior.Show24HourFormat;
}
set
{
Behavior.Show24HourFormat = value;
}
}
[Category("Behavior")]
public bool ShowSeconds
{
get
{
return Behavior.ShowSeconds;
}
set
{
Behavior.ShowSeconds = value;
}
}
public void SetTime(int hour, int minute, int second)
{
Behavior.SetTime(hour, minute, second);
}
public void SetTime(int hour, int minute)
{
Behavior.SetTime(hour, minute);
}
internal new class Designer : AdvancedTextBox.Designer
{
protected override void PostFilterProperties(IDictionary properties)
{
properties.Remove("Hour");
properties.Remove("Minute");
properties.Remove("Second");
properties.Remove("Value");
properties.Remove("Separator");
properties.Remove("Show24HourFormat");
base.PostFilterProperties(properties);
}
}
}
[Designer(typeof(DateTimeTextBox.Designer))]
public class DateTimeTextBox : TimeTextBox
{
public DateTimeTextBox() :
base(null)
{
m_behavior = new DateTimeBehavior(this);
}
public DateTimeTextBox(DateTimeBehavior behavior) :
base(behavior)
{
}
[Browsable(false)]
public new DateTimeBehavior Behavior
{
get
{
return (DateTimeBehavior)m_behavior;
}
}
[Browsable(false)]
public int Month
{
get
{
return Behavior.Month;
}
set
{
Behavior.Month = value;
}
}
[Browsable(false)]
public int Day
{
get
{
return Behavior.Day;
}
set
{
Behavior.Day = value;
}
}
[Browsable(false)]
public int Year
{
get
{
return Behavior.Year;
}
set
{
Behavior.Year = value;
}
}
[Browsable(false)]
public new object Value
{
get
{
return Behavior.Value;
}
set
{
Behavior.Value = value;
}
}
[Category("Behavior")]
public new DateTime RangeMin
{
get
{
return Behavior.RangeMin;
}
set
{
Behavior.RangeMin = value;
}
}
[Category("Behavior")]
public new DateTime RangeMax
{
get
{
return Behavior.RangeMax;
}
set
{
Behavior.RangeMax = value;
}
}
[Browsable(false)]
public char DateSeparator
{
get
{
return Behavior.DateSeparator;
}
set
{
Behavior.DateSeparator = value;
}
}
[Browsable(false)]
public char TimeSeparator
{
get
{
return Behavior.TimeSeparator;
}
set
{
Behavior.TimeSeparator = value;
}
}
[Browsable(false)]
private new char Separator
{
get
{
return Behavior.Separator;
}
}
[Browsable(false)]
public bool ShowDayBeforeMonth
{
get
{
return Behavior.ShowDayBeforeMonth;
}
set
{
Behavior.ShowDayBeforeMonth = value;
}
}
public void SetDate(int year, int month, int day)
{
Behavior.SetDate(year, month, day);
}
public void SetDateTime(int year, int month, int day, int hour, int minute)
{
Behavior.SetDateTime(year, month, day, hour, minute);
}
public void SetDateTime(int year, int month, int day, int hour, int minute, int second)
{
Behavior.SetDateTime(year, month, day, hour, minute, second);
}
internal new class Designer : TimeTextBox.Designer
{
protected override void PostFilterProperties(IDictionary properties)
{
properties.Remove("Month");
properties.Remove("Day");
properties.Remove("Year");
properties.Remove("DateSeparator");
properties.Remove("TimeSeparator");
properties.Remove("ShowDayBeforeMonth");
base.PostFilterProperties(properties);
}
}
}
public class MultiMaskedTextBox : AdvancedTextBox
{
// Fields
private string m_mask = "";
/// <summary>
/// Initializes a new instance of the MultiMaskedTextBox class by setting its mask to an
/// empty string and setting its Behavior field to <see cref="AlphanumericBehavior">Alphanumeric</see>. </summary>
public MultiMaskedTextBox() :
this("")
{
}
public MultiMaskedTextBox(string mask)
{
Mask = mask;
}
[Browsable(false)]
public Behavior Behavior
{
get
{
return m_behavior;
}
}
[Category("Behavior")]
public string Mask
{
get
{
return m_mask;
}
set
{
if (m_mask == value && m_behavior != null)
return;
if (m_behavior != null)
m_behavior.Dispose();
Text = "";
m_mask = value;
int length = value.Length;
// If it doesn't have numeric place holders then it's alphanumeric
int position = value.IndexOf('#');
if (position < 0)
{
m_behavior = new AlphanumericBehavior(this, "");
return;
}
// If it's exactly like the date mask, then it's a date
if (value == "##/##/#### ##:##:##")
{
m_behavior = new DateTimeBehavior(this);
((DateTimeBehavior)m_behavior).ShowSeconds = true;
return;
}
// If it's exactly like the date mask, then it's a date
else if (value == "##/##/#### ##:##")
{
m_behavior = new DateTimeBehavior(this);
return;
}
// If it's exactly like the date mask, then it's a date
else if (value == "##/##/####")
{
m_behavior = new DateBehavior(this);
return;
}
// If it's exactly like the time mask with seconds, then it's a time
else if (value == "##:##:##")
{
m_behavior = new TimeBehavior(this);
((TimeBehavior)m_behavior).ShowSeconds = true;
return;
}
// If it's exactly like the time mask, then it's a time
else if (value == "##:##")
{
m_behavior = new TimeBehavior(this);
return;
}
// If after the first numeric placeholder, we don't find any foreign characters,
// then it's numeric, otherwise it's masked numeric.
string smallMask = value.Substring(position + 1);
int smallLength = smallMask.Length;
char decimalPoint = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0];
char groupSeparator = NumberFormatInfo.CurrentInfo.NumberGroupSeparator[0];
for (int iPos = 0; iPos < smallLength; iPos++)
{
char c = smallMask[iPos];
if (c != '#' && c != decimalPoint && c != groupSeparator)
{
m_behavior = new MaskedBehavior(this, value);
return;
}
}
// Verify that it ends in a number; otherwise it's a masked numeric
if (smallLength > 0 && smallMask[smallLength - 1] != '#')
m_behavior = new MaskedBehavior(this, value);
else
m_behavior = new NumericBehavior(this, value);
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.PythonTools.Profiling {
/// <summary>
/// Provides a view model for the ProfilingTarget class.
/// </summary>
sealed class ProfilingTargetView : INotifyPropertyChanged {
private readonly ReadOnlyCollection<ProjectTargetView> _availableProjects;
private ProjectTargetView _project;
private bool _isProjectSelected, _isStandaloneSelected;
private bool _useVTune;
private bool _isVTuneAvailable;
private bool _isExternalProfilerEnabled;
private StandaloneTargetView _standalone;
private readonly string _startText;
private bool _isValid;
/// <summary>
/// Create a ProfilingTargetView with default values.
/// </summary>
public ProfilingTargetView(IServiceProvider serviceProvider) {
var solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution;
var availableProjects = new List<ProjectTargetView>();
foreach (var project in solution.EnumerateLoadedProjects()) {
availableProjects.Add(new ProjectTargetView((IVsHierarchy)project));
}
_availableProjects = new ReadOnlyCollection<ProjectTargetView>(availableProjects);
_project = null;
_standalone = new StandaloneTargetView(serviceProvider);
_isProjectSelected = true;
_isValid = false;
_useVTune = false;
#if EXTERNAL_PROFILER_DRIVER
_isVTuneAvailable = PythonProfilingPackage.CheckForExternalProfiler();
_isExternalProfilerEnabled = true;
#else
_isVTuneAvailable = false;
_isExternalProfilerEnabled = false;
#endif
PropertyChanged += new PropertyChangedEventHandler(ProfilingTargetView_PropertyChanged);
_standalone.PropertyChanged += new PropertyChangedEventHandler(Standalone_PropertyChanged);
var startupProject = PythonProfilingPackage.GetStartupProjectGuid(serviceProvider);
Project = AvailableProjects.FirstOrDefault(p => p.Guid == startupProject) ??
AvailableProjects.FirstOrDefault();
if (Project != null) {
IsStandaloneSelected = false;
IsProjectSelected = true;
} else {
IsProjectSelected = false;
IsStandaloneSelected = true;
}
_startText = Strings.LaunchProfiling_Start;
}
/// <summary>
/// Create a ProfilingTargetView with values taken from a template.
/// </summary>
public ProfilingTargetView(IServiceProvider serviceProvider, ProfilingTarget template)
: this(serviceProvider) {
if (template.ProjectTarget != null) {
Project = new ProjectTargetView(template.ProjectTarget);
IsStandaloneSelected = false;
IsProjectSelected = true;
} else if (template.StandaloneTarget != null) {
Standalone = new StandaloneTargetView(serviceProvider, template.StandaloneTarget);
IsProjectSelected = false;
IsStandaloneSelected = true;
}
_startText = Strings.LaunchProfiling_OK;
}
/// <summary>
/// Returns a ProfilingTarget with the values set from the view model.
/// </summary>
public ProfilingTarget GetTarget() {
if (IsValid) {
return new ProfilingTarget {
ProjectTarget = IsProjectSelected ? Project.GetTarget() : null,
StandaloneTarget = IsStandaloneSelected ? Standalone.GetTarget() : null,
UseVTune = _useVTune
};
} else {
return null;
}
}
public ReadOnlyCollection<ProjectTargetView> AvailableProjects {
get {
return _availableProjects;
}
}
/// <summary>
/// True if AvailableProjects has at least one item.
/// </summary>
public bool IsAnyAvailableProjects {
get {
return _availableProjects.Count > 0;
}
}
/// <summary>
/// A view of the details of the current project.
/// </summary>
public ProjectTargetView Project {
get {
return _project;
}
set {
if (_project != value) {
_project = value;
OnPropertyChanged("Project");
}
}
}
/// <summary>
/// True if a project is the currently selected target; otherwise, false.
/// </summary>
public bool IsProjectSelected {
get {
return _isProjectSelected;
}
set {
if (_isProjectSelected != value) {
_isProjectSelected = value;
OnPropertyChanged("IsProjectSelected");
}
}
}
/// <summary>
/// A view of the details of the current standalone script.
/// </summary>
public StandaloneTargetView Standalone {
get {
return _standalone;
}
set {
if (_standalone != value) {
if (_standalone != null) {
_standalone.PropertyChanged -= Standalone_PropertyChanged;
}
_standalone = value;
if (_standalone != null) {
_standalone.PropertyChanged += Standalone_PropertyChanged;
}
OnPropertyChanged("Standalone");
}
}
}
/// <summary>
/// True if a standalone script is the currently selected target; otherwise, false.
/// </summary>
public bool IsStandaloneSelected {
get {
return _isStandaloneSelected;
}
set {
if (_isStandaloneSelected != value) {
_isStandaloneSelected = value;
OnPropertyChanged("IsStandaloneSelected");
}
}
}
/// <summary>
/// </summary>
public bool UseVTune {
get { return _useVTune; }
set {
_useVTune = value;
OnPropertyChanged("UseVTune");
}
}
/// <summary>
/// Whether a VTune installation is available in this machine.
/// </summary>
public bool IsVTuneAvailable {
get { return _isVTuneAvailable; }
}
/// <summary>
/// Whether "ExternalProfilerDriver" has been compiled in this build of PTVS
/// </summary>
public bool IsExternalProfilerEnabled {
get { return _isExternalProfilerEnabled; }
}
/// <summary>
/// Receives our own property change events to update IsValid.
/// </summary>
void ProfilingTargetView_PropertyChanged(object sender, PropertyChangedEventArgs e) {
Debug.Assert(sender == this);
if (e.PropertyName != "IsValid") {
IsValid = (IsProjectSelected != IsStandaloneSelected) &&
(IsProjectSelected ?
Project != null :
(Standalone != null && Standalone.IsValid));
}
}
/// <summary>
/// Propagate property change events from Standalone.
/// </summary>
void Standalone_PropertyChanged(object sender, PropertyChangedEventArgs e) {
Debug.Assert(Standalone == sender);
OnPropertyChanged("Standalone");
}
/// <summary>
/// True if all settings are valid; otherwise, false.
/// </summary>
public bool IsValid {
get {
return _isValid;
}
private set {
if (_isValid != value) {
_isValid = value;
OnPropertyChanged("IsValid");
}
}
}
public string StartText {
get {
return _startText;
}
}
private void OnPropertyChanged(string propertyName) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Raised when the value of a property changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
}
}
| |
namespace Schema.NET;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A single or list of values which can be any of the specified types.
/// </summary>
/// <typeparam name="T1">The first type the values can take.</typeparam>
/// <typeparam name="T2">The second type the values can take.</typeparam>
/// <typeparam name="T3">The third type the values can take.</typeparam>
/// <typeparam name="T4">The fourth type the values can take.</typeparam>
public readonly struct Values<T1, T2, T3, T4>
: IReadOnlyCollection<object?>, IEnumerable<object?>, IValues, IEquatable<Values<T1, T2, T3, T4>>
{
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T1"/>.</param>
public Values(OneOrMany<T1> value)
{
this.Value1 = value;
this.Value2 = default;
this.Value3 = default;
this.Value4 = default;
this.HasValue1 = value.Count > 0;
this.HasValue2 = false;
this.HasValue3 = false;
this.HasValue4 = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T2"/>.</param>
public Values(OneOrMany<T2> value)
{
this.Value1 = default;
this.Value2 = value;
this.Value3 = default;
this.Value4 = default;
this.HasValue1 = false;
this.HasValue2 = value.Count > 0;
this.HasValue3 = false;
this.HasValue4 = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T3"/>.</param>
public Values(OneOrMany<T3> value)
{
this.Value1 = default;
this.Value2 = default;
this.Value3 = value;
this.Value4 = default;
this.HasValue1 = false;
this.HasValue2 = false;
this.HasValue3 = value.Count > 0;
this.HasValue4 = false;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="value">The value of type <typeparamref name="T4"/>.</param>
public Values(OneOrMany<T4> value)
{
this.Value1 = default;
this.Value2 = default;
this.Value3 = default;
this.Value4 = value;
this.HasValue1 = false;
this.HasValue2 = false;
this.HasValue3 = false;
this.HasValue4 = value.Count > 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="items">The items.</param>
public Values(params object[] items)
: this(items.AsEnumerable())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Values{T1,T2,T3,T4}"/> struct.
/// </summary>
/// <param name="items">The items.</param>
public Values(IEnumerable<object?> items)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(items);
#else
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
#endif
List<T1>? items1 = null;
List<T2>? items2 = null;
List<T3>? items3 = null;
List<T4>? items4 = null;
foreach (var item in items)
{
if (item is T4 itemT4)
{
if (items4 == null)
{
items4 = new List<T4>();
}
items4.Add(itemT4);
}
else if (item is T3 itemT3)
{
if (items3 == null)
{
items3 = new List<T3>();
}
items3.Add(itemT3);
}
else if (item is T2 itemT2)
{
if (items2 == null)
{
items2 = new List<T2>();
}
items2.Add(itemT2);
}
else if (item is T1 itemT1)
{
if (items1 == null)
{
items1 = new List<T1>();
}
items1.Add(itemT1);
}
}
this.HasValue1 = items1?.Count > 0;
this.HasValue2 = items2?.Count > 0;
this.HasValue3 = items3?.Count > 0;
this.HasValue4 = items4?.Count > 0;
this.Value1 = items1 == null ? default : (OneOrMany<T1>)items1;
this.Value2 = items2 == null ? default : (OneOrMany<T2>)items2;
this.Value3 = items3 == null ? default : (OneOrMany<T3>)items3;
this.Value4 = items4 == null ? default : (OneOrMany<T4>)items4;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
public int Count => this.Value1.Count + this.Value2.Count + this.Value3.Count + this.Value4.Count;
/// <summary>
/// Gets a value indicating whether this instance has a value.
/// </summary>
public bool HasValue => this.HasValue1 || this.HasValue2 || this.HasValue3 || this.HasValue4;
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T1" /> has a value.
/// </summary>
public bool HasValue1 { get; }
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T2" /> has a value.
/// </summary>
public bool HasValue2 { get; }
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T3" /> has a value.
/// </summary>
public bool HasValue3 { get; }
/// <summary>
/// Gets a value indicating whether the value of type <typeparamref name="T4" /> has a value.
/// </summary>
public bool HasValue4 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T1" />.
/// </summary>
public OneOrMany<T1> Value1 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T2" />.
/// </summary>
public OneOrMany<T2> Value2 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T3" />.
/// </summary>
public OneOrMany<T3> Value3 { get; }
/// <summary>
/// Gets the value of type <typeparamref name="T4" />.
/// </summary>
public OneOrMany<T4> Value4 { get; }
#pragma warning disable CA1002 // Do not expose generic lists
#pragma warning disable CA2225 // Operator overloads have named alternates
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T1"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T1 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T2"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T2 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T3"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T3 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T4"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="item">The single item value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T4 item) => new(item);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T1[]"/> to <see cref="Values{T1,T2,T,T43}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T1[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T2[]"/> to <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T2[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T3[]"/> to <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T3[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T4[]"/> to <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(T4[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T1}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(List<T1> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T2}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(List<T2> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T3}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(List<T3> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="List{T4}"/> to <see cref="Values{T1,T2}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(List<T4> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="object"/> array to <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
/// <param name="array">The array of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(object[] array) => new(array);
/// <summary>
/// Performs an implicit conversion from <see cref="List{Object}"/> to <see cref="Values{T1,T2,T3,T4}"/>.
/// </summary>
/// <param name="list">The list of values.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Values<T1, T2, T3, T4>(List<object> list) => new(list);
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to the first item of type <typeparamref name="T1"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T1?(Values<T1, T2, T3, T4> values) => values.Value1.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to the first item of type <typeparamref name="T2"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T2?(Values<T1, T2, T3, T4> values) => values.Value2.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to the first item of type <typeparamref name="T3"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T3?(Values<T1, T2, T3, T4> values) => values.Value3.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to the first item of type <typeparamref name="T4"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T4?(Values<T1, T2, T3, T4> values) => values.Value4.FirstOrDefault();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to an array of <typeparamref name="T1"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T1[](Values<T1, T2, T3, T4> values) => values.Value1.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to <see cref="List{T1}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T1>(Values<T1, T2, T3, T4> values) => values.Value1.ToList();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to an array of <typeparamref name="T2"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T2[](Values<T1, T2, T3, T4> values) => values.Value2.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to <see cref="List{T2}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T2>(Values<T1, T2, T3, T4> values) => values.Value2.ToList();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to an array of <typeparamref name="T3"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T3[](Values<T1, T2, T3, T4> values) => values.Value3.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to <see cref="List{T3}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T3>(Values<T1, T2, T3, T4> values) => values.Value3.ToList();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to an array of <typeparamref name="T4"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator T4[](Values<T1, T2, T3, T4> values) => values.Value4.ToArray();
/// <summary>
/// Performs an implicit conversion from <see cref="Values{T1, T2, T3, T4}"/> to <see cref="List{T4}"/>.
/// </summary>
/// <param name="values">The values.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator List<T4>(Values<T1, T2, T3, T4> values) => values.Value4.ToList();
#pragma warning restore CA2225 // Operator overloads have named alternates
#pragma warning restore CA1002 // Do not expose generic lists
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(Values<T1, T2, T3, T4> left, Values<T1, T2, T3, T4> right) => left.Equals(right);
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(Values<T1, T2, T3, T4> left, Values<T1, T2, T3, T4> right) => !(left == right);
/// <summary>Deconstructs the specified items.</summary>
/// <param name="items1">The items from value 1.</param>
/// <param name="items2">The items from value 2.</param>
/// <param name="items3">The items from value 3.</param>
/// <param name="items4">The items from value 4.</param>
public void Deconstruct(out IEnumerable<T1> items1, out IEnumerable<T2> items2, out IEnumerable<T3> items3, out IEnumerable<T4> items4)
{
items1 = this.Value1;
items2 = this.Value2;
items3 = this.Value3;
items4 = this.Value4;
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<object?> GetEnumerator()
{
if (this.HasValue1)
{
foreach (var item1 in this.Value1)
{
yield return item1;
}
}
if (this.HasValue2)
{
foreach (var item2 in this.Value2)
{
yield return item2;
}
}
if (this.HasValue3)
{
foreach (var item3 in this.Value3)
{
yield return item3;
}
}
if (this.HasValue4)
{
foreach (var item4 in this.Value4)
{
yield return item4;
}
}
}
/// <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() => this.GetEnumerator();
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.
/// </returns>
public bool Equals(Values<T1, T2, T3, T4> other)
{
if (!other.HasValue && !this.HasValue)
{
return true;
}
return this.Value1.Equals(other.Value1) &&
this.Value2.Equals(other.Value2) &&
this.Value3.Equals(other.Value3) &&
this.Value4.Equals(other.Value4);
}
/// <summary>
/// Determines whether the specified <see cref="object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => obj is Values<T1, T2, T3, T4> values && this.Equals(values);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() =>
HashCode.Of(this.Value1).And(this.Value2).And(this.Value3).And(this.Value4);
}
| |
using System;
using System.Collections;
using NBitcoin.BouncyCastle.Utilities;
using NBitcoin.BouncyCastle.Utilities.Collections;
namespace NBitcoin.BouncyCastle.Asn1.X509
{
public class X509Extensions
: Asn1Encodable
{
/**
* Subject Directory Attributes
*/
public static readonly DerObjectIdentifier SubjectDirectoryAttributes = new DerObjectIdentifier("2.5.29.9");
/**
* Subject Key Identifier
*/
public static readonly DerObjectIdentifier SubjectKeyIdentifier = new DerObjectIdentifier("2.5.29.14");
/**
* Key Usage
*/
public static readonly DerObjectIdentifier KeyUsage = new DerObjectIdentifier("2.5.29.15");
/**
* Private Key Usage Period
*/
public static readonly DerObjectIdentifier PrivateKeyUsagePeriod = new DerObjectIdentifier("2.5.29.16");
/**
* Subject Alternative Name
*/
public static readonly DerObjectIdentifier SubjectAlternativeName = new DerObjectIdentifier("2.5.29.17");
/**
* Issuer Alternative Name
*/
public static readonly DerObjectIdentifier IssuerAlternativeName = new DerObjectIdentifier("2.5.29.18");
/**
* Basic Constraints
*/
public static readonly DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19");
/**
* CRL Number
*/
public static readonly DerObjectIdentifier CrlNumber = new DerObjectIdentifier("2.5.29.20");
/**
* Reason code
*/
public static readonly DerObjectIdentifier ReasonCode = new DerObjectIdentifier("2.5.29.21");
/**
* Hold Instruction Code
*/
public static readonly DerObjectIdentifier InstructionCode = new DerObjectIdentifier("2.5.29.23");
/**
* Invalidity Date
*/
public static readonly DerObjectIdentifier InvalidityDate = new DerObjectIdentifier("2.5.29.24");
/**
* Delta CRL indicator
*/
public static readonly DerObjectIdentifier DeltaCrlIndicator = new DerObjectIdentifier("2.5.29.27");
/**
* Issuing Distribution Point
*/
public static readonly DerObjectIdentifier IssuingDistributionPoint = new DerObjectIdentifier("2.5.29.28");
/**
* Certificate Issuer
*/
public static readonly DerObjectIdentifier CertificateIssuer = new DerObjectIdentifier("2.5.29.29");
/**
* Name Constraints
*/
public static readonly DerObjectIdentifier NameConstraints = new DerObjectIdentifier("2.5.29.30");
/**
* CRL Distribution Points
*/
public static readonly DerObjectIdentifier CrlDistributionPoints = new DerObjectIdentifier("2.5.29.31");
/**
* Certificate Policies
*/
public static readonly DerObjectIdentifier CertificatePolicies = new DerObjectIdentifier("2.5.29.32");
/**
* Policy Mappings
*/
public static readonly DerObjectIdentifier PolicyMappings = new DerObjectIdentifier("2.5.29.33");
/**
* Authority Key Identifier
*/
public static readonly DerObjectIdentifier AuthorityKeyIdentifier = new DerObjectIdentifier("2.5.29.35");
/**
* Policy Constraints
*/
public static readonly DerObjectIdentifier PolicyConstraints = new DerObjectIdentifier("2.5.29.36");
/**
* Extended Key Usage
*/
public static readonly DerObjectIdentifier ExtendedKeyUsage = new DerObjectIdentifier("2.5.29.37");
/**
* Freshest CRL
*/
public static readonly DerObjectIdentifier FreshestCrl = new DerObjectIdentifier("2.5.29.46");
/**
* Inhibit Any Policy
*/
public static readonly DerObjectIdentifier InhibitAnyPolicy = new DerObjectIdentifier("2.5.29.54");
/**
* Authority Info Access
*/
public static readonly DerObjectIdentifier AuthorityInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.1");
/**
* Subject Info Access
*/
public static readonly DerObjectIdentifier SubjectInfoAccess = new DerObjectIdentifier("1.3.6.1.5.5.7.1.11");
/**
* Logo Type
*/
public static readonly DerObjectIdentifier LogoType = new DerObjectIdentifier("1.3.6.1.5.5.7.1.12");
/**
* BiometricInfo
*/
public static readonly DerObjectIdentifier BiometricInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.1.2");
/**
* QCStatements
*/
public static readonly DerObjectIdentifier QCStatements = new DerObjectIdentifier("1.3.6.1.5.5.7.1.3");
/**
* Audit identity extension in attribute certificates.
*/
public static readonly DerObjectIdentifier AuditIdentity = new DerObjectIdentifier("1.3.6.1.5.5.7.1.4");
/**
* NoRevAvail extension in attribute certificates.
*/
public static readonly DerObjectIdentifier NoRevAvail = new DerObjectIdentifier("2.5.29.56");
/**
* TargetInformation extension in attribute certificates.
*/
public static readonly DerObjectIdentifier TargetInformation = new DerObjectIdentifier("2.5.29.55");
private readonly IDictionary extensions = Platform.CreateHashtable();
private readonly IList ordering;
public static X509Extensions GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static X509Extensions GetInstance(
object obj)
{
if (obj == null || obj is X509Extensions)
{
return (X509Extensions) obj;
}
if (obj is Asn1Sequence)
{
return new X509Extensions((Asn1Sequence) obj);
}
if (obj is Asn1TaggedObject)
{
return GetInstance(((Asn1TaggedObject) obj).GetObject());
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor from Asn1Sequence.
*
* the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString)
*/
private X509Extensions(
Asn1Sequence seq)
{
this.ordering = Platform.CreateArrayList();
foreach (Asn1Encodable ae in seq)
{
Asn1Sequence s = Asn1Sequence.GetInstance(ae.ToAsn1Object());
if (s.Count < 2 || s.Count > 3)
throw new ArgumentException("Bad sequence size: " + s.Count);
DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(s[0].ToAsn1Object());
bool isCritical = s.Count == 3
&& DerBoolean.GetInstance(s[1].ToAsn1Object()).IsTrue;
Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object());
extensions.Add(oid, new X509Extension(isCritical, octets));
ordering.Add(oid);
}
}
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IDictionary extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
public X509Extensions(
IList ordering,
IDictionary extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension)extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
public X509Extensions(
IList oids,
IList values)
{
this.ordering = Platform.CreateArrayList(oids);
int count = 0;
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension)values[count++]);
}
}
#if !SILVERLIGHT
/**
* constructor from a table of extensions.
* <p>
* it's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
Hashtable extensions)
: this(null, extensions)
{
}
/**
* Constructor from a table of extensions with ordering.
* <p>
* It's is assumed the table contains Oid/string pairs.</p>
*/
[Obsolete]
public X509Extensions(
ArrayList ordering,
Hashtable extensions)
{
if (ordering == null)
{
this.ordering = Platform.CreateArrayList(extensions.Keys);
}
else
{
this.ordering = Platform.CreateArrayList(ordering);
}
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) extensions[oid]);
}
}
/**
* Constructor from two vectors
*
* @param objectIDs an ArrayList of the object identifiers.
* @param values an ArrayList of the extension values.
*/
[Obsolete]
public X509Extensions(
ArrayList oids,
ArrayList values)
{
this.ordering = Platform.CreateArrayList(oids);
int count = 0;
foreach (DerObjectIdentifier oid in this.ordering)
{
this.extensions.Add(oid, (X509Extension) values[count++]);
}
}
#endif
[Obsolete("Use ExtensionOids IEnumerable property")]
public IEnumerator Oids()
{
return ExtensionOids.GetEnumerator();
}
/**
* return an Enumeration of the extension field's object ids.
*/
public IEnumerable ExtensionOids
{
get { return new EnumerableProxy(ordering); }
}
/**
* return the extension represented by the object identifier
* passed in.
*
* @return the extension if it's present, null otherwise.
*/
public X509Extension GetExtension(
DerObjectIdentifier oid)
{
return (X509Extension) extensions[oid];
}
/**
* <pre>
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnId EXTENSION.&id ({ExtensionSet}),
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector vec = new Asn1EncodableVector();
foreach (DerObjectIdentifier oid in ordering)
{
X509Extension ext = (X509Extension) extensions[oid];
Asn1EncodableVector v = new Asn1EncodableVector(oid);
if (ext.IsCritical)
{
v.Add(DerBoolean.True);
}
v.Add(ext.Value);
vec.Add(new DerSequence(v));
}
return new DerSequence(vec);
}
public bool Equivalent(
X509Extensions other)
{
if (extensions.Count != other.extensions.Count)
return false;
foreach (DerObjectIdentifier oid in extensions.Keys)
{
if (!extensions[oid].Equals(other.extensions[oid]))
return false;
}
return true;
}
public DerObjectIdentifier[] GetExtensionOids()
{
return ToOidArray(ordering);
}
public DerObjectIdentifier[] GetNonCriticalExtensionOids()
{
return GetExtensionOids(false);
}
public DerObjectIdentifier[] GetCriticalExtensionOids()
{
return GetExtensionOids(true);
}
private DerObjectIdentifier[] GetExtensionOids(bool isCritical)
{
IList oids = Platform.CreateArrayList();
foreach (DerObjectIdentifier oid in this.ordering)
{
X509Extension ext = (X509Extension)extensions[oid];
if (ext.IsCritical == isCritical)
{
oids.Add(oid);
}
}
return ToOidArray(oids);
}
private static DerObjectIdentifier[] ToOidArray(IList oids)
{
DerObjectIdentifier[] oidArray = new DerObjectIdentifier[oids.Count];
oids.CopyTo(oidArray, 0);
return oidArray;
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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 Yaapii.Atoms.Enumerable;
namespace Yaapii.Atoms.Text
{
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public sealed class Paragraph : TextEnvelope
{
#region string head, IEnumerable<string> lines, params string[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5, head6),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, string head7, IEnumerable<string> lines, params string[] tail) : this(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5, head6, head7),
lines,
new LiveMany<string>(tail)
)
)
)
{ }
#endregion
#region IText head1, IEnumerable<string> lines, params string[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IText head7, IEnumerable<string> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6, head7),
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
lines,
new LiveMany<string>(tail)
)
)
)
)
{ }
#endregion
#region string head, IEnumerable<IText> lines, params string[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5, head6)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, string head7, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5, head6, head7)
),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
#endregion
#region IText head, IEnumerable<IText> lines, params string[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IText head7, IEnumerable<IText> lines, params string[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6, head7),
lines,
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(tail)
)
)
)
{ }
#endregion
#region string head, IEnumerable<string> lines, params IText[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5, head6),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, string head7, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new Joined<string>(
new LiveMany<string>(head1, head2, head3, head4, head5, head6, head7),
lines
)
),
new LiveMany<IText>(tail)
)
)
{ }
#endregion
#region IText head, IEnumerable<string> lines, params IText[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IText head7, IEnumerable<string> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6, head7),
new Mapped<string, IText>(
line => new LiveText(line),
lines
),
new LiveMany<IText>(tail)
)
)
{ }
#endregion
#region string head, IEnumerable<IText> lines, params IText[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5, head6)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(string head1, string head2, string head3, string head4, string head5, string head6, string head7, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new Mapped<string, IText>(
line => new LiveText(line),
new LiveMany<string>(head1, head2, head3, head4, head5, head6, head7)
),
lines,
new LiveMany<IText>(tail)
)
)
{ }
#endregion
#region IText head, IEnumerable<IText> lines, params IText[] tail
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6),
lines,
new LiveMany<IText>(tail)
)
)
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IText head1, IText head2, IText head3, IText head4, IText head5, IText head6, IText head7, IEnumerable<IText> lines, params IText[] tail) : this(
new Joined<IText>(
new LiveMany<IText>(head1, head2, head3, head4, head5, head6, head7),
lines,
new LiveMany<IText>(tail)
)
)
{ }
#endregion
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(params string[] lines) : this(new Mapped<string, IText>(line => new LiveText(line), lines))
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IEnumerable<string> lines) : this(new Mapped<string, IText>(line => new TextOf(line), lines))
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(params IText[] lines) : this(new LiveMany<IText>(lines))
{ }
/// <summary>
/// A paragraph which seperates the given lines by a carriage return.
/// </summary>
public Paragraph(IEnumerable<IText> lines)
: base(new Joined(Environment.NewLine, lines), false)
{ }
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Internal
{
using System;
using System.Collections.Generic;
using NLog.Config;
using NLog.Filters;
using NLog.Targets;
/// <summary>
/// Represents target with a chain of filters which determine
/// whether logging should happen.
/// </summary>
[NLogConfigurationItem]
internal class TargetWithFilterChain
{
internal static readonly TargetWithFilterChain[] NoTargetsByLevel = CreateLoggingConfiguration();
internal static TargetWithFilterChain[] CreateLoggingConfiguration() => new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 2]; // +2 to include LogLevel.Off
private MruCache<CallSiteKey, string> _callSiteClassNameCache;
/// <summary>
/// Initializes a new instance of the <see cref="TargetWithFilterChain" /> class.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="filterChain">The filter chain.</param>
/// <param name="filterDefaultAction">Default action if none of the filters match.</param>
public TargetWithFilterChain(Target target, IList<Filter> filterChain, FilterResult filterDefaultAction)
{
Target = target;
FilterChain = filterChain;
FilterDefaultAction = filterDefaultAction;
}
/// <summary>
/// Gets the target.
/// </summary>
/// <value>The target.</value>
public Target Target { get; }
/// <summary>
/// Gets the filter chain.
/// </summary>
/// <value>The filter chain.</value>
public IList<Filter> FilterChain { get; }
/// <summary>
/// Gets or sets the next <see cref="TargetWithFilterChain"/> item in the chain.
/// </summary>
/// <value>The next item in the chain.</value>
/// <example>This is for example the 'target2' logger in writeTo='target1,target2' </example>
public TargetWithFilterChain NextInChain { get; set; }
/// <summary>
/// Gets the stack trace usage.
/// </summary>
/// <returns>A <see cref="StackTraceUsage" /> value that determines stack trace handling.</returns>
public StackTraceUsage StackTraceUsage { get; private set; }
/// <summary>
/// Default action if none of the filters match.
/// </summary>
public FilterResult FilterDefaultAction { get; }
internal StackTraceUsage PrecalculateStackTraceUsage()
{
var stackTraceUsage = StackTraceUsage.None;
// find all objects which may need stack trace
// and determine maximum
if (Target != null)
{
stackTraceUsage = Target.StackTraceUsage;
}
//recurse into chain if not max
if (NextInChain != null && (stackTraceUsage & StackTraceUsage.Max) != StackTraceUsage.Max)
{
var stackTraceUsageForChain = NextInChain.PrecalculateStackTraceUsage();
stackTraceUsage |= stackTraceUsageForChain;
}
StackTraceUsage = stackTraceUsage;
return stackTraceUsage;
}
internal bool TryCallSiteClassNameOptimization(StackTraceUsage stackTraceUsage, LogEventInfo logEvent)
{
if ((stackTraceUsage & (StackTraceUsage.WithCallSiteClassName | StackTraceUsage.WithStackTrace)) != StackTraceUsage.WithCallSiteClassName)
return false;
if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath))
return false;
if (logEvent.HasStackTrace)
return false;
return true;
}
internal bool MustCaptureStackTrace(StackTraceUsage stackTraceUsage, LogEventInfo logEvent)
{
if (logEvent.HasStackTrace)
return false;
if ((stackTraceUsage & StackTraceUsage.WithStackTrace) != StackTraceUsage.None)
return true;
if ((stackTraceUsage & StackTraceUsage.WithCallSite) != StackTraceUsage.None && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerMethodName) && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath))
return true; // We don't have enough CallSiteInformation
return false;
}
internal bool TryRememberCallSiteClassName(LogEventInfo logEvent)
{
if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath))
return false;
string className = logEvent.CallSiteInformation.GetCallerClassName(null, true, true, true);
if (string.IsNullOrEmpty(className))
return false;
if (_callSiteClassNameCache is null)
return false;
string internClassName = logEvent.LoggerName == className ?
logEvent.LoggerName :
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
string.Intern(className); // Single string-reference for all logging-locations for the same class
#else
className;
#endif
CallSiteKey callSiteKey = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber);
return _callSiteClassNameCache.TryAddValue(callSiteKey, internClassName);
}
internal bool TryLookupCallSiteClassName(LogEventInfo logEvent, out string callSiteClassName)
{
callSiteClassName = logEvent.CallSiteInformation?.CallerClassName;
if (!string.IsNullOrEmpty(callSiteClassName))
return true;
if (_callSiteClassNameCache is null)
{
System.Threading.Interlocked.CompareExchange(ref _callSiteClassNameCache, new MruCache<CallSiteKey, string>(1000), null);
}
CallSiteKey callSiteKey = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber);
return _callSiteClassNameCache.TryGetValue(callSiteKey, out callSiteClassName);
}
struct CallSiteKey : IEquatable<CallSiteKey>
{
public CallSiteKey(string methodName, string fileSourceName, int fileSourceLineNumber)
{
MethodName = methodName ?? string.Empty;
FileSourceName = fileSourceName ?? string.Empty;
FileSourceLineNumber = fileSourceLineNumber;
}
public readonly string MethodName;
public readonly string FileSourceName;
public readonly int FileSourceLineNumber;
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
public override int GetHashCode()
{
return MethodName.GetHashCode() ^ FileSourceName.GetHashCode() ^ FileSourceLineNumber;
}
/// <summary>
/// Determines if two objects are equal in value.
/// </summary>
/// <param name="obj">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public override bool Equals(object obj)
{
return obj is CallSiteKey key && Equals(key);
}
/// <summary>
/// Determines if two objects of the same type are equal in value.
/// </summary>
/// <param name="other">Other object to compare to.</param>
/// <returns>True if objects are equal, false otherwise.</returns>
public bool Equals(CallSiteKey other)
{
return FileSourceLineNumber == other.FileSourceLineNumber
&& string.Equals(FileSourceName, other.FileSourceName, StringComparison.Ordinal)
&& string.Equals(MethodName, other.MethodName, StringComparison.Ordinal);
}
}
}
}
| |
//
// FacebookExport.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Jim Ramsay <i.am@jimramsay.com>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2009 Jim Ramsay
//
// 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.Collections;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Gnome.Keyring;
using FSpot.Core;
using FSpot.UI.Dialog;
using FSpot.Extensions;
using FSpot.Filters;
using Hyena;
using Hyena.Widgets;
using Mono.Facebook;
using System.Linq;
namespace FSpot.Exporters.Facebook
{
internal class FacebookAccount
{
static string keyring_item_name = "Facebook Account";
static string api_key = "c23d1683e87313fa046954ea253a240e";
/* INSECURE! According to:
*
* http://wiki.developers.facebook.com/index.php/Desktop_App_Auth_Process
*
* We should *NOT* put our secret code here, but do an external
* authorization using our own PHP page somewhere.
*/
static string secret = "743e9a2e6a1c35ce961321bceea7b514";
FacebookSession facebookSession;
bool connected = false;
public FacebookAccount ()
{
SessionInfo info = ReadSessionInfo ();
if (info != null) {
facebookSession = new FacebookSession (api_key, info);
try {
/* This basically functions like a ping to ensure the
* session is still valid:
*/
facebookSession.HasAppPermission("offline_access");
connected = true;
} catch (FacebookException) {
connected = false;
}
}
}
public Uri GetLoginUri ()
{
FacebookSession session = new FacebookSession (api_key, secret);
Uri uri = session.CreateToken();
facebookSession = session;
connected = false;
return uri;
}
public bool RevokePermission (string permission)
{
return facebookSession.RevokeAppPermission(permission);
}
public bool GrantPermission (string permission, Window parent)
{
if (facebookSession.HasAppPermission(permission))
return true;
Uri uri = facebookSession.GetGrantUri (permission);
GtkBeans.Global.ShowUri (parent.Screen, uri.ToString ());
HigMessageDialog mbox = new HigMessageDialog (parent, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Info, Gtk.ButtonsType.Ok, Catalog.GetString ("Waiting for authorization"),
Catalog.GetString ("F-Spot will now launch your browser so that you can enable the permission you just selected.\n\nOnce you are directed by Facebook to return to this application, click \"Ok\" below." ));
mbox.Run ();
mbox.Destroy ();
return facebookSession.HasAppPermission(permission);
}
public bool HasPermission(string permission)
{
return facebookSession.HasAppPermission(permission);
}
public FacebookSession Facebook
{
get { return facebookSession; }
}
public bool Authenticated
{
get { return connected; }
}
bool SaveSessionInfo (SessionInfo info)
{
string keyring;
try {
keyring = Ring.GetDefaultKeyring();
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
Hashtable attribs = new Hashtable();
//Dictionary<string,string> attribs = new Dictionary<string, string> ();
attribs["name"] = keyring_item_name;
attribs["uid"] = info.uid.ToString ();
attribs["session_key"] = info.session_key;
try {
Ring.CreateItem (keyring, ItemType.GenericSecret, keyring_item_name, attribs, info.secret, true);
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
return true;
}
SessionInfo ReadSessionInfo ()
{
SessionInfo info = null;
Hashtable request_attributes = new Hashtable ();
//Dictionary<string, string> request_attributes = new Dictionary<string, string> ();
request_attributes["name"] = keyring_item_name;
try {
foreach (ItemData result in Ring.Find (ItemType.GenericSecret, request_attributes)) {
if (!result.Attributes.ContainsKey ("name") ||
!result.Attributes.ContainsKey ("uid") ||
!result.Attributes.ContainsKey ("session_key") ||
(result.Attributes["name"] as string) != keyring_item_name)
continue;
string session_key = (string)result.Attributes["session_key"];
long uid = Int64.Parse((string)result.Attributes["uid"]);
string secret = result.Secret;
info = new SessionInfo (session_key, uid, secret);
break;
}
} catch (KeyringException e) {
Log.DebugException (e);
}
return info;
}
bool ForgetSessionInfo()
{
string keyring;
bool success = false;
try {
keyring = Ring.GetDefaultKeyring();
} catch (KeyringException e) {
Log.DebugException (e);
return false;
}
Hashtable request_attributes = new Hashtable ();
//Dictionary<string,string> request_attributes = new Dictionary<string, string> ();
request_attributes["name"] = keyring_item_name;
try {
foreach (ItemData result in Ring.Find (ItemType.GenericSecret, request_attributes)) {
Ring.DeleteItem(keyring, result.ItemID);
success = true;
}
} catch (KeyringException e) {
Log.DebugException (e);
}
return success;
}
public bool Authenticate ()
{
if (connected)
return true;
try {
SessionInfo info = facebookSession.GetSession();
connected = true;
if (SaveSessionInfo (info))
Log.Information ("Saved session information to keyring");
else
Log.Warning ("Could not save session information to keyring");
} catch (KeyringException e) {
connected = false;
Log.DebugException (e);
} catch (FacebookException fe) {
connected = false;
Log.DebugException (fe);
}
return connected;
}
public void Deauthenticate ()
{
connected = false;
ForgetSessionInfo ();
}
}
internal class TagStore : ListStore
{
private List<Mono.Facebook.Tag> _tags;
private Dictionary<long, User> _friends;
public TagStore (FacebookSession session, List<Mono.Facebook.Tag> tags, Dictionary<long, User> friends) : base (typeof (string))
{
_tags = tags;
_friends = friends;
foreach (Mono.Facebook.Tag tag in Tags) {
long subject = tag.Subject;
User info = _friends [subject];
if (info == null ) {
try {
info = session.GetUserInfo (new long[] { subject }, new string[] { "first_name", "last_name" }) [0];
}
catch (FacebookException) {
continue;
}
}
AppendValues (string.Format ("{0} {1}", info.first_name ?? "", info.last_name ?? ""));
}
}
public List<Mono.Facebook.Tag> Tags
{
get { return _tags ?? new List<Mono.Facebook.Tag> (); }
}
}
public class FacebookExport : IExporter
{
private int size = 720;
private int max_photos_per_album = 200;
FacebookExportDialog dialog;
ThreadProgressDialog progress_dialog;
System.Threading.Thread command_thread;
Album album = null;
public FacebookExport ()
{
}
public void Run (IBrowsableCollection selection)
{
dialog = new FacebookExportDialog (selection);
if (selection.Items.Count () > max_photos_per_album) {
HigMessageDialog mbox = new HigMessageDialog (dialog,
Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal, Gtk.MessageType.Error,
Gtk.ButtonsType.Ok, Catalog.GetString ("Too many images to export"),
string.Format (Catalog.GetString ("Facebook only permits {0} photographs per album. Please refine your selection and try again."), max_photos_per_album));
mbox.Run ();
mbox.Destroy ();
return;
}
if (dialog.Run () != (int)ResponseType.Ok) {
dialog.Destroy ();
return;
}
if (dialog.CreateAlbum) {
string name = dialog.AlbumName;
if (string.IsNullOrEmpty (name)) {
HigMessageDialog mbox = new HigMessageDialog (dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Album must have a name"),
Catalog.GetString ("Please name your album or choose an existing album."));
mbox.Run ();
mbox.Destroy ();
return;
}
string description = dialog.AlbumDescription;
string location = dialog.AlbumLocation;
try {
album = dialog.Account.Facebook.CreateAlbum (name, description, location);
}
catch (FacebookException fe) {
HigMessageDialog mbox = new HigMessageDialog (dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Creating a new album failed"),
string.Format (Catalog.GetString ("An error occurred creating a new album.\n\n{0}"), fe.Message));
mbox.Run ();
mbox.Destroy ();
return;
}
} else {
album = dialog.ActiveAlbum;
}
if (dialog.Account != null) {
dialog.Hide ();
command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (Upload));
command_thread.Name = Mono.Unix.Catalog.GetString ("Uploading Pictures");
progress_dialog = new ThreadProgressDialog (command_thread, selection.Items.Count ());
progress_dialog.Start ();
}
dialog.Destroy ();
}
void Upload ()
{
IPhoto [] items = dialog.Items;
string [] captions = dialog.Captions;
dialog.StoreCaption ();
long sent_bytes = 0;
FilterSet filters = new FilterSet ();
filters.Add (new JpegFilter ());
filters.Add (new ResizeFilter ((uint) size));
for (int i = 0; i < items.Length; i++) {
try {
IPhoto item = items [i];
FileInfo file_info;
Log.DebugFormat ("uploading {0}", i);
progress_dialog.Message = string.Format (Catalog.GetString ("Uploading picture \"{0}\" ({1} of {2})"), item.Name, i + 1, items.Length);
progress_dialog.ProgressText = string.Empty;
progress_dialog.Fraction = i / (double) items.Length;
FilterRequest request = new FilterRequest (item.DefaultVersion.Uri);
filters.Convert (request);
file_info = new FileInfo (request.Current.LocalPath);
album.Upload (captions [i] ?? "", request.Current.LocalPath);
sent_bytes += file_info.Length;
}
catch (Exception e) {
progress_dialog.Message = string.Format (Catalog.GetString ("Error Uploading To Facebook: {0}"), e.Message);
progress_dialog.ProgressText = Catalog.GetString ("Error");
Log.DebugException (e);
if (progress_dialog.PerformRetrySkip ())
i--;
}
}
progress_dialog.Message = Catalog.GetString ("Done Sending Photos");
progress_dialog.Fraction = 1.0;
progress_dialog.ProgressText = Catalog.GetString ("Upload Complete");
progress_dialog.ButtonLabel = Gtk.Stock.Ok;
var li = new LinkButton ("http://www.facebook.com/group.php?gid=158960179844&ref=mf", Catalog.GetString ("Visit F-Spot group on Facebook"));
progress_dialog.VBoxPackEnd (li);
li.ShowAll ();
}
}
}
| |
// EasyJoystick library is copyright (c) of Hedgehog Team
// Please send feedback or bug reports to the.hedgehog.team@gmail.com
using UnityEngine;
using System.Collections;
/// <summary>
/// Release notes:
/// EasyJoystick V2.2 Mai 2013
/// =============================
/// * Dynamic joystick no longer show when there are hover reserved area
///
/// EasyJoystick V2.1 Mai 2013
/// =============================
/// * Bugs fixed
/// ------------
/// - The joystick touch wasn't been correct in some case
///
///
/// EasyJoystick V2.0 Avril 2013
/// =============================
/// * New
/// -----------------
/// - Add virtual screen to keep size position
/// - Add new joystick events : On_JoystickMoveStart, On_JoystickTouchStart, On_JoystickTap, On_JoystickDoubleTap,On_JoystickTouchUp
/// - Add new option to reset joystick position, when touch exit the joystick area
/// - Add the possibility to enable / disable joystick axis X or Y
/// - Add new member isActivated to desactivated the joystick, but it always show on the screen
/// - Add new member to clamp rotation in direct mode when you're in localrotation
/// - Add new member to do an auto stabilisation in direct mode when you're in localrotation
/// - Add show dynamic joystick in edit mode
/// - Some optimisations
/// - Add new method Axis2Angle to MovingJoystick class that allow to return the joystick angle direction between -170 to 170
/// - Add option to show real area use by the joystick texture
/// - Add UseGuiLayout option
/// - Add Gui depth parameter
///
/// * Bugs fixed
/// ------------
/// - Gravity is now always apply correctly
/// - Dead zone is correctly take into account
/// - the event JoystickMoveEnd don't send any more at startup
///
/// V1.0 November 2012
/// =============================
/// - First release
/// <summary>
/// This is the main class of EasyJoystick engine.
///
/// For add joystick to your scene, use the menu Hedgehog Team<br>
/// </summary>
[ExecuteInEditMode]
public class EasyJoystick : MonoBehaviour {
#region Delegate
public delegate void JoystickMoveStartHandler(MovingJoystick move);
public delegate void JoystickMoveHandler(MovingJoystick move);
public delegate void JoystickMoveEndHandler(MovingJoystick move);
public delegate void JoystickTouchStartHandler(MovingJoystick move);
public delegate void JoystickTapHandler(MovingJoystick move);
public delegate void JoystickDoubleTapHandler(MovingJoystick move);
public delegate void JoystickTouchUpHandler(MovingJoystick move);
#endregion
#region Event
/// <summary>
/// Occurs the joystick starts move.
/// </summary>
public static event JoystickMoveStartHandler On_JoystickMoveStart;
/// <summary>
/// Occurs when the joystick move.
/// </summary>
public static event JoystickMoveHandler On_JoystickMove;
/// <summary>
/// Occurs when the joystick stops move
/// </summary>
public static event JoystickMoveEndHandler On_JoystickMoveEnd;
/// <summary>
/// Occurs when a touch start hover the joystick
/// </summary>
public static event JoystickTouchStartHandler On_JoystickTouchStart;
/// <summary>
/// Occurs when a tap happen's on the joystick
/// </summary>
public static event JoystickTapHandler On_JoystickTap;
/// <summary>
/// Occurs when a double tap happen's on the joystick
/// </summary>
public static event JoystickDoubleTapHandler On_JoystickDoubleTap;
/// <summary>
/// Occurs when touch up happen's on the joystick
/// </summary>
public static event JoystickTouchUpHandler On_JoystickTouchUp;
#endregion
#region Enumeration
/// <summary>
/// Joystick anchor.
/// </summary>
public enum JoystickAnchor {None,UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight};
/// <summary>
/// Properties influenced by the joystick
/// </summary>
public enum PropertiesInfluenced {Rotate, RotateLocal,Translate, TranslateLocal, Scale}
/// <summary>
/// Axis influenced by the joystick
/// </summary>
public enum AxisInfluenced{X,Y,Z,XYZ}
/// <summary>
/// Dynamic area zone.
/// </summary>
public enum DynamicArea {FullScreen, Left,Right,Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight};
/// <summary>
/// Interaction type.
/// </summary>
public enum InteractionType {Direct, Include, EventNotification, DirectAndEvent}
/// <summary>
/// Broadcast mode for javascript
/// </summary>
public enum Broadcast {SendMessage,SendMessageUpwards,BroadcastMessage }
/// <summary>
/// Message name.
/// </summary>
private enum MessageName{On_JoystickMoveStart,On_JoystickTouchStart, On_JoystickTouchUp, On_JoystickMove, On_JoystickMoveEnd, On_JoystickTap, On_JoystickDoubleTap};
#endregion
#region Members
#region Public Members
#region property
private Vector2 joystickAxis;
/// <summary>
/// Gets the joystick axis value between -1 & 1...
/// </summary>
/// <value>
/// The joystick axis.
/// </value>
public Vector2 JoystickAxis {
get {
return this.joystickAxis;
}
}
/// <summary>
/// Gest or set the touch position.
/// </summary>
private Vector2 joystickTouch;
public Vector2 JoystickTouch {
get {
return new Vector2(this.joystickTouch.x/zoneRadius, this.joystickTouch.y/zoneRadius);
}
set {
float x = Mathf.Clamp( value.x,-1f,1f)*zoneRadius;
float y = Mathf.Clamp( value.y,-1f,1f)*zoneRadius;
joystickTouch = new Vector2(x,y);
}
}
private Vector2 joystickValue;
/// <summary>
/// Gets the joystick value = joystic axis value * jostick speed * Time.deltaTime...
/// </summary>
/// <value>
/// The joystick value.
/// </value>
public Vector2 JoystickValue {
get {
return this.joystickValue;
}
}
#endregion
#region public joystick properties
/// <summary>
/// Enable or disable the joystick.
/// </summary>
public bool enable = true;
/// <summary>
/// Activacte or deactivate the joystick
/// </summary>
public bool isActivated = true;
/// <summary>
/// The show debug radius area
/// </summary>
public bool showDebugRadius=false;
/// <summary>
/// Use fixed update.
/// </summary>
public bool useFixedUpdate = false;
/// <summary>
/// Disable this lets you skip the GUI layout phase.
/// </summary>
public bool isUseGuiLayout=true;
#endregion
#region Joystick Position & size
[SerializeField]
private bool dynamicJoystick=false;
/// <summary>
/// Gets or sets a value indicating whether this is a dynamic joystick.
/// When this option is enabled, the joystick will display the location of the touch
/// </summary>
/// <value>
/// <c>true</c> if dynamic joystick; otherwise, <c>false</c>.
/// </value>
public bool DynamicJoystick {
get {
return this.dynamicJoystick;
}
set {
if (!Application.isPlaying){
joystickIndex=-1;
dynamicJoystick = value;
if (dynamicJoystick){
virtualJoystick=false;
}
else{
virtualJoystick=true;
joystickCenter = joystickPositionOffset;
}
}
}
}
/// <summary>
/// When the joystick is dynamic mode, this value indicates the area authorized for display
/// </summary>
public DynamicArea area = DynamicArea.FullScreen;
/// <summary>
/// The joystick anchor.
/// </summary>
[SerializeField]
private JoystickAnchor joyAnchor = JoystickAnchor.LowerLeft;
public JoystickAnchor JoyAnchor {
get {
return this.joyAnchor;
}
set {
joyAnchor = value;
ComputeJoystickAnchor(joyAnchor);
}
}
/// <summary>
/// The joystick position on the screen
/// </summary>
[SerializeField]
private Vector2 joystickPositionOffset = Vector2.zero;
public Vector2 JoystickPositionOffset {
get {
return this.joystickPositionOffset;
}
set {
joystickPositionOffset = value;
ComputeJoystickAnchor(joyAnchor);
}
}
/// <summary>
/// The zone radius size.
/// </summary>
///
[SerializeField]
private float zoneRadius=100f;
public float ZoneRadius {
get {
return this.zoneRadius;
}
set {
zoneRadius = value;
ComputeJoystickAnchor(joyAnchor);
}
}
[SerializeField]
private float touchSize = 30;
/// <summary>
/// Gets or sets the size of the touch.
///
/// </summary>
/// <value>
/// The size of the touch.
/// </value>
public float TouchSize {
get {
return this.touchSize;
}
set {
touchSize = value;
if (touchSize>zoneRadius/2 && restrictArea){
touchSize =zoneRadius/2;
}
ComputeJoystickAnchor(joyAnchor);
}
}
/// <summary>
/// The dead zone size. While the touch is in this area, the joystick is considered stalled
/// </summary>
public float deadZone=20;
[SerializeField]
private bool restrictArea=false;
/// <summary>
/// Gets or sets a value indicating whether the touch must be in the radius area.
/// </summary>
/// <value>
/// <c>true</c> if restrict area; otherwise, <c>false</c>.
/// </value>
public bool RestrictArea {
get {
return this.restrictArea;
}
set {
restrictArea = value;
if (restrictArea){
touchSizeCoef = touchSize;
}
else{
touchSizeCoef=0;
}
ComputeJoystickAnchor(joyAnchor);
}
}
/// <summary>
/// The reset finger exit.
/// </summary>
public bool resetFingerExit = false;
#endregion
#region Joystick axes properties & event
/// <summary>
/// The interaction.
/// </summary>
[SerializeField]
private InteractionType interaction = InteractionType.Direct;
public InteractionType Interaction {
get {
return this.interaction;
}
set {
interaction = value;
if (interaction == InteractionType.Direct || interaction == InteractionType.Include){
useBroadcast = false;
}
}
}
/// <summary>
/// The use broadcast for javascript
/// </summary>
public bool useBroadcast = false;
/// <summary>
/// The message sending mode fro broacast
/// </summary>
public Broadcast messageMode;
// Messaging
/// <summary>
/// The receiver gameobject when you're in broacast mode for events
/// </summary>
public GameObject receiverGameObject;
/// <summary>
/// The speed of each joystick axis
/// </summary>
public Vector2 speed;
#region X axis
public bool enableXaxis = true;
[SerializeField]
private Transform xAxisTransform;
/// <summary>
/// Gets or sets the transform influenced by x axis of the joystick.
/// </summary>
/// <value>
/// The X axis transform.
/// </value>
public Transform XAxisTransform {
get {
return this.xAxisTransform;
}
set {
xAxisTransform = value;
if (xAxisTransform!=null){
xAxisCharacterController = xAxisTransform.GetComponent<CharacterController>();
}
else{
xAxisCharacterController=null;
xAxisGravity=0;
}
}
}
/// <summary>
/// The character controller attached to the X axis transform (if exist)
/// </summary>
public CharacterController xAxisCharacterController;
/// <summary>
/// The gravity.
/// </summary>
public float xAxisGravity=0;
[SerializeField]
private PropertiesInfluenced xTI;
/// <summary>
/// The Property influenced by the x axis joystick
/// </summary>
public PropertiesInfluenced XTI {
get {
return this.xTI;
}
set {
xTI = value;
if (xTI != PropertiesInfluenced.RotateLocal){
enableXAutoStab = false;
enableXClamp = false;
}
}
}
/// <summary>
/// The axis influenced by the x axis joystick
/// </summary>
public AxisInfluenced xAI;
/// <summary>
/// Inverse X axis.
/// </summary>
public bool inverseXAxis=false;
/// <summary>
/// The limit angle.
/// </summary>
public bool enableXClamp=false;
/// <summary>
/// The clamp X max.
/// </summary>
public float clampXMax;
/// <summary>
/// The clamp X minimum.
/// </summary>
public float clampXMin;
/// <summary>
/// The enable X auto stab.
/// </summary>
public bool enableXAutoStab=false;
[SerializeField]
private float thresholdX=0.01f;
/// <summary>
/// Gets or sets the threshold x.
/// </summary>
/// <value>
/// The threshold x.
/// </value>
public float ThresholdX {
get {
return this.thresholdX;
}
set {
if (value<=0){
thresholdX=value*-1f;
}
else{
thresholdX = value;
}
}
}
[SerializeField]
private float stabSpeedX = 20f;
/// <summary>
/// Gets or sets the stab speed x.
/// </summary>
/// <value>
/// The stab speed x.
/// </value>
public float StabSpeedX {
get {
return this.stabSpeedX;
}
set {
if (value<=0){
stabSpeedX = value*-1f;
}
else{
stabSpeedX = value;
}
}
}
#endregion
#region Y axis
public bool enableYaxis = true;
[SerializeField]
private Transform yAxisTransform;
/// <summary>
/// Gets or sets the transform influenced by y axis of the joystick.
/// </summary>
/// <value>
/// The Y axis transform.
/// </value>
public Transform YAxisTransform {
get {
return this.yAxisTransform;
}
set {
yAxisTransform = value;
if (yAxisTransform!=null){
yAxisCharacterController = yAxisTransform.GetComponent<CharacterController>();
}
else{
yAxisCharacterController=null;
yAxisGravity=0;
}
}
}
/// <summary>
/// The character controller attached to the X axis transform (if exist)
/// </summary>
public CharacterController yAxisCharacterController;
/// <summary>
/// The y axis gravity.
/// </summary>
public float yAxisGravity=0;
/// <summary>
/// The Property influenced by the y axis joystick
/// </summary>
[SerializeField]
private PropertiesInfluenced yTI;
public PropertiesInfluenced YTI {
get {
return this.yTI;
}
set {
yTI = value;
if (yTI != PropertiesInfluenced.RotateLocal){
enableYAutoStab = false;
enableYClamp = false;
}
}
}
/// <summary>
/// The axis influenced by the y axis joystick
/// </summary>
public AxisInfluenced yAI;
/// <summary>
/// Inverse Y axis.
/// </summary>
public bool inverseYAxis=false;
/// <summary>
/// The enable Y clamp.
/// </summary>
public bool enableYClamp=false;
/// <summary>
/// The clamp Y max.
/// </summary>
public float clampYMax;
/// <summary>
/// The clamp Y minimum.
/// </summary>
public float clampYMin;
/// <summary>
/// The enable Y auto stab.
/// </summary>
public bool enableYAutoStab = false;
[SerializeField]
private float thresholdY=0.01f;
/// <summary>
/// Gets or sets the threshold y.
/// </summary>
/// <value>
/// The threshold y.
/// </value>
public float ThresholdY {
get {
return this.thresholdY;
}
set {
if (value<=0){
thresholdY=value*-1f;
}
else{
thresholdY = value;
}
}
}
[SerializeField]
private float stabSpeedY = 20f;
/// <summary>
/// Gets or sets the stab speed y.
/// </summary>
/// <value>
/// The stab speed y.
/// </value>
public float StabSpeedY {
get {
return this.stabSpeedY;
}
set {
if (value<=0){
stabSpeedY=value*-1f;
}
else{
stabSpeedY = value;
};
}
}
#endregion
/// <summary>
/// The enable smoothing.When smoothing is enabled, resets the joystick slowly in the start position
/// </summary>
public bool enableSmoothing = false;
[SerializeField]
public Vector2 smoothing = new Vector2(2f,2f);
/// <summary>
/// Gets or sets the smoothing values
/// </summary>
/// <value>
/// The smoothing.
/// </value>
public Vector2 Smoothing {
get {
return this.smoothing;
}
set {
smoothing = value;
if (smoothing.x<0f){
smoothing.x=0;
}
if (smoothing.y<0){
smoothing.y=0;
}
}
}
/// <summary>
/// The enable inertia. Inertia simulates sliding movements (like a hovercraft, for example)
/// </summary>
public bool enableInertia = false;
[SerializeField]
public Vector2 inertia = new Vector2(100,100);
/// <summary>
/// Gets or sets the inertia values
/// </summary>
/// <value>
/// The inertia.
/// </value>
public Vector2 Inertia {
get {
return this.inertia;
}
set {
inertia = value;
if (inertia.x<=0){
inertia.x=1;
}
if (inertia.y<=0){
inertia.y=1;
}
}
}
#endregion
#region Joystick textures & color
/// <summary>
/// The GUI depth.
/// </summary>
public int guiDepth = 0;
// Joystick Texture
/// <summary>
/// The show zone.
/// </summary>
public bool showZone = true;
/// <summary>
/// The show touch.
/// </summary>
public bool showTouch = true;
/// <summary>
/// The show dead zone.
/// </summary>
public bool showDeadZone = true;
/// <summary>
/// The area texture.
/// </summary>
public Texture areaTexture;
/// <summary>
/// The color of the area.
/// </summary>
public Color areaColor = Color.white;
/// <summary>
/// The touch texture.
/// </summary>
public Texture touchTexture;
/// <summary>
/// The color of the touch.
/// </summary>
public Color touchColor = Color.white;
/// <summary>
/// The dead texture.
/// </summary>
public Texture deadTexture;
#endregion
#region Inspector
public bool showProperties=true;
public bool showInteraction=false;
public bool showAppearance=false;
public bool showPosition=true;
#endregion
#endregion
#region private members
// Joystick properties
private Vector2 joystickCenter;
private Rect areaRect;
private Rect deadRect;
private Vector2 anchorPosition = Vector2.zero;
private bool virtualJoystick = true;
private int joystickIndex=-1;
private float touchSizeCoef=0;
private bool sendEnd=true;
private float startXLocalAngle=0;
private float startYLocalAngle=0;
#endregion
#endregion
#region Monobehaviour methods
void OnEnable(){
EasyTouch.On_TouchStart += On_TouchStart;
EasyTouch.On_TouchUp += On_TouchUp;
EasyTouch.On_TouchDown += On_TouchDown;
EasyTouch.On_SimpleTap += On_SimpleTap;
EasyTouch.On_DoubleTap += On_DoubleTap;
}
void OnDisable(){
EasyTouch.On_TouchStart -= On_TouchStart;
EasyTouch.On_TouchUp -= On_TouchUp;
EasyTouch.On_TouchDown -= On_TouchDown;
EasyTouch.On_SimpleTap -= On_SimpleTap;
EasyTouch.On_DoubleTap -= On_DoubleTap;
if (Application.isPlaying){
EasyTouch.RemoveReservedArea( areaRect );
}
}
void OnDestroy(){
EasyTouch.On_TouchStart -= On_TouchStart;
EasyTouch.On_TouchUp -= On_TouchUp;
EasyTouch.On_TouchDown -= On_TouchDown;
EasyTouch.On_SimpleTap -= On_SimpleTap;
EasyTouch.On_DoubleTap -= On_DoubleTap;
if (Application.isPlaying){
EasyTouch.RemoveReservedArea( areaRect);
}
}
void Start(){
if (!dynamicJoystick){
joystickCenter = joystickPositionOffset;
ComputeJoystickAnchor(joyAnchor);
virtualJoystick = true;
}
else{
virtualJoystick = false;
}
VirtualScreen.ComputeVirtualScreen();
startXLocalAngle = GetStartAutoStabAngle( xAxisTransform, xAI);
startYLocalAngle = GetStartAutoStabAngle( yAxisTransform, yAI);
}
void Update(){
if (!useFixedUpdate && enable){
UpdateJoystick();
}
}
void FixedUpdate(){
if (useFixedUpdate && enable){
UpdateJoystick();
}
}
void UpdateJoystick(){
if (Application.isPlaying){
if (isActivated){
if ((joystickIndex==-1) || (joystickAxis == Vector2.zero && joystickIndex>-1)){
if (enableXAutoStab){
DoAutoStabilisation(xAxisTransform, xAI,thresholdX,stabSpeedX,startXLocalAngle);
}
if (enableYAutoStab){
DoAutoStabilisation(yAxisTransform, yAI,thresholdY,stabSpeedY,startYLocalAngle);
}
}
if (!dynamicJoystick){
joystickCenter = joystickPositionOffset;
}
// Reset to initial position
if (joystickIndex==-1){
if (!enableSmoothing){
joystickTouch = Vector2.zero;
}
else{
if (joystickTouch.sqrMagnitude>0.0001){
joystickTouch = new Vector2( joystickTouch.x - joystickTouch.x*smoothing.x*Time.deltaTime, joystickTouch.y - joystickTouch.y*smoothing.y*Time.deltaTime);
}
else{
joystickTouch = Vector2.zero;
}
}
}
// Joystick Axis & dead zone
Vector2 oldJoystickAxis = new Vector2(joystickAxis.x,joystickAxis.y);
float deadCoef = ComputeDeadZone();
joystickAxis= new Vector2(joystickTouch.x*deadCoef, joystickTouch.y*deadCoef);
// Inverse axis ?
if (inverseXAxis){
joystickAxis.x *= -1;
}
if (inverseYAxis){
joystickAxis.y *= -1;
}
// Joystick Value
Vector2 realvalue = new Vector2( speed.x*joystickAxis.x,speed.y*joystickAxis.y);
if (enableInertia){
Vector2 tmp = (realvalue - joystickValue);
tmp.x /= inertia.x;
tmp.y /= inertia.y;
joystickValue += tmp;
}
else{
joystickValue = realvalue;
}
// Start moving
if (oldJoystickAxis == Vector2.zero && joystickAxis != Vector2.zero){
if (interaction != InteractionType.Direct && interaction != InteractionType.Include){
CreateEvent(MessageName.On_JoystickMoveStart);
}
}
// interaction manager
UpdateGravity();
if (joystickAxis != Vector2.zero){
sendEnd = false;
switch(interaction){
case InteractionType.Direct:
UpdateDirect();
break;
case InteractionType.EventNotification:
CreateEvent(MessageName.On_JoystickMove);
break;
case InteractionType.DirectAndEvent:
UpdateDirect();
CreateEvent(MessageName.On_JoystickMove);
break;
}
}
else{
if (!sendEnd){
CreateEvent(MessageName.On_JoystickMoveEnd);
sendEnd = true;
}
}
}
}
}
void OnGUI(){
if (enable){
GUI.depth = guiDepth;
useGUILayout = isUseGuiLayout;
if (dynamicJoystick && Application.isEditor && !Application.isPlaying){
switch (area){
case DynamicArea.Bottom:
ComputeJoystickAnchor(JoystickAnchor.LowerCenter);
break;
case DynamicArea.BottomLeft:
ComputeJoystickAnchor(JoystickAnchor.LowerLeft);
break;
case DynamicArea.BottomRight:
ComputeJoystickAnchor(JoystickAnchor.LowerRight);
break;
case DynamicArea.FullScreen:
ComputeJoystickAnchor(JoystickAnchor.MiddleCenter);
break;
case DynamicArea.Left:
ComputeJoystickAnchor(JoystickAnchor.MiddleLeft);
break;
case DynamicArea.Right:
ComputeJoystickAnchor(JoystickAnchor.MiddleRight);
break;
case DynamicArea.Top:
ComputeJoystickAnchor(JoystickAnchor.UpperCenter);
break;
case DynamicArea.TopLeft:
ComputeJoystickAnchor(JoystickAnchor.UpperLeft);
break;
case DynamicArea.TopRight:
ComputeJoystickAnchor(JoystickAnchor.UpperRight);
break;
}
}
if (Application.isEditor && !Application.isPlaying){
VirtualScreen.ComputeVirtualScreen();
ComputeJoystickAnchor( joyAnchor);
}
VirtualScreen.SetGuiScaleMatrix();
// area zone
if ((showZone && areaTexture!=null && !dynamicJoystick) || (showZone && dynamicJoystick && virtualJoystick && areaTexture!=null)
|| (dynamicJoystick && Application.isEditor && !Application.isPlaying)){
if (isActivated){
GUI.color = areaColor;
if (Application.isPlaying && !dynamicJoystick){
EasyTouch.RemoveReservedArea( areaRect );
EasyTouch.AddReservedArea( areaRect );
}
}
else{
GUI.color = new Color(areaColor.r,areaColor.g,areaColor.b,0.2f);
if (Application.isPlaying && !dynamicJoystick){
EasyTouch.RemoveReservedArea( areaRect );
}
}
if (showDebugRadius && Application.isEditor){
GUI.Box( areaRect,"");
}
GUI.DrawTexture( areaRect, areaTexture,ScaleMode.StretchToFill,true);
}
// area touch
if ((showTouch && touchTexture!=null && !dynamicJoystick)|| (showTouch && dynamicJoystick && virtualJoystick && touchTexture!=null)
|| (dynamicJoystick && Application.isEditor && !Application.isPlaying)){
if (isActivated){
GUI.color = touchColor;
}
else{
GUI.color = new Color(touchColor.r,touchColor.g,touchColor.b,0.2f);
}
GUI.DrawTexture( new Rect(anchorPosition.x + joystickCenter.x+(joystickTouch.x -touchSize) ,anchorPosition.y + joystickCenter.y-(joystickTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true);
}
// dead zone
if ((showDeadZone && deadTexture!=null && !dynamicJoystick)|| (showDeadZone && dynamicJoystick && virtualJoystick && deadTexture!=null)
|| (dynamicJoystick && Application.isEditor && !Application.isPlaying)){
GUI.DrawTexture( deadRect, deadTexture,ScaleMode.ScaleToFit,true);
}
GUI.color = Color.white;
}
else{
EasyTouch.RemoveReservedArea( areaRect );
}
}
void OnDrawGizmos(){
}
#endregion
#region Private methods
void CreateEvent(MessageName message){
MovingJoystick move = new MovingJoystick();
move.joystickName = gameObject.name;
move.joystickAxis = joystickAxis;
move.joystickValue = joystickValue;
move.joystick = this;
//
if (!useBroadcast){
switch (message){
case MessageName.On_JoystickMoveStart:
if (On_JoystickMoveStart!=null){
On_JoystickMoveStart( move);
}
break;
case MessageName.On_JoystickMove:
if (On_JoystickMove!=null){
On_JoystickMove( move);
}
break;
case MessageName.On_JoystickMoveEnd:
if (On_JoystickMoveEnd!=null){
On_JoystickMoveEnd( move);
}
break;
case MessageName.On_JoystickTouchStart:
if (On_JoystickTouchStart!=null){
On_JoystickTouchStart( move);
}
break;
case MessageName.On_JoystickTap:
if (On_JoystickTap!=null){
On_JoystickTap( move);
}
break;
case MessageName.On_JoystickDoubleTap:
if (On_JoystickDoubleTap!=null){
On_JoystickDoubleTap( move);
}
break;
case MessageName.On_JoystickTouchUp:
if (On_JoystickTouchUp!=null){
On_JoystickTouchUp( move);
}
break;
}
}
else if (useBroadcast){
if (receiverGameObject!=null){
switch(messageMode){
case Broadcast.BroadcastMessage:
receiverGameObject.BroadcastMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver);
break;
case Broadcast.SendMessage:
receiverGameObject.SendMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver);
break;
case Broadcast.SendMessageUpwards:
receiverGameObject.SendMessageUpwards( message.ToString(),move,SendMessageOptions.DontRequireReceiver);
break;
}
}
else{
Debug.LogError("Joystick : " + gameObject.name + " : you must setup receiver gameobject");
}
}
}
void UpdateDirect(){
// X joystick axis
if (xAxisTransform !=null){
// Axis influenced
Vector3 axis =GetInfluencedAxis( xAI);
// Action
DoActionDirect( xAxisTransform, xTI, axis, joystickValue.x, xAxisCharacterController);
if (enableXClamp && xTI == PropertiesInfluenced.RotateLocal){
DoAngleLimitation( xAxisTransform, xAI, clampXMin,clampXMax, startXLocalAngle );
}
}
// y joystick axis
if (YAxisTransform !=null){
// Axis
Vector3 axis = GetInfluencedAxis(yAI);
// Action
DoActionDirect( yAxisTransform, yTI, axis,joystickValue.y, yAxisCharacterController);
if (enableYClamp && yTI == PropertiesInfluenced.RotateLocal){
DoAngleLimitation( yAxisTransform, yAI, clampYMin, clampYMax, startYLocalAngle );
}
}
}
void UpdateGravity(){
// Gravity
if (xAxisCharacterController!=null && xAxisGravity>0){
xAxisCharacterController.Move( Vector3.down*xAxisGravity*Time.deltaTime);
}
if (yAxisCharacterController!=null && yAxisGravity>0){
yAxisCharacterController.Move( Vector3.down*yAxisGravity*Time.deltaTime);
}
}
Vector3 GetInfluencedAxis(AxisInfluenced axisInfluenced){
Vector3 axis = Vector3.zero;
switch(axisInfluenced){
case AxisInfluenced.X:
axis = Vector3.right;
break;
case AxisInfluenced.Y:
axis = Vector3.up;
break;
case AxisInfluenced.Z:
axis = Vector3.forward;
break;
case AxisInfluenced.XYZ:
axis = Vector3.one;
break;
}
return axis;
}
void DoActionDirect(Transform axisTransform, PropertiesInfluenced inlfuencedProperty,Vector3 axis, float sensibility, CharacterController charact){
switch(inlfuencedProperty){
case PropertiesInfluenced.Rotate:
axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.World);
break;
case PropertiesInfluenced.RotateLocal:
axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.Self);
break;
case PropertiesInfluenced.Translate:
if (charact==null){
axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.World);
}
else{
charact.Move( axis * sensibility * Time.deltaTime );
}
break;
case PropertiesInfluenced.TranslateLocal:
if (charact==null){
axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.Self);
}
else{
charact.Move( charact.transform.TransformDirection(axis) * sensibility * Time.deltaTime );
}
break;
case PropertiesInfluenced.Scale:
axisTransform.localScale += axis * sensibility * Time.deltaTime;
break;
}
}
void DoAngleLimitation(Transform axisTransform, AxisInfluenced axisInfluenced,float clampMin, float clampMax,float startAngle){
float angle=0;
switch(axisInfluenced){
case AxisInfluenced.X:
angle = axisTransform.localRotation.eulerAngles.x;
break;
case AxisInfluenced.Y:
angle = axisTransform.localRotation.eulerAngles.y;
break;
case AxisInfluenced.Z:
angle = axisTransform.localRotation.eulerAngles.z;
break;
}
if (angle<=360 && angle>=180){
angle = angle -360;
}
//angle = Mathf.Clamp (angle, startAngle-clampMax, clampMin+startAngle);
angle = Mathf.Clamp (angle, -clampMax, clampMin);
switch(axisInfluenced){
case AxisInfluenced.X:
axisTransform.localEulerAngles = new Vector3( angle,axisTransform.localEulerAngles.y, axisTransform.localEulerAngles.z);
break;
case AxisInfluenced.Y:
axisTransform.localEulerAngles = new Vector3( axisTransform.localEulerAngles.x,angle, axisTransform.localEulerAngles.z);
break;
case AxisInfluenced.Z:
axisTransform.localEulerAngles = new Vector3( axisTransform.localEulerAngles.x,axisTransform.localEulerAngles.y,angle);
break;
}
}
void DoAutoStabilisation(Transform axisTransform, AxisInfluenced axisInfluenced, float threshold, float speed,float startAngle){
float angle=0;
switch(axisInfluenced){
case AxisInfluenced.X:
angle = axisTransform.localRotation.eulerAngles.x;
break;
case AxisInfluenced.Y:
angle = axisTransform.localRotation.eulerAngles.y;
break;
case AxisInfluenced.Z:
angle = axisTransform.localRotation.eulerAngles.z;
break;
}
if (angle<=360 && angle>=180){
angle = angle -360;
}
if (angle > startAngle - threshold || angle < startAngle + threshold){
float axis=0;
Vector3 stabAngle = Vector3.zero;
if (angle > startAngle - threshold){
axis = angle + speed/100f*Mathf.Abs (angle-startAngle) * Time.deltaTime*-1;
}
if (angle < startAngle + threshold){
axis = angle + speed/100f*Mathf.Abs (angle-startAngle) * Time.deltaTime;
}
switch(axisInfluenced){
case AxisInfluenced.X:
stabAngle = new Vector3(axis,axisTransform.localRotation.eulerAngles.y,axisTransform.localRotation.eulerAngles.z);
break;
case AxisInfluenced.Y:
stabAngle = new Vector3(axisTransform.localRotation.eulerAngles.x,axis,axisTransform.localRotation.eulerAngles.z);
break;
case AxisInfluenced.Z:
stabAngle = new Vector3(axisTransform.localRotation.eulerAngles.x,axisTransform.localRotation.eulerAngles.y,axis);
break;
}
axisTransform.localRotation = Quaternion.Euler( stabAngle);
}
}
float GetStartAutoStabAngle(Transform axisTransform, AxisInfluenced axisInfluenced){
float angle=0;
if (axisTransform!=null){
switch(axisInfluenced){
case AxisInfluenced.X:
angle = axisTransform.localRotation.eulerAngles.x;
break;
case AxisInfluenced.Y:
angle = axisTransform.localRotation.eulerAngles.y;
break;
case AxisInfluenced.Z:
angle = axisTransform.localRotation.eulerAngles.z;
break;
}
if (angle<=360 && angle>=180){
angle = angle -360;
}
}
return angle;
}
float ComputeDeadZone(){
float dead = 0;
float dist = Mathf.Max(joystickTouch.magnitude,0.1f);
if (restrictArea){
dead = Mathf.Max(dist - deadZone, 0)/(zoneRadius-touchSize - deadZone)/dist;
}
else{
dead = Mathf.Max(dist - deadZone, 0)/(zoneRadius - deadZone)/dist;
}
return dead;
}
void ComputeJoystickAnchor(JoystickAnchor anchor){
float touch=0;
if (!restrictArea){
touch = touchSize;
}
// Anchor position
switch (anchor){
case JoystickAnchor.UpperLeft:
anchorPosition = new Vector2( zoneRadius+touch, zoneRadius+touch);
break;
case JoystickAnchor.UpperCenter:
anchorPosition = new Vector2( VirtualScreen.width/2, zoneRadius+touch);
break;
case JoystickAnchor.UpperRight:
anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,zoneRadius+touch);
break;
case JoystickAnchor.MiddleLeft:
anchorPosition = new Vector2( zoneRadius+touch, VirtualScreen.height/2);
break;
case JoystickAnchor.MiddleCenter:
anchorPosition = new Vector2( VirtualScreen.width/2, VirtualScreen.height/2);
break;
case JoystickAnchor.MiddleRight:
anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,VirtualScreen.height/2);
break;
case JoystickAnchor.LowerLeft:
anchorPosition = new Vector2( zoneRadius+touch, VirtualScreen.height-zoneRadius-touch);
break;
case JoystickAnchor.LowerCenter:
anchorPosition = new Vector2( VirtualScreen.width/2, VirtualScreen.height-zoneRadius-touch);
break;
case JoystickAnchor.LowerRight:
anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,VirtualScreen.height-zoneRadius-touch);
break;
case JoystickAnchor.None:
anchorPosition = Vector2.zero;
break;
}
//joystick rect
areaRect = new Rect(anchorPosition.x + joystickCenter.x -zoneRadius , anchorPosition.y+joystickCenter.y-zoneRadius,zoneRadius*2,zoneRadius*2);
deadRect = new Rect(anchorPosition.x + joystickCenter.x -deadZone,anchorPosition.y + joystickCenter.y-deadZone,deadZone*2,deadZone*2);
}
#endregion
#region EasyTouch events
// Touch start
void On_TouchStart(Gesture gesture){
if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){
if (isActivated){
if (!dynamicJoystick){
Vector2 center = new Vector2( (anchorPosition.x+joystickCenter.x) * VirtualScreen.xRatio , (VirtualScreen.height-anchorPosition.y - joystickCenter.y) * VirtualScreen.yRatio);
if ((gesture.position - center).sqrMagnitude < (zoneRadius *VirtualScreen.xRatio )*(zoneRadius *VirtualScreen.xRatio )){
joystickIndex = gesture.fingerIndex;
CreateEvent(MessageName.On_JoystickTouchStart);
}
}
else{
if (!virtualJoystick){
#region area restriction
switch (area){
// full
case DynamicArea.FullScreen:
virtualJoystick = true; ;
break;
// bottom
case DynamicArea.Bottom:
if (gesture.position.y< Screen.height/2){
virtualJoystick = true;
}
break;
// top
case DynamicArea.Top:
if (gesture.position.y> Screen.height/2){
virtualJoystick = true;
}
break;
// Right
case DynamicArea.Right:
if (gesture.position.x> Screen.width/2){
virtualJoystick = true;
}
break;
// Left
case DynamicArea.Left:
if (gesture.position.x< Screen.width/2){
virtualJoystick = true;
}
break;
// top Right
case DynamicArea.TopRight:
if (gesture.position.y> Screen.height/2 && gesture.position.x> Screen.width/2){
virtualJoystick = true;
}
break;
// top Left
case DynamicArea.TopLeft:
if (gesture.position.y> Screen.height/2 && gesture.position.x< Screen.width/2){
virtualJoystick = true;
}
break;
// bottom Right
case DynamicArea.BottomRight:
if (gesture.position.y< Screen.height/2 && gesture.position.x> Screen.width/2){
virtualJoystick = true;
}
break;
// bottom left
case DynamicArea.BottomLeft:
if (gesture.position.y< Screen.height/2 && gesture.position.x< Screen.width/2){
virtualJoystick = true;
}
break;
}
#endregion
if (virtualJoystick){
joystickCenter =new Vector2(gesture.position.x/VirtualScreen.xRatio, VirtualScreen.height - gesture.position.y/VirtualScreen.yRatio);
JoyAnchor = JoystickAnchor.None;
joystickIndex = gesture.fingerIndex;
}
}
}
}
}
}
// Simple tap
void On_SimpleTap(Gesture gesture){
if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){
if (isActivated){
if (gesture.fingerIndex == joystickIndex){
CreateEvent(MessageName.On_JoystickTap);
}
}
}
}
// Double tap
void On_DoubleTap(Gesture gesture){
if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){
if (isActivated){
if (gesture.fingerIndex == joystickIndex){
CreateEvent(MessageName.On_JoystickDoubleTap);
}
}
}
}
// Joystick move
void On_TouchDown(Gesture gesture){
if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){
if (isActivated){
Vector2 center = new Vector2( (anchorPosition.x+joystickCenter.x) * VirtualScreen.xRatio , (VirtualScreen.height-(anchorPosition.y +joystickCenter.y)) * VirtualScreen.yRatio);
if (gesture.fingerIndex == joystickIndex){
if (((gesture.position - center).sqrMagnitude < (zoneRadius *VirtualScreen.xRatio )*(zoneRadius *VirtualScreen.xRatio) && resetFingerExit) || !resetFingerExit) {
joystickTouch = new Vector2( gesture.position.x , gesture.position.y) - center;
joystickTouch = new Vector2( joystickTouch.x / VirtualScreen.xRatio, joystickTouch.y / VirtualScreen.yRatio);
if (!enableXaxis){
joystickTouch.x =0;
}
if (!enableYaxis){
joystickTouch.y=0;
}
if ((joystickTouch/(zoneRadius-touchSizeCoef)).sqrMagnitude > 1){
joystickTouch.Normalize();
joystickTouch *= zoneRadius-touchSizeCoef;
}
}
else{
On_TouchUp( gesture);
}
}
}
}
}
// Touch end
void On_TouchUp( Gesture gesture){
if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){
if (isActivated){
if (gesture.fingerIndex == joystickIndex){
joystickIndex=-1;
if (dynamicJoystick){
virtualJoystick=false;
}
CreateEvent(MessageName.On_JoystickTouchUp);
}
}
}
}
#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.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpListener class provide TCP services at a higher level of abstraction
// than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpListener is used to create a
// host process that listens for connections from TCP clients.
public class TcpListener
{
private readonly IPEndPoint _serverSocketEP;
private Socket _serverSocket;
private bool _active;
private bool _exclusiveAddressUse;
// Initializes a new instance of the TcpListener class with the specified local end point.
public TcpListener(IPEndPoint localEP)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localEP);
if (localEP == null)
{
throw new ArgumentNullException(nameof(localEP));
}
_serverSocketEP = localEP;
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Initializes a new instance of the TcpListener class that listens to the specified IP address
// and port.
public TcpListener(IPAddress localaddr, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localaddr);
if (localaddr == null)
{
throw new ArgumentNullException(nameof(localaddr));
}
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_serverSocketEP = new IPEndPoint(localaddr, port);
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Initiailizes a new instance of the TcpListener class that listens on the specified port.
[Obsolete("This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListener(int port)
{
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_serverSocketEP = new IPEndPoint(IPAddress.Any, port);
_serverSocket = new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
// Used by the class to provide the underlying network socket.
public Socket Server
{
get
{
CreateNewSocketIfNeeded();
return _serverSocket;
}
}
// Used by the class to indicate that the listener's socket has been bound to a port
// and started listening.
protected bool Active
{
get
{
return _active;
}
}
// Gets the m_Active EndPoint for the local listener socket.
public EndPoint LocalEndpoint
{
get
{
return _active ? _serverSocket.LocalEndPoint : _serverSocketEP;
}
}
public bool ExclusiveAddressUse
{
get
{
return _serverSocket != null ? _serverSocket.ExclusiveAddressUse : _exclusiveAddressUse;
}
set
{
if (_active)
{
throw new InvalidOperationException(SR.net_tcplistener_mustbestopped);
}
if (_serverSocket != null)
{
_serverSocket.ExclusiveAddressUse = value;
}
_exclusiveAddressUse = value;
}
}
public void AllowNatTraversal(bool allowed)
{
if (_active)
{
throw new InvalidOperationException(SR.net_tcplistener_mustbestopped);
}
_serverSocket.SetIPProtectionLevel(allowed ? IPProtectionLevel.Unrestricted : IPProtectionLevel.EdgeRestricted);
}
// Starts listening to network requests.
public void Start()
{
Start((int)SocketOptionName.MaxConnections);
}
public void Start(int backlog)
{
if (backlog > (int)SocketOptionName.MaxConnections || backlog < 0)
{
throw new ArgumentOutOfRangeException(nameof(backlog));
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// Already listening.
if (_active)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return;
}
CreateNewSocketIfNeeded();
_serverSocket.Bind(_serverSocketEP);
try
{
_serverSocket.Listen(backlog);
}
catch (SocketException)
{
// When there is an exception, unwind previous actions (bind, etc).
Stop();
throw;
}
_active = true;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Closes the network connection.
public void Stop()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
_serverSocket?.Dispose();
_active = false;
_serverSocket = null;
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
// Determine if there are pending connection requests.
public bool Pending()
{
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
return _serverSocket.Poll(0, SelectMode.SelectRead);
}
// Accept the first pending connection
public Socket AcceptSocket()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket socket = _serverSocket.Accept();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, socket);
return socket;
}
public TcpClient AcceptTcpClient()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
Socket acceptedSocket = _serverSocket.Accept();
TcpClient returnValue = new TcpClient(acceptedSocket);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, returnValue);
return returnValue;
}
public IAsyncResult BeginAcceptSocket(AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return result;
}
public Socket EndAcceptSocket(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, socket);
return socket;
}
public IAsyncResult BeginAcceptTcpClient(AsyncCallback callback, object state)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (!_active)
{
throw new InvalidOperationException(SR.net_stopped);
}
IAsyncResult result = _serverSocket.BeginAccept(callback, state);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result);
return result;
}
public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
Socket asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
if (asyncSocket == null)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
// This will throw ObjectDisposedException if Stop() has been called.
Socket socket = asyncSocket.EndAccept(asyncResult);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this, socket);
return new TcpClient(socket);
}
public Task<Socket> AcceptSocketAsync()
{
return Task<Socket>.Factory.FromAsync(
(callback, state) => ((TcpListener)state).BeginAcceptSocket(callback, state),
asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptSocket(asyncResult),
state: this);
}
public Task<TcpClient> AcceptTcpClientAsync()
{
return Task<TcpClient>.Factory.FromAsync(
(callback, state) => ((TcpListener)state).BeginAcceptTcpClient(callback, state),
asyncResult => ((TcpListener)asyncResult.AsyncState).EndAcceptTcpClient(asyncResult),
state: this);
}
// This creates a TcpListener that listens on both IPv4 and IPv6 on the given port.
public static TcpListener Create(int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, port);
if (!TcpValidationHelpers.ValidatePortNumber(port))
{
throw new ArgumentOutOfRangeException(nameof(port));
}
TcpListener listener;
if (Socket.OSSupportsIPv6)
{
// If OS supports IPv6 use dual mode so both address families work.
listener = new TcpListener(IPAddress.IPv6Any, port);
listener.Server.DualMode = true;
}
else
{
// If not, fall-back to old IPv4.
listener = new TcpListener(IPAddress.Any, port);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, port);
return listener;
}
private void CreateNewSocketIfNeeded()
{
_serverSocket ??= new Socket(_serverSocketEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (_exclusiveAddressUse)
{
_serverSocket.ExclusiveAddressUse = true;
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// A target that buffers log events and sends them in batches to the wrapped target.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso>
[Target("BufferingWrapper", IsWrapper = true)]
public class BufferingTargetWrapper : WrapperTargetBase
{
private AsyncRequestQueue _buffer;
private Timer _flushTimer;
private readonly object _lockObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
public BufferingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize)
: this(wrappedTarget, bufferSize, -1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout)
: this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
/// <param name="overflowAction">The action to take when the buffer overflows.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction)
{
WrappedTarget = wrappedTarget;
BufferSize = bufferSize;
FlushTimeout = flushTimeout;
OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events to be buffered.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed
/// if there's no write in the specified period of time. Use -1 to disable timed flushes.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
public int FlushTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use sliding timeout.
/// </summary>
/// <remarks>
/// This value determines how the inactivity period is determined. If sliding timeout is enabled,
/// the inactivity timer is reset after each write, if it is disabled - inactivity timer will
/// count from the first event written to the buffer.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
public bool SlidingTimeout { get; set; } = true;
/// <summary>
/// Gets or sets the action to take if the buffer overflows.
/// </summary>
/// <remarks>
/// Setting to <see cref="BufferingTargetWrapperOverflowAction.Discard"/> will replace the
/// oldest event with new events without sending events down to the wrapped target, and
/// setting to <see cref="BufferingTargetWrapperOverflowAction.Flush"/> will flush the
/// entire buffer to the wrapped target.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
public BufferingTargetWrapperOverflowAction OverflowAction { get; set; }
/// <summary>
/// Flushes pending events in the buffer (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
WriteEventsInBuffer("Flush Async");
base.FlushAsync(asyncContinuation);
}
/// <inheritdoc/>
protected override void InitializeTarget()
{
base.InitializeTarget();
_buffer = new AsyncRequestQueue(BufferSize, AsyncTargetWrapperOverflowAction.Discard);
InternalLogger.Trace("{0}: Create Timer", this);
_flushTimer = new Timer(FlushCallback, null, Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Closes the target by flushing pending events in the buffer (if any).
/// </summary>
protected override void CloseTarget()
{
var currentTimer = _flushTimer;
if (currentTimer != null)
{
_flushTimer = null;
if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)))
{
if (OverflowAction == BufferingTargetWrapperOverflowAction.Discard)
{
_buffer.Clear();
}
else
{
WriteEventsInBuffer("Closing Target");
}
}
}
base.CloseTarget();
}
/// <summary>
/// Adds the specified log event to the buffer and flushes
/// the buffer in case the buffer gets full.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
PrecalculateVolatileLayouts(logEvent.LogEvent);
var firstEventInQueue = _buffer.Enqueue(logEvent);
if (_buffer.RequestCount >= BufferSize)
{
// If the OverflowAction action is set to "Discard", the buffer will automatically
// roll over the oldest item.
if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush)
{
WriteEventsInBuffer("Exceeding BufferSize");
}
}
else
{
if (FlushTimeout > 0 && (SlidingTimeout || firstEventInQueue))
{
// reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true
_flushTimer.Change(FlushTimeout, -1);
}
}
}
private void FlushCallback(object state)
{
bool lockTaken = false;
try
{
int timeoutMilliseconds = Math.Min(FlushTimeout / 2, 100);
lockTaken = Monitor.TryEnter(_lockObject, timeoutMilliseconds);
if (lockTaken)
{
if (_flushTimer is null)
return;
WriteEventsInBuffer(null);
}
else
{
if (!_buffer.IsEmpty)
_flushTimer?.Change(FlushTimeout, -1); // Schedule new retry timer
}
}
catch (Exception exception)
{
#if DEBUG
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
InternalLogger.Error(exception, "{0}: Error in flush procedure.", this);
}
finally
{
if (lockTaken)
{
Monitor.Exit(_lockObject);
}
}
}
private void WriteEventsInBuffer(string reason)
{
if (WrappedTarget is null)
{
InternalLogger.Error("{0}: WrappedTarget is NULL", this);
return;
}
lock (_lockObject)
{
AsyncLogEventInfo[] logEvents = _buffer.DequeueBatch(int.MaxValue);
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("{0}: Writing {1} events ({2})", this, logEvents.Length, reason);
WrappedTarget.WriteAsyncLogEvents(logEvents);
}
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System;
namespace QuantConnect.Securities
{
/// <summary>
/// This class implements interface <see cref="ISecurityService"/> providing methods for creating new <see cref="Security"/>
/// </summary>
public class SecurityService : ISecurityService
{
private readonly CashBook _cashBook;
private readonly MarketHoursDatabase _marketHoursDatabase;
private readonly SymbolPropertiesDatabase _symbolPropertiesDatabase;
private readonly IRegisteredSecurityDataTypesProvider _registeredTypes;
private readonly ISecurityInitializerProvider _securityInitializerProvider;
private readonly SecurityCacheProvider _cacheProvider;
private readonly IPrimaryExchangeProvider _primaryExchangeProvider;
private bool _isLiveMode;
/// <summary>
/// Creates a new instance of the SecurityService class
/// </summary>
public SecurityService(CashBook cashBook,
MarketHoursDatabase marketHoursDatabase,
SymbolPropertiesDatabase symbolPropertiesDatabase,
ISecurityInitializerProvider securityInitializerProvider,
IRegisteredSecurityDataTypesProvider registeredTypes,
SecurityCacheProvider cacheProvider,
IPrimaryExchangeProvider primaryExchangeProvider=null)
{
_cashBook = cashBook;
_registeredTypes = registeredTypes;
_marketHoursDatabase = marketHoursDatabase;
_symbolPropertiesDatabase = symbolPropertiesDatabase;
_securityInitializerProvider = securityInitializerProvider;
_cacheProvider = cacheProvider;
_primaryExchangeProvider = primaryExchangeProvider;
}
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
public Security CreateSecurity(Symbol symbol,
List<SubscriptionDataConfig> subscriptionDataConfigList,
decimal leverage = 0,
bool addToSymbolCache = true,
Security underlying = null)
{
var configList = new SubscriptionDataConfigList(symbol);
configList.AddRange(subscriptionDataConfigList);
var exchangeHours = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours;
var defaultQuoteCurrency = _cashBook.AccountCurrency;
if (symbol.ID.SecurityType == SecurityType.Forex)
{
defaultQuoteCurrency = symbol.Value.Substring(3);
}
if (symbol.ID.SecurityType == SecurityType.Crypto && !_symbolPropertiesDatabase.ContainsKey(symbol.ID.Market, symbol, symbol.ID.SecurityType))
{
throw new ArgumentException($"Symbol can't be found in the Symbol Properties Database: {symbol.Value}");
}
// For Futures Options that don't have a SPDB entry, the futures entry will be used instead.
var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(
symbol.ID.Market,
symbol,
symbol.SecurityType,
defaultQuoteCurrency);
// add the symbol to our cache
if (addToSymbolCache)
{
SymbolCache.Set(symbol.Value, symbol);
}
// verify the cash book is in a ready state
var quoteCurrency = symbolProperties.QuoteCurrency;
if (!_cashBook.ContainsKey(quoteCurrency))
{
// since we have none it's safe to say the conversion is zero
_cashBook.Add(quoteCurrency, 0, 0);
}
if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto)
{
// decompose the symbol into each currency pair
string baseCurrency;
if (symbol.ID.SecurityType == SecurityType.Forex)
{
Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency);
}
else
{
Crypto.Crypto.DecomposeCurrencyPair(symbol, symbolProperties, out baseCurrency, out quoteCurrency);
}
if (!_cashBook.ContainsKey(baseCurrency))
{
// since we have none it's safe to say the conversion is zero
_cashBook.Add(baseCurrency, 0, 0);
}
if (!_cashBook.ContainsKey(quoteCurrency))
{
// since we have none it's safe to say the conversion is zero
_cashBook.Add(quoteCurrency, 0, 0);
}
}
var quoteCash = _cashBook[symbolProperties.QuoteCurrency];
var cache = _cacheProvider.GetSecurityCache(symbol);
Security security;
switch (symbol.ID.SecurityType)
{
case SecurityType.Equity:
var primaryExchange =
_primaryExchangeProvider?.GetPrimaryExchange(symbol.ID) ??
Exchange.UNKNOWN;
security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache, primaryExchange);
break;
case SecurityType.Option:
if (addToSymbolCache) SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
security = new Option.Option(symbol, exchangeHours, quoteCash, new Option.OptionSymbolProperties(symbolProperties), _cashBook, _registeredTypes, cache, underlying);
break;
case SecurityType.IndexOption:
if (addToSymbolCache) SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
security = new IndexOption.IndexOption(symbol, exchangeHours, quoteCash, new IndexOption.IndexOptionSymbolProperties(symbolProperties), _cashBook, _registeredTypes, cache, underlying);
break;
case SecurityType.FutureOption:
if (addToSymbolCache) SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying);
var optionSymbolProperties = new Option.OptionSymbolProperties(symbolProperties);
// Future options exercised only gives us one contract back, rather than the
// 100x seen in equities.
optionSymbolProperties.SetContractUnitOfTrade(1);
security = new FutureOption.FutureOption(symbol, exchangeHours, quoteCash, optionSymbolProperties, _cashBook, _registeredTypes, cache, underlying);
break;
case SecurityType.Future:
security = new Future.Future(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache, underlying);
break;
case SecurityType.Forex:
security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
break;
case SecurityType.Cfd:
security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
break;
case SecurityType.Index:
security = new Index.Index(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
break;
case SecurityType.Crypto:
security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
break;
default:
case SecurityType.Base:
security = new Security(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache);
break;
}
// if we're just creating this security and it only has an internal
// feed, mark it as non-tradable since the user didn't request this data
if (!configList.IsInternalFeed)
{
security.IsTradable = true;
}
security.AddData(configList);
// invoke the security initializer
_securityInitializerProvider.SecurityInitializer.Initialize(security);
// if leverage was specified then apply to security after the initializer has run, parameters of this
// method take precedence over the intializer
if (leverage != Security.NullLeverage)
{
security.SetLeverage(leverage);
}
var isNotNormalized = configList.DataNormalizationMode() == DataNormalizationMode.Raw;
// In live mode and non normalized data, equity assumes specific price variation model
if ((_isLiveMode || isNotNormalized) && security.Type == SecurityType.Equity)
{
security.PriceVariationModel = new EquityPriceVariationModel();
}
return security;
}
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
public Security CreateSecurity(Symbol symbol, SubscriptionDataConfig subscriptionDataConfig, decimal leverage = 0, bool addToSymbolCache = true, Security underlying = null)
{
return CreateSecurity(symbol, new List<SubscriptionDataConfig> { subscriptionDataConfig }, leverage, addToSymbolCache, underlying);
}
/// <summary>
/// Set live mode state of the algorithm
/// </summary>
/// <param name="isLiveMode">True, live mode is enabled</param>
public void SetLiveMode(bool isLiveMode)
{
_isLiveMode = isLiveMode;
}
}
}
| |
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
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 FlushedSegment = Lucene.Net.Index.DocumentsWriterPerThread.FlushedSegment;
/// <summary>
/// @lucene.internal
/// </summary>
internal class DocumentsWriterFlushQueue
{
private readonly LinkedList<FlushTicket> queue = new LinkedList<FlushTicket>();
// we track tickets separately since count must be present even before the ticket is
// constructed ie. queue.size would not reflect it.
private readonly AtomicInt32 ticketCount = new AtomicInt32();
private readonly ReentrantLock purgeLock = new ReentrantLock();
internal virtual void AddDeletes(DocumentsWriterDeleteQueue deleteQueue)
{
lock (this)
{
IncTickets(); // first inc the ticket count - freeze opens
// a window for #anyChanges to fail
bool success = false;
try
{
queue.AddLast(new GlobalDeletesTicket(deleteQueue.FreezeGlobalBuffer(null)));
success = true;
}
finally
{
if (!success)
{
DecTickets();
}
}
}
}
private void IncTickets()
{
int numTickets = ticketCount.IncrementAndGet();
Debug.Assert(numTickets > 0);
}
private void DecTickets()
{
int numTickets = ticketCount.DecrementAndGet();
Debug.Assert(numTickets >= 0);
}
internal virtual SegmentFlushTicket AddFlushTicket(DocumentsWriterPerThread dwpt)
{
lock (this)
{
// Each flush is assigned a ticket in the order they acquire the ticketQueue
// lock
IncTickets();
bool success = false;
try
{
// prepare flush freezes the global deletes - do in synced block!
SegmentFlushTicket ticket = new SegmentFlushTicket(dwpt.PrepareFlush());
queue.AddLast(ticket);
success = true;
return ticket;
}
finally
{
if (!success)
{
DecTickets();
}
}
}
}
internal virtual void AddSegment(SegmentFlushTicket ticket, FlushedSegment segment)
{
lock (this)
{
// the actual flush is done asynchronously and once done the FlushedSegment
// is passed to the flush ticket
ticket.SetSegment(segment);
}
}
internal virtual void MarkTicketFailed(SegmentFlushTicket ticket)
{
lock (this)
{
// to free the queue we mark tickets as failed just to clean up the queue.
ticket.SetFailed();
}
}
internal virtual bool HasTickets
{
get
{
Debug.Assert(ticketCount.Get() >= 0, "ticketCount should be >= 0 but was: " + ticketCount.Get());
return ticketCount.Get() != 0;
}
}
private int InnerPurge(IndexWriter writer)
{
//Debug.Assert(PurgeLock.HeldByCurrentThread);
int numPurged = 0;
while (true)
{
FlushTicket head;
bool canPublish;
lock (this)
{
head = queue.Count <= 0 ? null : queue.First.Value;
canPublish = head != null && head.CanPublish; // do this synced
}
if (canPublish)
{
numPurged++;
try
{
/*
* if we block on publish -> lock IW -> lock BufferedDeletes we don't block
* concurrent segment flushes just because they want to append to the queue.
* the downside is that we need to force a purge on fullFlush since ther could
* be a ticket still in the queue.
*/
head.Publish(writer);
}
finally
{
lock (this)
{
// finally remove the published ticket from the queue
FlushTicket poll = queue.First.Value;
queue.Remove(poll);
ticketCount.DecrementAndGet();
Debug.Assert(poll == head);
}
}
}
else
{
break;
}
}
return numPurged;
}
internal virtual int ForcePurge(IndexWriter writer)
{
//Debug.Assert(!Thread.HoldsLock(this));
//Debug.Assert(!Thread.holdsLock(writer));
purgeLock.@Lock();
try
{
return InnerPurge(writer);
}
finally
{
purgeLock.Unlock();
}
}
internal virtual int TryPurge(IndexWriter writer)
{
//Debug.Assert(!Thread.holdsLock(this));
//Debug.Assert(!Thread.holdsLock(writer));
if (purgeLock.TryLock())
{
try
{
return InnerPurge(writer);
}
finally
{
purgeLock.Unlock();
}
}
return 0;
}
public virtual int TicketCount
{
get
{
return ticketCount.Get();
}
}
internal virtual void Clear()
{
lock (this)
{
queue.Clear();
ticketCount.Set(0);
}
}
internal abstract class FlushTicket
{
protected FrozenBufferedUpdates m_frozenUpdates;
protected bool m_published = false;
protected FlushTicket(FrozenBufferedUpdates frozenUpdates)
{
Debug.Assert(frozenUpdates != null);
this.m_frozenUpdates = frozenUpdates;
}
protected internal abstract void Publish(IndexWriter writer);
protected internal abstract bool CanPublish { get; }
/// <summary>
/// Publishes the flushed segment, segment private deletes (if any) and its
/// associated global delete (if present) to <see cref="IndexWriter"/>. The actual
/// publishing operation is synced on IW -> BDS so that the <see cref="SegmentInfo"/>'s
/// delete generation is always <see cref="FrozenBufferedUpdates.DelGen"/> (<paramref name="globalPacket"/>) + 1
/// </summary>
protected void PublishFlushedSegment(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates globalPacket)
{
Debug.Assert(newSegment != null);
Debug.Assert(newSegment.segmentInfo != null);
FrozenBufferedUpdates segmentUpdates = newSegment.segmentUpdates;
//System.out.println("FLUSH: " + newSegment.segmentInfo.info.name);
if (indexWriter.infoStream.IsEnabled("DW"))
{
indexWriter.infoStream.Message("DW", "publishFlushedSegment seg-private updates=" + segmentUpdates);
}
if (segmentUpdates != null && indexWriter.infoStream.IsEnabled("DW"))
{
indexWriter.infoStream.Message("DW", "flush: push buffered seg private updates: " + segmentUpdates);
}
// now publish!
indexWriter.PublishFlushedSegment(newSegment.segmentInfo, segmentUpdates, globalPacket);
}
protected void FinishFlush(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates bufferedUpdates)
{
// Finish the flushed segment and publish it to IndexWriter
if (newSegment == null)
{
Debug.Assert(bufferedUpdates != null);
if (bufferedUpdates != null && bufferedUpdates.Any())
{
indexWriter.PublishFrozenUpdates(bufferedUpdates);
if (indexWriter.infoStream.IsEnabled("DW"))
{
indexWriter.infoStream.Message("DW", "flush: push buffered updates: " + bufferedUpdates);
}
}
}
else
{
PublishFlushedSegment(indexWriter, newSegment, bufferedUpdates);
}
}
}
internal sealed class GlobalDeletesTicket : FlushTicket
{
internal GlobalDeletesTicket(FrozenBufferedUpdates frozenUpdates) // LUCENENET NOTE: Made internal rather than protected because class is sealed
: base(frozenUpdates)
{
}
protected internal override void Publish(IndexWriter writer)
{
Debug.Assert(!m_published, "ticket was already publised - can not publish twice");
m_published = true;
// its a global ticket - no segment to publish
FinishFlush(writer, null, m_frozenUpdates);
}
protected internal override bool CanPublish
{
get { return true; }
}
}
internal sealed class SegmentFlushTicket : FlushTicket
{
internal FlushedSegment segment;
internal bool failed = false;
internal SegmentFlushTicket(FrozenBufferedUpdates frozenDeletes) // LUCENENET NOTE: Made internal rather than protected because class is sealed
: base(frozenDeletes)
{
}
protected internal override void Publish(IndexWriter writer)
{
Debug.Assert(!m_published, "ticket was already publised - can not publish twice");
m_published = true;
FinishFlush(writer, segment, m_frozenUpdates);
}
internal void SetSegment(FlushedSegment segment) // LUCENENET NOTE: Made internal rather than protected because class is sealed
{
Debug.Assert(!failed);
this.segment = segment;
}
internal void SetFailed() // LUCENENET NOTE: Made internal rather than protected because class is sealed
{
Debug.Assert(segment == null);
failed = true;
}
protected internal override bool CanPublish
{
get { return segment != null || failed; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace DrillTime.WebApiNoOwEf.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Orleans.Transactions.Abstractions;
namespace Orleans.Transactions.TestKit.Correctnesss
{
[Serializable]
public class BitArrayState
{
protected bool Equals(BitArrayState other)
{
if (ReferenceEquals(null, this.value)) return false;
if (ReferenceEquals(null, other.value)) return false;
if (this.value.Length != other.value.Length) return false;
for (var i = 0; i < this.value.Length; i++)
{
if (this.value[i] != other.value[i])
{
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((BitArrayState) obj);
}
public override int GetHashCode()
{
return (value != null ? value.GetHashCode() : 0);
}
private static readonly int BitsInInt = sizeof(int) * 8;
[JsonProperty("v")]
private int[] value = { 0 };
[JsonIgnore]
public int[] Value => value;
[JsonIgnore]
public int Length => this.value.Length;
public BitArrayState()
{
}
public BitArrayState(BitArrayState other)
{
this.value = new int[other.value.Length];
for (var i = 0; i < other.value.Length; i++)
{
this.value[i] = other.value[i];
}
}
public void Set(int index, bool value)
{
int idx = index / BitsInInt;
if (idx >= this.value.Length)
{
Array.Resize(ref this.value, idx+1);
}
int shift = 1 << (index % BitsInInt);
if (value)
{
this.value[idx] |= shift;
} else
this.value[idx] &= ~shift;
}
public IEnumerator<int> GetEnumerator()
{
foreach (var v in this.value) yield return v;
}
public override string ToString()
{
// Write the values from least significant bit to most significant bit
var builder = new StringBuilder();
foreach (var v in this.value)
{
builder.Append(Reverse(Convert.ToString(v, 2)).PadRight(BitsInInt, '0'));
string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
return builder.ToString();
}
public int this[int index]
{
get => this.value[index];
set => this.value[index] = value;
}
public static bool operator ==(BitArrayState left, BitArrayState right)
{
if (ReferenceEquals(left, right)) return true;
if (ReferenceEquals(left, null)) return false;
if (ReferenceEquals(right, null)) return false;
return left.Equals(right);
}
public static bool operator !=(BitArrayState left, BitArrayState right)
{
return !(left == right);
}
public static BitArrayState operator ^(BitArrayState left, BitArrayState right)
{
return Apply(left, right, (l, r) => l ^ r);
}
public static BitArrayState operator |(BitArrayState left, BitArrayState right)
{
return Apply(left, right, (l, r) => l | r);
}
public static BitArrayState operator &(BitArrayState left, BitArrayState right)
{
return Apply(left, right, (l, r) => l & r);
}
public static BitArrayState Apply(BitArrayState left, BitArrayState right, Func<int, int, int> op)
{
var result = new BitArrayState(left.value.Length > right.value.Length ? left : right);
var overlappingLength = Math.Min(left.value.Length, right.value.Length);
var i = 0;
for (; i < overlappingLength; i++)
{
result.value[i] = op(left.value[i], right.value[i]);
}
// Continue with the non-overlapping portion.
for (; i < result.value.Length; i++)
{
var leftVal = left.value.Length > i ? left.value[i] : 0;
var rightVal = right.value.Length > i ? right.value[i] : 0;
result.value[i] = op(leftVal, rightVal);
}
return result;
}
}
public class MaxStateTransactionalGrain : MultiStateTransactionalBitArrayGrain
{
public MaxStateTransactionalGrain(ITransactionalStateFactory stateFactory,
ILoggerFactory loggerFactory)
: base(Enumerable.Range(0, TransactionTestConstants.MaxCoordinatedTransactions)
.Select(i => stateFactory.Create<BitArrayState>(new TransactionalStateConfiguration(new TransactionalStateAttribute($"data{i}", TransactionTestConstants.TransactionStore))))
.ToArray(),
loggerFactory)
{
}
}
public class DoubleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain
{
public DoubleStateTransactionalGrain(
[TransactionalState("data1", TransactionTestConstants.TransactionStore)]
ITransactionalState<BitArrayState> data1,
[TransactionalState("data2", TransactionTestConstants.TransactionStore)]
ITransactionalState<BitArrayState> data2,
ILoggerFactory loggerFactory)
: base(new ITransactionalState<BitArrayState>[2] { data1, data2 }, loggerFactory)
{
}
}
public class SingleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain
{
public SingleStateTransactionalGrain(
[TransactionalState("data", TransactionTestConstants.TransactionStore)]
ITransactionalState<BitArrayState> data,
ILoggerFactory loggerFactory)
: base(new ITransactionalState<BitArrayState>[1] { data }, loggerFactory)
{
}
}
public class MultiStateTransactionalBitArrayGrain : Grain, ITransactionalBitArrayGrain
{
protected ITransactionalState<BitArrayState>[] dataArray;
private readonly ILoggerFactory loggerFactory;
protected ILogger logger;
public MultiStateTransactionalBitArrayGrain(
ITransactionalState<BitArrayState>[] dataArray,
ILoggerFactory loggerFactory)
{
this.dataArray = dataArray;
this.loggerFactory = loggerFactory;
}
public override Task OnActivateAsync()
{
this.logger = this.loggerFactory.CreateLogger(this.GetGrainIdentity().ToString());
this.logger.LogTrace($"GrainId : {this.GetPrimaryKey()}.");
return base.OnActivateAsync();
}
public Task Ping()
{
return Task.CompletedTask;
}
public Task SetBit(int index)
{
return Task.WhenAll(this.dataArray
.Select(data => data.PerformUpdate(state =>
{
this.logger.LogTrace($"Setting bit {index} in state {state}. Transaction {TransactionContext.CurrentTransactionId}");
state.Set(index, true);
this.logger.LogTrace($"Set bit {index} in state {state}.");
})));
}
public async Task<List<BitArrayState>> Get()
{
return (await Task.WhenAll(this.dataArray
.Select(state => state.PerformRead(s =>
{
this.logger.LogTrace($"Get state {s}.");
return s;
})))).ToList();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualNetworkGatewaysOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewaysOperations
{
/// <summary>
/// The Put VirtualNetworkGateway operation creates/updates a virtual
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Virtual Network
/// Gateway operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Put VirtualNetworkGateway operation creates/updates a virtual
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Virtual Network
/// Gateway operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Get VirtualNetworkGateway operation retrieves information
/// about the specified virtual network gateway through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Delete VirtualNetworkGateway operation deletes the specified
/// virtual network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Delete VirtualNetworkGateway operation deletes the specified
/// virtual network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGateways operation retrieves all the
/// virtual network gateways stored.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Reset VirtualNetworkGateway operation resets the primary of
/// the virtual network gateway in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the Begin Reset of
/// Active-Active feature enabled Gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Reset VirtualNetworkGateway operation resets the primary of
/// the virtual network gateway in the specified resource group
/// through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the Begin Reset of
/// Active-Active feature enabled Gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Generatevpnclientpackage operation generates Vpn client
/// package for P2S client of the virtual network gateway in the
/// specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Generating Virtual Network
/// Gateway Vpn client package operation through Network resource
/// provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The List VirtualNetworkGateways operation retrieves all the
/// virtual network gateways stored.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
#if UNITY_WSA && !UNITY_EDITOR
using System.Threading.Tasks;
#endif
namespace Foundation
{
/// <summary>
/// The Injector is a static application service for resolving dependencies by asking for a components type or interface
/// </summary>
public class Injector
{
#region container
/// <summary>
/// represents a injection subscriber
/// </summary>
protected class InjectSubscription
{
/// <summary>
/// ValueType of the export
/// </summary>
public readonly Type MemberType;
/// <summary>
/// Optional lookup key
/// </summary>
public string InjectKey { get; private set; }
/// <summary>
/// Is there an optional lookup key ?
/// </summary>
public bool HasKey
{
get
{
return !string.IsNullOrEmpty(InjectKey);
}
}
/// <summary>
/// Importing Member
/// </summary>
public readonly MemberInfo Member;
/// <summary>
/// Importing instance
/// </summary>
/// <remarks>
/// Handler target
/// </remarks>
public readonly object Instance;
public InjectSubscription(Type mtype, object instance, MemberInfo member)
{
MemberType = mtype;
Member = member;
Instance = instance;
}
public InjectSubscription(Type mtype, object instance, MemberInfo member, string key)
{
MemberType = mtype;
Member = member;
Instance = instance;
InjectKey = key;
}
}
/// <summary>
/// represents a injection export
/// </summary>
protected class InjectExport
{
/// <summary>
/// ValueType of the export
/// </summary>
public readonly Type MemberType;
/// <summary>
/// Importing instance
/// </summary>
/// <remarks>
/// Handler target
/// </remarks>
public readonly object Instance;
/// <summary>
/// Optional lookup key
/// </summary>
public string InjectKey { get; private set; }
/// <summary>
/// Is there an optional lookup key ?
/// </summary>
public bool HasKey
{
get
{
return !string.IsNullOrEmpty(InjectKey);
}
}
public InjectExport(Type mtype, object instance)
{
MemberType = mtype;
Instance = instance;
}
public InjectExport(Type mtype, object instance, string key)
{
MemberType = mtype;
Instance = instance;
InjectKey = key;
}
}
/// <summary>
/// delegates
/// </summary>
static readonly List<InjectSubscription> Subscriptions = new List<InjectSubscription>();
/// <summary>
/// delegates
/// </summary>
static readonly List<InjectExport> Exports = new List<InjectExport>();
static readonly List<InjectSubscription> LateImports = new List<InjectSubscription>();
/// <summary>
/// determines if the subscription should be invoked
/// </summary>
/// <returns></returns>
static IEnumerable<InjectExport> GetExports(Type memberType, string key)
{
if (!string.IsNullOrEmpty(key))
{
return Exports.Where(o => (o.HasKey && o.InjectKey == key));
}
return
Exports.Where(o =>
// is message type
memberType == o.MemberType
// or handler is an interface of message
#if UNITY_WSA && !UNITY_EDITOR
|| (memberType.GetTypeInfo().IsAssignableFrom(o.MemberType.GetTypeInfo())));
#else
|| (memberType.IsAssignableFrom(o.MemberType)));
#endif
}
/// <summary>
/// determines if the subscription should be invoked
/// </summary>
/// <returns></returns>
static IEnumerable<InjectSubscription> GetSubscriptionsFor(InjectExport export)
{
if (export.HasKey)
{
return Subscriptions.Where(o => (o.HasKey && o.InjectKey == export.InjectKey));
}
#if UNITY_WSA && !UNITY_EDITOR
return
Subscriptions.Where(o =>
// is message type
o.MemberType == export.MemberType
// or handler is an interface of message
|| (o.MemberType.GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
// support for GetAll
// ReSharper disable once PossibleNullReferenceException
|| (o.MemberType.IsArray && o.MemberType.GetElementType().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
|| (o.MemberType.GetTypeInfo().IsGenericType && o.MemberType.GetTypeInfo().GenericTypeArguments.First().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo())));
#else
return
Subscriptions.Where(o =>
// is message type
o.MemberType == export.MemberType
// or handler is an interface of message
|| (o.MemberType.IsAssignableFrom(export.MemberType))
// support for GetAll
// ReSharper disable once PossibleNullReferenceException
|| (o.MemberType.IsArray && o.MemberType.GetElementType().IsAssignableFrom(export.MemberType))
|| (o.MemberType.IsGenericType && o.MemberType.GetGenericArguments().First().IsAssignableFrom(export.MemberType)));
#endif
}
static IEnumerable<InjectSubscription> GetLateImportsFor(InjectExport export)
{
if (export.HasKey)
return LateImports.Where(o => o.HasKey && o.InjectKey == export.InjectKey);
#if UNITY_WSA && !UNITY_EDITOR
return
LateImports.Where(o =>
o.MemberType == export.MemberType
|| (o.MemberType.GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
|| (o.MemberType.IsArray && o.MemberType.GetElementType().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo()))
|| (o.MemberType.GetTypeInfo().IsGenericType && o.MemberType.GetTypeInfo().GenericTypeArguments.First().GetTypeInfo().IsAssignableFrom(export.MemberType.GetTypeInfo())));
#else
return LateImports
.Where(o => o.MemberType == export.MemberType
|| o.MemberType.IsAssignableFrom(export.MemberType)
|| (o.MemberType.IsArray && o.MemberType.GetElementType().IsAssignableFrom(export.MemberType))
|| (o.MemberType.IsGenericType && o.MemberType.GetGenericArguments().First().IsAssignableFrom(export.MemberType)));
#endif
}
#endregion
#region ctor
static Injector()
{
InjectorInitialized.LoadServices();
}
/// <summary>
/// Initializes the injector.
/// </summary>
public static void ConfirmInit()
{
}
#endregion
#region exporting
/// <summary>
/// Adds the instance to the export container.
/// Will publish to pending imports
/// </summary>
/// <param name="instance">The instance to add</param>
public static void AddExport(object instance)
{
// add as self
var type = instance.GetType();
#if UNITY_WSA && !UNITY_EDITOR
if (type.IsGenericParameter || type.IsArray)
#else
if (type.IsGenericType || type.IsArray)
#endif
{
Debug.LogError("Generics and Arrays are not valid exports. Export individually or a container.");
return;
}
if (Exports.Any(o => o.Instance == instance))
Debug.LogWarning("Export is being added multiple times ! " + instance.GetType());
var key = type.GetAttribute<ExportAttribute>();
// add to container
var e = new InjectExport(type, instance, key == null ? null : key.InjectKey);
Exports.Add(e);
// notify imports
foreach (var sub in GetSubscriptionsFor(e))
{
Import(sub.Instance, sub.Member, sub.InjectKey);
}
// can't modify the list while inside foreach, will throw a exception
var toRemove = new List<InjectSubscription>();
// Check for late imports and resolve it
foreach (InjectSubscription late in GetLateImportsFor(e))
{
Import(late.Instance, late.Member, late.InjectKey);
toRemove.Add(late);
}
LateImports.RemoveAll(subscription => toRemove.Contains(subscription));
}
/// <summary>
/// Removes the instance to the container.
/// Will publish changes to imports
/// </summary>
/// <param name="instance">The instance to remove</param>
public static void RemoveExport(object instance)
{
// get exports
var es = Exports.Where(o => o.Instance == instance).ToArray();
//remove
Exports.RemoveAll(o => o.Instance == instance);
// clean up publish
for (int index = 0;index < es.Length;index++)
{
var export = es[index];
// notify imports
foreach (var sub in GetSubscriptionsFor(export))
{
Clear(sub.Instance, sub.Member);
}
}
}
#endregion
#region importing
/// <summary>
/// Will import to member fields/properties with Import Attribute
/// </summary>
/// <param name="instance"></param>
public static void Import(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetTypeInfo().DeclaredFields.Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetTypeInfo().DeclaredProperties.Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0; i < fields.Length; i++)
{
Import(instance, fields[i], fields[i].GetAttribute<ImportAttribute>().InjectKey);
}
for (int i = 0; i < props.Length; i++)
{
Import(instance, props[i], props[i].GetAttribute<ImportAttribute>().InjectKey);
}
CheckForLateImports(instance);
}
/// <summary>
/// Will inject instance into member
/// </summary>
static void Import(object instance, MemberInfo member, string key)
{
// get member type
var memberType = member.GetMemberType();
if (memberType.IsArray)
{
// get array type
var type = memberType.GetElementType();
// ReSharper disable once AssignNullToNotNullAttribute
var arg = GetExports(type, key).Select(o => ConvertTo(o.Instance, type)).ToArray();
// ReSharper disable once AssignNullToNotNullAttribute
var a = Array.CreateInstance(type, arg.Length);
Array.Copy(arg, a, arg.Length);
member.SetMemberValue(instance, a);
}
#if UNITY_WSA && !UNITY_EDITOR
else if (memberType.GetTypeInfo().IsGenericType)
#else
else if (memberType.IsGenericType)
#endif
{
#if UNITY_WSA && !UNITY_EDITOR
var type = memberType.GetTypeInfo().GenericTypeArguments.First();
#else
var type = memberType.GetGenericArguments().First();
#endif
//get enumerable generic type
#if UNITY_WSA && !UNITY_EDITOR
if (memberType.GetTypeInfo().IsInterface)
#else
if (memberType.IsInterface)
#endif
{
var arg = GetExports(type, key).Select(o => ConvertTo(o.Instance, type)).ToArray();
var a = Array.CreateInstance(type, arg.Length);
Array.Copy(arg, a, arg.Length);
member.SetMemberValue(instance, a);
}
else
{
Debug.LogError("Injecting into non-Array / non-IEnumerable not supported.");
}
}
else
{
var arg = GetExports(memberType, key).FirstOrDefault();
if (arg != null)
member.SetMemberValue(instance, arg.Instance);
}
}
static void CheckForLateImports(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetTypeInfo().DeclaredFields.Where(o => o.HasAttribute<LateImportAttribute>()).ToArray();
var props = instance.GetType().GetTypeInfo().DeclaredProperties.Where(o => o.HasAttribute<LateImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<LateImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<LateImportAttribute>()).ToArray();
#endif
for (int i = 0; i < fields.Length; i++)
{
var lateInject = fields[i].GetAttribute<LateImportAttribute>();
if (HasExport(fields[i].FieldType))
Import(instance, fields[i], lateInject.InjectKey);
else
LateImports.Add(new InjectSubscription(fields[i].GetMemberType(), instance, fields[i], lateInject.InjectKey == null ? null : lateInject.InjectKey));
}
for (int i = 0; i < props.Length; i++)
{
var lateInject = props[i].GetAttribute<LateImportAttribute>();
if (HasExport(props[i].PropertyType))
Import(instance, props[i], lateInject.InjectKey);
else
LateImports.Add(new InjectSubscription(props[i].GetMemberType(), instance, props[i], lateInject.InjectKey == null ? null : lateInject.InjectKey));
}
}
static object ConvertTo(object instance, Type type)
{
#if UNITY_WSA && !UNITY_EDITOR
if (type.GetTypeInfo().IsInterface)
#else
if (type.IsInterface)
#endif
{
return instance;
}
// ReSharper disable once AssignNullToNotNullAttribute
return Convert.ChangeType(instance, type);
}
/// <summary>
/// Will set value to null
/// </summary>
public static void Clear(object instance, MemberInfo member)
{
member.SetMemberValue(instance, null);
}
#endregion
#region Resolving
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static bool HasExport<T>()
{
var t = typeof(T);
return HasExport(t);
}
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <returns></returns>
public static bool HasExport(Type t)
{
#if UNITY_WSA && !UNITY_EDITOR
return Exports.Any(o => o.MemberType == t || (o.MemberType.GetTypeInfo().IsAssignableFrom(t.GetTypeInfo())));
#else
return Exports.Any(o => o.MemberType == t || (t.IsAssignableFrom(o.MemberType)));
#endif
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetFirst<T>()
{
return (T)GetFirst(typeof(T));
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <returns></returns>
public static object GetFirst(Type t)
{
var es = GetExports(t, null).ToArray();
if (es.Count() > 1)
{
Debug.LogWarning("Multiple exports of type : " + t);
}
if (!es.Any())
{
return null;
}
return es.First().Instance;
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<T> GetAll<T>()
{
return GetAll(typeof(T)).Cast<T>();
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<object> GetAll(Type t)
{
return GetExports(t, null).Select(o => o.Instance).ToArray();
}
/// <summary>
/// Returns true if the container contains any T
/// </summary>
/// <returns></returns>
public static bool HasExport(string key)
{
return Exports.Any(o => o.HasKey && o.InjectKey == key);
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetFirst<T>(string key)
{
return (T)GetFirst(key);
}
/// <summary>
/// returns the first instance of T
/// </summary>
/// <returns></returns>
public static object GetFirst(string key)
{
var es = Exports.Where(o => o.HasKey && o.InjectKey == key).ToArray();
if (es.Count() > 1)
{
Debug.LogWarning("Multiple exports of key : " + key);
}
if (!es.Any())
{
return null;
}
return es.First().Instance;
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<T> GetAll<T>(string key)
{
return GetAll(typeof(T)).Cast<T>();
}
/// <summary>
/// Returns all instances of T
/// </summary>
/// <returns></returns>
public static IEnumerable<object> GetAll(string key)
{
return Exports.Where(o => o.HasKey && o.InjectKey == key).Select(o => o.Instance).ToArray();
}
#endregion
#region subscribing
/// <summary>
/// Will subscribe members for late injection
/// </summary>
/// <param name="instance"></param>
public static void Subscribe(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetRuntimeFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetRuntimeProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0;i < fields.Length;i++)
{
Subscribe(instance, fields[i]);
}
for (int i = 0;i < props.Length;i++)
{
Subscribe(instance, props[i]);
}
}
/// <summary>
/// Will subscribe instance into member
/// </summary>
public static void Subscribe(object instance, MemberInfo member)
{
//Import First
var key = member.GetAttribute<ImportAttribute>();
Import(instance, member, key == null ? null : key.InjectKey);
var a = member.GetCustomAttributes(typeof(ImportAttribute), true).Cast<ImportAttribute>().FirstOrDefault();
// add subscription
Subscriptions.Add(new InjectSubscription(member.GetMemberType(), instance, member, a == null ? null : a.InjectKey));
}
/// <summary>
/// Will unsubscribe from late injection
/// </summary>
/// <param name="instance"></param>
public static void UnSubscribe(object instance)
{
#if UNITY_WSA && !UNITY_EDITOR
var fields = instance.GetType().GetRuntimeFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetRuntimeProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#else
var fields = instance.GetType().GetFields().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
var props = instance.GetType().GetProperties().Where(o => o.HasAttribute<ImportAttribute>()).ToArray();
#endif
for (int i = 0;i < fields.Length;i++)
{
fields[i].SetValue(instance, null);
}
for (int i = 0;i < props.Length;i++)
{
props[i].SetValue(instance, null, null);
}
Subscriptions.RemoveAll(o => o.Instance == instance);
}
/// <summary>
/// Will remove instance member subscription
/// </summary>
public static void UnSubscribe(object instance, MemberInfo member)
{
//Remove Imports First
Clear(instance, member);
//remove
Subscriptions.RemoveAll(o => o.Instance == instance && Equals(o.Member, member));
}
#endregion
}
}
| |
/*******************************************************************************
*
* Copyright (C) 2013-2014 Frozen North Computing
*
* 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.Drawing;
namespace FrozenNorth.OpenGL.FN2D
{
public enum FN2DTessellation
{
CoreFade = 0,
Core = 1,
OuterFade = 2,
InnerFade = 3
}
public enum FN2DLineCap
{
Butt = 0,
Round = 1,
Square = 2,
Rect = 3
}
public enum FN2DLineJoin
{
Miter = 0,
Bevel = 1,
Round = 2
}
public class FN2DPolyLine
{
private const float ApproximationCutoff = 1.6f;
protected List<Point> points = new List<Point>();
protected Color color;
protected float width;
protected FN2DTessellation tessellation;
protected FN2DLineJoin lineJoin;
protected FN2DLineCap startCap;
protected FN2DLineCap endCap;
public FN2DPolyLine(Color color, float width, FN2DTessellation tessellation, FN2DLineJoin lineJoin,
FN2DLineCap startCap, FN2DLineCap endCap)
{
this.color = color;
this.width = width;
this.tessellation = tessellation;
this.lineJoin = lineJoin;
this.startCap = startCap;
this.endCap = endCap;
}
double PointLength(Point p)
{
return Math.Sqrt(p.X * p.X + p.Y * p.Y);
}
double PointNormalize(Point p)
{
double length = PointLength(p);
if (length > double.Epsilon)
{
p.X /= length;
p.Y /= length;
}
return length;
}
public void Refresh()
{
if (width < ApproximationCutoff)
{
Exact();
return;
}
int a = 0;
int b = 0;
bool on = false;
for (int i = 1; i < points.Count - 1; i++)
{
Point v1 = points[i] - points[i - 1];
Point v2 = points[i + 1] - points[i];
double len = PointNormalize(v1) * 0.5;
len += PointNormalize(v2) * 0.5;
double costho = v1.X * v2.X + v1.Y * v2.Y;
const double cos_a = Math.Cos(15 * Math.PI / 180);
const double cos_b = Math.Cos(10 * Math.PI / 180);
const double cos_c = Math.Cos(25 * Math.PI / 180);
bool approx = (width < 7 && costho > cos_a) || (costho > cos_b) || (len < width && costho > cos_c);
if (approx && !on)
{
a = (i == 1) ? 0 : i;
on = true;
if (a > 1)
Range(b, a, false);
}
else if (!approx && on)
{
b = i;
on = false;
Range(a, b, true);
}
}
if (on && b < points.Count - 1)
{
b = points.Count - 1;
Range(a, b, true);
}
else if (!on && a < points.Count - 1)
{
a = points.Count - 1;
Range(b, a, false);
}
}
private Point PointInter(int index, double t)
{
if (t == 0)
{
return points[index];
}
if (t == 1)
{
return points[index + 1];
}
return new Point(points[index].X * points[index + 1].X * t, points[index].Y * points[index + 1].Y * t);
}
private void Exact()
{
Point mid_l, mid_n; //the last and the next mid point
Color c_l, c_n;
double w_l, w_n;
mid_l = PointInter(0, 0.5);
st_anchor SA;
if (points.Count == 2)
{
segment();
}
else
{
for (int i = 1; i < points.Count - 1; i++)
{
if ( i==size_of_P-2 && !join_last)
mid_n = PointInter(i, 1.0);
else
mid_n = PointInter(i, 0.5);
SA.P[0]=mid_l.vec(); SA.C[0]=c_l; SA.W[0]=w_l;
SA.P[2]=mid_n.vec(); SA.C[2]=c_n; SA.W[2]=w_n;
SA.P[1]=P[i];
SA.C[1]=color(i);
SA.W[1]=weight(i);
anchor( SA, opt, i==1&&cap_first, i==size_of_P-2&&cap_last);
mid_l = mid_n;
c_l = c_n;
w_l = w_n;
}
}
//draw or not
if( opt && opt->tess && opt->tess->tessellate_only && opt->tess->holder)
(*(vertex_array_holder*)opt->tess->holder).push(SA.vah);
else
SA.vah.draw();
//draw triangles
if( opt && opt->tess && opt->tess->triangulation)
SA.vah.draw_triangles();
}
//the struct to hold info for anchor_late() to perform triangluation
private class PolyLine
{
//for all joints
Point vP; //vector to intersection point
Point vR; //fading vector at sharp end
//all vP,vR are outward
//for djoint==PLJ_bevel
Point T; //core thickness of a line
Point R; //fading edge of a line
Point bR; //out stepping vector, same direction as cap
Point T1,R1; //alternate vectors, same direction as T21
//all T,R,T1,R1 are outward
//for djoint==PLJ_round
float t,r;
//for degeneration case
bool degenT; //core degenerated
bool degenR; //fade degenerated
bool pre_full; //draw the preceding segment in full
Point PT,PR;
float pt; //parameter at intersection
bool R_full_degen;
char djoint; //determined joint
// e.g. originally a joint is PLJ_miter. but it is smaller than critical angle, should then set djoint to PLJ_bevel
}
private class Anchor
{
Point P = new Point[3];
Point cap_start, cap_end;
PolyLine SL = new PolyLine[3];
vertex_array_holder vah;
}
}
}
| |
// 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 DuplicateOddIndexedSingle()
{
var test = new SimpleUnaryOpTest__DuplicateOddIndexedSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// 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();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
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 SimpleUnaryOpTest__DuplicateOddIndexedSingle
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data = new Single[ElementCount];
private static Vector256<Single> _clsVar;
private Vector256<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single> _dataTable;
static SimpleUnaryOpTest__DuplicateOddIndexedSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__DuplicateOddIndexedSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single>(_data, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.DuplicateOddIndexed(
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.DuplicateOddIndexed(
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.DuplicateOddIndexed(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.DuplicateOddIndexed), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.DuplicateOddIndexed(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr);
var result = Avx.DuplicateOddIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.DuplicateOddIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.DuplicateOddIndexed(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__DuplicateOddIndexedSingle();
var result = Avx.DuplicateOddIndexed(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.DuplicateOddIndexed(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(firstOp[1]) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < firstOp.Length; i++)
{
if ((i % 2 == 0) ? (BitConverter.SingleToInt32Bits(firstOp[i + 1]) != BitConverter.SingleToInt32Bits(result[i])) : (BitConverter.SingleToInt32Bits(firstOp[i]) != BitConverter.SingleToInt32Bits(result[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.DuplicateOddIndexed)}<Single>: {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
//using log4net;
namespace Rawr
{
public static class ItemIcons
{
//private static readonly ILog log = LogManager.GetLogger(typeof(ItemIcons));
private static ImageList _largeIcons = null;
public static ImageList LargeIcons
{
get
{
if (_largeIcons == null)
{
_largeIcons = new ImageList();
_largeIcons.ImageSize = new Size(64, 64);
_largeIcons.ColorDepth = ColorDepth.Depth24Bit;
}
return _largeIcons;
}
}
private static ImageList _smallIcons = null;
public static ImageList SmallIcons
{
get
{
if (_smallIcons == null)
{
_smallIcons = new ImageList();
_smallIcons.ImageSize = new Size(32, 32);
_smallIcons.ColorDepth = ColorDepth.Depth24Bit;
}
return _smallIcons;
}
}
private static ImageList _talentIcons = null;
public static ImageList TalentIcons
{
get
{
if (_talentIcons == null)
{
_talentIcons = new ImageList();
_talentIcons.ImageSize = new Size(33, 35);
//_talentIcons.ImageSize = new Size(45, 47);
_talentIcons.ColorDepth = ColorDepth.Depth24Bit;
}
return _talentIcons;
}
}
private static Dictionary<string, Image> _talentTreeBackgrounds = null;
public static Dictionary<string, Image> TalentTreeBackgrounds
{
get
{
if (_talentTreeBackgrounds == null)
{
_talentTreeBackgrounds = new Dictionary<string, Image>();
}
return _talentTreeBackgrounds;
}
}
public static void CacheAllIcons(Item[] items)
{
StatusMessaging.UpdateStatus("Cache Item Icons", "Caching all Item Icons");
WebRequestWrapper webRequests = new WebRequestWrapper();
List<string> filesDownloading = new List<string>();
for(int i=0;i<items.Length && !WebRequestWrapper.LastWasFatalError;i++)
{
string iconName = items[i].IconPath.Replace(".png", "").Replace(".jpg", "").ToLower();
webRequests.DownloadItemIconAsync(iconName);
}
while (webRequests.RequestQueueCount > 0 && !WebRequestWrapper.LastWasFatalError)
{
Thread.Sleep(200);
}
//TODO: Display any error information appropriotly here,
//such as, proxy information incorrect or network connection down. Can get pretty detailed about exactly what went
//wrong by analyzing the exception.
if (WebRequestWrapper.LastWasFatalError)
{
StatusMessaging.ReportError("Cache All Icons", null, "There was an error trying to retrieve images from the armory. Please check your proxy settings and network connection.");
}
StatusMessaging.UpdateStatusFinished("Cache Item Icons");
}
public static Image GetItemIcon(Item item)
{
return GetItemIcon(item, false);
}
public static Image GetItemIcon(Item item, bool small)
{
return GetItemIcon(item.IconPath, small);
}
public static Image GetItemIcon(string iconPath)
{
return GetItemIcon(iconPath, false);
}
public static Image GetItemIcon(string iconName, bool small)
{
Image returnImage = null;
iconName = iconName.Replace(".png", "").Replace(".jpg", "").ToLower();
if (small && SmallIcons.Images.ContainsKey(iconName))
{
returnImage = SmallIcons.Images[iconName];
}
else if (!small && LargeIcons.Images.ContainsKey(iconName))
{
returnImage = LargeIcons.Images[iconName];
}
else
{
string pathToIcon = null;
WebRequestWrapper wrapper = null;
try
{
wrapper = new WebRequestWrapper();
if (!String.IsNullOrEmpty(iconName))
{
pathToIcon = wrapper.DownloadItemIcon(iconName);
//just in case the network code is in a disconnected mode. (e.g. no network traffic sent, so no network exception)
}
if (pathToIcon == null)
{
pathToIcon = wrapper.DownloadTempImage();
}
}
catch (Exception)
{
try
{
pathToIcon = wrapper.DownloadTempImage();
}
catch (Exception)
{
}
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
//log.Error("Exception trying to retrieve an icon from the armory", ex);
}
if (!String.IsNullOrEmpty(pathToIcon))
{
int retry = 0;
do
{
try
{
using (Stream fileStream = File.Open(pathToIcon, FileMode.Open, FileAccess.Read, FileShare.Read))
{
returnImage = Image.FromStream(fileStream);
}
}
catch
{
returnImage = null;
//possibly still downloading, give it a second
Thread.Sleep(TimeSpan.FromSeconds(1));
if (retry >= 3)
{
//log.Error("Exception trying to load an icon from local", ex);
MessageBox.Show(
"Rawr encountered an error while attempting to load a saved image. If you encounter this error multiple times, please ensure that Rawr is unzipped in a location that you have full file read/write access, such as your Desktop, or My Documents.");
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
#if DEBUG
throw;
#endif
}
}
retry++;
} while (returnImage == null && retry < 5);
if (returnImage != null)
{
if (small)
{
returnImage = ScaleByPercent(returnImage, 50);
SmallIcons.Images.Add(iconName, returnImage);
}
else
{
LargeIcons.Images.Add(iconName, returnImage);
}
}
}
}
return returnImage;
}
public static Image GetTalentIcon(CharacterClass charClass, string talentTree, string talentName, string icon)
{
Image returnImage = null;
string key = string.Format("{0}-{1}-{2}", charClass, talentTree, talentName);
if (TalentIcons.Images.ContainsKey(key))
{
returnImage = TalentIcons.Images[key];
}
else
{
string pathToIcon = null;
WebRequestWrapper wrapper = new WebRequestWrapper();
try
{
if (!string.IsNullOrEmpty(talentTree) && !string.IsNullOrEmpty(talentName))
{
pathToIcon = wrapper.DownloadTalentIcon(charClass, talentTree, talentName, icon);
//just in case the network code is in a disconnected mode. (e.g. no network traffic sent, so no network exception)
}
if (pathToIcon == null)
{
pathToIcon = wrapper.DownloadTempImage();
}
}
catch (Exception /*ex*/)
{
/*Rawr.Base.ErrorBox eb = new Rawr.Base.ErrorBox("Error Getting Talent Icon",
ex.Message, "GetTalentIcon(...)",
string.Format("\r\n- Talent Tree: {0}\r\n- Talent Name: {1}\r\n- Icon: {2}\r\n- PathToIcon: {3}", talentTree, talentName, icon, pathToIcon ?? (pathToIcon = "null")),
ex.StackTrace);*/
pathToIcon = wrapper.DownloadTempImage();
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
//log.Error("Exception trying to retrieve an icon from the armory", ex);
}
if (!string.IsNullOrEmpty(pathToIcon))
{
int retry = 0;
do
{
try
{
using (Stream fileStream = File.Open(pathToIcon, FileMode.Open, FileAccess.Read, FileShare.Read))
{
returnImage = Image.FromStream(fileStream);
}
}
catch
{
returnImage = null;
//possibly still downloading, give it a second
Thread.Sleep(TimeSpan.FromSeconds(1));
if (retry >= 3)
{
//log.Error("Exception trying to load an icon from local", ex);
MessageBox.Show(
"Rawr encountered an error while attempting to load a saved image. If you encounter this error multiple times, please ensure that Rawr is unzipped in a location that you have full file read/write access, such as your Desktop, or My Documents.");
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
#if DEBUG
throw;
#endif
}
}
retry++;
} while (returnImage == null && retry < 5);
if (returnImage != null)
{
returnImage = Offset(returnImage, new Size(4, 4));
TalentIcons.Images.Add(key, returnImage);
}
}
}
return returnImage;
}
public static Image GetTalentTreeBackground(CharacterClass charClass, string talentTree)
{
Image returnImage = null;
string key = string.Format("{0}-{1}", charClass, talentTree);
if (TalentTreeBackgrounds.ContainsKey(key))
{
returnImage = TalentTreeBackgrounds[key];
}
else
{
string pathToIcon = null;
try
{
WebRequestWrapper wrapper = new WebRequestWrapper();
if (!string.IsNullOrEmpty(talentTree))
{
pathToIcon = wrapper.DownloadTalentIcon(charClass, talentTree);
//just in case the network code is in a disconnected mode. (e.g. no network traffic sent, so no network exception)
}
if (pathToIcon == null)
{
pathToIcon = wrapper.DownloadTempImage();
}
}
catch (Exception)
{
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
//log.Error("Exception trying to retrieve an icon from the armory", ex);
}
if (!string.IsNullOrEmpty(pathToIcon))
{
int retry = 0;
do
{
try
{
using (Stream fileStream = File.Open(pathToIcon, FileMode.Open, FileAccess.Read, FileShare.Read))
{
returnImage = Image.FromStream(fileStream);
}
}
catch
{
returnImage = null;
//possibly still downloading, give it a second
Thread.Sleep(TimeSpan.FromSeconds(1));
if (retry >= 3)
{
//log.Error("Exception trying to load an icon from local", ex);
MessageBox.Show(
"Rawr encountered an error while attempting to load a saved image. If you encounter this error multiple times, please ensure that Rawr is unzipped in a location that you have full file read/write access, such as your Desktop, or My Documents.");
//Log.Write(ex.Message);
//Log.Write(ex.StackTrace);
#if DEBUG
throw;
#endif
}
}
retry++;
} while (returnImage == null && retry < 5);
if (returnImage != null)
{
TalentTreeBackgrounds.Add(key, returnImage);
}
}
}
return returnImage;
}
private static Image Offset(Image img, Size offset)
{
int smallCheck = (img.Width < 40 ? 10 : 0);
Bitmap bmp = new Bitmap(img.Width + offset.Width + smallCheck, img.Height + offset.Height + smallCheck, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bmp);
g.DrawImageUnscaled(img, offset.Width, offset.Height);
g.Dispose();
return bmp;
}
private static Image ScaleByPercent(Image img, int Percent)
{
float nPercent = ((float) Percent/100);
int sourceWidth = img.Width;
int sourceHeight = img.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int destWidth = (int) (sourceWidth*nPercent);
int destHeight = (int) (sourceHeight*nPercent);
Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
PixelFormat.Format24bppRgb);
if(Type.GetType("Mono.Runtime") == null){
// Only run this on .NET platforms. It breaks Mono 2.4+
bmPhoto.SetResolution(img.HorizontalResolution,
img.VerticalResolution);
}
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(img,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
}
}
| |
// ***********************************************************************
// 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.
// ***********************************************************************
using System;
using System.IO;
using System.Text;
using System.Collections;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
using NUnit.Framework;
namespace NUnitLite.Runner
{
/// <summary>
/// The CommandLineOptions class parses and holds the values of
/// any options entered at the command line.
/// </summary>
public class CommandLineOptions
{
private string optionChars;
private static string NL = NUnit.Env.NewLine;
private bool wait = false;
private bool noheader = false;
private bool help = false;
private bool full = false;
private bool explore = false;
private bool labelTestsInOutput = false;
private string exploreFile;
private string resultFile;
private string resultFormat;
private string outFile;
private string includeCategory;
private string excludeCategory;
private bool error = false;
private StringList tests = new StringList();
private StringList invalidOptions = new StringList();
private StringList parameters = new StringList();
private int randomSeed = -1;
#region Properties
/// <summary>
/// Gets a value indicating whether the 'wait' option was used.
/// </summary>
public bool Wait
{
get { return wait; }
}
/// <summary>
/// Gets a value indicating whether the 'nologo' option was used.
/// </summary>
public bool NoHeader
{
get { return noheader; }
}
/// <summary>
/// Gets a value indicating whether the 'help' option was used.
/// </summary>
public bool ShowHelp
{
get { return help; }
}
/// <summary>
/// Gets a list of all tests specified on the command line
/// </summary>
public string[] Tests
{
get { return (string[])tests.ToArray(); }
}
/// <summary>
/// Gets a value indicating whether a full report should be displayed
/// </summary>
public bool Full
{
get { return full; }
}
/// <summary>
/// Gets a value indicating whether tests should be listed
/// rather than run.
/// </summary>
public bool Explore
{
get { return explore; }
}
/// <summary>
/// Gets the name of the file to be used for listing tests
/// </summary>
public string ExploreFile
{
get { return exploreFile; }
}
/// <summary>
/// Gets the name of the file to be used for test results
/// </summary>
public string ResultFile
{
get { return resultFile; }
}
/// <summary>
/// Gets the format to be used for test results
/// </summary>
public string ResultFormat
{
get { return resultFormat; }
}
/// <summary>
/// Gets the full path of the file to be used for output
/// </summary>
public string OutFile
{
get
{
return outFile;
}
}
/// <summary>
/// Gets the list of categories to include
/// </summary>
public string Include
{
get
{
return includeCategory;
}
}
/// <summary>
/// Gets the list of categories to exclude
/// </summary>
public string Exclude
{
get
{
return excludeCategory;
}
}
/// <summary>
/// Gets a flag indicating whether each test should
/// be labeled in the output.
/// </summary>
public bool LabelTestsInOutput
{
get { return labelTestsInOutput; }
}
private string ExpandToFullPath(string path)
{
if (path == null) return null;
#if NETCF
return Path.Combine(NUnit.Env.DocumentFolder, path);
#else
return Path.GetFullPath(path);
#endif
}
/// <summary>
/// Gets the test count
/// </summary>
public int TestCount
{
get { return tests.Count; }
}
/// <summary>
/// Gets the seed to be used for generating random values
/// </summary>
public int InitialSeed
{
get
{
if (randomSeed < 0)
randomSeed = new Random().Next();
return randomSeed;
}
}
#endregion
/// <summary>
/// Construct a CommandLineOptions object using default option chars
/// </summary>
public CommandLineOptions()
{
this.optionChars = System.IO.Path.DirectorySeparatorChar == '/' ? "-" : "/-";
}
/// <summary>
/// Construct a CommandLineOptions object using specified option chars
/// </summary>
/// <param name="optionChars"></param>
public CommandLineOptions(string optionChars)
{
this.optionChars = optionChars;
}
/// <summary>
/// Parse command arguments and initialize option settings accordingly
/// </summary>
/// <param name="args">The argument list</param>
public void Parse(params string[] args)
{
foreach( string arg in args )
{
if (optionChars.IndexOf(arg[0]) >= 0 )
ProcessOption(arg);
else
ProcessParameter(arg);
}
}
/// <summary>
/// Gets the parameters provided on the commandline
/// </summary>
public string[] Parameters
{
get { return (string[])parameters.ToArray(); }
}
private void ProcessOption(string option)
{
string opt = option;
int pos = opt.IndexOfAny( new char[] { ':', '=' } );
string val = string.Empty;
if (pos >= 0)
{
val = opt.Substring(pos + 1);
opt = opt.Substring(0, pos);
}
switch (opt.Substring(1))
{
case "wait":
wait = true;
break;
case "noheader":
case "noh":
noheader = true;
break;
case "help":
case "h":
help = true;
break;
case "test":
tests.Add(val);
break;
case "full":
full = true;
break;
case "explore":
explore = true;
if (val == null || val.Length == 0)
val = "tests.xml";
try
{
exploreFile = ExpandToFullPath(val);
}
catch
{
InvalidOption(option);
}
break;
case "result":
if (val == null || val.Length == 0)
val = "TestResult.xml";
try
{
resultFile = ExpandToFullPath(val);
}
catch
{
InvalidOption(option);
}
break;
case "format":
resultFormat = val;
if (resultFormat != "nunit3" && resultFormat != "nunit2")
InvalidOption(option);
break;
case "out":
try
{
outFile = ExpandToFullPath(val);
}
catch
{
InvalidOption(option);
}
break;
case "labels":
labelTestsInOutput = true;
break;
case "include":
includeCategory = val;
break;
case "exclude":
excludeCategory = val;
break;
case "seed":
try
{
randomSeed = int.Parse(val);
}
catch
{
InvalidOption(option);
}
break;
default:
InvalidOption(option);
break;
}
}
private void InvalidOption(string option)
{
error = true;
invalidOptions.Add(option);
}
private void ProcessParameter(string param)
{
parameters.Add(param);
}
/// <summary>
/// Gets a value indicating whether there was an error in parsing the options.
/// </summary>
/// <value><c>true</c> if error; otherwise, <c>false</c>.</value>
public bool Error
{
get { return error; }
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>The error message.</value>
public string ErrorMessage
{
get
{
StringBuilder sb = new StringBuilder();
foreach (string opt in invalidOptions)
sb.Append( "Invalid option: " + opt + NL );
return sb.ToString();
}
}
/// <summary>
/// Gets the help text.
/// </summary>
/// <value>The help text.</value>
public string HelpText
{
get
{
StringBuilder sb = new StringBuilder();
#if PocketPC || WindowsCE || NETCF || SILVERLIGHT
string name = "NUnitLite";
#else
string name = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
#endif
sb.Append("Usage: " + name + " [assemblies] [options]" + NL + NL);
sb.Append("Runs a set of NUnitLite tests from the console." + NL + NL);
sb.Append("You may specify one or more test assemblies by name, without a path or" + NL);
sb.Append("extension. They must be in the same in the same directory as the exe" + NL);
sb.Append("or on the probing path. If no assemblies are provided, tests in the" + NL);
sb.Append("executing assembly itself are run." + NL + NL);
sb.Append("Options:" + NL);
sb.Append(" -test:testname Provides the name of a test to run. This option may be" + NL);
sb.Append(" repeated. If no test names are given, all tests are run." + NL + NL);
sb.Append(" -out:FILE File to which output is redirected. If this option is not" + NL);
sb.Append(" used, output is to the Console, which means it is lost" + NL);
sb.Append(" on devices without a Console." + NL + NL);
sb.Append(" -full Prints full report of all test results." + NL + NL);
sb.Append(" -result:FILE File to which the xml test result is written." + NL + NL);
sb.Append(" -format:FORMAT Format in which the result is to be written. FORMAT must be" + NL);
sb.Append(" either nunit3 or nunit2. The default is nunit3." + NL + NL);
sb.Append(" -explore:FILE If provided, this option indicates that the tests" + NL);
sb.Append(" should be listed rather than executed. They are listed" + NL);
sb.Append(" to the specified file in XML format." + NL);
sb.Append(" -help,-h Displays this help" + NL + NL);
sb.Append(" -noheader,-noh Suppresses display of the initial message" + NL + NL);
sb.Append(" -labels Displays the name of each test when it starts" + NL + NL);
sb.Append(" -seed:SEED If provided, this option allows you to set the seed for the" + NL + NL);
sb.Append(" random generator in the test context." + NL + NL);
sb.Append(" -include:CAT List of categories to include" + NL + NL);
sb.Append(" -exclude:CAT List of categories to exclude" + NL + NL);
sb.Append(" -wait Waits for a key press before exiting" + NL + NL);
sb.Append("Notes:" + NL);
sb.Append(" * File names may be listed by themselves, with a relative path or " + NL);
sb.Append(" using an absolute path. Any relative path is based on the current " + NL);
sb.Append(" directory or on the Documents folder if running on a under the " +NL);
sb.Append(" compact framework." + NL + NL);
if (System.IO.Path.DirectorySeparatorChar != '/')
sb.Append(" * On Windows, options may be prefixed by a '/' character if desired" + NL + NL);
sb.Append(" * Options that take values may use an equal sign or a colon" + NL);
sb.Append(" to separate the option from its value." + NL + NL);
return sb.ToString();
}
}
#if CLR_2_0 || CLR_4_0
class StringList : List<string> { }
#else
class StringList : ArrayList
{
public new string[] ToArray()
{
return (string[])ToArray(typeof(string));
}
}
#endif
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Lucene.Net.Analysis.In
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Normalizes the Unicode representation of text in Indian languages.
/// <para>
/// Follows guidelines from Unicode 5.2, chapter 6, South Asian Scripts I
/// and graphical decompositions from http://ldc.upenn.edu/myl/IndianScriptsUnicode.html
/// </para>
/// </summary>
public class IndicNormalizer
{
// LUCENENET NOTE: This class was refactored from its Java couterpart,
// favoring the .NET Regex class to determine the "Unicode Block" rather than
// porting over that part of the Java Character class.
// References:
// https://msdn.microsoft.com/en-us/library/20bw873z.aspx#SupportedNamedBlocks
// http://stackoverflow.com/a/11414800/181087
private class ScriptData
{
internal readonly UnicodeBlock flag;
internal readonly int @base;
internal OpenBitSet decompMask;
internal ScriptData(UnicodeBlock flag, int @base)
{
this.flag = flag;
this.@base = @base;
}
}
private static readonly IDictionary<Regex, ScriptData> scripts = new Dictionary<Regex, ScriptData>() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
{ new Regex(@"\p{IsDevanagari}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.DEVANAGARI, 0x0900) },
{ new Regex(@"\p{IsBengali}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.BENGALI, 0x0980) },
{ new Regex(@"\p{IsGurmukhi}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.GURMUKHI, 0x0A00) },
{ new Regex(@"\p{IsGujarati}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.GUJARATI, 0x0A80) },
{ new Regex(@"\p{IsOriya}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.ORIYA, 0x0B00) },
{ new Regex(@"\p{IsTamil}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.TAMIL, 0x0B80) },
{ new Regex(@"\p{IsTelugu}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.TELUGU, 0x0C00) },
{ new Regex(@"\p{IsKannada}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.KANNADA, 0x0C80) },
{ new Regex(@"\p{IsMalayalam}", RegexOptions.Compiled), new ScriptData(UnicodeBlock.MALAYALAM, 0x0D00) },
};
[Flags]
internal enum UnicodeBlock
{
DEVANAGARI = 1,
BENGALI = 2,
GURMUKHI = 4,
GUJARATI = 8,
ORIYA = 16,
TAMIL = 32,
TELUGU = 64,
KANNADA = 128,
MALAYALAM = 256
}
static IndicNormalizer()
{
foreach (ScriptData sd in scripts.Values)
{
sd.decompMask = new OpenBitSet(0x7F);
for (int i = 0; i < decompositions.Length; i++)
{
int ch = decompositions[i][0];
int flags = decompositions[i][4];
if ((flags & (int)sd.flag) != 0)
{
sd.decompMask.Set(ch);
}
}
}
}
/// <summary>
/// Decompositions according to Unicode 5.2,
/// and http://ldc.upenn.edu/myl/IndianScriptsUnicode.html
/// <para/>
/// Most of these are not handled by unicode normalization anyway.
/// <para/>
/// The numbers here represent offsets into the respective codepages,
/// with -1 representing null and 0xFF representing zero-width joiner.
/// <para/>
/// the columns are: ch1, ch2, ch3, res, flags
/// ch1, ch2, and ch3 are the decomposition
/// res is the composition, and flags are the scripts to which it applies.
/// </summary>
private static readonly int[][] decompositions = new int[][] // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
/* devanagari, gujarati vowel candra O */
new int[] { 0x05, 0x3E, 0x45, 0x11, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari short O */
new int[] { 0x05, 0x3E, 0x46, 0x12, (int)UnicodeBlock.DEVANAGARI },
/* devanagari, gujarati letter O */
new int[] { 0x05, 0x3E, 0x47, 0x13, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari letter AI, gujarati letter AU */
new int[] { 0x05, 0x3E, 0x48, 0x14, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari, bengali, gurmukhi, gujarati, oriya AA */
new int[] { 0x05, 0x3E, -1, 0x06, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.BENGALI | (int)UnicodeBlock.GURMUKHI | (int)UnicodeBlock.GUJARATI | (int)UnicodeBlock.ORIYA },
/* devanagari letter candra A */
new int[] { 0x05, 0x45, -1, 0x72, (int)UnicodeBlock.DEVANAGARI },
/* gujarati vowel candra E */
new int[] { 0x05, 0x45, -1, 0x0D, (int)UnicodeBlock.GUJARATI },
/* devanagari letter short A */
new int[] { 0x05, 0x46, -1, 0x04, (int)UnicodeBlock.DEVANAGARI },
/* gujarati letter E */
new int[] { 0x05, 0x47, -1, 0x0F, (int)UnicodeBlock.GUJARATI },
/* gurmukhi, gujarati letter AI */
new int[] { 0x05, 0x48, -1, 0x10, (int)UnicodeBlock.GURMUKHI | (int)UnicodeBlock.GUJARATI },
/* devanagari, gujarati vowel candra O */
new int[] { 0x05, 0x49, -1, 0x11, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari short O */
new int[] { 0x05, 0x4A, -1, 0x12, (int)UnicodeBlock.DEVANAGARI },
/* devanagari, gujarati letter O */
new int[] { 0x05, 0x4B, -1, 0x13, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari letter AI, gurmukhi letter AU, gujarati letter AU */
new int[] { 0x05, 0x4C, -1, 0x14, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GURMUKHI | (int)UnicodeBlock.GUJARATI },
/* devanagari, gujarati vowel candra O */
new int[] { 0x06, 0x45, -1, 0x11, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari short O */
new int[] { 0x06, 0x46, -1, 0x12, (int)UnicodeBlock.DEVANAGARI },
/* devanagari, gujarati letter O */
new int[] { 0x06, 0x47, -1, 0x13, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari letter AI, gujarati letter AU */
new int[] { 0x06, 0x48, -1, 0x14, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* malayalam letter II */
new int[] { 0x07, 0x57, -1, 0x08, (int)UnicodeBlock.MALAYALAM },
/* devanagari letter UU */
new int[] { 0x09, 0x41, -1, 0x0A, (int)UnicodeBlock.DEVANAGARI },
/* tamil, malayalam letter UU (some styles) */
new int[] { 0x09, 0x57, -1, 0x0A, (int)UnicodeBlock.TAMIL | (int)UnicodeBlock.MALAYALAM },
/* malayalam letter AI */
new int[] { 0x0E, 0x46, -1, 0x10, (int)UnicodeBlock.MALAYALAM },
/* devanagari candra E */
new int[] { 0x0F, 0x45, -1, 0x0D, (int)UnicodeBlock.DEVANAGARI },
/* devanagari short E */
new int[] { 0x0F, 0x46, -1, 0x0E, (int)UnicodeBlock.DEVANAGARI },
/* devanagari AI */
new int[] { 0x0F, 0x47, -1, 0x10, (int)UnicodeBlock.DEVANAGARI },
/* oriya AI */
new int[] { 0x0F, 0x57, -1, 0x10, (int)UnicodeBlock.ORIYA },
/* malayalam letter OO */
new int[] { 0x12, 0x3E, -1, 0x13, (int)UnicodeBlock.MALAYALAM },
/* telugu, kannada letter AU */
new int[] { 0x12, 0x4C, -1, 0x14, (int)UnicodeBlock.TELUGU | (int)UnicodeBlock.KANNADA },
/* telugu letter OO */
new int[] { 0x12, 0x55, -1, 0x13, (int)UnicodeBlock.TELUGU },
/* tamil, malayalam letter AU */
new int[] { 0x12, 0x57, -1, 0x14, (int)UnicodeBlock.TAMIL | (int)UnicodeBlock.MALAYALAM },
/* oriya letter AU */
new int[] { 0x13, 0x57, -1, 0x14, (int)UnicodeBlock.ORIYA },
/* devanagari qa */
new int[] { 0x15, 0x3C, -1, 0x58, (int)UnicodeBlock.DEVANAGARI },
/* devanagari, gurmukhi khha */
new int[] { 0x16, 0x3C, -1, 0x59, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GURMUKHI },
/* devanagari, gurmukhi ghha */
new int[] { 0x17, 0x3C, -1, 0x5A, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GURMUKHI },
/* devanagari, gurmukhi za */
new int[] { 0x1C, 0x3C, -1, 0x5B, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GURMUKHI },
/* devanagari dddha, bengali, oriya rra */
new int[] { 0x21, 0x3C, -1, 0x5C, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.BENGALI | (int)UnicodeBlock.ORIYA },
/* devanagari, bengali, oriya rha */
new int[] { 0x22, 0x3C, -1, 0x5D, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.BENGALI | (int)UnicodeBlock.ORIYA },
/* malayalam chillu nn */
new int[] { 0x23, 0x4D, 0xFF, 0x7A, (int)UnicodeBlock.MALAYALAM },
/* bengali khanda ta */
new int[] { 0x24, 0x4D, 0xFF, 0x4E, (int)UnicodeBlock.BENGALI },
/* devanagari nnna */
new int[] { 0x28, 0x3C, -1, 0x29, (int)UnicodeBlock.DEVANAGARI },
/* malayalam chillu n */
new int[] { 0x28, 0x4D, 0xFF, 0x7B, (int)UnicodeBlock.MALAYALAM },
/* devanagari, gurmukhi fa */
new int[] { 0x2B, 0x3C, -1, 0x5E, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GURMUKHI },
/* devanagari, bengali yya */
new int[] { 0x2F, 0x3C, -1, 0x5F, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.BENGALI },
/* telugu letter vocalic R */
new int[] { 0x2C, 0x41, 0x41, 0x0B, (int)UnicodeBlock.TELUGU },
/* devanagari rra */
new int[] { 0x30, 0x3C, -1, 0x31, (int)UnicodeBlock.DEVANAGARI },
/* malayalam chillu rr */
new int[] { 0x30, 0x4D, 0xFF, 0x7C, (int)UnicodeBlock.MALAYALAM },
/* malayalam chillu l */
new int[] { 0x32, 0x4D, 0xFF, 0x7D, (int)UnicodeBlock.MALAYALAM },
/* devanagari llla */
new int[] { 0x33, 0x3C, -1, 0x34, (int)UnicodeBlock.DEVANAGARI },
/* malayalam chillu ll */
new int[] { 0x33, 0x4D, 0xFF, 0x7E, (int)UnicodeBlock.MALAYALAM },
/* telugu letter MA */
new int[] { 0x35, 0x41, -1, 0x2E, (int)UnicodeBlock.TELUGU },
/* devanagari, gujarati vowel sign candra O */
new int[] { 0x3E, 0x45, -1, 0x49, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari vowel sign short O */
new int[] { 0x3E, 0x46, -1, 0x4A, (int)UnicodeBlock.DEVANAGARI },
/* devanagari, gujarati vowel sign O */
new int[] { 0x3E, 0x47, -1, 0x4B, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* devanagari, gujarati vowel sign AU */
new int[] { 0x3E, 0x48, -1, 0x4C, (int)UnicodeBlock.DEVANAGARI | (int)UnicodeBlock.GUJARATI },
/* kannada vowel sign II */
new int[] { 0x3F, 0x55, -1, 0x40, (int)UnicodeBlock.KANNADA },
/* gurmukhi vowel sign UU (when stacking) */
new int[] { 0x41, 0x41, -1, 0x42, (int)UnicodeBlock.GURMUKHI },
/* tamil, malayalam vowel sign O */
new int[] { 0x46, 0x3E, -1, 0x4A, (int)UnicodeBlock.TAMIL | (int)UnicodeBlock.MALAYALAM },
/* kannada vowel sign OO */
new int[] { 0x46, 0x42, 0x55, 0x4B, (int)UnicodeBlock.KANNADA },
/* kannada vowel sign O */
new int[] { 0x46, 0x42, -1, 0x4A, (int)UnicodeBlock.KANNADA },
/* malayalam vowel sign AI (if reordered twice) */
new int[] { 0x46, 0x46, -1, 0x48, (int)UnicodeBlock.MALAYALAM },
/* telugu, kannada vowel sign EE */
new int[] { 0x46, 0x55, -1, 0x47, (int)UnicodeBlock.TELUGU | (int)UnicodeBlock.KANNADA },
/* telugu, kannada vowel sign AI */
new int[] { 0x46, 0x56, -1, 0x48, (int)UnicodeBlock.TELUGU | (int)UnicodeBlock.KANNADA },
/* tamil, malayalam vowel sign AU */
new int[] { 0x46, 0x57, -1, 0x4C, (int)UnicodeBlock.TAMIL | (int)UnicodeBlock.MALAYALAM },
/* bengali, oriya vowel sign O, tamil, malayalam vowel sign OO */
new int[] { 0x47, 0x3E, -1, 0x4B, (int)UnicodeBlock.BENGALI | (int)UnicodeBlock.ORIYA | (int)UnicodeBlock.TAMIL | (int)UnicodeBlock.MALAYALAM },
/* bengali, oriya vowel sign AU */
new int[] { 0x47, 0x57, -1, 0x4C, (int)UnicodeBlock.BENGALI | (int)UnicodeBlock.ORIYA },
/* kannada vowel sign OO */
new int[] { 0x4A, 0x55, -1, 0x4B, (int)UnicodeBlock.KANNADA },
/* gurmukhi letter I */
new int[] { 0x72, 0x3F, -1, 0x07, (int)UnicodeBlock.GURMUKHI },
/* gurmukhi letter II */
new int[] { 0x72, 0x40, -1, 0x08, (int)UnicodeBlock.GURMUKHI },
/* gurmukhi letter EE */
new int[] { 0x72, 0x47, -1, 0x0F, (int)UnicodeBlock.GURMUKHI },
/* gurmukhi letter U */
new int[] { 0x73, 0x41, -1, 0x09, (int)UnicodeBlock.GURMUKHI },
/* gurmukhi letter UU */
new int[] { 0x73, 0x42, -1, 0x0A, (int)UnicodeBlock.GURMUKHI },
/* gurmukhi letter OO */
new int[] { 0x73, 0x4B, -1, 0x13, (int)UnicodeBlock.GURMUKHI }
};
/// <summary>
/// Normalizes input text, and returns the new length.
/// The length will always be less than or equal to the existing length.
/// </summary>
/// <param name="text"> input text </param>
/// <param name="len"> valid length </param>
/// <returns> normalized length </returns>
public virtual int Normalize(char[] text, int len)
{
for (int i = 0; i < len; i++)
{
var block = GetBlockForChar(text[i]);
ScriptData sd;
if (scripts.TryGetValue(block, out sd) && sd != null)
{
int ch = text[i] - sd.@base;
if (sd.decompMask.Get(ch))
{
len = Compose(ch, block, sd, text, i, len);
}
}
}
return len;
}
/// <summary>
/// Compose into standard form any compositions in the decompositions table.
/// </summary>
private int Compose(int ch0, Regex block0, ScriptData sd, char[] text, int pos, int len)
{
if (pos + 1 >= len) // need at least 2 chars!
{
return len;
}
int ch1 = text[pos + 1] - sd.@base;
var block1 = GetBlockForChar(text[pos + 1]);
if (block1 != block0) // needs to be the same writing system
{
return len;
}
int ch2 = -1;
if (pos + 2 < len)
{
ch2 = text[pos + 2] - sd.@base;
var block2 = GetBlockForChar(text[pos + 2]);
if (text[pos + 2] == '\u200D') // ZWJ
{
ch2 = 0xFF;
}
else if (block2 != block1) // still allow a 2-char match
{
ch2 = -1;
}
}
for (int i = 0; i < decompositions.Length; i++)
{
if (decompositions[i][0] == ch0 && (decompositions[i][4] & (int)sd.flag) != 0)
{
if (decompositions[i][1] == ch1 && (decompositions[i][2] < 0 || decompositions[i][2] == ch2))
{
text[pos] = (char)(sd.@base + decompositions[i][3]);
len = StemmerUtil.Delete(text, pos + 1, len);
if (decompositions[i][2] >= 0)
{
len = StemmerUtil.Delete(text, pos + 1, len);
}
return len;
}
}
}
return len;
}
/// <summary>
/// LUCENENET: Returns the unicode block for the specified character
/// </summary>
private Regex GetBlockForChar(char c)
{
string charAsString = c.ToString();
foreach (var block in scripts.Keys)
{
if (block.IsMatch(charAsString))
{
return block;
}
}
// return a regex that never matches, nor is in our scripts dictionary
return new Regex(@"[^\S\s]");
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record
{
using System;
using NUnit.Framework;
using NPOI.HSSF.Record;
using NPOI.HSSF.UserModel;
using NPOI.SS;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.Util;
using TestCases.Exceptions;
using TestCases.HSSF;
using TestCases.HSSF.UserModel;
/**
* @author Josh Micich
*/
[TestFixture]
public class TestSharedFormulaRecord
{
/**
* A sample spreadsheet known to have one sheet with 4 shared formula ranges
*/
private static String SHARED_FORMULA_TEST_XLS = "SharedFormulaTest.xls";
/**
* Binary data for an encoded formula. Taken from attachment 22062 (bugzilla 45123/45421).
* The shared formula is in Sheet1!C6:C21, with text "SUMPRODUCT(--(End_Acct=$C6),--(End_Bal))"
* This data is found at offset 0x1A4A (within the shared formula record).
* The critical thing about this formula is that it Contains shared formula tokens (tRefN*,
* tAreaN*) with operand class 'array'.
*/
private static byte[] SHARED_FORMULA_WITH_REF_ARRAYS_DATA = {
0x1A, 0x00,
0x63, 0x02, 0x00, 0x00, 0x00,
0x6C, 0x00, 0x00, 0x02, (byte)0x80, // tRefNA
0x0B,
0x15,
0x13,
0x13,
0x63, 0x03, 0x00, 0x00, 0x00,
0x15,
0x13,
0x13,
0x42, 0x02, (byte)0xE4, 0x00,
};
/**
* The method <tt>SharedFormulaRecord.ConvertSharedFormulas()</tt> Converts formulas from
* 'shared formula' to 'single cell formula' format. It is important that token operand
* classes are preserved during this transformation, because Excel may not tolerate the
* incorrect encoding. The formula here is one such example (Excel displays #VALUE!).
*/
[Test]
public void TestConvertSharedFormulasOperandClasses_bug45123()
{
ILittleEndianInput in1 = TestcaseRecordInputStream.CreateLittleEndian(SHARED_FORMULA_WITH_REF_ARRAYS_DATA);
int encodedLen = in1.ReadUShort();
Ptg[] sharedFormula = Ptg.ReadTokens(encodedLen, in1);
SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
Ptg[] ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 100, 200);
RefPtg refPtg = (RefPtg)ConvertedFormula[1];
Assert.AreEqual("$C101", refPtg.ToFormulaString());
if (refPtg.PtgClass == Ptg.CLASS_REF)
{
throw new AssertionException("Identified bug 45123");
}
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
}
private static void ConfirmOperandClasses(Ptg[] originalPtgs, Ptg[] convertedPtg)
{
Assert.AreEqual(originalPtgs.Length, convertedPtg.Length);
for (int i = 0; i < convertedPtg.Length; i++)
{
Ptg originalPtg = originalPtgs[i];
Ptg ConvertedPtg = convertedPtg[i];
if (originalPtg.PtgClass != ConvertedPtg.PtgClass)
{
throw new ComparisonFailure("Different operand class for token[" + i + "]",
originalPtg.PtgClass.ToString(), ConvertedPtg.PtgClass.ToString());
}
}
}
[Test]
public void TestConvertSharedFormulas()
{
IWorkbook wb = new HSSFWorkbook();
HSSFEvaluationWorkbook fpb = HSSFEvaluationWorkbook.Create(wb);
Ptg[] sharedFormula, ConvertedFormula;
SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL97);
sharedFormula = FormulaParser.Parse("A2", fpb, FormulaType.Cell, -1);
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
//conversion relative to [0,0] should return the original formula
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A2");
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
//one row down
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "A3");
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
//one row down and one cell right
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "B3");
sharedFormula = FormulaParser.Parse("SUM(A1:C1)", fpb, FormulaType.Cell, -1);
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 0, 0);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A1:C1)");
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 0);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(A2:C2)");
ConvertedFormula = sf.ConvertSharedFormulas(sharedFormula, 1, 1);
ConfirmOperandClasses(sharedFormula, ConvertedFormula);
Assert.AreEqual(FormulaRenderer.ToFormulaString(fpb, ConvertedFormula), "SUM(B2:D2)");
}
/**
* Make sure that POI preserves {@link SharedFormulaRecord}s
*/
[Test]
public void TestPreserveOnReSerialize()
{
HSSFWorkbook wb;
ISheet sheet;
ICell cellB32769;
ICell cellC32769;
// Reading directly from XLS file
wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS);
sheet = wb.GetSheetAt(0);
cellB32769 = sheet.GetRow(32768).GetCell(1);
cellC32769 = sheet.GetRow(32768).GetCell(2);
// check Reading of formulas which are shared (two cells from a 1R x 8C range)
Assert.AreEqual("B32770*2", cellB32769.CellFormula);
Assert.AreEqual("C32770*2", cellC32769.CellFormula);
ConfirmCellEvaluation(wb, cellB32769, 4);
ConfirmCellEvaluation(wb, cellC32769, 6);
// Confirm this example really does have SharedFormulas.
// there are 3 others besides the one at A32769:H32769
Assert.AreEqual(4, countSharedFormulas(sheet));
// Re-serialize and check again
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = wb.GetSheetAt(0);
cellB32769 = sheet.GetRow(32768).GetCell(1);
cellC32769 = sheet.GetRow(32768).GetCell(2);
Assert.AreEqual("B32770*2", cellB32769.CellFormula);
ConfirmCellEvaluation(wb, cellB32769, 4);
Assert.AreEqual(4, countSharedFormulas(sheet));
}
[Test]
public void TestUnshareFormulaDueToChangeFormula()
{
HSSFWorkbook wb;
ISheet sheet;
ICell cellB32769;
ICell cellC32769;
wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS);
sheet = wb.GetSheetAt(0);
cellB32769 = sheet.GetRow(32768).GetCell(1);
cellC32769 = sheet.GetRow(32768).GetCell(2);
// Updating cell formula, causing it to become unshared
cellB32769.CellFormula = (/*setter*/"1+1");
ConfirmCellEvaluation(wb, cellB32769, 2);
// currently (Oct 2008) POI handles this by exploding the whole shared formula group
Assert.AreEqual(3, countSharedFormulas(sheet)); // one less now
// check that nearby cell of the same group still has the same formula
Assert.AreEqual("C32770*2", cellC32769.CellFormula);
ConfirmCellEvaluation(wb, cellC32769, 6);
}
[Test]
public void TestUnshareFormulaDueToDelete()
{
HSSFWorkbook wb;
ISheet sheet;
ICell cell;
int ROW_IX = 2;
// changing shared formula cell to blank
wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS);
sheet = wb.GetSheetAt(0);
Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX).GetCell(1).CellFormula);
cell = sheet.GetRow(ROW_IX).GetCell(1);
cell.SetCellType(CellType.Blank);
Assert.AreEqual(3, countSharedFormulas(sheet));
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = wb.GetSheetAt(0);
Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX + 1).GetCell(1).CellFormula);
// deleting shared formula cell
wb = HSSFTestDataSamples.OpenSampleWorkbook(SHARED_FORMULA_TEST_XLS);
sheet = wb.GetSheetAt(0);
Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX).GetCell(1).CellFormula);
cell = sheet.GetRow(ROW_IX).GetCell(1);
sheet.GetRow(ROW_IX).RemoveCell(cell);
Assert.AreEqual(3, countSharedFormulas(sheet));
wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = wb.GetSheetAt(0);
Assert.AreEqual("A$1*2", sheet.GetRow(ROW_IX + 1).GetCell(1).CellFormula);
}
private static void ConfirmCellEvaluation(IWorkbook wb, ICell cell, double expectedValue)
{
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
CellValue cv = fe.Evaluate(cell);
Assert.AreEqual(CellType.Numeric, cv.CellType);
Assert.AreEqual(expectedValue, cv.NumberValue, 0.0);
}
/**
* @return the number of {@link SharedFormulaRecord}s encoded for the specified sheet
*/
private static int countSharedFormulas(ISheet sheet)
{
NPOI.HSSF.Record.Record[] records = RecordInspector.GetRecords(sheet, 0);
int count = 0;
for (int i = 0; i < records.Length; i++)
{
NPOI.HSSF.Record.Record rec = records[i];
if (rec is SharedFormulaRecord)
{
count++;
}
}
return count;
}
}
}
| |
// Copyright 2019 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Text.Json;
using NodaTime.Serialization.SystemTextJson;
using NUnit.Framework;
using static NodaTime.Serialization.Test.SystemText.TestHelper;
namespace NodaTime.Serialization.Test.SystemText
{
/// <summary>
/// Tests for the converters exposed in NodaConverters.
/// </summary>
public class NodaConvertersTest
{
[Test]
public void OffsetConverter()
{
var value = Offset.FromHoursAndMinutes(5, 30);
string json = "\"\\u002B05:30\"";
AssertConversions(value, json, NodaConverters.OffsetConverter);
}
[Test]
public void InstantConverter()
{
var value = Instant.FromUtc(2012, 1, 2, 3, 4, 5);
string json = "\"2012-01-02T03:04:05Z\"";
AssertConversions(value, json, NodaConverters.InstantConverter);
}
[Test]
public void InstantConverter_EquivalentToIsoDateTimeConverter()
{
var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Utc);
var instant = Instant.FromDateTimeUtc(dateTime);
var jsonDateTime = JsonSerializer.Serialize(dateTime);
var jsonInstant = JsonSerializer.Serialize(instant, new JsonSerializerOptions
{
Converters = {NodaConverters.InstantConverter},
WriteIndented = false
});
Assert.AreEqual(jsonDateTime, jsonInstant);
}
[Test]
public void LocalDateConverter()
{
var value = new LocalDate(2012, 1, 2, CalendarSystem.Iso);
string json = "\"2012-01-02\"";
AssertConversions(value, json, NodaConverters.LocalDateConverter);
}
[Test]
public void LocalDateConverter_SerializeNonIso_Throws()
{
var localDate = new LocalDate(2012, 1, 2, CalendarSystem.Coptic);
var options = new JsonSerializerOptions
{
WriteIndented = false,
Converters = { NodaConverters.LocalDateConverter }
};
Assert.Throws<ArgumentException>(() => JsonSerializer.Serialize(localDate, options));
}
[Test]
public void LocalDateTimeConverter()
{
var value = new LocalDateTime(2012, 1, 2, 3, 4, 5, CalendarSystem.Iso).PlusNanoseconds(123456789);
var json = "\"2012-01-02T03:04:05.123456789\"";
AssertConversions(value, json, NodaConverters.LocalDateTimeConverter);
}
[Test]
public void LocalDateTimeConverter_EquivalentToIsoDateTimeConverter()
{
var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, 6, DateTimeKind.Unspecified);
var localDateTime = new LocalDateTime(2012, 1, 2, 3, 4, 5, 6, CalendarSystem.Iso);
var jsonDateTime = JsonSerializer.Serialize(dateTime);
var jsonLocalDateTime = JsonSerializer.Serialize(localDateTime, new JsonSerializerOptions
{
Converters = {NodaConverters.LocalDateTimeConverter},
WriteIndented = false
});
Assert.AreEqual(jsonDateTime, jsonLocalDateTime);
}
[Test]
public void LocalDateTimeConverter_SerializeNonIso_Throws()
{
var localDateTime = new LocalDateTime(2012, 1, 2, 3, 4, 5, CalendarSystem.Coptic);
Assert.Throws<ArgumentException>(() => JsonSerializer.Serialize(localDateTime, new JsonSerializerOptions
{
Converters = {NodaConverters.LocalDateTimeConverter},
WriteIndented = false
}));
}
[Test]
public void LocalTimeConverter()
{
var value = LocalTime.FromHourMinuteSecondMillisecondTick(1, 2, 3, 4, 5).PlusNanoseconds(67);
var json = "\"01:02:03.004000567\"";
AssertConversions(value, json, NodaConverters.LocalTimeConverter);
}
[Test]
public void RoundtripPeriodConverter()
{
var value = Period.FromDays(2) + Period.FromHours(3) + Period.FromMinutes(90);
string json = "\"P2DT3H90M\"";
AssertConversions(value, json, NodaConverters.RoundtripPeriodConverter);
}
[Test]
public void NormalizingIsoPeriodConverter_RequiresNormalization()
{
// Can't use AssertConversions here, as it doesn't round-trip
var period = Period.FromDays(2) + Period.FromHours(3) + Period.FromMinutes(90);
var json = JsonSerializer.Serialize(period, new JsonSerializerOptions
{
Converters = {NodaConverters.NormalizingIsoPeriodConverter},
WriteIndented = false
});
string expectedJson = "\"P2DT4H30M\"";
Assert.AreEqual(expectedJson, json);
}
[Test]
public void NormalizingIsoPeriodConverter_AlreadyNormalized()
{
// This time we're okay as it's already a normalized value.
var value = Period.FromDays(2) + Period.FromHours(4) + Period.FromMinutes(30);
string json = "\"P2DT4H30M\"";
AssertConversions(value, json, NodaConverters.NormalizingIsoPeriodConverter);
}
[Test]
public void ZonedDateTimeConverter()
{
// Deliberately give it an ambiguous local time, in both ways.
var zone = DateTimeZoneProviders.Tzdb["Europe/London"];
var earlierValue = new ZonedDateTime(new LocalDateTime(2012, 10, 28, 1, 30), zone, Offset.FromHours(1));
var laterValue = new ZonedDateTime(new LocalDateTime(2012, 10, 28, 1, 30), zone, Offset.FromHours(0));
string earlierJson = "\"2012-10-28T01:30:00\\u002B01 Europe/London\"";
string laterJson = "\"2012-10-28T01:30:00Z Europe/London\"";
var converter = NodaConverters.CreateZonedDateTimeConverter(DateTimeZoneProviders.Tzdb);
AssertConversions(earlierValue, earlierJson, converter);
AssertConversions(laterValue, laterJson, converter);
}
[Test]
public void OffsetDateTimeConverter()
{
var value = new LocalDateTime(2012, 1, 2, 3, 4, 5).PlusNanoseconds(123456789).WithOffset(Offset.FromHoursAndMinutes(-1, -30));
string json = "\"2012-01-02T03:04:05.123456789-01:30\"";
AssertConversions(value, json, NodaConverters.OffsetDateTimeConverter);
}
[Test]
public void OffsetDateTimeConverter_WholeHours()
{
// Redundantly specify the minutes, so that Javascript can parse it and it's RFC3339-compliant.
// See issue 284 for details.
var value = new LocalDateTime(2012, 1, 2, 3, 4, 5).PlusNanoseconds(123456789).WithOffset(Offset.FromHours(5));
string json = "\"2012-01-02T03:04:05.123456789\\u002B05:00\"";
AssertConversions(value, json, NodaConverters.OffsetDateTimeConverter);
}
[Test]
public void OffsetDateTimeConverter_ZeroOffset()
{
// Redundantly specify the minutes, so that Javascript can parse it and it's RFC3339-compliant.
// See issue 284 for details.
var value = new LocalDateTime(2012, 1, 2, 3, 4, 5).PlusNanoseconds(123456789).WithOffset(Offset.Zero);
string json = "\"2012-01-02T03:04:05.123456789Z\"";
AssertConversions(value, json, NodaConverters.OffsetDateTimeConverter);
}
[Test]
public void Duration_WholeSeconds()
{
AssertConversions(Duration.FromHours(48), "\"48:00:00\"", NodaConverters.DurationConverter);
}
[Test]
public void Duration_FractionalSeconds()
{
AssertConversions(Duration.FromHours(48) + Duration.FromSeconds(3) + Duration.FromNanoseconds(123456789), "\"48:00:03.123456789\"", NodaConverters.DurationConverter);
AssertConversions(Duration.FromHours(48) + Duration.FromSeconds(3) + Duration.FromTicks(1230000), "\"48:00:03.123\"", NodaConverters.DurationConverter);
AssertConversions(Duration.FromHours(48) + Duration.FromSeconds(3) + Duration.FromTicks(1234000), "\"48:00:03.1234\"", NodaConverters.DurationConverter);
AssertConversions(Duration.FromHours(48) + Duration.FromSeconds(3) + Duration.FromTicks(12345), "\"48:00:03.0012345\"", NodaConverters.DurationConverter);
}
[Test]
public void Duration_MinAndMaxValues()
{
AssertConversions(Duration.FromTicks(long.MaxValue), "\"256204778:48:05.4775807\"", NodaConverters.DurationConverter);
AssertConversions(Duration.FromTicks(long.MinValue), "\"-256204778:48:05.4775808\"", NodaConverters.DurationConverter);
}
/// <summary>
/// The pre-release converter used either 3 or 7 decimal places for fractions of a second; never less.
/// This test checks that the "new" converter (using DurationPattern) can still parse the old output.
/// </summary>
[Test]
public void Duration_ParsePartialFractionalSecondsWithTrailingZeroes()
{
var parsed = JsonSerializer.Deserialize<Duration>("\"25:10:00.1234000\"", new JsonSerializerOptions{Converters = {NodaConverters.DurationConverter }});
Assert.AreEqual(Duration.FromHours(25) + Duration.FromMinutes(10) + Duration.FromTicks(1234000), parsed);
}
[Test]
public void OffsetDateConverter()
{
var value = new LocalDate(2012, 1, 2).WithOffset(Offset.FromHoursAndMinutes(-1, -30));
string json = "\"2012-01-02-01:30\"";
AssertConversions(value, json, NodaConverters.OffsetDateConverter);
}
[Test]
public void OffsetTimeConverter()
{
var value = new LocalTime(3, 4, 5).PlusNanoseconds(123456789).WithOffset(Offset.FromHoursAndMinutes(-1, -30));
string json = "\"03:04:05.123456789-01:30\"";
AssertConversions(value, json, NodaConverters.OffsetTimeConverter);
}
}
}
| |
/*
* Copyright 2007-2012 Alfresco Software Limited.
*
* 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.
*
* This file is part of an unsupported extension to Alfresco.
*
* [BRIEF DESCRIPTION OF FILE CONTENTS]
*/
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
namespace AlfrescoWord2003
{
public partial class ThisAddIn
{
private const string COMMANDBAR_NAME = "Alfresco";
private const string COMMANDBAR_BUTTON_CAPTION = "Alfresco";
private const string COMMANDBAR_BUTTON_DESCRIPTION = "Show/hide the Alfresco Add-In window";
private const string COMMANDBAR_HELP_DESCRIPTION = "Alfresco Add-In online help";
// Win32 SDK functions
[DllImport("user32.dll")]
public static extern int GetForegroundWindow();
private AlfrescoPane m_AlfrescoPane;
private string m_DefaultTemplate = "wcservice/office/";
private string m_helpUrl = null;
private Office.CommandBar m_CommandBar;
private Office.CommandBarButton m_AlfrescoButton;
private Office.CommandBarButton m_HelpButton;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
m_DefaultTemplate = Properties.Settings.Default.DefaultTemplate.ToString(System.Globalization.CultureInfo.InvariantCulture);
// Register event interest with the Word Application
Application.WindowActivate += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowActivateEventHandler(Application_WindowActivate);
Application.WindowDeactivate += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowDeactivateEventHandler(Application_WindowDeactivate);
Application.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose);
Application.DocumentChange += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentChangeEventHandler(Application_DocumentChange);
// Add the button to the Office toolbar
AddToolbar();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
SaveToolbarPosition();
CloseAlfrescoPane();
m_AlfrescoPane = null;
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
/// <summary>
/// Adds commandBars to Word Application
/// </summary>
private void AddToolbar()
{
// VSTO API uses object-wrapped booleans
object falseValue = false;
object trueValue = true;
// Try to get a handle to an existing COMMANDBAR_NAME CommandBar
try
{
m_CommandBar = Application.CommandBars[COMMANDBAR_NAME];
// If we found the CommandBar, then it's a permanent one we need to delete
// Note: if the user has manually created a toolbar called COMMANDBAR_NAME it will get torched here
if (m_CommandBar != null)
{
m_CommandBar.Delete();
}
}
catch
{
// Benign - the CommandBar didn't exist
}
// Create a temporary CommandBar named COMMANDBAR_NAME
m_CommandBar = Application.CommandBars.Add(COMMANDBAR_NAME, Office.MsoBarPosition.msoBarTop, falseValue, trueValue);
if (m_CommandBar != null)
{
// Load any saved toolbar position
LoadToolbarPosition();
// Add our button to the command bar (as a temporary control) and an event handler.
m_AlfrescoButton = (Office.CommandBarButton)m_CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, trueValue);
if (m_AlfrescoButton != null)
{
m_AlfrescoButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
m_AlfrescoButton.Caption = COMMANDBAR_BUTTON_CAPTION;
m_AlfrescoButton.DescriptionText = COMMANDBAR_BUTTON_DESCRIPTION;
m_AlfrescoButton.TooltipText = COMMANDBAR_BUTTON_DESCRIPTION;
Bitmap bmpButton = new Bitmap(GetType(), "toolbar.ico");
m_AlfrescoButton.Picture = new ToolbarPicture(bmpButton);
Bitmap bmpMask = new Bitmap(GetType(), "toolbar_mask.ico");
m_AlfrescoButton.Mask = new ToolbarPicture(bmpMask);
m_AlfrescoButton.Tag = "AlfrescoButton";
// Finally add the event handler and make sure the button is visible
m_AlfrescoButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(m_AlfrescoButton_Click);
}
// Add the help button to the command bar (as a temporary control) and an event handler.
m_HelpButton = (Office.CommandBarButton)m_CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, trueValue);
if (m_HelpButton != null)
{
m_HelpButton.Style = Office.MsoButtonStyle.msoButtonIcon;
m_HelpButton.DescriptionText = COMMANDBAR_HELP_DESCRIPTION;
m_HelpButton.TooltipText = COMMANDBAR_HELP_DESCRIPTION;
m_HelpButton.FaceId = 984;
m_HelpButton.Tag = "AlfrescoHelpButton";
// Finally add the event handler and make sure the button is visible
m_HelpButton.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(m_HelpButton_Click);
}
// We need to find this toolbar later, so protect it from user changes
m_CommandBar.Protection = Microsoft.Office.Core.MsoBarProtection.msoBarNoCustomize;
m_CommandBar.Visible = true;
}
}
/// <summary>
/// Save CommandBar position
/// </summary>
private void SaveToolbarPosition()
{
if (m_CommandBar != null)
{
Properties.Settings.Default.ToolbarPosition = (int)m_CommandBar.Position;
Properties.Settings.Default.ToolbarRowIndex = m_CommandBar.RowIndex;
Properties.Settings.Default.ToolbarTop = m_CommandBar.Top;
Properties.Settings.Default.ToolbarLeft = m_CommandBar.Left;
Properties.Settings.Default.ToolbarSaved = true;
Properties.Settings.Default.Save();
}
}
/// <summary>
/// Load CommandBar position
/// </summary>
private void LoadToolbarPosition()
{
if (m_CommandBar != null)
{
if (Properties.Settings.Default.ToolbarSaved)
{
m_CommandBar.Position = (Microsoft.Office.Core.MsoBarPosition)Properties.Settings.Default.ToolbarPosition;
m_CommandBar.RowIndex = Properties.Settings.Default.ToolbarRowIndex;
m_CommandBar.Top = Properties.Settings.Default.ToolbarTop;
m_CommandBar.Left = Properties.Settings.Default.ToolbarLeft;
}
}
}
/// <summary>
/// Alfresco toolbar button event handler
/// </summary>
/// <param name="Ctrl"></param>
/// <param name="CancelDefault"></param>
void m_AlfrescoButton_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault)
{
if (m_AlfrescoPane != null)
{
m_AlfrescoPane.OnToggleVisible();
}
else
{
OpenAlfrescoPane(true);
}
}
/// <summary>
/// Help toolbar button event handler
/// </summary>
/// <param name="Ctrl"></param>
/// <param name="CancelDefault"></param>
void m_HelpButton_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
if (m_helpUrl == null)
{
StringBuilder helpUrl = new StringBuilder(Properties.Resources.HelpURL);
Assembly asm = Assembly.GetExecutingAssembly();
Version version = asm.GetName().Version;
string edition = "Community";
object[] attr = asm.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
if (attr.Length > 0)
{
AssemblyConfigurationAttribute aca = (AssemblyConfigurationAttribute)attr[0];
edition = aca.Configuration;
}
helpUrl.Replace("{major}", version.Major.ToString());
helpUrl.Replace("{minor}", version.Minor.ToString());
helpUrl.Replace("{edition}", edition);
m_helpUrl = helpUrl.ToString();
}
System.Diagnostics.Process.Start(m_helpUrl);
}
/// <summary>
/// Fired when active document changes
/// </summary>
void Application_DocumentChange()
{
if (m_AlfrescoPane != null)
{
m_AlfrescoPane.OnDocumentChanged();
}
}
/// <summary>
/// Fired when Word Application becomes the active window
/// </summary>
/// <param name="Doc"></param>
/// <param name="Wn"></param>
void Application_WindowActivate(Word.Document Doc, Word.Window Wn)
{
if (m_AlfrescoPane != null)
{
m_AlfrescoPane.OnWindowActivate();
}
}
/// <summary>
/// Fired when the Word Application loses focus
/// </summary>
/// <param name="Doc"></param>
/// <param name="Wn"></param>
void Application_WindowDeactivate(Word.Document Doc, Word.Window Wn)
{
if (m_AlfrescoPane != null)
{
if (m_AlfrescoPane.Handle.ToInt32() != GetForegroundWindow())
{
m_AlfrescoPane.OnWindowDeactivate();
}
}
}
/// <summary>
/// Fired as a document is being closed
/// </summary>
/// <param name="Doc"></param>
/// <param name="Cancel"></param>
void Application_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
{
if (m_AlfrescoPane != null)
{
m_AlfrescoPane.OnDocumentBeforeClose();
}
}
public void OpenAlfrescoPane()
{
OpenAlfrescoPane(true);
}
public void OpenAlfrescoPane(bool Show)
{
if (m_AlfrescoPane == null)
{
m_AlfrescoPane = new AlfrescoPane();
m_AlfrescoPane.DefaultTemplate = m_DefaultTemplate;
m_AlfrescoPane.WordApplication = Application;
}
if (Show)
{
m_AlfrescoPane.Show();
if (Application.Documents.Count > 0)
{
m_AlfrescoPane.showDocumentDetails();
}
else
{
m_AlfrescoPane.showHome(false);
}
Application.Activate();
}
}
public void CloseAlfrescoPane()
{
if (m_AlfrescoPane != null)
{
m_AlfrescoPane.Hide();
}
}
}
}
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Configuration;
using Umbraco.Core.Logging;
using umbraco.BusinessLogic;
using System.Security.Cryptography;
using System.Web.Util;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Collections;
#endregion
namespace umbraco.presentation.nodeFactory
{
public sealed class UmbracoSiteMapProvider : StaticSiteMapProvider
{
private SiteMapNode _root;
private readonly Dictionary<string, SiteMapNode> _nodes = new Dictionary<string, SiteMapNode>(16);
private string _defaultDescriptionAlias = "";
private bool _enableSecurityTrimming;
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("Config is null");
if (string.IsNullOrEmpty(name))
name = "UmbracoSiteMapProvider";
if (string.IsNullOrEmpty(config["defaultDescriptionAlias"]) == false)
{
_defaultDescriptionAlias = config["defaultDescriptionAlias"];
config.Remove("defaultDescriptionAlias");
}
if (config["securityTrimmingEnabled"] != null)
{
_enableSecurityTrimming = bool.Parse(config["securityTrimmingEnabled"]);
}
base.Initialize(name, config);
// Throw an exception if unrecognized attributes remain
if (config.Count > 0)
{
string attr = config.GetKey(0);
if (string.IsNullOrEmpty(attr) == false)
throw new ProviderException
(string.Format("Unrecognized attribute: {0}", attr));
}
}
public override SiteMapNode BuildSiteMap()
{
lock (this)
{
if (_root != null)
return _root;
_root = CreateNode("-1", "root", "umbraco root", "/", null);
try
{
AddNode(_root, null);
}
catch (Exception ex)
{
LogHelper.Error<UmbracoSiteMapProvider>("Error adding to SiteMapProvider", ex);
}
LoadNodes(_root.Key, _root);
}
return _root;
}
public void UpdateNode(NodeFactory.Node node)
{
lock (this)
{
// validate sitemap
BuildSiteMap();
SiteMapNode n;
if (_nodes.ContainsKey(node.Id.ToString()) == false)
{
n = CreateNode(node.Id.ToString(),
node.Name,
node.GetProperty(_defaultDescriptionAlias) != null ? node.GetProperty(_defaultDescriptionAlias).Value : "",
node.Url,
FindRoles(node.Id, node.Path));
string parentNode = node.Parent == null ? "-1" : node.Parent.Id.ToString();
try
{
AddNode(n, _nodes[parentNode]);
}
catch (Exception ex)
{
LogHelper.Error<UmbracoSiteMapProvider>(String.Format("Error adding node with url '{0}' and Id {1} to SiteMapProvider", node.Name, node.Id), ex);
}
}
else
{
n = _nodes[node.Id.ToString()];
n.Url = node.Url;
n.Description = node.GetProperty(_defaultDescriptionAlias) != null ? node.GetProperty(_defaultDescriptionAlias).Value : "";
n.Title = node.Name;
n.Roles = FindRoles(node.Id, node.Path).Split(",".ToCharArray());
}
}
}
public void RemoveNode(int nodeId)
{
lock (this)
{
if (_nodes.ContainsKey(nodeId.ToString()))
RemoveNode(_nodes[nodeId.ToString()]);
}
}
private void LoadNodes(string parentId, SiteMapNode parentNode)
{
lock (this)
{
NodeFactory.Node n = new NodeFactory.Node(int.Parse(parentId));
foreach (NodeFactory.Node child in n.Children)
{
string roles = FindRoles(child.Id, child.Path);
SiteMapNode childNode = CreateNode(
child.Id.ToString(),
child.Name,
child.GetProperty(_defaultDescriptionAlias) != null ? child.GetProperty(_defaultDescriptionAlias).Value : "",
child.Url,
roles);
try
{
AddNode(childNode, parentNode);
}
catch (Exception ex)
{
LogHelper.Error<UmbracoSiteMapProvider>(string.Format("Error adding node {0} to SiteMapProvider in loadNodes()", child.Id), ex);
}
LoadNodes(child.Id.ToString(), childNode);
}
}
}
private string FindRoles(int nodeId, string nodePath)
{
// check for roles
string roles = "";
if (_enableSecurityTrimming && !string.IsNullOrEmpty(nodePath) && nodePath.Length > 0)
{
string[] roleArray = cms.businesslogic.web.Access.GetAccessingMembershipRoles(nodeId, nodePath);
if (roleArray != null)
roles = String.Join(",", roleArray);
else
roles = "*";
}
return roles;
}
protected override SiteMapNode GetRootNodeCore()
{
BuildSiteMap();
return _root;
}
public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node)
{
if (!_enableSecurityTrimming)
return true;
if (node.Roles == null || node.Roles.Count == -1)
return true;
if (node.Roles[0].ToString() == "*")
return true;
foreach (string role in node.Roles)
if (context.User.IsInRole(role))
return true;
return false;
}
private SiteMapNode CreateNode(string id, string name, string description, string url, string roles)
{
lock (this)
{
if (_nodes.ContainsKey(id))
throw new ProviderException(String.Format("A node with id '{0}' already exists", id));
// Get title, URL, description, and roles from the DataReader
// If roles were specified, turn the list into a string array
string[] rolelist = null;
if (!String.IsNullOrEmpty(roles))
rolelist = roles.Split(new char[] { ',', ';' }, 512);
// Create a SiteMapNode
SiteMapNode node = new SiteMapNode(this, id, url, name, description, rolelist, null, null, null);
_nodes.Add(id, node);
// Return the node
return node;
}
}
}
}
| |
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Tests
{
[TestFixture]
public class RenderMaterialsTests
{
[TestFixtureSetUp]
public void Init()
{
}
[Test]
public void RenderMaterial_OSDFromToTest()
{
RenderMaterial mat = new RenderMaterial(UUID.Zero, UUID.Zero);
OSD map = mat.GetOSD();
RenderMaterial matFromOSD = RenderMaterial.FromOSD(map);
Assert.That(mat, Is.EqualTo(matFromOSD));
Assert.That(matFromOSD.NormalID, Is.EqualTo(UUID.Zero));
Assert.That(matFromOSD.NormalOffsetX, Is.EqualTo(0.0f));
Assert.That(matFromOSD.NormalOffsetY, Is.EqualTo(0.0f));
Assert.That(matFromOSD.NormalRepeatX, Is.EqualTo(1.0f));
Assert.That(matFromOSD.NormalRepeatY, Is.EqualTo(1.0f));
Assert.That(matFromOSD.NormalRotation, Is.EqualTo(0.0f));
Assert.That(matFromOSD.SpecularID, Is.EqualTo(UUID.Zero));
Assert.That(matFromOSD.SpecularOffsetX, Is.EqualTo(0.0f));
Assert.That(matFromOSD.SpecularOffsetY, Is.EqualTo(0.0f));
Assert.That(matFromOSD.SpecularRepeatX, Is.EqualTo(1.0f));
Assert.That(matFromOSD.SpecularRepeatY, Is.EqualTo(1.0f));
Assert.That(matFromOSD.SpecularRotation, Is.EqualTo(0.0f));
Assert.That(matFromOSD.SpecularLightColorR, Is.EqualTo(255));
Assert.That(matFromOSD.SpecularLightColorG, Is.EqualTo(255));
Assert.That(matFromOSD.SpecularLightColorB, Is.EqualTo(255));
Assert.That(matFromOSD.SpecularLightColorA, Is.EqualTo(255));
Assert.That(matFromOSD.SpecularLightExponent, Is.EqualTo(RenderMaterial.DEFAULT_SPECULAR_LIGHT_EXPONENT));
Assert.That(matFromOSD.EnvironmentIntensity, Is.EqualTo(RenderMaterial.DEFAULT_ENV_INTENSITY));
Assert.That(matFromOSD.DiffuseAlphaMode, Is.EqualTo((byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_BLEND));
Assert.That(matFromOSD.AlphaMaskCutoff, Is.EqualTo(0));
}
[Test]
public void RenderMaterial_ToFromOSDPreservesValues()
{
RenderMaterial mat = new RenderMaterial();
mat.NormalID = UUID.Random();
mat.NormalOffsetX = 2.0f;
mat.NormalOffsetY = 2.0f;
mat.NormalRepeatX = 2.0f;
mat.NormalRepeatY = 2.0f;
mat.NormalRotation = 180.0f;
mat.SpecularID = UUID.Random();
mat.SpecularOffsetX = 2.0f;
mat.SpecularOffsetY = 2.0f;
mat.SpecularRepeatX = 2.0f;
mat.SpecularRepeatY = 2.0f;
mat.SpecularRotation = 180.0f;
mat.SpecularLightColorR = 127;
mat.SpecularLightColorG = 127;
mat.SpecularLightColorB = 127;
mat.SpecularLightColorA = 255;
mat.SpecularLightExponent = 2;
mat.EnvironmentIntensity = 2;
mat.DiffuseAlphaMode = (byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_MASK;
mat.AlphaMaskCutoff = 2;
OSD map = mat.GetOSD();
RenderMaterial newmat = RenderMaterial.FromOSD(map);
Assert.That(newmat, Is.EqualTo(mat));
}
[Test]
public void RenderMaterial_SerializationPreservesValues()
{
RenderMaterial mat = new RenderMaterial();
mat.NormalID = UUID.Random();
mat.NormalOffsetX = 2.0f;
mat.NormalOffsetY = 2.0f;
mat.NormalRepeatX = 2.0f;
mat.NormalRepeatY = 2.0f;
mat.NormalRotation = 180.0f;
mat.SpecularID = UUID.Random();
mat.SpecularOffsetX = 2.0f;
mat.SpecularOffsetY = 2.0f;
mat.SpecularRepeatX = 2.0f;
mat.SpecularRepeatY = 2.0f;
mat.SpecularRotation = 180.0f;
mat.SpecularLightColorR = 127;
mat.SpecularLightColorG = 127;
mat.SpecularLightColorB = 127;
mat.SpecularLightColorA = 255;
mat.SpecularLightExponent = 2;
mat.EnvironmentIntensity = 2;
mat.DiffuseAlphaMode = (byte)RenderMaterial.eDiffuseAlphaMode.DIFFUSE_ALPHA_MODE_MASK;
mat.AlphaMaskCutoff = 2;
byte[] bytes = mat.ToBytes();
RenderMaterial newmat = RenderMaterial.FromBytes(bytes, 0, bytes.Length);
Assert.That(newmat, Is.EqualTo(mat));
}
[Test]
public void RenderMaterial_ToFromBinaryTest()
{
RenderMaterial mat = new RenderMaterial();
RenderMaterials mats = new RenderMaterials();
UUID key = mats.AddMaterial(mat);
byte[] bytes = mats.ToBytes();
RenderMaterials newmats = RenderMaterials.FromBytes(bytes, 0);
Assert.DoesNotThrow(() =>
{
RenderMaterial newmat = newmats.GetMaterial(key);
Assert.That(mat, Is.EqualTo(newmat));
});
}
[Test]
public void RenderMaterial_ColorValueToFromMaterialTest()
{
RenderMaterial mat = new RenderMaterial();
mat.SpecularLightColorR = 127;
mat.SpecularLightColorG = 127;
mat.SpecularLightColorB = 127;
mat.SpecularLightColorA = 255;
byte[] bytes = mat.ToBytes();
RenderMaterial newmat = RenderMaterial.FromBytes(bytes, 0, bytes.Length);
Assert.That(mat, Is.EqualTo(newmat));
Assert.That(mat.SpecularLightColorR, Is.EqualTo(127));
Assert.That(mat.SpecularLightColorG, Is.EqualTo(127));
Assert.That(mat.SpecularLightColorB, Is.EqualTo(127));
Assert.That(mat.SpecularLightColorA, Is.EqualTo(255));
}
[Test]
public void RenderMaterial_CopiedMaterialGeneratesTheSameMaterialID()
{
RenderMaterial mat = new RenderMaterial();
RenderMaterial matCopy = (RenderMaterial)mat.Clone();
UUID matID = RenderMaterial.GenerateMaterialID(mat);
UUID matCopyID = RenderMaterial.GenerateMaterialID(matCopy);
Assert.That(mat, Is.EqualTo(matCopy));
Assert.That(matID, Is.EqualTo(matCopyID));
}
[Test]
public void RenderMaterial_DefaultConstructedMaterialsGeneratesTheSameMaterialID()
{
RenderMaterial mat = new RenderMaterial();
RenderMaterial mat2 = new RenderMaterial();
UUID matID = RenderMaterial.GenerateMaterialID(mat);
UUID mat2ID = RenderMaterial.GenerateMaterialID(mat2);
Assert.That(mat, Is.EqualTo(mat2));
Assert.That(matID, Is.EqualTo(mat2ID));
}
[Test]
public void RenderMaterial_SerializedMaterialGeneratesTheSameMaterialID()
{
RenderMaterial mat = new RenderMaterial();
UUID matID = new UUID(mat.ComputeMD5Hash(), 0);
byte[] matData = mat.ToBytes();
RenderMaterial newmat = RenderMaterial.FromBytes(matData, 0, matData.Length);
UUID newmatID = RenderMaterial.GenerateMaterialID(newmat);
Assert.That(mat, Is.EqualTo(newmat));
Assert.That(matID, Is.EqualTo(newmatID));
}
[Test]
public void RenderMaterial_SerializedMaterialsDataGeneratesTheSameMaterialID()
{
RenderMaterials materials = new RenderMaterials();
RenderMaterial mat = new RenderMaterial();
UUID matID = materials.AddMaterial(mat);
byte[] matData = materials.ToBytes();
RenderMaterials newMaterials = RenderMaterials.FromBytes(matData, 0, matData.Length);
Assert.That(materials, Is.EqualTo(newMaterials));
Assert.DoesNotThrow(() =>
{
RenderMaterial newmat = newMaterials.GetMaterial(matID);
UUID newmatID = RenderMaterial.GenerateMaterialID(newmat);
Assert.That(mat, Is.EqualTo(newmat));
Assert.That(matID, Is.EqualTo(newmatID));
});
}
[Test]
public void RenderMaterial_DifferentMaterialsGeneratesDifferentMaterialID()
{
RenderMaterial mat = new RenderMaterial();
RenderMaterial mat2 = new RenderMaterial();
mat2.NormalID = UUID.Random();
Assert.AreNotEqual(mat, mat2);
UUID matID = RenderMaterial.GenerateMaterialID(mat);
UUID mat2ID = RenderMaterial.GenerateMaterialID(mat2);
Assert.AreNotEqual(matID, mat2ID);
}
[Test]
public void RenderMaterials_CopiedMaterialsGeneratesTheSameMaterialID()
{
RenderMaterial mat = new RenderMaterial();
RenderMaterials mats = new RenderMaterials();
UUID matID = mats.AddMaterial(mat);
RenderMaterials matsCopy = mats.Copy();
Assert.True(mats.ContainsMaterial(matID));
Assert.True(matsCopy.ContainsMaterial(matID));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Polymorphism operations.
/// </summary>
public partial class Polymorphism : IServiceOperations<AutoRestComplexTestService>, IPolymorphism
{
/// <summary>
/// Initializes a new instance of the Polymorphism class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Polymorphism(AutoRestComplexTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Diagnostics;
using OTFontFile;
namespace OTFontFileVal
{
/// <summary>
/// Summary description for val_EBDT.
/// </summary>
public class val_EBDT : Table_EBDT, ITableValidate
{
/************************
* constructors
*/
public val_EBDT(OTTag tag, MBOBuffer buf) : base(tag, buf)
{
}
public class bigGlyphMetrics_val : bigGlyphMetrics
{
public static bigGlyphMetrics_val CreateFromBigGlyphMetrics(bigGlyphMetrics bgm)
{
bigGlyphMetrics_val bgm_val = new bigGlyphMetrics_val();
bgm_val.height = bgm.height;
bgm_val.width = bgm.width;
bgm_val.horiBearingX = bgm.horiBearingX;
bgm_val.horiBearingY = bgm.horiBearingY;
bgm_val.horiAdvance = bgm.horiAdvance;
bgm_val.vertBearingX = bgm.vertBearingX;
bgm_val.vertBearingY = bgm.vertBearingY;
bgm_val.vertAdvance = bgm.vertAdvance;
return bgm_val;
}
public bool Validate(Validator v, string sIdentity, OTTable tableOwner)
{
bool bOk = true;
// ???
// ??? are there any values that are invalid ???
// ???
return bOk;
}
}
public class smallGlyphMetrics_val : smallGlyphMetrics
{
public static smallGlyphMetrics_val CreateFromSmallGlyphMetrics(smallGlyphMetrics sgm)
{
smallGlyphMetrics_val sgm_val = new smallGlyphMetrics_val();
sgm_val.height = sgm.height;
sgm_val.width = sgm.width;
sgm_val.BearingX = sgm.BearingX;
sgm_val.BearingY = sgm.BearingY;
sgm_val.Advance = sgm.Advance;
return sgm_val;
}
public bool Validate(Validator v, string sIdentity, OTTable tableOwner)
{
bool bOk = true;
// ???
// ??? are there any values that are invalid ???
// ???
return bOk;
}
}
/************************
* public methods
*/
public bool Validate(Validator v, OTFontVal fontOwner)
{
bool bRet = true;
m_nCachedMaxpNumGlyphs = fontOwner.GetMaxpNumGlyphs();
if (v.PerformTest(T.EBDT_version))
{
if (version.GetUint() == 0x00020000)
{
v.Pass(T.EBDT_version, P.EBDT_P_version, m_tag);
}
else
{
v.Error(T.EBDT_version, E.EBDT_E_version, m_tag, "version = 0x" + version.GetUint().ToString("x8") + ", unable to continue validation");
return false;
}
}
if (v.PerformTest(T.EBDT_TableDependency))
{
Table_EBLC EBLCTable = (Table_EBLC)fontOwner.GetTable("EBLC");
if (EBLCTable != null)
{
v.Pass(T.EBDT_TableDependency, P.EBDT_P_TableDependency, m_tag);
}
else
{
v.Error(T.EBDT_TableDependency, E.EBDT_E_TableDependency, m_tag);
bRet = false;
}
}
if (v.PerformTest(T.EBDT_GlyphImageData))
{
bool bGlyphImageDataOk = true;
Table_EBLC EBLCTable = (Table_EBLC)fontOwner.GetTable("EBLC");
// for each bitmap size
for (uint i=0; i<EBLCTable.numSizes; i++)
{
Table_EBLC.bitmapSizeTable bst = EBLCTable.GetBitmapSizeTable(i);
string sSize = "bitmapsize[" + i + "], ppemX=" + bst.ppemX + ", ppemY=" + bst.ppemY;
Table_EBLC.indexSubTableArray[] ista = EBLCTable.GetIndexSubTableArray(bst);
if (ista != null)
{
for (uint j=0; j < bst.numberOfIndexSubTables; j++)
{
Table_EBLC.indexSubTable ist = null;
if (ista[j] != null)
{
ist = bst.GetIndexSubTable(ista[j]);
}
if (ist != null)
{
string sID = sSize + ", indexSubTable[" + j + "](index fmt " + ist.header.indexFormat +
", image fmt " + ist.header.imageFormat + ")";
switch(ist.header.imageFormat)
{
case 1:
if (!Validate_Format1(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 2:
if (!Validate_Format2(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 3:
if (!Validate_Format3(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 4:
if (!Validate_Format4(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 5:
if (!Validate_Format5(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 6:
if (!Validate_Format6(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 7:
if (!Validate_Format7(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 8:
if (!Validate_Format8(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
case 9:
if (!Validate_Format9(v, sID, ist))
{
bGlyphImageDataOk = false;
bRet = false;
}
break;
default:
break;
}
}
}
}
}
if (bGlyphImageDataOk)
{
v.Pass(T.EBDT_GlyphImageData, P.EBDT_P_GlyphImageData, m_tag);
}
}
return bRet;
}
public bool Validate_Format1(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate small metrics
smallGlyphMetrics sgm = GetSmallMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (sgm != null)
{
smallGlyphMetrics_val sgm_val = smallGlyphMetrics_val.CreateFromSmallGlyphMetrics(sgm);
if (!sgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
// validate image data
// - this is just bitmap data, any values should be valid
}
}
return bOk;
}
public bool Validate_Format2(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate small metrics
smallGlyphMetrics sgm = GetSmallMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (sgm != null)
{
smallGlyphMetrics_val sgm_val = smallGlyphMetrics_val.CreateFromSmallGlyphMetrics(sgm);
if (!sgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
// validate image data
// - this is just bitmap data, any values should be valid
}
}
return bOk;
}
public bool Validate_Format3(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
// this format is obsolete!
// - however the image format number is actually stored in the EBLC table
// - and so any errors should get reported there
return bOk;
}
public bool Validate_Format4(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
// this format is not supported!
// - however the image format number is actually stored in the EBLC table
// - and so any errors should get reported there
return bOk;
}
public bool Validate_Format5(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// no metrics in format 5
// validate image data
// - this is just bitmap data, any values should be valid
}
return bOk;
}
public bool Validate_Format6(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate big metrics
bigGlyphMetrics bgm = GetBigMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (bgm != null)
{
bigGlyphMetrics_val bgm_val = bigGlyphMetrics_val.CreateFromBigGlyphMetrics(bgm);
if (!bgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
// validate image data
// - this is just bitmap data, any values should be valid
}
}
return bOk;
}
public bool Validate_Format7(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate big metrics
bigGlyphMetrics bgm = GetBigMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (bgm != null)
{
bigGlyphMetrics_val bgm_val = bigGlyphMetrics_val.CreateFromBigGlyphMetrics(bgm);
if (!bgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
// validate image data
// - this is just bitmap data, any values should be valid
}
}
return bOk;
}
public bool Validate_Format8(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate small metrics
smallGlyphMetrics sgm = GetSmallMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (sgm != null)
{
smallGlyphMetrics_val sgm_val = smallGlyphMetrics_val.CreateFromSmallGlyphMetrics(sgm);
if (!sgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
ushort numComponents = this.GetNumComponents(ist, idGlyph, ista.firstGlyphIndex);
// validate component array
for (uint i=0; i<numComponents; i++)
{
ebdtComponent component = GetComponent(ist, idGlyph, ista.firstGlyphIndex, i);
Debug.Assert(component!= null);
// validate the ebdtComponent
// verify that the component's glyph code is less than maxp numGlyphs
if (component.glyphCode >= m_nCachedMaxpNumGlyphs)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode +
", maxp.numGlyphs = " + m_nCachedMaxpNumGlyphs;
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
// verify that the component's glyph code isn't 0, which should be reserved as the empty glyph
// (technically, someone could use the empty glyph as a component, but it's more likely to be an error)
if (component.glyphCode == 0)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode;
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
// verify that the component's glyph code isn't the glyph code of its parent
if (component.glyphCode == idGlyph)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode + " (glyph can't use itself as a component)";
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
}
}
}
return bOk;
}
public bool Validate_Format9(Validator v, string sIdentity, Table_EBLC.indexSubTable ist)
{
bool bOk = true;
Table_EBLC.indexSubTableArray ista = ist.GetIndexSubTableArray();
for (ushort idGlyph=ista.firstGlyphIndex; idGlyph <= ista.lastGlyphIndex; idGlyph++)
{
// validate big metrics
bigGlyphMetrics bgm = GetBigMetrics(ist, idGlyph, ista.firstGlyphIndex);
if (bgm != null)
{
bigGlyphMetrics_val bgm_val = bigGlyphMetrics_val.CreateFromBigGlyphMetrics(bgm);
if (!bgm_val.Validate(v, sIdentity + ", idGlyph=" + idGlyph, this))
{
bOk = false;
}
ushort numComponents = this.GetNumComponents(ist, idGlyph, ista.firstGlyphIndex);
// validate component array
for (uint i=0; i<numComponents; i++)
{
ebdtComponent component = GetComponent(ist, idGlyph, ista.firstGlyphIndex, i);
Debug.Assert(component!= null);
// validate the ebdtComponent
// verify that the component's glyph code is less than maxp numGlyphs
if (component.glyphCode >= m_nCachedMaxpNumGlyphs)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode +
", maxp.numGlyphs = " + m_nCachedMaxpNumGlyphs;
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
// verify that the component's glyph code isn't 0, which should be reserved as the empty glyph
// (technically, someone could use the empty glyph as a component, but it's more likely to be an error)
if (component.glyphCode == 0)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode;
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
// verify that the component's glyph code isn't the glyph code of its parent
if (component.glyphCode == idGlyph)
{
string sDetails = sIdentity + ", idGlyph=" + idGlyph +
", component[" + i + "].glyphCode=" + component.glyphCode + " (glyph can't use itself as a component)";
v.Error(T.EBDT_GlyphImageData, E.EBDT_E_GlyphImageData, m_tag, sDetails);
bOk = false;
}
}
}
}
return bOk;
}
public ushort m_nCachedMaxpNumGlyphs;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class SelectTests
{
public struct CustomerRec
{
#pragma warning disable 0649
public string name;
public int custID;
#pragma warning restore 0649
}
public class Helper
{
// selector function to test index=0
public static string index_zero(CustomerRec cr, int index)
{
if (index == 0) return cr.name;
else return null;
}
// selector function to test index=max value is right
// Tests if index increments correctly
public static string index_five(CustomerRec cr, int index)
{
if (index == 5) return cr.name;
else return null;
}
}
public class Select003
{
private static int Select001()
{
var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" }
select x1; ;
var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 }
select x2;
var q = from x3 in q1
from x4 in q2
select new { a1 = x3, a2 = x4 };
var rst1 = q.Select(e => e.a1);
var rst2 = q.Select(e => e.a1);
return Verification.Allequal(rst1, rst2);
}
public static int Main()
{
int ret = RunTest(Select001);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select1a
{
// Overload-1: source is empty
public static int Test1a()
{
CustomerRec[] source = { };
string[] expected = { };
Func<CustomerRec, string> selector = (e) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select1b
{
// Overload-1: source has one element
public static int Test1b()
{
CustomerRec[] source = { new CustomerRec { name = "Prakash", custID = 98088 } };
string[] expected = { "Prakash" };
Func<CustomerRec, string> selector = (e) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select1c
{
// Overload-1: source has limited number of elements
public static int Test1c()
{
CustomerRec[] source = {new CustomerRec{name="Prakash", custID=98088},
new CustomerRec{name="Bob", custID=29099},
new CustomerRec{name="Chris", custID=39033},
new CustomerRec{name=null, custID=30349},
new CustomerRec{name="Prakash", custID=39030}
};
string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" };
Func<CustomerRec, string> selector = (e) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2a
{
// Overload-2: source is empty
public static int Test2a()
{
CustomerRec[] source = { };
string[] expected = { };
Func<CustomerRec, int, string> selector = (e, index) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2b
{
// Overload-2: source has one element
public static int Test2b()
{
CustomerRec[] source = { new CustomerRec { name = "Prakash", custID = 98088 } };
string[] expected = { "Prakash" };
Func<CustomerRec, int, string> selector = (e, index) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2c
{
// Overload-2: source has limited number of elements
public static int Test2c()
{
CustomerRec[] source = {new CustomerRec{name="Prakash", custID=98088},
new CustomerRec{name="Bob", custID=29099},
new CustomerRec{name="Chris", custID=39033},
new CustomerRec{name=null, custID=30349},
new CustomerRec{name="Prakash", custID=39030}
};
string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" };
Func<CustomerRec, int, string> selector = (e, index) => e.name;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2d
{
// Overload-2: index=0 returns the first element from source
public static int Test2d()
{
CustomerRec[] source = {new CustomerRec{name="Prakash", custID=98088},
new CustomerRec{name="Bob", custID=29099},
new CustomerRec{name="Chris", custID=39033},
};
string[] expected = { "Prakash", null, null };
Func<CustomerRec, int, string> selector = Helper.index_zero;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2e
{
// Overload-2: index=max value is right
public static int Test2e()
{
CustomerRec[] source = {new CustomerRec{name="Prakash", custID=98088},
new CustomerRec{name="Bob", custID=29099},
new CustomerRec{name="Chris", custID=39033},
new CustomerRec{name="Robert", custID=39033},
new CustomerRec{name="Allen", custID=39033},
new CustomerRec{name="Chuck", custID=39033}
};
string[] expected = { null, null, null, null, null, "Chuck" };
Func<CustomerRec, int, string> selector = Helper.index_five;
var actual = source.Select(selector);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test2e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class Select2f
{
// Overload-2: Check for overflow exception
public static int Test2f()
{
IEnumerable<int> source = Functions.NumRange(5, (long)Int32.MaxValue + 10);
int[] expected = { }; // Overflow Exception is thrown
Func<int, int, int> selector = (e, index) => e;
try
{
var actual = source.Select(selector);
Verification.Allequal(source, actual);
return 1;
}
catch (OverflowException)
{
return 0;
}
}
public static int Main()
{
//return Test2f();
return 0;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using OpenMetaverse;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.PhysicsModule.ubODEMeshing;
public class Vertex : IComparable<Vertex>
{
Vector3 vector;
public float X
{
get { return vector.X; }
set { vector.X = value; }
}
public float Y
{
get { return vector.Y; }
set { vector.Y = value; }
}
public float Z
{
get { return vector.Z; }
set { vector.Z = value; }
}
public Vertex(float x, float y, float z)
{
vector.X = x;
vector.Y = y;
vector.Z = z;
}
public Vertex normalize()
{
float tlength = vector.Length();
if (tlength != 0f)
{
float mul = 1.0f / tlength;
return new Vertex(vector.X * mul, vector.Y * mul, vector.Z * mul);
}
else
{
return new Vertex(0f, 0f, 0f);
}
}
public Vertex cross(Vertex v)
{
return new Vertex(vector.Y * v.Z - vector.Z * v.Y, vector.Z * v.X - vector.X * v.Z, vector.X * v.Y - vector.Y * v.X);
}
// disable warning: mono compiler moans about overloading
// operators hiding base operator but should not according to C#
// language spec
#pragma warning disable 0108
public static Vertex operator *(Vertex v, Quaternion q)
{
// From http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/
Vertex v2 = new Vertex(0f, 0f, 0f);
v2.X = q.W * q.W * v.X +
2f * q.Y * q.W * v.Z -
2f * q.Z * q.W * v.Y +
q.X * q.X * v.X +
2f * q.Y * q.X * v.Y +
2f * q.Z * q.X * v.Z -
q.Z * q.Z * v.X -
q.Y * q.Y * v.X;
v2.Y =
2f * q.X * q.Y * v.X +
q.Y * q.Y * v.Y +
2f * q.Z * q.Y * v.Z +
2f * q.W * q.Z * v.X -
q.Z * q.Z * v.Y +
q.W * q.W * v.Y -
2f * q.X * q.W * v.Z -
q.X * q.X * v.Y;
v2.Z =
2f * q.X * q.Z * v.X +
2f * q.Y * q.Z * v.Y +
q.Z * q.Z * v.Z -
2f * q.W * q.Y * v.X -
q.Y * q.Y * v.Z +
2f * q.W * q.X * v.Y -
q.X * q.X * v.Z +
q.W * q.W * v.Z;
return v2;
}
public static Vertex operator +(Vertex v1, Vertex v2)
{
return new Vertex(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}
public static Vertex operator -(Vertex v1, Vertex v2)
{
return new Vertex(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z);
}
public static Vertex operator *(Vertex v1, Vertex v2)
{
return new Vertex(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z);
}
public static Vertex operator +(Vertex v1, float am)
{
v1.X += am;
v1.Y += am;
v1.Z += am;
return v1;
}
public static Vertex operator -(Vertex v1, float am)
{
v1.X -= am;
v1.Y -= am;
v1.Z -= am;
return v1;
}
public static Vertex operator *(Vertex v1, float am)
{
v1.X *= am;
v1.Y *= am;
v1.Z *= am;
return v1;
}
public static Vertex operator /(Vertex v1, float am)
{
if (am == 0f)
{
return new Vertex(0f,0f,0f);
}
float mul = 1.0f / am;
v1.X *= mul;
v1.Y *= mul;
v1.Z *= mul;
return v1;
}
#pragma warning restore 0108
public float dot(Vertex v)
{
return X * v.X + Y * v.Y + Z * v.Z;
}
public Vertex(Vector3 v)
{
vector = v;
}
public Vertex Clone()
{
return new Vertex(X, Y, Z);
}
public static Vertex FromAngle(double angle)
{
return new Vertex((float) Math.Cos(angle), (float) Math.Sin(angle), 0.0f);
}
public float Length()
{
return vector.Length();
}
public virtual bool Equals(Vertex v, float tolerance)
{
Vertex diff = this - v;
float d = diff.Length();
if (d < tolerance)
return true;
return false;
}
public int CompareTo(Vertex other)
{
if (X < other.X)
return -1;
if (X > other.X)
return 1;
if (Y < other.Y)
return -1;
if (Y > other.Y)
return 1;
if (Z < other.Z)
return -1;
if (Z > other.Z)
return 1;
return 0;
}
public static bool operator >(Vertex me, Vertex other)
{
return me.CompareTo(other) > 0;
}
public static bool operator <(Vertex me, Vertex other)
{
return me.CompareTo(other) < 0;
}
public String ToRaw()
{
// Why this stuff with the number formatter?
// Well, the raw format uses the english/US notation of numbers
// where the "," separates groups of 1000 while the "." marks the border between 1 and 10E-1.
// The german notation uses these characters exactly vice versa!
// The Float.ToString() routine is a localized one, giving different results depending on the country
// settings your machine works with. Unusable for a machine readable file format :-(
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
nfi.NumberDecimalDigits = 6;
String s1 = X.ToString(nfi) + " " + Y.ToString(nfi) + " " + Z.ToString(nfi);
return s1;
}
}
public class Triangle
{
public Vertex v1;
public Vertex v2;
public Vertex v3;
public Triangle(Vertex _v1, Vertex _v2, Vertex _v3)
{
v1 = _v1;
v2 = _v2;
v3 = _v3;
}
public Triangle(float _v1x,float _v1y,float _v1z,
float _v2x,float _v2y,float _v2z,
float _v3x,float _v3y,float _v3z)
{
v1 = new Vertex(_v1x, _v1y, _v1z);
v2 = new Vertex(_v2x, _v2y, _v2z);
v3 = new Vertex(_v3x, _v3y, _v3z);
}
public override String ToString()
{
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
nfi.CurrencyDecimalSeparator = ".";
String s1 = "<" + v1.X.ToString(nfi) + "," + v1.Y.ToString(nfi) + "," + v1.Z.ToString(nfi) + ">";
String s2 = "<" + v2.X.ToString(nfi) + "," + v2.Y.ToString(nfi) + "," + v2.Z.ToString(nfi) + ">";
String s3 = "<" + v3.X.ToString(nfi) + "," + v3.Y.ToString(nfi) + "," + v3.Z.ToString(nfi) + ">";
return s1 + ";" + s2 + ";" + s3;
}
public Vector3 getNormal()
{
// Vertices
// Vectors for edges
Vector3 e1;
Vector3 e2;
e1 = new Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z);
e2 = new Vector3(v1.X - v3.X, v1.Y - v3.Y, v1.Z - v3.Z);
// Cross product for normal
Vector3 n = Vector3.Cross(e1, e2);
// Length
float l = n.Length();
// Normalized "normal"
n = n/l;
return n;
}
public void invertNormal()
{
Vertex vt;
vt = v1;
v1 = v2;
v2 = vt;
}
// Dumps a triangle in the "raw faces" format, blender can import. This is for visualisation and
// debugging purposes
public String ToStringRaw()
{
String output = v1.ToRaw() + " " + v2.ToRaw() + " " + v3.ToRaw();
return output;
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ManagedBass;
using osu.Framework.Utils;
using osu.Framework.Audio.Callbacks;
namespace osu.Framework.Audio.Track
{
/// <summary>
/// Processes audio sample data such that it can then be consumed to generate waveform plots of the audio.
/// </summary>
public class Waveform : IDisposable
{
/// <summary>
/// <see cref="Point"/>s are initially generated to a 1ms resolution to cover most use cases.
/// </summary>
private const float resolution = 0.001f;
/// <summary>
/// The data stream is iteratively decoded to provide this many points per iteration so as to not exceed BASS's internal buffer size.
/// </summary>
private const int points_per_iteration = 100000;
/// <summary>
/// FFT1024 gives ~40hz accuracy.
/// </summary>
private const DataFlags fft_samples = DataFlags.FFT1024;
/// <summary>
/// Number of bins generated by the FFT. Must correspond to <see cref="fft_samples"/>.
/// </summary>
private const int fft_bins = 512;
/// <summary>
/// Minimum frequency for low-range (bass) frequencies. Based on lower range of bass drum fallout.
/// </summary>
private const double low_min = 20;
/// <summary>
/// Minimum frequency for mid-range frequencies. Based on higher range of bass drum fallout.
/// </summary>
private const double mid_min = 100;
/// <summary>
/// Minimum frequency for high-range (treble) frequencies.
/// </summary>
private const double high_min = 2000;
/// <summary>
/// Maximum frequency for high-range (treble) frequencies. A sane value.
/// </summary>
private const double high_max = 12000;
private int channels;
private List<Point> points = new List<Point>();
private readonly CancellationTokenSource cancelSource = new CancellationTokenSource();
private readonly Task readTask;
private FileCallbacks fileCallbacks;
/// <summary>
/// Constructs a new <see cref="Waveform"/> from provided audio data.
/// </summary>
/// <param name="data">The sample data stream. If null, an empty waveform is constructed.</param>
public Waveform(Stream data)
{
if (data == null) return;
readTask = Task.Run(() =>
{
// for the time being, this code cannot run if there is no bass device available.
if (Bass.CurrentDevice <= 0)
return;
fileCallbacks = new FileCallbacks(new DataStreamFileProcedures(data));
int decodeStream = Bass.CreateStream(StreamSystem.NoBuffer, BassFlags.Decode | BassFlags.Float, fileCallbacks.Callbacks, fileCallbacks.Handle);
Bass.ChannelGetInfo(decodeStream, out ChannelInfo info);
long length = Bass.ChannelGetLength(decodeStream);
// Each "point" is generated from a number of samples, each sample contains a number of channels
int samplesPerPoint = (int)(info.Frequency * resolution * info.Channels);
int bytesPerPoint = samplesPerPoint * TrackBass.BYTES_PER_SAMPLE;
points.Capacity = (int)(length / bytesPerPoint);
// Each iteration pulls in several samples
int bytesPerIteration = bytesPerPoint * points_per_iteration;
var sampleBuffer = new float[bytesPerIteration / TrackBass.BYTES_PER_SAMPLE];
// Read sample data
while (length > 0)
{
length = Bass.ChannelGetData(decodeStream, sampleBuffer, bytesPerIteration);
int samplesRead = (int)(length / TrackBass.BYTES_PER_SAMPLE);
// Each point is composed of multiple samples
for (int i = 0; i < samplesRead; i += samplesPerPoint)
{
// Channels are interleaved in the sample data (data[0] -> channel0, data[1] -> channel1, data[2] -> channel0, etc)
// samplesPerPoint assumes this interleaving behaviour
var point = new Point(info.Channels);
for (int j = i; j < i + samplesPerPoint; j += info.Channels)
{
// Find the maximum amplitude for each channel in the point
for (int c = 0; c < info.Channels; c++)
point.Amplitude[c] = Math.Max(point.Amplitude[c], Math.Abs(sampleBuffer[j + c]));
}
// BASS may provide unclipped samples, so clip them ourselves
for (int c = 0; c < info.Channels; c++)
point.Amplitude[c] = Math.Min(1, point.Amplitude[c]);
points.Add(point);
}
}
Bass.ChannelSetPosition(decodeStream, 0);
length = Bass.ChannelGetLength(decodeStream);
// Read FFT data
float[] bins = new float[fft_bins];
int currentPoint = 0;
long currentByte = 0;
while (length > 0)
{
length = Bass.ChannelGetData(decodeStream, bins, (int)fft_samples);
currentByte += length;
double lowIntensity = computeIntensity(info, bins, low_min, mid_min);
double midIntensity = computeIntensity(info, bins, mid_min, high_min);
double highIntensity = computeIntensity(info, bins, high_min, high_max);
// In general, the FFT function will read more data than the amount of data we have in one point
// so we'll be setting intensities for all points whose data fits into the amount read by the FFT
// We know that each data point required sampleDataPerPoint amount of data
for (; currentPoint < points.Count && currentPoint * bytesPerPoint < currentByte; currentPoint++)
{
points[currentPoint].LowIntensity = lowIntensity;
points[currentPoint].MidIntensity = midIntensity;
points[currentPoint].HighIntensity = highIntensity;
}
}
channels = info.Channels;
}, cancelSource.Token);
}
private double computeIntensity(ChannelInfo info, float[] bins, double startFrequency, double endFrequency)
{
int startBin = (int)(fft_bins * 2 * startFrequency / info.Frequency);
int endBin = (int)(fft_bins * 2 * endFrequency / info.Frequency);
startBin = Math.Clamp(startBin, 0, bins.Length);
endBin = Math.Clamp(endBin, 0, bins.Length);
double value = 0;
for (int i = startBin; i < endBin; i++)
value += bins[i];
return value;
}
/// <summary>
/// Creates a new <see cref="Waveform"/> containing a specific number of data points by selecting the average value of each sampled group.
/// </summary>
/// <param name="pointCount">The number of points the resulting <see cref="Waveform"/> should contain.</param>
/// <param name="cancellationToken">The token to cancel the task.</param>
/// <returns>An async task for the generation of the <see cref="Waveform"/>.</returns>
public async Task<Waveform> GenerateResampledAsync(int pointCount, CancellationToken cancellationToken = default)
{
if (pointCount < 0) throw new ArgumentOutOfRangeException(nameof(pointCount));
if (pointCount == 0 || readTask == null)
return new Waveform(null);
await readTask.ConfigureAwait(false);
return await Task.Run(() =>
{
var generatedPoints = new List<Point>();
float pointsPerGeneratedPoint = (float)points.Count / pointCount;
// Determines at which width (relative to the resolution) our smoothing filter is truncated.
// Should not effect overall appearance much, except when the value is too small.
// A gaussian contains almost all its mass within its first 3 standard deviations,
// so a factor of 3 is a very good choice here.
const int kernel_width_factor = 3;
int kernelWidth = (int)(pointsPerGeneratedPoint * kernel_width_factor) + 1;
float[] filter = new float[kernelWidth + 1];
for (int i = 0; i < filter.Length; ++i)
{
filter[i] = (float)Blur.EvalGaussian(i, pointsPerGeneratedPoint);
}
// we're keeping two indices: one for the original (fractional!) point we're generating based on,
// and one (integral) for the points we're going to be generating.
// it's important to avoid adding by pointsPerGeneratedPoint in a loop, as floating-point errors can result in
// drifting of the computed values in either direction - we multiply the generated index by pointsPerGeneratedPoint instead.
float originalPointIndex = 0;
int generatedPointIndex = 0;
while (originalPointIndex < points.Count)
{
if (cancellationToken.IsCancellationRequested) break;
int startIndex = (int)originalPointIndex - kernelWidth;
int endIndex = (int)originalPointIndex + kernelWidth;
var point = new Point(channels);
float totalWeight = 0;
for (int j = startIndex; j < endIndex; j++)
{
if (j < 0 || j >= points.Count) continue;
float weight = filter[Math.Abs(j - startIndex - kernelWidth)];
totalWeight += weight;
for (int c = 0; c < channels; c++)
point.Amplitude[c] += weight * points[j].Amplitude[c];
point.LowIntensity += weight * points[j].LowIntensity;
point.MidIntensity += weight * points[j].MidIntensity;
point.HighIntensity += weight * points[j].HighIntensity;
}
// Means
for (int c = 0; c < channels; c++)
point.Amplitude[c] /= totalWeight;
point.LowIntensity /= totalWeight;
point.MidIntensity /= totalWeight;
point.HighIntensity /= totalWeight;
generatedPoints.Add(point);
generatedPointIndex += 1;
originalPointIndex = generatedPointIndex * pointsPerGeneratedPoint;
}
return new Waveform(null)
{
points = generatedPoints,
channels = channels
};
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the points represented by this <see cref="Waveform"/>.
/// </summary>
public List<Point> GetPoints() => GetPointsAsync().Result;
/// <summary>
/// Gets all the points represented by this <see cref="Waveform"/>.
/// </summary>
public async Task<List<Point>> GetPointsAsync()
{
if (readTask == null)
return points;
await readTask.ConfigureAwait(false);
return points;
}
/// <summary>
/// Gets the number of channels represented by each <see cref="Point"/>.
/// </summary>
public int GetChannels() => GetChannelsAsync().Result;
/// <summary>
/// Gets the number of channels represented by each <see cref="Point"/>.
/// </summary>
public async Task<int> GetChannelsAsync()
{
if (readTask == null)
return channels;
await readTask.ConfigureAwait(false);
return channels;
}
#region Disposal
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (isDisposed)
return;
isDisposed = true;
cancelSource?.Cancel();
cancelSource?.Dispose();
points = null;
fileCallbacks?.Dispose();
fileCallbacks = null;
}
#endregion
/// <summary>
/// Represents a singular point of data in a <see cref="Waveform"/>.
/// </summary>
public class Point
{
/// <summary>
/// An array of amplitudes, one for each channel.
/// </summary>
public readonly float[] Amplitude;
/// <summary>
/// Unnormalised total intensity of the low-range (bass) frequencies.
/// </summary>
public double LowIntensity;
/// <summary>
/// Unnormalised total intensity of the mid-range frequencies.
/// </summary>
public double MidIntensity;
/// <summary>
/// Unnormalised total intensity of the high-range (treble) frequencies.
/// </summary>
public double HighIntensity;
/// <summary>
/// Constructs a <see cref="Point"/>.
/// </summary>
/// <param name="channels">The number of channels that contain data.</param>
public Point(int channels)
{
Amplitude = new float[channels];
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.