context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright 2008 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 BinaryBitmap = com.google.zxing.BinaryBitmap;
using DecodeHintType = com.google.zxing.DecodeHintType;
using Reader = com.google.zxing.Reader;
using ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using ResultMetadataType = com.google.zxing.ResultMetadataType;
using ResultPoint = com.google.zxing.ResultPoint;
using BitArray = com.google.zxing.common.BitArray;
namespace com.google.zxing.oned
{
/// <summary> Encapsulates functionality and implementation that is common to all families
/// of one-dimensional barcodes.
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class OneDReader : Reader
{
private const int INTEGER_MATH_SHIFT = 8;
//UPGRADE_NOTE: Final was removed from the declaration of 'PATTERN_MATCH_RESULT_SCALE_FACTOR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
public virtual Result decode(BinaryBitmap image)
{
return decode(image, null);
}
// Note that we don't try rotation without the try harder flag, even if rotation was supported.
public virtual Result decode(BinaryBitmap image, System.Collections.Hashtable hints)
{
try
{
return doDecode(image, hints);
}
catch (ReaderException re)
{
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
if (tryHarder && image.RotateSupported)
{
BinaryBitmap rotatedImage = image.rotateCounterClockwise();
Result result = doDecode(rotatedImage, hints);
// Record that we found it rotated 90 degrees CCW / 270 degrees CW
System.Collections.Hashtable metadata = result.ResultMetadata;
int orientation = 270;
if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
{
// But if we found it reversed in doDecode(), add in that result here:
orientation = (orientation + ((System.Int32) metadata[ResultMetadataType.ORIENTATION])) % 360;
}
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) orientation);
// Update result points
ResultPoint[] points = result.ResultPoints;
int height = rotatedImage.Height;
for (int i = 0; i < points.Length; i++)
{
points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
}
return result;
}
else
{
throw re;
}
}
}
/// <summary> We're going to examine rows from the middle outward, searching alternately above and below the
/// middle, and farther out each time. rowStep is the number of rows between each successive
/// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
/// middle + rowStep, then middle - (2 * rowStep), etc.
/// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
/// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
/// image if "trying harder".
///
/// </summary>
/// <param name="image">The image to decode
/// </param>
/// <param name="hints">Any hints that were requested
/// </param>
/// <returns> The contents of the decoded barcode
/// </returns>
/// <throws> ReaderException Any spontaneous errors which occur </throws>
private Result doDecode(BinaryBitmap image, System.Collections.Hashtable hints)
{
int width = image.Width;
int height = image.Height;
BitArray row = new BitArray(width);
int middle = height >> 1;
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
int rowStep = System.Math.Max(1, height >> (tryHarder?7:4));
int maxLines;
if (tryHarder)
{
maxLines = height; // Look at the whole image, not just the center
}
else
{
maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
}
for (int x = 0; x < maxLines; x++)
{
// Scanning from the middle out. Determine which row we're looking at next:
int rowStepsAboveOrBelow = (x + 1) >> 1;
bool isAbove = (x & 0x01) == 0; // i.e. is x even?
int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
if (rowNumber < 0 || rowNumber >= height)
{
// Oops, if we run off the top or bottom, stop
break;
}
// Estimate black point for this row and load it:
try
{
row = image.getBlackRow(rowNumber, row);
}
catch (ReaderException)
{
continue;
}
// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for (int attempt = 0; attempt < 2; attempt++)
{
if (attempt == 1)
{
// trying again?
row.reverse(); // reverse the row and continue
// This means we will only ever draw result points *once* in the life of this method
// since we want to avoid drawing the wrong points after flipping the row, and,
// don't want to clutter with noise from every single row scan -- just the scans
// that start on the center line.
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
System.Collections.Hashtable newHints = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); // Can't use clone() in J2ME
System.Collections.IEnumerator hintEnum = hints.Keys.GetEnumerator();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (hintEnum.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
System.Object key = hintEnum.Current;
if (!key.Equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
newHints[key] = hints[key];
}
}
hints = newHints;
}
}
try
{
// Look for a barcode
Result result = decodeRow(rowNumber, row, hints);
// We found our barcode
if (attempt == 1)
{
// But it was upside down, so note that
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) 180);
// And remember to flip the result points horizontally.
ResultPoint[] points = result.ResultPoints;
points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y);
points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y);
}
return result;
}
catch (ReaderException)
{
// continue -- just couldn't decode this row
}
}
}
throw ReaderException.Instance;
}
/// <summary> Records the size of successive runs of white and black pixels in a row, starting at a given point.
/// The values are recorded in the given array, and the number of runs recorded is equal to the size
/// of the array. If the row starts on a white pixel at the given start point, then the first count
/// recorded is the run of white pixels starting from that point; likewise it is the count of a run
/// of black pixels if the row begin on a black pixels at that point.
///
/// </summary>
/// <param name="row">row to count from
/// </param>
/// <param name="start">offset into row to start at
/// </param>
/// <param name="counters">array into which to record counts
/// </param>
/// <throws> ReaderException if counters cannot be filled entirely from row before running out </throws>
/// <summary> of pixels
/// </summary>
internal static void recordPattern(BitArray row, int start, int[] counters)
{
int numCounters = counters.Length;
for (int i = 0; i < numCounters; i++)
{
counters[i] = 0;
}
int end = row.Size;
if (start >= end)
{
throw ReaderException.Instance;
}
bool isWhite = !row.get_Renamed(start);
int counterPosition = 0;
int i2 = start;
while (i2 < end)
{
bool pixel = row.get_Renamed(i2);
if (pixel ^ isWhite)
{
// that is, exactly one is true
counters[counterPosition]++;
}
else
{
counterPosition++;
if (counterPosition == numCounters)
{
break;
}
else
{
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
i2++;
}
// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i2 == end)))
{
throw ReaderException.Instance;
}
}
/// <summary> Determines how closely a set of observed counts of runs of black/white values matches a given
/// target pattern. This is reported as the ratio of the total variance from the expected pattern
/// proportions across all pattern elements, to the length of the pattern.
///
/// </summary>
/// <param name="counters">observed counters
/// </param>
/// <param name="pattern">expected pattern
/// </param>
/// <param name="maxIndividualVariance">The most any counter can differ before we give up
/// </param>
/// <returns> ratio of total variance between counters and pattern compared to total pattern size,
/// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
/// the total variance between counters and patterns equals the pattern length, higher values mean
/// even more variance
/// </returns>
internal static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance)
{
int numCounters = counters.Length;
int total = 0;
int patternLength = 0;
for (int i = 0; i < numCounters; i++)
{
total += counters[i];
patternLength += pattern[i];
}
if (total < patternLength)
{
// If we don't even have one pixel per unit of bar width, assume this is too small
// to reliably match, so fail:
return System.Int32.MaxValue;
}
// We're going to fake floating-point math in integers. We just need to use more bits.
// Scale up patternLength so that intermediate values below like scaledCounter will have
// more "significant digits"
int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
int totalVariance = 0;
for (int x = 0; x < numCounters; x++)
{
int counter = counters[x] << INTEGER_MATH_SHIFT;
int scaledPattern = pattern[x] * unitBarWidth;
int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter;
if (variance > maxIndividualVariance)
{
return System.Int32.MaxValue;
}
totalVariance += variance;
}
return totalVariance / total;
}
/// <summary> <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
///
/// </summary>
/// <param name="rowNumber">row number from top of the row
/// </param>
/// <param name="row">the black/white pixel data of the row
/// </param>
/// <param name="hints">decode hints
/// </param>
/// <returns> {@link Result} containing encoded string and start/end of barcode
/// </returns>
/// <throws> ReaderException if an error occurs or barcode cannot be found </throws>
public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints);
}
}
| |
// Copyright 2014, Google 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.v201403;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
namespace Google.Api.Ads.Dfp.Tests.v201403 {
/// <summary>
/// UnitTests for <see cref="InventoryServiceTests"/> class.
/// </summary>
[TestFixture]
public class InventoryServiceTests : BaseTests {
/// <summary>
/// UnitTests for <see cref="InventoryService"/> class.
/// </summary>
private InventoryService inventoryService;
/// <summary>
/// The ad unit 1 for running tests.
/// </summary>
private AdUnit adUnit1;
/// <summary>
/// The ad unit 2 for running tests.
/// </summary>
private AdUnit adUnit2;
/// <summary>
/// Default public constructor.
/// </summary>
public InventoryServiceTests() : base() {
}
/// <summary>
/// Initialize the test case.
/// </summary>
[SetUp]
public void Init() {
TestUtils utils = new TestUtils();
inventoryService = (InventoryService) user.GetService(DfpService.v201403.InventoryService);
adUnit1 = utils.CreateAdUnit(user);
adUnit2 = utils.CreateAdUnit(user);
}
/// <summary>
/// Test whether we can create a list of ad units.
/// </summary>
[Test]
public void TestCreateAdUnits() {
// Create ad unit 1.
AdUnit localAdUnit1 = new AdUnit();
localAdUnit1.name = string.Format("Ad_Unit_{0}", new TestUtils().GetTimeStamp());
localAdUnit1.parentId = adUnit1.id;
Size size1 = new Size();
size1.width = 300;
size1.height = 250;
AdUnitSize adUnitSize1 = new AdUnitSize();
adUnitSize1.size = size1;
adUnitSize1.environmentType = EnvironmentType.BROWSER;
localAdUnit1.adUnitSizes = new AdUnitSize[] {adUnitSize1};
// Create ad unit 2.
AdUnit localAdUnit2 = new AdUnit();
localAdUnit2.name = string.Format("Ad_Unit_{0}", new TestUtils().GetTimeStamp());
localAdUnit2.parentId = adUnit1.id;
Size size2 = new Size();
size2.width = 300;
size2.height = 250;
AdUnitSize adUnitSize2 = new AdUnitSize();
adUnitSize2.size = size2;
adUnitSize2.environmentType = EnvironmentType.BROWSER;
localAdUnit2.adUnitSizes = new AdUnitSize[] {adUnitSize2};
AdUnit[] newAdUnits = null;
Assert.DoesNotThrow(delegate() {
newAdUnits = inventoryService.createAdUnits(new AdUnit[] {localAdUnit1, localAdUnit2});
});
Assert.NotNull(newAdUnits);
Assert.AreEqual(newAdUnits.Length, 2);
Assert.AreEqual(newAdUnits[0].name, localAdUnit1.name);
Assert.AreEqual(newAdUnits[0].parentId, localAdUnit1.parentId);
Assert.AreEqual(newAdUnits[0].parentId, adUnit1.id);
Assert.AreEqual(newAdUnits[0].status, localAdUnit1.status);
Assert.AreEqual(newAdUnits[0].targetWindow, localAdUnit1.targetWindow);
Assert.AreEqual(newAdUnits[1].name, localAdUnit2.name);
Assert.AreEqual(newAdUnits[1].parentId, localAdUnit2.parentId);
Assert.AreEqual(newAdUnits[1].parentId, adUnit1.id);
Assert.AreEqual(newAdUnits[1].status, localAdUnit2.status);
Assert.AreEqual(newAdUnits[1].targetWindow, localAdUnit2.targetWindow);
}
/// <summary>
/// Test whether we can fetch a list of existing ad units that match given
/// statement.
/// </summary>
[Test]
public void TestGetAdUnitsByStatement() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", adUnit1.id);
AdUnitPage page = null;
Assert.DoesNotThrow(delegate() {
page = inventoryService.getAdUnitsByStatement(statement);
});
Assert.NotNull(page);
Assert.NotNull(page.results);
Assert.AreEqual(page.totalResultSetSize, 1);
Assert.NotNull(page.results[0]);
Assert.AreEqual(page.results[0].name, adUnit1.name);
Assert.AreEqual(page.results[0].parentId, adUnit1.parentId);
Assert.AreEqual(page.results[0].id, adUnit1.id);
Assert.AreEqual(page.results[0].status, adUnit1.status);
Assert.AreEqual(page.results[0].targetWindow, adUnit1.targetWindow);
}
/// <summary>
/// Test whether we can deactivate an ad unit.
/// </summary>
[Test]
public void TestPerformAdUnitAction() {
Statement statement = new Statement();
statement.query = string.Format("WHERE id = '{0}' LIMIT 1", adUnit1.id);
UpdateResult result = null;
Assert.DoesNotThrow(delegate() {
result = inventoryService.performAdUnitAction(new DeactivateAdUnits(), statement);
});
Assert.NotNull(result);
Assert.AreEqual(result.numChanges, 1);
}
/// <summary>
/// Test whether we can update a list of an ad units.
/// </summary>
[Test]
public void TestUpdateAdUnits() {
List<AdUnitSize> adUnitSizes = null;
Size size = null;
// Modify ad unit 1.
adUnitSizes = new List<AdUnitSize>(adUnit1.adUnitSizes);
size = new Size();
size.width = 728;
size.height = 90;
// Create ad unit size.
AdUnitSize adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnitSizes.Add(adUnitSize);
adUnit1.adUnitSizes = adUnitSizes.ToArray();
// Modify ad unit 2.
adUnitSizes = new List<AdUnitSize>(adUnit2.adUnitSizes);
size = new Size();
size.width = 728;
size.height = 90;
// Create ad unit size.
adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnitSizes.Add(adUnitSize);
adUnit2.adUnitSizes = adUnitSizes.ToArray();
AdUnit[] newAdUnits = null;
Assert.DoesNotThrow(delegate() {
newAdUnits = inventoryService.updateAdUnits(new AdUnit[] {adUnit1, adUnit2});
});
Assert.NotNull(newAdUnits);
Assert.AreEqual(newAdUnits.Length, 2);
Assert.AreEqual(newAdUnits[0].name, adUnit1.name);
Assert.AreEqual(newAdUnits[0].parentId, adUnit1.parentId);
Assert.AreEqual(newAdUnits[0].id, adUnit1.id);
Assert.AreEqual(newAdUnits[0].status, adUnit1.status);
Assert.AreEqual(newAdUnits[0].targetWindow, adUnit1.targetWindow);
Assert.AreEqual(newAdUnits[0].adUnitSizes.Length, adUnit1.adUnitSizes.Length);
Assert.AreEqual(newAdUnits[1].name, adUnit2.name);
Assert.AreEqual(newAdUnits[1].parentId, adUnit2.parentId);
Assert.AreEqual(newAdUnits[1].id, adUnit2.id);
Assert.AreEqual(newAdUnits[1].status, adUnit2.status);
Assert.AreEqual(newAdUnits[1].targetWindow, adUnit2.targetWindow);
Assert.AreEqual(newAdUnits[1].adUnitSizes.Length, adUnit2.adUnitSizes.Length);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if DEBUG
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Build.Shared.Debugging;
using Shouldly;
using Xunit;
using CommonWriterType = System.Action<string, string, System.Collections.Generic.IEnumerable<string>>;
namespace Microsoft.Build.UnitTests
{
public sealed class PrintLineDebugger_Tests
{
private class MockWriter
{
public readonly List<string> Logs = new List<string>();
public CommonWriterType Writer()
{
return (id, callsite, args) => Logs.Add($"{id}{callsite}{string.Join(";", args)}");
}
}
private void AssertContextInfo(List<string> writerLogs, string id = "", [CallerMemberName] string memberName = "")
{
foreach (var log in writerLogs)
{
log.ShouldStartWith($"{id}@{nameof(PrintLineDebugger_Tests)}.{memberName}(");
}
}
[Fact]
public void DebuggerCanLogToWriter()
{
var writer = new MockWriter();
using (var logger = PrintLineDebugger.Create(writer.Writer()))
{
logger.Log("Hello World");
}
writer.Logs.ShouldNotBeEmpty();
writer.Logs.First().ShouldEndWith("Hello World");
writer.Logs.ShouldHaveSingleItem();
AssertContextInfo(writer.Logs);
}
[Fact]
public void CompositeWriterCanWriteToMultipleWriters()
{
var writer1 = new MockWriter();
var writer2 = new MockWriter();
var compositeWriter = new PrintLineDebuggerWriters.CompositeWriter(
new []
{
writer1.Writer(),
writer2.Writer()
});
using (var logger = PrintLineDebugger.Create(compositeWriter.Writer))
{
logger.Log("Hello World");
}
writer1.Logs.ShouldNotBeEmpty();
writer1.Logs.First().ShouldEndWith("Hello World");
writer1.Logs.ShouldHaveSingleItem();
AssertContextInfo(writer1.Logs);
writer1.Logs.ShouldBe(writer2.Logs, Case.Sensitive);
}
[Fact]
public void DebuggerCanPrependAnId()
{
var writer = new MockWriter();
using (var logger = PrintLineDebugger.Create(writer.Writer(), "foo"))
{
logger.Log("Hello World");
}
writer.Logs.ShouldNotBeEmpty();
writer.Logs.First().ShouldEndWith("Hello World");
writer.Logs.ShouldHaveSingleItem();
AssertContextInfo(writer.Logs, "foo");
}
[Fact]
public void TestEnvironmentBasedPrintLineDebuggerShouldWork()
{
var writer = new MockWriter();
// loggers should not log anything if there's no static writer set
// this is useful to enable logging just for the duration of one test
PrintLineDebugger.Default.Value.Log("outOfContext1");
// This pattern is useful when debugging individual tests under CI.
// The TestEnvironment the writer, so the logs will only be collected during the test
// Caveat: One cannot use writers instantiated in the test in out of proc nodes. Either turn multiproc off, or set the writer in each node, probably in OutOfProcNode.Run
using (var env = TestEnvironment.Create())
{
env.CreatePrintLineDebugger(writer.Writer());
PrintLineDebugger.Default.Value.Log("inner");
}
PrintLineDebugger.Default.Value.Log("outOfContext2");
writer.Logs.ShouldNotBeEmpty();
writer.Logs[0].ShouldEndWith("inner");
writer.Logs.Count.ShouldBe(1);
AssertContextInfo(writer.Logs);
}
[Fact]
public void DefaultDebuggerCanUseStaticallyControlledWriters()
{
var writer = new MockWriter();
try
{
PrintLineDebugger.Default.Value.Log("outOfContext1");
// This pattern is useful when debugging msbuild under VS / CLI, not individual tests under CI
// The writer would be set at the start of each central and out of proc node, and the ID could be used to pick which file to dump the logs in (per process, per class emitting the log, etc)
PrintLineDebugger.SetWriter(writer.Writer());
PrintLineDebugger.Default.Value.Log("inner");
}
finally
{
PrintLineDebugger.UnsetWriter();
}
PrintLineDebugger.Default.Value.Log("outOfContext2");
writer.Logs.ShouldNotBeEmpty();
writer.Logs[0].ShouldEndWith("inner");
writer.Logs.Count.ShouldBe(1);
AssertContextInfo(writer.Logs);
}
[Fact]
// This is one way to use the debugger without a TestEnvironment
public void DefaultDebuggerShouldUseOuterDebuggerWriter()
{
var writer = new MockWriter();
PrintLineDebugger.Default.Value.Log("outOfContext1");
using (var logger = PrintLineDebugger.Create(writer.Writer()))
{
logger.Log("outer1");
// this is what you'd litter throughout the codebase to gather random logs
PrintLineDebugger.Default.Value.Log("inner");
logger.Log("outer2");
}
PrintLineDebugger.Default.Value.Log("outOfContext2");
writer.Logs.ShouldNotBeEmpty();
writer.Logs[0].ShouldEndWith("outer1");
writer.Logs[1].ShouldEndWith("inner");
writer.Logs[2].ShouldEndWith("outer2");
writer.Logs.Count.ShouldBe(3);
AssertContextInfo(writer.Logs);
}
[Fact]
public void CannotSetTwoWritersViaStaticSetters()
{
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
PrintLineDebugger.SetWriter(new MockWriter().Writer());
using (var env = TestEnvironment.Create())
{
env.SetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER", "1");
Should.Throw<Exception>(
() =>
{
PrintLineDebugger.SetWriter(new MockWriter().Writer());
});
}
PrintLineDebugger.UnsetWriter();
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
}
[Fact]
public void CannotSetWriterDuringADebuggerWhichAlreadySetAWriter()
{
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
using (var env = TestEnvironment.Create())
{
env.SetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER", "1");
env.CreatePrintLineDebugger(new MockWriter().Writer());
Should.Throw<Exception>(
() =>
{
PrintLineDebugger.SetWriter(new MockWriter().Writer());
});
}
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
}
[Fact]
public void CannotUnsetWriterWhenNoWriterIsSet()
{
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
using (var env = TestEnvironment.Create())
{
env.SetEnvironmentVariable("MSBUILDDONOTLAUNCHDEBUGGER", "1");
Should.Throw<Exception>(
() =>
{
PrintLineDebugger.UnsetWriter();
});
}
PrintLineDebugger.SetWriter(new MockWriter().Writer());
PrintLineDebugger.UnsetWriter();
}
}
}
#endif
| |
//
// 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.
//
using System.Linq;
using System.Text;
#pragma warning disable 0618
namespace NLog.UnitTests.Contexts
{
using System;
using System.Collections.Generic;
using System.Threading;
using Xunit;
public class MappedDiagnosticsContextTests
{
/// <summary>
/// Same as <see cref="MappedDiagnosticsContext" />, but there is one <see cref="MappedDiagnosticsContext"/> per each thread.
/// </summary>
[Fact]
public void MDCTest1()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
MappedDiagnosticsContext.Clear();
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.False(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2"));
Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count);
MappedDiagnosticsContext.Set("foo", "bar");
MappedDiagnosticsContext.Set("foo2", "bar2");
Assert.True(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal("bar", MappedDiagnosticsContext.Get("foo"));
Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count);
MappedDiagnosticsContext.Remove("foo");
Assert.False(MappedDiagnosticsContext.Contains("foo"));
Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
Assert.True(MappedDiagnosticsContext.Contains("foo2"));
Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2"));
Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count);
Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2"));
Assert.Null(MappedDiagnosticsContext.GetObject("foo3"));
MappedDiagnosticsContext.Set("foo3", new { One = 1 });
}
catch (Exception exception)
{
lock (exceptions)
{
exceptions.Add(exception);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
[Fact]
public void MDCTest2()
{
List<Exception> exceptions = new List<Exception>();
ManualResetEvent mre = new ManualResetEvent(false);
int counter = 100;
int remaining = counter;
for (int i = 0; i < counter; ++i)
{
ThreadPool.QueueUserWorkItem(
s =>
{
try
{
MDC.Clear();
Assert.False(MDC.Contains("foo"));
Assert.Equal(string.Empty, MDC.Get("foo"));
Assert.False(MDC.Contains("foo2"));
Assert.Equal(string.Empty, MDC.Get("foo2"));
MDC.Set("foo", "bar");
MDC.Set("foo2", "bar2");
Assert.True(MDC.Contains("foo"));
Assert.Equal("bar", MDC.Get("foo"));
MDC.Remove("foo");
Assert.False(MDC.Contains("foo"));
Assert.Equal(string.Empty, MDC.Get("foo"));
Assert.True(MDC.Contains("foo2"));
Assert.Equal("bar2", MDC.Get("foo2"));
Assert.Null(MDC.GetObject("foo3"));
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(ex);
}
}
finally
{
if (Interlocked.Decrement(ref remaining) == 0)
{
mre.Set();
}
}
});
}
mre.WaitOne();
StringBuilder exceptionsMessage = new StringBuilder();
foreach (var ex in exceptions)
{
if (exceptionsMessage.Length > 0)
{
exceptionsMessage.Append("\r\n");
}
exceptionsMessage.Append(ex.ToString());
}
Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
}
[Fact]
public void timer_cannot_inherit_mappedcontext()
{
object getObject = null;
string getValue = null;
var mre = new ManualResetEvent(false);
Timer thread = new Timer((s) =>
{
try
{
getObject = MDC.GetObject("DoNotExist");
getValue = MDC.Get("DoNotExistEither");
}
finally
{
mre.Set();
}
});
thread.Change(0, Timeout.Infinite);
mre.WaitOne();
Assert.Null(getObject);
Assert.Empty(getValue);
}
[Fact]
public void disposable_removes_item()
{
const string itemNotRemovedKey = "itemNotRemovedKey";
const string itemRemovedKey = "itemRemovedKey";
MappedDiagnosticsContext.Clear();
MappedDiagnosticsContext.Set(itemNotRemovedKey, "itemNotRemoved");
using (MappedDiagnosticsContext.SetScoped(itemRemovedKey, "itemRemoved"))
{
Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey, itemRemovedKey });
}
Assert.Equal(MappedDiagnosticsContext.GetNames(), new[] { itemNotRemovedKey });
}
[Fact]
public void dispose_is_idempotent()
{
const string itemKey = "itemKey";
MappedDiagnosticsContext.Clear();
IDisposable disposable = MappedDiagnosticsContext.SetScoped(itemKey, "item1");
disposable.Dispose();
Assert.False(MappedDiagnosticsContext.Contains(itemKey));
//This item shouldn't be removed since it is not the disposable one
MappedDiagnosticsContext.Set(itemKey, "item2");
disposable.Dispose();
Assert.True(MappedDiagnosticsContext.Contains(itemKey));
}
}
}
| |
// 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.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DictionaryOperations operations.
/// </summary>
internal partial class DictionaryOperations : IServiceOperations<AzureCompositeModelClient>, IDictionaryOperations
{
/// <summary>
/// Initializes a new instance of the DictionaryOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DictionaryOperations(AzureCompositeModelClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModelClient
/// </summary>
public AzureCompositeModelClient Client { get; private set; }
/// <summary>
/// Get complex types with dictionary property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> 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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, 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 with dictionary property
/// </summary>
/// <param name='defaultProgram'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
DictionaryWrapper complexBody = new DictionaryWrapper();
if (defaultProgram != null)
{
complexBody.DefaultProgram = defaultProgram;
}
// 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 = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with dictionary property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(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, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, 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 with dictionary property which is empty
/// </summary>
/// <param name='defaultProgram'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
DictionaryWrapper complexBody = new DictionaryWrapper();
if (defaultProgram != null)
{
complexBody.DefaultProgram = defaultProgram;
}
// 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, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with dictionary property which is null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(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, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, 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>
/// Get complex types with dictionary property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(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, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, 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;
}
}
}
| |
//
// Copyright 2010, Novell, Inc.
// Copyright 2011, 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSDictionary : IDictionary, IDictionary<NSObject, NSObject> {
public NSDictionary (NSObject first, NSObject second, params NSObject [] args) : this (PickOdd (second, args), PickEven (first, args))
{
}
public NSDictionary (object first, object second, params object [] args) : this (PickOdd (second, args), PickEven (first, args))
{
}
static NSArray PickEven (NSObject f, NSObject [] args)
{
int al = args.Length;
if ((al % 2) != 0)
throw new ArgumentException ("The arguments to NSDictionary should be a multiple of two", "args");
var ret = new NSObject [1+al/2];
ret [0] = f;
for (int i = 0, target = 1; i < al; i += 2)
ret [target++] = args [i];
return NSArray.FromNSObjects (ret);
}
static NSArray PickOdd (NSObject f, NSObject [] args)
{
var ret = new NSObject [1+args.Length/2];
ret [0] = f;
for (int i = 1, target = 1; i < args.Length; i += 2)
ret [target++] = args [i];
return NSArray.FromNSObjects (ret);
}
static NSArray PickEven (object f, object [] args)
{
int al = args.Length;
if ((al % 2) != 0)
throw new ArgumentException ("The arguments to NSDictionary should be a multiple of two", "args");
var ret = new object [1+al/2];
ret [0] = f;
for (int i = 0, target = 1; i < al; i += 2)
ret [target++] = args [i];
return NSArray.FromObjects (ret);
}
static NSArray PickOdd (object f, object [] args)
{
var ret = new object [1+args.Length/2];
ret [0] = f;
for (int i = 1, target = 1; i < args.Length; i += 2)
ret [target++] = args [i];
return NSArray.FromObjects (ret);
}
public static NSDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
var no = NSArray.FromNSObjects (objects);
var nk = NSArray.FromNSObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSDictionary FromObjectsAndKeys (object [] objects, object [] keys)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
var no = NSArray.FromObjects (objects);
var nk = NSArray.FromObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSDictionary FromObjectsAndKeys (NSObject [] objects, NSObject [] keys, int count)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
if (count < 1 || objects.Length < count || keys.Length < count)
throw new ArgumentException ("count");
var no = NSArray.FromNSObjects ((IList<NSObject>) objects, count);
var nk = NSArray.FromNSObjects ((IList<NSObject>) keys, count);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
public static NSDictionary FromObjectsAndKeys (object [] objects, object [] keys, int count)
{
if (objects.Length != keys.Length)
throw new ArgumentException ("objects and keys arrays have different sizes");
if (count < 1 || objects.Length < count || keys.Length < count)
throw new ArgumentException ("count");
var no = NSArray.FromObjects (objects);
var nk = NSArray.FromObjects (keys);
var r = FromObjectsAndKeysInternal (no, nk);
no.Dispose ();
nk.Dispose ();
return r;
}
internal bool ContainsKeyValuePair (KeyValuePair<NSObject, NSObject> pair)
{
NSObject value;
if (!TryGetValue (pair.Key, out value))
return false;
return EqualityComparer<NSObject>.Default.Equals (pair.Value, value);
}
#region ICollection
void ICollection.CopyTo (Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException ("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException ("arrayIndex");
if (array.Rank > 1)
throw new ArgumentException ("array is multidimensional");
if ((array.Length > 0) && (arrayIndex >= array.Length))
throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
if (arrayIndex + Count > array.Length)
throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable");
IDictionaryEnumerator e = ((IDictionary) this).GetEnumerator ();
int i = arrayIndex;
while (e.MoveNext ())
array.SetValue (e.Entry, i++);
}
int ICollection.Count {
get {return (int) Count;}
}
bool ICollection.IsSynchronized {
get {return false;}
}
object ICollection.SyncRoot {
get {return this;}
}
#endregion
#region ICollection<KeyValuePair<NSObject, NSObject>>
void ICollection<KeyValuePair<NSObject, NSObject>>.Add (KeyValuePair<NSObject, NSObject> item)
{
throw new NotSupportedException ();
}
void ICollection<KeyValuePair<NSObject, NSObject>>.Clear ()
{
throw new NotSupportedException ();
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.Contains (KeyValuePair<NSObject, NSObject> keyValuePair)
{
return ContainsKeyValuePair (keyValuePair);
}
void ICollection<KeyValuePair<NSObject, NSObject>>.CopyTo (KeyValuePair<NSObject, NSObject>[] array, int index)
{
if (array == null)
throw new ArgumentNullException ("array");
if (index < 0)
throw new ArgumentOutOfRangeException ("index");
// we want no exception for index==array.Length && Count == 0
if (index > array.Length)
throw new ArgumentException ("index larger than largest valid index of array");
if (array.Length - index < Count)
throw new ArgumentException ("Destination array cannot hold the requested elements!");
var e = GetEnumerator ();
while (e.MoveNext ())
array [index++] = e.Current;
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.Remove (KeyValuePair<NSObject, NSObject> keyValuePair)
{
throw new NotSupportedException ();
}
int ICollection<KeyValuePair<NSObject, NSObject>>.Count {
get {return (int) Count;}
}
bool ICollection<KeyValuePair<NSObject, NSObject>>.IsReadOnly {
get {return true;}
}
#endregion
#region IDictionary
void IDictionary.Add (object key, object value)
{
throw new NotSupportedException ();
}
void IDictionary.Clear ()
{
throw new NotSupportedException ();
}
bool IDictionary.Contains (object key)
{
if (key == null)
throw new ArgumentNullException ("key");
NSObject _key = key as NSObject;
if (_key == null)
return false;
return ContainsKey (_key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return new ShimEnumerator (this);
}
[Serializable]
class ShimEnumerator : IDictionaryEnumerator, IDisposable, IEnumerator {
IEnumerator<KeyValuePair<NSObject, NSObject>> e;
public ShimEnumerator (NSDictionary host)
{
e = host.GetEnumerator ();
}
public void Dispose ()
{
e.Dispose ();
}
public bool MoveNext ()
{
return e.MoveNext ();
}
public DictionaryEntry Entry {
get { return new DictionaryEntry { Key = e.Current.Key, Value = e.Current.Value }; }
}
public object Key {
get { return e.Current.Key; }
}
public object Value {
get { return e.Current.Value; }
}
public object Current {
get {return Entry;}
}
public void Reset ()
{
e.Reset ();
}
}
void IDictionary.Remove (object key)
{
throw new NotSupportedException ();
}
bool IDictionary.IsFixedSize {
get {return true;}
}
bool IDictionary.IsReadOnly {
get {return true;}
}
object IDictionary.this [object key] {
get {
NSObject _key = key as NSObject;
if (_key == null)
return null;
return ObjectForKey (_key);
}
set {
throw new NotSupportedException ();
}
}
ICollection IDictionary.Keys {
get {return Keys;}
}
ICollection IDictionary.Values {
get {return Values;}
}
#endregion
#region IDictionary<NSObject, NSObject>
void IDictionary<NSObject, NSObject>.Add (NSObject key, NSObject value)
{
throw new NotSupportedException ();
}
static readonly NSObject marker = new NSObject ();
public bool ContainsKey (NSObject key)
{
if (key == null)
throw new ArgumentNullException ("key");
return ObjectForKey (key) != null;
}
bool IDictionary<NSObject, NSObject>.Remove (NSObject key)
{
throw new NotSupportedException ();
}
public bool TryGetValue (NSObject key, out NSObject value)
{
if (key == null)
throw new ArgumentNullException ("key");
value = ObjectForKey (key);
// NSDictionary can not contain NULLs, if you want a NULL, it exists as an NSNulln
if (value == null)
return false;
return true;
}
public virtual NSObject this [NSObject key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
return ObjectForKey (key);
}
set {
throw new NotSupportedException ();
}
}
public virtual NSObject this [NSString key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
return ObjectForKey (key);
}
set {
throw new NotSupportedException ();
}
}
public virtual NSObject this [string key] {
get {
if (key == null)
throw new ArgumentNullException ("key");
using (var nss = new NSString (key)){
return ObjectForKey (nss);
}
}
set {
throw new NotSupportedException ();
}
}
ICollection<NSObject> IDictionary<NSObject, NSObject>.Keys {
get {return Keys;}
}
ICollection<NSObject> IDictionary<NSObject, NSObject>.Values {
get {return Values;}
}
#endregion
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public IEnumerator<KeyValuePair<NSObject, NSObject>> GetEnumerator ()
{
foreach (var key in Keys) {
yield return new KeyValuePair<NSObject, NSObject> (key, ObjectForKey (key));
}
}
public IntPtr LowlevelObjectForKey (IntPtr key)
{
return MonoMac.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, selObjectForKey_, key);
}
}
}
| |
#if UNITY_2017_2_OR_NEWER
using PlayFab.SharedModels;
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
namespace PlayFab.Internal
{
public class PlayFabUnityHttp : ITransportPlugin
{
private bool _isInitialized = false;
private readonly int _pendingWwwMessages = 0;
public bool IsInitialized { get { return _isInitialized; } }
public void Initialize() { _isInitialized = true; }
public void Update() { }
public void OnDestroy() { }
public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback)
{
PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("get", fullUrl, null, successCallback, errorCallback));
}
public void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("put", fullUrl, payload, successCallback, errorCallback));
}
public void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
PlayFabHttp.instance.StartCoroutine(SimpleCallCoroutine("post", fullUrl, payload, successCallback, errorCallback));
}
private static IEnumerator SimpleCallCoroutine(string method, string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback)
{
if (payload == null)
{
using (UnityWebRequest www = UnityWebRequest.Get(fullUrl))
{
#if UNITY_2017_2_OR_NEWER
yield return www.SendWebRequest();
#else
yield return www.Send();
#endif
if (!string.IsNullOrEmpty(www.error))
errorCallback(www.error);
else
successCallback(www.downloadHandler.data);
};
}
else
{
UnityWebRequest request;
if (method == "put")
{
request = UnityWebRequest.Put(fullUrl, payload);
}
else
{
request = new UnityWebRequest(fullUrl, "POST");
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(payload);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
}
#if UNITY_2017_2_OR_NEWER
#if !UNITY_2019_1_OR_NEWER
request.chunkedTransfer = false; // can be removed after Unity's PUT will be more stable
#endif
yield return request.SendWebRequest();
#else
yield return request.Send();
#endif
#if UNITY_2021_1_OR_NEWER
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
#else
if (request.isNetworkError || request.isHttpError)
#endif
{
errorCallback(request.error);
}
else
{
successCallback(request.downloadHandler.data);
}
request.Dispose();
}
}
public void MakeApiCall(object reqContainerObj)
{
CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj;
reqContainer.RequestHeaders["Content-Type"] = "application/json";
// Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
PlayFabHttp.instance.StartCoroutine(Post(reqContainer));
}
private IEnumerator Post(CallRequestContainer reqContainer)
{
#if PLAYFAB_REQUEST_TIMING
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var startTime = DateTime.UtcNow;
#endif
var www = new UnityWebRequest(reqContainer.FullUrl)
{
uploadHandler = new UploadHandlerRaw(reqContainer.Payload),
downloadHandler = new DownloadHandlerBuffer(),
method = "POST"
};
foreach (var headerPair in reqContainer.RequestHeaders)
{
if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value))
www.SetRequestHeader(headerPair.Key, headerPair.Value);
else
Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value);
}
#if UNITY_2017_2_OR_NEWER
yield return www.SendWebRequest();
#else
yield return www.Send();
#endif
#if PLAYFAB_REQUEST_TIMING
stopwatch.Stop();
var timing = new PlayFabHttp.RequestTiming {
StartTimeUtc = startTime,
ApiEndpoint = reqContainer.ApiEndpoint,
WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds,
MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
};
PlayFabHttp.SendRequestTiming(timing);
#endif
if (!string.IsNullOrEmpty(www.error))
{
OnError(www.error, reqContainer);
}
else
{
try
{
byte[] responseBytes = www.downloadHandler.data;
string responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);
OnResponse(responseText, reqContainer);
}
catch (Exception e)
{
OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer);
}
}
www.Dispose();
}
public int GetPendingMessages()
{
return _pendingWwwMessages;
}
public void OnResponse(string response, CallRequestContainer reqContainer)
{
try
{
#if PLAYFAB_REQUEST_TIMING
var startTime = DateTime.UtcNow;
#endif
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer);
var httpResult = serializer.DeserializeObject<HttpResponseObject>(response);
if (httpResult.code == 200)
{
// We have a good response from the server
reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson();
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
PlayFabHttp.instance.OnPlayFabApiResult(reqContainer);
#if !DISABLE_PLAYFABCLIENT_API
PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult, reqContainer.settings, reqContainer.instanceApi);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
}
catch (Exception e)
{
Debug.LogException(e);
}
try
{
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
else
{
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, response, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
public void OnError(string error, CallRequestContainer reqContainer)
{
reqContainer.JsonResponse = error;
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
}
}
}
#endif
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Matthew Ward" email="mrward@users.sourceforge.net"/>
// <version>$Revision: 915 $</version>
// </file>
using System;
using System.Collections;
using System.Collections.Generic;
namespace InnovatorAdmin.Editor
{
/// <summary>
/// A collection that stores <see cref='QualifiedName'/> objects.
/// </summary>
[Serializable()]
public class QualifiedNameCollection : CollectionBase
{
/// <summary>
/// Initializes a new instance of <see cref='QualifiedNameCollection'/>.
/// </summary>
public QualifiedNameCollection()
{
}
/// <summary>
/// Initializes a new instance of <see cref='QualifiedNameCollection'/> based on another <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <param name='val'>
/// A <see cref='QualifiedNameCollection'/> from which the contents are copied
/// </param>
public QualifiedNameCollection(QualifiedNameCollection val)
{
this.AddRange(val);
}
/// <summary>
/// Initializes a new instance of <see cref='QualifiedNameCollection'/> containing any array of <see cref='QualifiedName'/> objects.
/// </summary>
/// <param name='val'>
/// A array of <see cref='QualifiedName'/> objects with which to intialize the collection
/// </param>
public QualifiedNameCollection(QualifiedName[] val)
{
this.AddRange(val);
}
/// <summary>
/// Represents the entry at the specified index of the <see cref='QualifiedName'/>.
/// </summary>
/// <param name='index'>The zero-based index of the entry to locate in the collection.</param>
/// <value>The entry at the specified index of the collection.</value>
/// <exception cref='ArgumentOutOfRangeException'><paramref name='index'/> is outside the valid range of indexes for the collection.</exception>
public QualifiedName this[int index] {
get {
return ((QualifiedName)(List[index]));
}
set {
List[index] = value;
}
}
/// <summary>
/// Adds a <see cref='QualifiedName'/> with the specified value to the
/// <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <param name='val'>The <see cref='QualifiedName'/> to add.</param>
/// <returns>The index at which the new element was inserted.</returns>
/// <seealso cref='QualifiedNameCollection.AddRange'/>
public int Add(QualifiedName val)
{
return List.Add(val);
}
/// <summary>
/// Copies the elements of an array to the end of the <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <param name='val'>
/// An array of type <see cref='QualifiedName'/> containing the objects to add to the collection.
/// </param>
/// <seealso cref='QualifiedNameCollection.Add'/>
public void AddRange(QualifiedName[] val)
{
for (int i = 0; i < val.Length; i++) {
this.Add(val[i]);
}
}
/// <summary>
/// Adds the contents of another <see cref='QualifiedNameCollection'/> to the end of the collection.
/// </summary>
/// <param name='val'>
/// A <see cref='QualifiedNameCollection'/> containing the objects to add to the collection.
/// </param>
/// <seealso cref='QualifiedNameCollection.Add'/>
public void AddRange(QualifiedNameCollection val)
{
for (int i = 0; i < val.Count; i++)
{
this.Add(val[i]);
}
}
/// <summary>
/// Gets a value indicating whether the
/// <see cref='QualifiedNameCollection'/> contains the specified <see cref='QualifiedName'/>.
/// </summary>
/// <param name='val'>The <see cref='QualifiedName'/> to locate.</param>
/// <returns>
/// <see langword='true'/> if the <see cref='QualifiedName'/> is contained in the collection;
/// otherwise, <see langword='false'/>.
/// </returns>
/// <seealso cref='QualifiedNameCollection.IndexOf'/>
public bool Contains(QualifiedName val)
{
return List.Contains(val);
}
/// <summary>
/// Copies the <see cref='QualifiedNameCollection'/> values to a one-dimensional <see cref='Array'/> instance at the
/// specified index.
/// </summary>
/// <param name='array'>The one-dimensional <see cref='Array'/> that is the destination of the values copied from <see cref='QualifiedNameCollection'/>.</param>
/// <param name='index'>The index in <paramref name='array'/> where copying begins.</param>
/// <exception cref='ArgumentException'>
/// <para><paramref name='array'/> is multidimensional.</para>
/// <para>-or-</para>
/// <para>The number of elements in the <see cref='QualifiedNameCollection'/> is greater than
/// the available space between <paramref name='arrayIndex'/> and the end of
/// <paramref name='array'/>.</para>
/// </exception>
/// <exception cref='ArgumentNullException'><paramref name='array'/> is <see langword='null'/>. </exception>
/// <exception cref='ArgumentOutOfRangeException'><paramref name='arrayIndex'/> is less than <paramref name='array'/>'s lowbound. </exception>
/// <seealso cref='Array'/>
public void CopyTo(QualifiedName[] array, int index)
{
List.CopyTo(array, index);
}
/// <summary>
/// Returns the index of a <see cref='QualifiedName'/> in
/// the <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <param name='val'>The <see cref='QualifiedName'/> to locate.</param>
/// <returns>
/// The index of the <see cref='QualifiedName'/> of <paramref name='val'/> in the
/// <see cref='QualifiedNameCollection'/>, if found; otherwise, -1.
/// </returns>
/// <seealso cref='QualifiedNameCollection.Contains'/>
public int IndexOf(QualifiedName val)
{
return List.IndexOf(val);
}
/// <summary>
/// Inserts a <see cref='QualifiedName'/> into the <see cref='QualifiedNameCollection'/> at the specified index.
/// </summary>
/// <param name='index'>The zero-based index where <paramref name='val'/> should be inserted.</param>
/// <param name='val'>The <see cref='QualifiedName'/> to insert.</param>
/// <seealso cref='QualifiedNameCollection.Add'/>
public void Insert(int index, QualifiedName val)
{
List.Insert(index, val);
}
/// <summary>
/// Returns an enumerator that can iterate through the <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <seealso cref='IEnumerator'/>
public new QualifiedNameEnumerator GetEnumerator()
{
return new QualifiedNameEnumerator(this);
}
/// <summary>
/// Removes a specific <see cref='QualifiedName'/> from the <see cref='QualifiedNameCollection'/>.
/// </summary>
/// <param name='val'>The <see cref='QualifiedName'/> to remove from the <see cref='QualifiedNameCollection'/>.</param>
/// <exception cref='ArgumentException'><paramref name='val'/> is not found in the Collection.</exception>
public void Remove(QualifiedName val)
{
List.Remove(val);
}
/// <summary>
/// Removes the last item in this collection.
/// </summary>
public void RemoveLast()
{
if (Count > 0) {
RemoveAt(Count - 1);
}
}
/// <summary>
/// Removes the first item in the collection.
/// </summary>
public void RemoveFirst()
{
if (Count > 0) {
RemoveAt(0);
}
}
/// <summary>
/// Gets the namespace prefix of the last item.
/// </summary>
public string LastPrefix {
get {
string prefix = String.Empty;
if (Count > 0) {
QualifiedName name = this[Count - 1];
prefix = name.Prefix;
}
return prefix;
}
}
/// <summary>
/// Enumerator that can iterate through a QualifiedNameCollection.
/// </summary>
/// <seealso cref='IEnumerator'/>
/// <seealso cref='QualifiedNameCollection'/>
/// <seealso cref='QualifiedName'/>
public class QualifiedNameEnumerator : IEnumerator<QualifiedName>
{
IEnumerator baseEnumerator;
IEnumerable temp;
/// <summary>
/// Initializes a new instance of <see cref='QualifiedNameEnumerator'/>.
/// </summary>
public QualifiedNameEnumerator(QualifiedNameCollection mappings)
{
this.temp = ((IEnumerable)(mappings));
this.baseEnumerator = temp.GetEnumerator();
}
/// <summary>
/// Gets the current <see cref='QualifiedName'/> in the <seealso cref='QualifiedNameCollection'/>.
/// </summary>
public QualifiedName Current {
get {
return ((QualifiedName)(baseEnumerator.Current));
}
}
object IEnumerator.Current {
get {
return baseEnumerator.Current;
}
}
/// <summary>
/// Advances the enumerator to the next <see cref='QualifiedName'/> of the <see cref='QualifiedNameCollection'/>.
/// </summary>
public bool MoveNext()
{
return baseEnumerator.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the <see cref='QualifiedNameCollection'/>.
/// </summary>
public void Reset()
{
baseEnumerator.Reset();
}
public void Dispose()
{
// Do Nothing
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
// this file contains the data structures for the in memory database
// containing display and formatting information
using System.Collections.Generic;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
#region Table View Definitions
/// <summary>
/// alignment values
/// NOTE: we do not use an enum because this will have to be
/// serialized and ERS/serialization do not support enumerations
/// </summary>
internal static class TextAlignment
{
internal const int Undefined = 0;
internal const int Left = 1;
internal const int Center = 2;
internal const int Right = 3;
}
/// <summary>
/// definition of a table control
/// </summary>
internal sealed class TableControlBody : ControlBody
{
/// <summary>
/// optional, if not present, use data off the default table row definition
/// </summary>
internal TableHeaderDefinition header = new TableHeaderDefinition();
/// <summary>
/// default row definition
/// It's mandatory
/// </summary>
internal TableRowDefinition defaultDefinition;
/// <summary>
/// optional list of row definition overrides. It can be empty if there are no overrides
/// </summary>
internal List<TableRowDefinition> optionalDefinitionList = new List<TableRowDefinition>();
internal override ControlBase Copy()
{
TableControlBody result = new TableControlBody
{
autosize = this.autosize,
header = this.header.Copy()
};
if (null != defaultDefinition)
{
result.defaultDefinition = this.defaultDefinition.Copy();
}
foreach (TableRowDefinition trd in this.optionalDefinitionList)
{
result.optionalDefinitionList.Add(trd);
}
return result;
}
}
/// <summary>
/// information about the table header
/// NOTE: if an instance of this class is present, the list must not be empty
/// </summary>
internal sealed class TableHeaderDefinition
{
/// <summary>
/// if true, direct the outputter to suppress table header printing
/// </summary>
internal bool hideHeader;
/// <summary>
/// mandatory list of column header definitions
/// </summary>
internal List<TableColumnHeaderDefinition> columnHeaderDefinitionList =
new List<TableColumnHeaderDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableHeaderDefinition Copy()
{
TableHeaderDefinition result = new TableHeaderDefinition { hideHeader = this.hideHeader };
foreach (TableColumnHeaderDefinition tchd in this.columnHeaderDefinitionList)
{
result.columnHeaderDefinitionList.Add(tchd);
}
return result;
}
}
internal sealed class TableColumnHeaderDefinition
{
/// <summary>
/// optional label
/// If not present, use the name of the property from the matching
/// mandatory row description
/// </summary>
internal TextToken label = null;
/// <summary>
/// general alignment for the column
/// If not present, either use the one from the row definition
/// or the data driven heuristics
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// width of the column
/// </summary>
internal int width = 0; // undefined
}
/// <summary>
/// definition of the data to be displayed in a table row
/// </summary>
internal sealed class TableRowDefinition
{
/// <summary>
/// applicability clause
/// Only valid if not the default definition
/// </summary>
internal AppliesTo appliesTo;
/// <summary>
/// if true, the current table row should be allowed
/// to wrap to multiple lines, else truncated
/// </summary>
internal bool multiLine;
/// <summary>
/// mandatory list of column items.
/// It cannot be empty
/// </summary>
internal List<TableRowItemDefinition> rowItemDefinitionList = new List<TableRowItemDefinition>();
/// <summary>
/// Returns a Shallow Copy of the current object.
/// </summary>
/// <returns></returns>
internal TableRowDefinition Copy()
{
TableRowDefinition result = new TableRowDefinition
{
appliesTo = this.appliesTo,
multiLine = this.multiLine
};
foreach (TableRowItemDefinition trid in this.rowItemDefinitionList)
{
result.rowItemDefinitionList.Add(trid);
}
return result;
}
}
/// <summary>
/// cell definition inside a row
/// </summary>
internal sealed class TableRowItemDefinition
{
/// <summary>
/// optional alignment to override the default one at the header level
/// </summary>
internal int alignment = TextAlignment.Undefined;
/// <summary>
/// format directive body telling how to format the cell
/// RULE: the body can only contain
/// * TextToken
/// * PropertyToken
/// * NOTHING (provide an empty cell)
/// </summary>
internal List<FormatToken> formatTokenList = new List<FormatToken>();
}
#endregion
}
namespace System.Management.Automation
{
/// <summary>
/// Defines a table control
/// </summary>
public sealed class TableControl : PSControl
{
/// <summary>Collection of column header definitions for this table control</summary>
public List<TableControlColumnHeader> Headers { get; set; }
/// <summary>Collection of row definitions for this table control</summary>
public List<TableControlRow> Rows { get; set; }
/// <summary>When true, column widths are calculated based on more than the first object.</summary>
public bool AutoSize { get; set; }
/// <summary>When true, table headers are not displayed</summary>
public bool HideTableHeaders { get; set; }
/// <summary>Create a default TableControl</summary>
public static TableControlBuilder Create(bool outOfBand = false, bool autoSize = false, bool hideTableHeaders = false)
{
var table = new TableControl { OutOfBand = outOfBand, AutoSize = autoSize, HideTableHeaders = hideTableHeaders };
return new TableControlBuilder(table);
}
/// <summary>Public default constructor for TableControl</summary>
public TableControl()
{
Headers = new List<TableControlColumnHeader>();
Rows = new List<TableControlRow>();
}
internal override void WriteToXml(FormatXmlWriter writer)
{
writer.WriteTableControl(this);
}
/// <summary>
/// Determines if this object is safe to be written
/// </summary>
/// <returns>true if safe, false otherwise</returns>
internal override bool SafeForExport()
{
if (!base.SafeForExport())
return false;
foreach (var row in Rows)
{
if (!row.SafeForExport())
return false;
}
return true;
}
internal override bool CompatibleWithOldPowerShell()
{
if (!base.CompatibleWithOldPowerShell())
return false;
foreach (var row in Rows)
{
if (!row.CompatibleWithOldPowerShell())
return false;
}
return true;
}
internal TableControl(TableControlBody tcb, ViewDefinition viewDefinition) : this()
{
this.OutOfBand = viewDefinition.outOfBand;
this.GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy);
this.AutoSize = tcb.autosize.HasValue && tcb.autosize.Value;
this.HideTableHeaders = tcb.header.hideHeader;
TableControlRow row = new TableControlRow(tcb.defaultDefinition);
Rows.Add(row);
foreach (TableRowDefinition rd in tcb.optionalDefinitionList)
{
row = new TableControlRow(rd);
Rows.Add(row);
}
foreach (TableColumnHeaderDefinition hd in tcb.header.columnHeaderDefinitionList)
{
TableControlColumnHeader header = new TableControlColumnHeader(hd);
Headers.Add(header);
}
}
/// <summary>
/// public constructor for TableControl that only takes 'tableControlRows'.
/// </summary>
/// <param name="tableControlRow"></param>
public TableControl(TableControlRow tableControlRow) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
this.Rows.Add(tableControlRow);
}
/// <summary>
/// public constructor for TableControl that takes both 'tableControlRows' and 'tableControlColumnHeaders'.
/// </summary>
/// <param name="tableControlRow"></param>
/// <param name="tableControlColumnHeaders"></param>
public TableControl(TableControlRow tableControlRow, IEnumerable<TableControlColumnHeader> tableControlColumnHeaders) : this()
{
if (tableControlRow == null)
throw PSTraceSource.NewArgumentNullException("tableControlRows");
if (tableControlColumnHeaders == null)
throw PSTraceSource.NewArgumentNullException("tableControlColumnHeaders");
this.Rows.Add(tableControlRow);
foreach (TableControlColumnHeader header in tableControlColumnHeaders)
{
this.Headers.Add(header);
}
}
}
/// <summary>
/// Defines the header for a particular column in a table control
/// </summary>
public sealed class TableControlColumnHeader
{
/// <summary>Label for the column</summary>
public string Label { get; set; }
/// <summary>Alignment of the string within the column</summary>
public Alignment Alignment { get; set; }
/// <summary>Width of the column - in number of display cells</summary>
public int Width { get; set; }
internal TableControlColumnHeader(TableColumnHeaderDefinition colheaderdefinition)
{
if (colheaderdefinition.label != null)
{
Label = colheaderdefinition.label.text;
}
Alignment = (Alignment)colheaderdefinition.alignment;
Width = colheaderdefinition.width;
}
/// <summary>Default constructor</summary>
public TableControlColumnHeader()
{
}
/// <summary>
/// Public constructor for TableControlColumnHeader.
/// </summary>
/// <param name="label">Could be null if no label to specify</param>
/// <param name="width">The Value should be non-negative</param>
/// <param name="alignment">The default value is Alignment.Undefined</param>
public TableControlColumnHeader(string label, int width, Alignment alignment)
{
if (width < 0)
throw PSTraceSource.NewArgumentOutOfRangeException("width", width);
this.Label = label;
this.Width = width;
this.Alignment = alignment;
}
}
/// <summary>
/// Defines a particular column within a row
/// in a table control
/// </summary>
public sealed class TableControlColumn
{
/// <summary>Alignment of the particular column</summary>
public Alignment Alignment { get; set; }
/// <summary>Display Entry</summary>
public DisplayEntry DisplayEntry { get; set; }
/// <summary>Format string to apply</summary>
public string FormatString { get; internal set; }
/// <summary>
/// Returns the value of the entry
/// </summary>
/// <returns></returns>
public override string ToString()
{
return DisplayEntry.Value;
}
/// <summary>Default constructor</summary>
public TableControlColumn()
{
}
internal TableControlColumn(string text, int alignment, bool isscriptblock, string formatString)
{
Alignment = (Alignment)alignment;
DisplayEntry = new DisplayEntry(text, isscriptblock ? DisplayEntryValueType.ScriptBlock : DisplayEntryValueType.Property);
FormatString = formatString;
}
/// <summary>
/// Public constructor for TableControlColumn.
/// </summary>
/// <param name="alignment"></param>
/// <param name="entry"></param>
public TableControlColumn(Alignment alignment, DisplayEntry entry)
{
this.Alignment = alignment;
this.DisplayEntry = entry;
}
internal bool SafeForExport()
{
return DisplayEntry.SafeForExport();
}
}
/// <summary>
/// Defines a single row in a table control
/// </summary>
public sealed class TableControlRow
{
/// <summary>Collection of column definitions for this row</summary>
public List<TableControlColumn> Columns { get; set; }
/// <summary>List of typenames which select this entry</summary>
public EntrySelectedBy SelectedBy { get; internal set; }
/// <summary>When true, instead of truncating to the column width, use multiple lines.</summary>
public bool Wrap { get; set; }
/// <summary>Public constructor for TableControlRow</summary>
public TableControlRow()
{
Columns = new List<TableControlColumn>();
}
internal TableControlRow(TableRowDefinition rowdefinition) : this()
{
Wrap = rowdefinition.multiLine;
if (rowdefinition.appliesTo != null)
{
SelectedBy = EntrySelectedBy.Get(rowdefinition.appliesTo.referenceList);
}
foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList)
{
FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken;
TableControlColumn column;
if (fpt != null)
{
column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment,
fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString);
}
else
{
column = new TableControlColumn();
}
Columns.Add(column);
}
}
/// <summary>Public constructor for TableControlRow.</summary>
public TableControlRow(IEnumerable<TableControlColumn> columns) : this()
{
if (columns == null)
throw PSTraceSource.NewArgumentNullException("columns");
foreach (TableControlColumn column in columns)
{
Columns.Add(column);
}
}
internal bool SafeForExport()
{
foreach (var column in Columns)
{
if (!column.SafeForExport())
return false;
}
return SelectedBy != null && SelectedBy.SafeForExport();
}
internal bool CompatibleWithOldPowerShell()
{
// Old versions of PowerShell don't support multiple row definitions.
return SelectedBy == null;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableRowDefinitionBuilder
{
internal readonly TableControlBuilder _tcb;
internal readonly TableControlRow _tcr;
internal TableRowDefinitionBuilder(TableControlBuilder tcb, TableControlRow tcr)
{
_tcb = tcb;
_tcr = tcr;
}
private TableRowDefinitionBuilder AddItem(string value, DisplayEntryValueType entryType, Alignment alignment, string format)
{
if (string.IsNullOrEmpty(value))
throw PSTraceSource.NewArgumentException("value");
var tableControlColumn = new TableControlColumn(alignment, new DisplayEntry(value, entryType))
{
FormatString = format
};
_tcr.Columns.Add(tableControlColumn);
return this;
}
/// <summary>
/// Add a column to the current row definition that calls a script block.
/// </summary>
public TableRowDefinitionBuilder AddScriptBlockColumn(string scriptBlock, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(scriptBlock, DisplayEntryValueType.ScriptBlock, alignment, format);
}
/// <summary>
/// Add a column to the current row definition that references a property.
/// </summary>
public TableRowDefinitionBuilder AddPropertyColumn(string propertyName, Alignment alignment = Alignment.Undefined, string format = null)
{
return AddItem(propertyName, DisplayEntryValueType.Property, alignment, format);
}
/// <summary>
/// Complete a row definition
/// </summary>
public TableControlBuilder EndRowDefinition()
{
return _tcb;
}
}
/// <summary>A helper class for defining table controls</summary>
public sealed class TableControlBuilder
{
internal readonly TableControl _table;
internal TableControlBuilder(TableControl table)
{
_table = table;
}
/// <summary>Group instances by the property name with an optional label.</summary>
public TableControlBuilder GroupByProperty(string property, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(property, DisplayEntryValueType.Property),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Group instances by the script block expression with an optional label.</summary>
public TableControlBuilder GroupByScriptBlock(string scriptBlock, CustomControl customControl = null, string label = null)
{
_table.GroupBy = new PSControlGroupBy
{
Expression = new DisplayEntry(scriptBlock, DisplayEntryValueType.ScriptBlock),
CustomControl = customControl,
Label = label
};
return this;
}
/// <summary>Add a header</summary>
public TableControlBuilder AddHeader(Alignment alignment = Alignment.Undefined, int width = 0, string label = null)
{
_table.Headers.Add(new TableControlColumnHeader(label, width, alignment));
return this;
}
/// <summary>Add a header</summary>
public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerable<string> entrySelectedByType = null, IEnumerable<DisplayEntry> entrySelectedByCondition = null)
{
var row = new TableControlRow { Wrap = wrap };
if (entrySelectedByType != null || entrySelectedByCondition != null)
{
row.SelectedBy = new EntrySelectedBy();
if (entrySelectedByType != null)
{
row.SelectedBy.TypeNames = new List<string>(entrySelectedByType);
}
if (entrySelectedByCondition != null)
{
row.SelectedBy.SelectionCondition = new List<DisplayEntry>(entrySelectedByCondition);
}
}
_table.Rows.Add(row);
return new TableRowDefinitionBuilder(this, row);
}
/// <summary>Complete a table definition</summary>
public TableControl EndTable()
{
return _table;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.ComponentModel.Design;
namespace stUI
{
/// <summary>
/// Aqua Gauge Control - A Windows User Control.
/// Author : Ambalavanar Thirugnanam
/// Date : 24th August 2007
/// email : ambalavanar.thiru@gmail.com
/// This is control is for free. You can use for any commercial or non-commercial purposes.
/// [Please do no remove this header when using this control in your application.]
/// </summary>
[DefaultProperty("Threshold"),
DefaultEvent("ThresholdExceeded"),
HelpKeywordAttribute(typeof(System.Windows.Forms.UserControl)),
ToolboxItem("System.Windows.Forms.Design.AutoSizeToolboxItem,System.Design"),
ToolboxBitmap(typeof(System.Windows.Forms.Timer))]
public partial class stGauge : UserControl
{
#region Private Attributes
private System.ComponentModel.IContainer components = null;
private float minValue;
private float maxValue;
private float threshold;
private float currentValue;
private float recommendedValue;
private int noOfDivisions;
private int noOfSubDivisions;
private string dialText;
private Color dialColor = Color.Lavender;
private float glossinessAlpha = 25;
private int oldWidth, oldHeight;
int x, y, width, height;
float fromAngle = 135F;
float toAngle = 405F;
private bool enableTransparentBackground;
private bool requiresRedraw;
private Image backgroundImg;
private Rectangle rectImg;
#endregion
public stGauge()
{
InitializeComponent();
x = 5;
y = 5;
width = this.Width - 10;
height = this.Height - 10;
this.noOfDivisions = 10;
this.noOfSubDivisions = 3;
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.BackColor = Color.Transparent;
this.Resize += new EventHandler(stGauge_Resize);
this.requiresRedraw = true;
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// stGauge
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "stGauge";
this.ResumeLayout(false);
}
#endregion
#region Public Properties
/// <summary>
/// Mininum value on the scale
/// </summary>
[DefaultValue(0)]
[Description("Mininum value on the scale")]
public float MinValue
{
get { return minValue; }
set
{
if (value < maxValue)
{
minValue = value;
if (currentValue < minValue)
currentValue = minValue;
if (recommendedValue < minValue)
recommendedValue = minValue;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Maximum value on the scale
/// </summary>
[DefaultValue(100)]
[Description("Maximum value on the scale")]
public float MaxValue
{
get { return maxValue; }
set
{
if (value > minValue)
{
maxValue = value;
if (currentValue > maxValue)
currentValue = maxValue;
if (recommendedValue > maxValue)
recommendedValue = maxValue;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Gets or Sets the Threshold area from the Recommended Value. (1-99%)
/// </summary>
[DefaultValue(25)]
[Description("Gets or Sets the Threshold area from the Recommended Value. (1-99%)")]
public float ThresholdPercent
{
get { return threshold; }
set
{
if (value > 0 && value < 100)
{
threshold = value;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Threshold value from which green area will be marked.
/// </summary>
[DefaultValue(25)]
[Description("Threshold value from which green area will be marked.")]
public float RecommendedValue
{
get { return recommendedValue; }
set
{
if (value > minValue && value < maxValue)
{
recommendedValue = value;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Value where the pointer will point to.
/// </summary>
[DefaultValue(0)]
[Description("Value where the pointer will point to.")]
public float Value
{
get { return currentValue; }
set
{
if (value >= minValue && value <= maxValue)
{
currentValue = value;
this.Refresh();
}
}
}
/// <summary>
/// Background color of the dial
/// </summary>
[Description("Background color of the dial")]
public Color DialColor
{
get { return dialColor; }
set
{
dialColor = value;
requiresRedraw = true;
this.Invalidate();
}
}
/// <summary>
/// Glossiness strength. Range: 0-100
/// </summary>
[DefaultValue(72)]
[Description("Glossiness strength. Range: 0-100")]
public float Glossiness
{
get
{
return (glossinessAlpha * 100) / 220;
}
set
{
float val = value;
if(val > 100)
value = 100;
if(val < 0)
value = 0;
glossinessAlpha = (value * 220) / 100;
this.Refresh();
}
}
/// <summary>
/// Get or Sets the number of Divisions in the dial scale.
/// </summary>
[DefaultValue(10)]
[Description("Get or Sets the number of Divisions in the dial scale.")]
public int NoOfDivisions
{
get { return this.noOfDivisions; }
set
{
if (value > 1 && value < 25)
{
this.noOfDivisions = value;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Gets or Sets the number of Sub Divisions in the scale per Division.
/// </summary>
[DefaultValue(3)]
[Description("Gets or Sets the number of Sub Divisions in the scale per Division.")]
public int NoOfSubDivisions
{
get { return this.noOfSubDivisions; }
set
{
if (value > 0 && value <= 10)
{
this.noOfSubDivisions = value;
requiresRedraw = true;
this.Invalidate();
}
}
}
/// <summary>
/// Gets or Sets the Text to be displayed in the dial
/// </summary>
[Description("Gets or Sets the Text to be displayed in the dial")]
public string DialText
{
get { return this.dialText; }
set
{
this.dialText = value;
requiresRedraw = true;
this.Invalidate();
}
}
/// <summary>
/// Enables or Disables Transparent Background color.
/// Note: Enabling this will reduce the performance and may make the control flicker.
/// </summary>
[DefaultValue(false)]
[Description("Enables or Disables Transparent Background color. Note: Enabling this will reduce the performance and may make the control flicker.")]
public bool EnableTransparentBackground
{
get { return this.enableTransparentBackground; }
set
{
this.enableTransparentBackground = value;
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, !enableTransparentBackground);
requiresRedraw = true;
this.Refresh();
}
}
#endregion
#region Overriden Control methods
/// <summary>
/// Draws the pointer.
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
width = this.Width - x*2;
height = this.Height - y*2;
DrawPointer(e.Graphics, ((width) / 2) + x, ((height) / 2) + y);
}
/// <summary>
/// Draws the dial background.
/// </summary>
/// <param name="e"></param>
protected override void OnPaintBackground(PaintEventArgs e)
{
if (!enableTransparentBackground)
{
base.OnPaintBackground(e);
}
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
e.Graphics.FillRectangle(new SolidBrush(Color.Transparent), new Rectangle(0,0,Width,Height));
if (backgroundImg == null || requiresRedraw)
{
backgroundImg = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(backgroundImg);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
width = this.Width - x * 2;
height = this.Height - y * 2;
rectImg = new Rectangle(x, y, width, height);
//Draw background color
Brush backGroundBrush = new SolidBrush(Color.FromArgb(120, dialColor));
if (enableTransparentBackground && this.Parent != null)
{
float gg = width / 60;
//g.FillEllipse(new SolidBrush(this.Parent.BackColor), -gg, -gg, this.Width+gg*2, this.Height+gg*2);
}
g.FillEllipse(backGroundBrush, x, y, width, height);
//Draw Rim
SolidBrush outlineBrush = new SolidBrush(Color.FromArgb(100, Color.SlateGray));
Pen outline = new Pen(outlineBrush, (float)(width * .03));
g.DrawEllipse(outline, rectImg);
Pen darkRim = new Pen(Color.SlateGray);
g.DrawEllipse(darkRim, x, y, width, height);
//Draw Callibration
DrawCalibration(g, rectImg, ((width) / 2) + x, ((height) / 2) + y);
//Draw Colored Rim
Pen colorPen = new Pen(Color.FromArgb(190, Color.Gainsboro), this.Width / 40);
Pen blackPen = new Pen(Color.FromArgb(250, Color.Black), this.Width / 200);
int gap = (int)(this.Width * 0.03F);
Rectangle rectg = new Rectangle(rectImg.X + gap, rectImg.Y + gap, rectImg.Width - gap * 2, rectImg.Height - gap * 2);
g.DrawArc(colorPen, rectg, 135, 270);
//Draw Threshold
colorPen = new Pen(Color.FromArgb(200, Color.LawnGreen), this.Width / 50);
rectg = new Rectangle(rectImg.X + gap, rectImg.Y + gap, rectImg.Width - gap * 2, rectImg.Height - gap * 2);
float val = MaxValue - MinValue;
val = (100 * (this.recommendedValue - MinValue)) / val;
val = ((toAngle - fromAngle) * val) / 100;
val += fromAngle;
float stAngle = val - ((270 * threshold) / 200);
if (stAngle <= 135) stAngle = 135;
float sweepAngle = ((270 * threshold) / 100);
if (stAngle + sweepAngle > 405) sweepAngle = 405 - stAngle;
g.DrawArc(colorPen, rectg, stAngle, sweepAngle);
//Draw Digital Value
RectangleF digiRect = new RectangleF((float)this.Width / 2F - (float)this.width / 5F, (float)this.height / 1.2F, (float)this.width / 2.5F, (float)this.Height / 9F);
RectangleF digiFRect = new RectangleF(this.Width / 2 - this.width / 7, (int)(this.height / 1.18), this.width / 4, this.Height / 12);
g.FillRectangle(new SolidBrush(Color.FromArgb(30, Color.Gray)), digiRect);
DisplayNumber(g, this.currentValue, digiFRect);
SizeF textSize = g.MeasureString(this.dialText, this.Font);
RectangleF digiFRectText = new RectangleF(this.Width / 2 - textSize.Width / 2, (int)(this.height / 1.5), textSize.Width, textSize.Height);
g.DrawString(dialText, this.Font, new SolidBrush(this.ForeColor), digiFRectText);
requiresRedraw = false;
}
e.Graphics.DrawImage(backgroundImg, rectImg);
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20;
return cp;
}
}
#endregion
#region Private methods
/// <summary>
/// Draws the Pointer.
/// </summary>
/// <param name="gr"></param>
/// <param name="cx"></param>
/// <param name="cy"></param>
private void DrawPointer(Graphics gr, int cx, int cy)
{
float radius = this.Width / 2 - (this.Width * .12F);
float val = MaxValue - MinValue;
Image img = new Bitmap(this.Width, this.Height);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
val = (100 * (this.currentValue - MinValue)) / val;
val = ((toAngle - fromAngle) * val) / 100;
val += fromAngle;
float angle = GetRadian(val);
float gradientAngle = angle;
PointF[] pts = new PointF[5];
pts[0].X = (float)(cx + radius * Math.Cos(angle));
pts[0].Y = (float)(cy + radius * Math.Sin(angle));
pts[4].X = (float)(cx + radius * Math.Cos(angle - 0.02));
pts[4].Y = (float)(cy + radius * Math.Sin(angle - 0.02));
angle = GetRadian((val + 20));
pts[1].X = (float)(cx + (this.Width * .09F) * Math.Cos(angle));
pts[1].Y = (float)(cy + (this.Width * .09F) * Math.Sin(angle));
pts[2].X = cx;
pts[2].Y = cy;
angle = GetRadian((val - 20));
pts[3].X = (float)(cx + (this.Width * .09F) * Math.Cos(angle));
pts[3].Y = (float)(cy + (this.Width * .09F) * Math.Sin(angle));
Brush pointer = new SolidBrush(Color.Black);
g.FillPolygon(pointer, pts);
PointF[] shinePts = new PointF[3];
angle = GetRadian(val);
shinePts[0].X = (float)(cx + radius * Math.Cos(angle));
shinePts[0].Y = (float)(cy + radius * Math.Sin(angle));
angle = GetRadian(val + 20);
shinePts[1].X = (float)(cx + (this.Width * .09F) * Math.Cos(angle));
shinePts[1].Y = (float)(cy + (this.Width * .09F) * Math.Sin(angle));
shinePts[2].X = cx;
shinePts[2].Y = cy;
LinearGradientBrush gpointer = new LinearGradientBrush(shinePts[0], shinePts[2], Color.SlateGray, Color.Black);
g.FillPolygon(gpointer, shinePts);
Rectangle rect = new Rectangle(x, y, width, height);
DrawCenterPoint(g, rect, ((width) / 2) + x, ((height) / 2) + y);
DrawGloss(g);
gr.DrawImage(img, 0, 0);
}
/// <summary>
/// Draws the glossiness.
/// </summary>
/// <param name="g"></param>
private void DrawGloss(Graphics g)
{
RectangleF glossRect = new RectangleF(
x + (float)(width * 0.10),
y + (float)(height * 0.07),
(float)(width * 0.80),
(float)(height * 0.7));
LinearGradientBrush gradientBrush =
new LinearGradientBrush(glossRect,
Color.FromArgb((int)glossinessAlpha, Color.White),
Color.Transparent,
LinearGradientMode.Vertical);
g.FillEllipse(gradientBrush, glossRect);
//TODO: Gradient from bottom
glossRect = new RectangleF(
x + (float)(width * 0.25),
y + (float)(height * 0.77),
(float)(width * 0.50),
(float)(height * 0.2));
int gloss = (int)(glossinessAlpha / 3);
gradientBrush =
new LinearGradientBrush(glossRect,
Color.Transparent, Color.FromArgb(gloss, this.BackColor),
LinearGradientMode.Vertical);
g.FillEllipse(gradientBrush, glossRect);
}
/// <summary>
/// Draws the center point.
/// </summary>
/// <param name="g"></param>
/// <param name="rect"></param>
/// <param name="cX"></param>
/// <param name="cY"></param>
private void DrawCenterPoint(Graphics g, Rectangle rect, int cX, int cY)
{
float shift = Width / 5;
RectangleF rectangle = new RectangleF(cX - (shift / 2), cY - (shift / 2), shift, shift);
LinearGradientBrush brush = new LinearGradientBrush(rect, Color.Black, Color.FromArgb(100,this.dialColor), LinearGradientMode.Vertical);
g.FillEllipse(brush, rectangle);
shift = Width / 7;
rectangle = new RectangleF(cX - (shift / 2), cY - (shift / 2), shift, shift);
brush = new LinearGradientBrush(rect, Color.SlateGray, Color.Black, LinearGradientMode.ForwardDiagonal);
g.FillEllipse(brush, rectangle);
}
/// <summary>
/// Draws the Ruler
/// </summary>
/// <param name="g"></param>
/// <param name="rect"></param>
/// <param name="cX"></param>
/// <param name="cY"></param>
private void DrawCalibration(Graphics g, Rectangle rect, int cX, int cY)
{
int noOfParts = this.noOfDivisions + 1;
int noOfIntermediates = this.noOfSubDivisions;
float currentAngle = GetRadian(fromAngle);
int gap = (int)(this.Width * 0.01F);
float shift = this.Width / 25;
Rectangle rectangle = new Rectangle(rect.Left + gap, rect.Top + gap, rect.Width - gap, rect.Height - gap);
float x,y,x1,y1,tx,ty,radius;
radius = rectangle.Width/2 - gap*5;
float totalAngle = toAngle - fromAngle;
float incr = GetRadian(((totalAngle) / ((noOfParts - 1) * (noOfIntermediates + 1))));
Pen thickPen = new Pen(Color.Black, Width/50);
Pen thinPen = new Pen(Color.Black, Width/100);
float rulerValue = MinValue;
for (int i = 0; i <= noOfParts; i++)
{
//Draw Thick Line
x = (float)(cX + radius * Math.Cos(currentAngle));
y = (float)(cY + radius * Math.Sin(currentAngle));
x1 = (float)(cX + (radius - Width/20) * Math.Cos(currentAngle));
y1 = (float)(cY + (radius - Width/20) * Math.Sin(currentAngle));
g.DrawLine(thickPen, x, y, x1, y1);
//Draw Strings
StringFormat format = new StringFormat();
tx = (float)(cX + (radius - Width / 10) * Math.Cos(currentAngle));
ty = (float)(cY-shift + (radius - Width / 10) * Math.Sin(currentAngle));
Brush stringPen = new SolidBrush(this.ForeColor);
StringFormat strFormat = new StringFormat(StringFormatFlags.NoClip);
strFormat.Alignment = StringAlignment.Center;
Font f = new Font(this.Font.FontFamily, (float)(this.Width / 23), this.Font.Style);
g.DrawString(rulerValue.ToString() + "", f, stringPen, new PointF(tx, ty), strFormat);
rulerValue += (float)((MaxValue - MinValue) / (noOfParts - 1));
rulerValue = (float)Math.Round(rulerValue, 2);
//currentAngle += incr;
if (i == noOfParts -1)
break;
for (int j = 0; j <= noOfIntermediates; j++)
{
//Draw thin lines
currentAngle += incr;
x = (float)(cX + radius * Math.Cos(currentAngle));
y = (float)(cY + radius * Math.Sin(currentAngle));
x1 = (float)(cX + (radius - Width/50) * Math.Cos(currentAngle));
y1 = (float)(cY + (radius - Width/50) * Math.Sin(currentAngle));
g.DrawLine(thinPen, x, y, x1, y1);
}
}
}
/// <summary>
/// Converts the given degree to radian.
/// </summary>
/// <param name="theta"></param>
/// <returns></returns>
public float GetRadian(float theta)
{
return theta * (float)Math.PI / 180F;
}
/// <summary>
/// Displays the given number in the 7-Segement format.
/// </summary>
/// <param name="g"></param>
/// <param name="number"></param>
/// <param name="drect"></param>
private void DisplayNumber(Graphics g, float number, RectangleF drect)
{
try
{
string num = number.ToString("000.00");
num.PadLeft(3, '0');
float shift = 0;
if (number < 0)
{
shift -= width/17;
}
bool drawDPS = false;
char[] chars = num.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (i < chars.Length - 1 && chars[i + 1] == '.')
drawDPS = true;
else
drawDPS = false;
if (c != '.')
{
if (c == '-')
{
DrawDigit(g, -1, new PointF(drect.X + shift, drect.Y), drawDPS, drect.Height);
}
else
{
DrawDigit(g, Int16.Parse(c.ToString()), new PointF(drect.X + shift, drect.Y), drawDPS, drect.Height);
}
shift += 15 * this.width / 250;
}
else
{
shift += 2 * this.width / 250;
}
}
}
catch (Exception)
{
}
}
/// <summary>
/// Draws a digit in 7-Segement format.
/// </summary>
/// <param name="g"></param>
/// <param name="number"></param>
/// <param name="position"></param>
/// <param name="dp"></param>
/// <param name="height"></param>
private void DrawDigit(Graphics g, int number, PointF position, bool dp, float height)
{
float width;
width = 10F * height/13;
Pen outline = new Pen(Color.FromArgb(40, this.dialColor));
Pen fillPen = new Pen(Color.Black);
#region Form Polygon Points
//Segment A
PointF[] segmentA = new PointF[5];
segmentA[0] = segmentA[4] = new PointF(position.X + GetX(2.8F, width), position.Y + GetY(1F, height));
segmentA[1] = new PointF(position.X + GetX(10, width), position.Y + GetY(1F, height));
segmentA[2] = new PointF(position.X + GetX(8.8F, width), position.Y + GetY(2F, height));
segmentA[3] = new PointF(position.X + GetX(3.8F, width), position.Y + GetY(2F, height));
//Segment B
PointF[] segmentB = new PointF[5];
segmentB[0] = segmentB[4] = new PointF(position.X + GetX(10, width), position.Y + GetY(1.4F, height));
segmentB[1] = new PointF(position.X + GetX(9.3F, width), position.Y + GetY(6.8F, height));
segmentB[2] = new PointF(position.X + GetX(8.4F, width), position.Y + GetY(6.4F, height));
segmentB[3] = new PointF(position.X + GetX(9F, width), position.Y + GetY(2.2F, height));
//Segment C
PointF[] segmentC = new PointF[5];
segmentC[0] = segmentC[4] = new PointF(position.X + GetX(9.2F, width), position.Y + GetY(7.2F, height));
segmentC[1] = new PointF(position.X + GetX(8.7F, width), position.Y + GetY(12.7F, height));
segmentC[2] = new PointF(position.X + GetX(7.6F, width), position.Y + GetY(11.9F, height));
segmentC[3] = new PointF(position.X + GetX(8.2F, width), position.Y + GetY(7.7F, height));
//Segment D
PointF[] segmentD = new PointF[5];
segmentD[0] = segmentD[4] = new PointF(position.X + GetX(7.4F, width), position.Y + GetY(12.1F, height));
segmentD[1] = new PointF(position.X + GetX(8.4F, width), position.Y + GetY(13F, height));
segmentD[2] = new PointF(position.X + GetX(1.3F, width), position.Y + GetY(13F, height));
segmentD[3] = new PointF(position.X + GetX(2.2F, width), position.Y + GetY(12.1F, height));
//Segment E
PointF[] segmentE = new PointF[5];
segmentE[0] = segmentE[4] = new PointF(position.X + GetX(2.2F, width), position.Y + GetY(11.8F, height));
segmentE[1] = new PointF(position.X + GetX(1F, width), position.Y + GetY(12.7F, height));
segmentE[2] = new PointF(position.X + GetX(1.7F, width), position.Y + GetY(7.2F, height));
segmentE[3] = new PointF(position.X + GetX(2.8F, width), position.Y + GetY(7.7F, height));
//Segment F
PointF[] segmentF = new PointF[5];
segmentF[0] = segmentF[4] = new PointF(position.X + GetX(3F, width), position.Y + GetY(6.4F, height));
segmentF[1] = new PointF(position.X + GetX(1.8F, width), position.Y + GetY(6.8F, height));
segmentF[2] = new PointF(position.X + GetX(2.6F, width), position.Y + GetY(1.3F, height));
segmentF[3] = new PointF(position.X + GetX(3.6F, width), position.Y + GetY(2.2F, height));
//Segment G
PointF[] segmentG = new PointF[7];
segmentG[0] = segmentG[6] = new PointF(position.X + GetX(2F, width), position.Y + GetY(7F, height));
segmentG[1] = new PointF(position.X + GetX(3.1F, width), position.Y + GetY(6.5F, height));
segmentG[2] = new PointF(position.X + GetX(8.3F, width), position.Y + GetY(6.5F, height));
segmentG[3] = new PointF(position.X + GetX(9F, width), position.Y + GetY(7F, height));
segmentG[4] = new PointF(position.X + GetX(8.2F, width), position.Y + GetY(7.5F, height));
segmentG[5] = new PointF(position.X + GetX(2.9F, width), position.Y + GetY(7.5F, height));
//Segment DP
#endregion
#region Draw Segments Outline
g.FillPolygon(outline.Brush, segmentA);
g.FillPolygon(outline.Brush, segmentB);
g.FillPolygon(outline.Brush, segmentC);
g.FillPolygon(outline.Brush, segmentD);
g.FillPolygon(outline.Brush, segmentE);
g.FillPolygon(outline.Brush, segmentF);
g.FillPolygon(outline.Brush, segmentG);
#endregion
#region Fill Segments
//Fill SegmentA
if (IsNumberAvailable(number, 0, 2, 3, 5, 6, 7, 8, 9))
{
g.FillPolygon(fillPen.Brush, segmentA);
}
//Fill SegmentB
if (IsNumberAvailable(number, 0, 1, 2, 3, 4, 7, 8, 9))
{
g.FillPolygon(fillPen.Brush, segmentB);
}
//Fill SegmentC
if (IsNumberAvailable(number, 0, 1, 3, 4, 5, 6, 7, 8, 9))
{
g.FillPolygon(fillPen.Brush, segmentC);
}
//Fill SegmentD
if (IsNumberAvailable(number, 0, 2, 3, 5, 6, 8, 9))
{
g.FillPolygon(fillPen.Brush, segmentD);
}
//Fill SegmentE
if (IsNumberAvailable(number, 0, 2, 6, 8))
{
g.FillPolygon(fillPen.Brush, segmentE);
}
//Fill SegmentF
if (IsNumberAvailable(number, 0, 4, 5, 6, 7, 8, 9))
{
g.FillPolygon(fillPen.Brush, segmentF);
}
//Fill SegmentG
if (IsNumberAvailable(number, 2, 3, 4, 5, 6, 8, 9, -1))
{
g.FillPolygon(fillPen.Brush, segmentG);
}
#endregion
//Draw decimal point
if (dp)
{
g.FillEllipse(fillPen.Brush, new RectangleF(
position.X + GetX(10F, width),
position.Y + GetY(12F, height),
width/7,
width/7));
}
}
/// <summary>
/// Gets Relative X for the given width to draw digit
/// </summary>
/// <param name="x"></param>
/// <param name="width"></param>
/// <returns></returns>
private float GetX(float x, float width)
{
return x * width / 12;
}
/// <summary>
/// Gets relative Y for the given height to draw digit
/// </summary>
/// <param name="y"></param>
/// <param name="height"></param>
/// <returns></returns>
private float GetY(float y, float height)
{
return y * height / 15;
}
/// <summary>
/// Returns true if a given number is available in the given list.
/// </summary>
/// <param name="number"></param>
/// <param name="listOfNumbers"></param>
/// <returns></returns>
private bool IsNumberAvailable(int number, params int[] listOfNumbers)
{
if (listOfNumbers.Length > 0)
{
foreach (int i in listOfNumbers)
{
if (i == number)
return true;
}
}
return false;
}
/// <summary>
/// Restricts the size to make sure the height and width are always same.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void stGauge_Resize(object sender, EventArgs e)
{
if (this.Width < 136)
{
this.Width = 136;
}
if (oldWidth != this.Width)
{
this.Height = this.Width;
oldHeight = this.Width;
}
if (oldHeight != this.Height)
{
this.Width = this.Height;
oldWidth = this.Width;
}
}
#endregion
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace HtmlAgilityPack
{
/// <summary>
/// Represents an HTML navigator on an HTML document seen as a data store.
/// </summary>
public class HtmlNodeNavigator : XPathNavigator
{
#region Fields
private int _attindex;
private HtmlNode _currentnode;
private HtmlDocument _doc = new HtmlDocument();
private HtmlNameTable _nametable = new HtmlNameTable();
internal bool Trace;
#endregion
#region Constructors
internal HtmlNodeNavigator()
{
Reset();
}
internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode)
{
if (currentNode == null)
{
throw new ArgumentNullException("currentNode");
}
if (currentNode.OwnerDocument != doc)
{
throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild);
}
InternalTrace(null);
_doc = doc;
Reset();
_currentnode = currentNode;
}
private HtmlNodeNavigator(HtmlNodeNavigator nav)
{
if (nav == null)
{
throw new ArgumentNullException("nav");
}
InternalTrace(null);
_doc = nav._doc;
_currentnode = nav._currentnode;
_attindex = nav._attindex;
_nametable = nav._nametable; // REVIEW: should we do this?
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public HtmlNodeNavigator(Stream stream)
{
_doc.Load(stream);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding)
{
_doc.Load(stream, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document.</param>
public HtmlNodeNavigator(TextReader reader)
{
_doc.Load(reader);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
public HtmlNodeNavigator(string path)
{
_doc.Load(path);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(string path, Encoding encoding)
{
_doc.Load(path, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
#endregion
#region Properties
/// <summary>
/// Gets the base URI for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string BaseURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the current HTML document.
/// </summary>
public HtmlDocument CurrentDocument
{
get { return _doc; }
}
/// <summary>
/// Gets the current HTML node.
/// </summary>
public HtmlNode CurrentNode
{
get { return _currentnode; }
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasAttributes
{
get
{
InternalTrace(">" + (_currentnode.Attributes.Count > 0));
return (_currentnode.Attributes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasChildren
{
get
{
InternalTrace(">" + (_currentnode.ChildNodes.Count > 0));
return (_currentnode.ChildNodes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node is an empty element.
/// </summary>
public override bool IsEmptyElement
{
get
{
InternalTrace(">" + !HasChildren);
// REVIEW: is this ok?
return !HasChildren;
}
}
/// <summary>
/// Gets the name of the current HTML node without the namespace prefix.
/// </summary>
public override string LocalName
{
get
{
if (_attindex != -1)
{
InternalTrace("att>" + _currentnode.Attributes[_attindex].Name);
return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name);
}
InternalTrace("node>" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the qualified name of the current node.
/// </summary>
public override string Name
{
get
{
InternalTrace(">" + _currentnode.Name);
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string NamespaceURI
{
get
{
InternalTrace(">");
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the <see cref="XmlNameTable"/> associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get
{
InternalTrace(null);
return _nametable;
}
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + XPathNodeType.Comment);
return XPathNodeType.Comment;
case HtmlNodeType.Document:
InternalTrace(">" + XPathNodeType.Root);
return XPathNodeType.Root;
case HtmlNodeType.Text:
InternalTrace(">" + XPathNodeType.Text);
return XPathNodeType.Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + XPathNodeType.Attribute);
return XPathNodeType.Attribute;
}
InternalTrace(">" + XPathNodeType.Element);
return XPathNodeType.Element;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the prefix associated with the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string Prefix
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
InternalTrace("nt=" + _currentnode.NodeType);
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment);
return ((HtmlCommentNode) _currentnode).Comment;
case HtmlNodeType.Document:
InternalTrace(">");
return "";
case HtmlNodeType.Text:
InternalTrace(">" + ((HtmlTextNode) _currentnode).Text);
return ((HtmlTextNode) _currentnode).Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
InternalTrace(">" + _currentnode.Attributes[_attindex].Value);
return _currentnode.Attributes[_attindex].Value;
}
return _currentnode.InnerText;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the xml:lang scope for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string XmlLang
{
get
{
InternalTrace(null);
return _nametable.GetOrAdd(string.Empty);
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator.
/// </summary>
/// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns>
public override XPathNavigator Clone()
{
InternalTrace(null);
return new HtmlNodeNavigator(this);
}
/// <summary>
/// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns>
public override string GetAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
HtmlAttribute att = _currentnode.Attributes[localName];
if (att == null)
{
InternalTrace(">null");
return null;
}
InternalTrace(">" + att.Value);
return att.Value;
}
/// <summary>
/// Returns the value of the namespace node corresponding to the specified local name.
/// Always returns string.Empty for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns>
public override string GetNamespace(string name)
{
InternalTrace("name=" + name);
return string.Empty;
}
/// <summary>
/// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator that you want to compare against.</param>
/// <returns>true if the two navigators have the same position, otherwise, false.</returns>
public override bool IsSamePosition(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false");
return false;
}
InternalTrace(">" + (nav._currentnode == _currentnode));
return (nav._currentnode == _currentnode);
}
/// <summary>
/// Moves to the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param>
/// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveTo(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
InternalTrace(">false (nav is not an HtmlNodeNavigator)");
return false;
}
InternalTrace("moveto oid=" + nav.GetHashCode()
+ ", n:" + nav._currentnode.Name
+ ", a:" + nav._attindex);
if (nav._doc == _doc)
{
_currentnode = nav._currentnode;
_attindex = nav._attindex;
InternalTrace(">true");
return true;
}
// we don't know how to handle that
InternalTrace(">false (???)");
return false;
}
/// <summary>
/// Moves to the HTML attribute with matching LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
int index = _currentnode.Attributes.GetAttributeIndex(localName);
if (index == -1)
{
InternalTrace(">false");
return false;
}
_attindex = index;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToFirst()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
if (_currentnode.ParentNode.FirstChild == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode.FirstChild;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first HTML attribute.
/// </summary>
/// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns>
public override bool MoveToFirstAttribute()
{
if (!HasAttributes)
{
InternalTrace(">false");
return false;
}
_attindex = 0;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the first child of the current node.
/// </summary>
/// <returns>true if there is a first child node, otherwise false.</returns>
public override bool MoveToFirstChild()
{
if (!_currentnode.HasChildNodes)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ChildNodes[0];
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the first namespace node of the current element.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the node that has an attribute of type ID whose value matches the specified string.
/// </summary>
/// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param>
/// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToId(string id)
{
InternalTrace("id=" + id);
HtmlNode node = _doc.GetElementbyId(id);
if (node == null)
{
InternalTrace(">false");
return false;
}
_currentnode = node;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the namespace node with the specified local name.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNamespace(string name)
{
InternalTrace("name=" + name);
return false;
}
/// <summary>
/// Moves to the next sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToNext()
{
if (_currentnode.NextSibling == null)
{
InternalTrace(">false");
return false;
}
InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml);
InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml);
_currentnode = _currentnode.NextSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the next HTML attribute.
/// </summary>
/// <returns></returns>
public override bool MoveToNextAttribute()
{
InternalTrace(null);
if (_attindex >= (_currentnode.Attributes.Count - 1))
{
InternalTrace(">false");
return false;
}
_attindex++;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves the XPathNavigator to the next namespace node.
/// Always returns falsefor the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
InternalTrace(null);
return false;
}
/// <summary>
/// Moves to the parent of the current node.
/// </summary>
/// <returns>true if there is a parent node, otherwise false.</returns>
public override bool MoveToParent()
{
if (_currentnode.ParentNode == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.ParentNode;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the previous sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToPrevious()
{
if (_currentnode.PreviousSibling == null)
{
InternalTrace(">false");
return false;
}
_currentnode = _currentnode.PreviousSibling;
InternalTrace(">true");
return true;
}
/// <summary>
/// Moves to the root node to which the current node belongs.
/// </summary>
public override void MoveToRoot()
{
_currentnode = _doc.DocumentNode;
InternalTrace(null);
}
#endregion
#region Internal Methods
[Conditional("TRACE")]
internal void InternalTrace(object traceValue)
{
if (!Trace)
{
return;
}
StackFrame sf = new StackFrame(1, true);
string name = sf.GetMethod().Name;
string nodename = _currentnode == null ? "(null)" : _currentnode.Name;
string nodevalue;
if (_currentnode == null)
{
nodevalue = "(null)";
}
else
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
nodevalue = ((HtmlCommentNode) _currentnode).Comment;
break;
case HtmlNodeType.Document:
nodevalue = "";
break;
case HtmlNodeType.Text:
nodevalue = ((HtmlTextNode) _currentnode).Text;
break;
default:
nodevalue = _currentnode.CloneNode(false).OuterHtml;
break;
}
}
HtmlAgilityPack.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name);
}
#endregion
#region Private Methods
private void Reset()
{
InternalTrace(null);
_currentnode = _doc.DocumentNode;
_attindex = -1;
}
#endregion
}
}
| |
// 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.AcceptanceTestsBodyDateTimeRfc1123
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class Datetimerfc1123Extensions
{
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetNull(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetNullAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetInvalid(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetInvalidAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetOverflow(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetOverflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetOverflowAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUnderflow(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUnderflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUnderflowAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMaxDateTime(this IDatetimerfc1123 operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMaxDateTimeAsync( this IDatetimerfc1123 operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcLowercaseMaxDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcLowercaseMaxDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcUppercaseMaxDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcUppercaseMaxDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
public static void PutUtcMinDateTime(this IDatetimerfc1123 operations, DateTime? datetimeBody)
{
Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='datetimeBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutUtcMinDateTimeAsync( this IDatetimerfc1123 operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static DateTime? GetUtcMinDateTime(this IDatetimerfc1123 operations)
{
return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DateTime?> GetUtcMinDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Lucene.Net.Support;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Encapsulates sort criteria for returned hits.
///
/// <para/>The fields used to determine sort order must be carefully chosen.
/// <see cref="Documents.Document"/>s must contain a single term in such a field,
/// and the value of the term should indicate the document's relative position in
/// a given sort order. The field must be indexed, but should not be tokenized,
/// and does not need to be stored (unless you happen to want it back with the
/// rest of your document data). In other words:
///
/// <para/><code>document.Add(new Field("byNumber", x.ToString(CultureInfo.InvariantCulture), Field.Store.NO, Field.Index.NOT_ANALYZED));</code>
///
///
/// <para/><h3>Valid Types of Values</h3>
///
/// <para/>There are four possible kinds of term values which may be put into
/// sorting fields: <see cref="int"/>s, <see cref="long"/>s, <see cref="float"/>s, or <see cref="string"/>s. Unless
/// <see cref="SortField"/> objects are specified, the type of value
/// in the field is determined by parsing the first term in the field.
///
/// <para/><see cref="int"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="int.MinValue"/> and <see cref="int.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values
/// (i.e. the documents should be numbered <c>1..n</c> where
/// <c>1</c> is the first and <c>n</c> the last).
///
/// <para/><see cref="long"/> term values should contain only digits and an optional
/// preceding negative sign. Values must be base 10 and in the range
/// <see cref="long.MinValue"/> and <see cref="long.MaxValue"/> inclusive.
/// Documents which should appear first in the sort
/// should have low value integers, later documents high values.
///
/// <para/><see cref="float"/> term values should conform to values accepted by
/// <see cref="float"/> (except that <c>NaN</c>
/// and <c>Infinity</c> are not supported).
/// <see cref="Documents.Document"/>s which should appear first in the sort
/// should have low values, later documents high values.
///
/// <para/><see cref="string"/> term values can contain any valid <see cref="string"/>, but should
/// not be tokenized. The values are sorted according to their
/// comparable natural order (<see cref="System.StringComparer.Ordinal"/>). Note that using this type
/// of term value has higher memory requirements than the other
/// two types.
///
/// <para/><h3>Object Reuse</h3>
///
/// <para/>One of these objects can be
/// used multiple times and the sort order changed between usages.
///
/// <para/>This class is thread safe.
///
/// <para/><h3>Memory Usage</h3>
///
/// <para/>Sorting uses of caches of term values maintained by the
/// internal HitQueue(s). The cache is static and contains an <see cref="int"/>
/// or <see cref="float"/> array of length <c>IndexReader.MaxDoc</c> for each field
/// name for which a sort is performed. In other words, the size of the
/// cache in bytes is:
///
/// <para/><code>4 * IndexReader.MaxDoc * (# of different fields actually used to sort)</code>
///
/// <para/>For <see cref="string"/> fields, the cache is larger: in addition to the
/// above array, the value of every term in the field is kept in memory.
/// If there are many unique terms in the field, this could
/// be quite large.
///
/// <para/>Note that the size of the cache is not affected by how many
/// fields are in the index and <i>might</i> be used to sort - only by
/// the ones actually used to sort a result set.
///
/// <para/>Created: Feb 12, 2004 10:53:57 AM
/// <para/>
/// @since lucene 1.4
/// </summary>
public class Sort
{
/// <summary>
/// Represents sorting by computed relevance. Using this sort criteria returns
/// the same results as calling
/// <see cref="IndexSearcher.Search(Query, int)"/>without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public static readonly Sort RELEVANCE = new Sort();
/// <summary>
/// Represents sorting by index order. </summary>
public static readonly Sort INDEXORDER = new Sort(SortField.FIELD_DOC);
// internal representation of the sort criteria
internal SortField[] fields;
/// <summary>
/// Sorts by computed relevance. This is the same sort criteria as calling
/// <see cref="IndexSearcher.Search(Query, int)"/> without a sort criteria,
/// only with slightly more overhead.
/// </summary>
public Sort()
: this(SortField.FIELD_SCORE)
{
}
/// <summary>
/// Sorts by the criteria in the given <see cref="SortField"/>. </summary>
public Sort(SortField field)
{
SetSort(field);
}
/// <summary>
/// Sorts in succession by the criteria in each <see cref="SortField"/>. </summary>
public Sort(params SortField[] fields)
{
SetSort(fields);
}
/// <summary>Sets the sort to the given criteria. </summary>
public virtual void SetSort(SortField field)
{
this.fields = new SortField[] { field };
}
/// <summary>Sets the sort to the given criteria in succession. </summary>
public virtual void SetSort(params SortField[] fields)
{
this.fields = fields;
}
/// <summary> Representation of the sort criteria.</summary>
/// <returns> Array of <see cref="SortField"/> objects used in this sort criteria
/// </returns>
[WritableArray]
public virtual SortField[] GetSort()
{
return fields;
}
/// <summary>
/// Rewrites the <see cref="SortField"/>s in this <see cref="Sort"/>, returning a new <see cref="Sort"/> if any of the fields
/// changes during their rewriting.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <param name="searcher"> <see cref="IndexSearcher"/> to use in the rewriting </param>
/// <returns> <c>this</c> if the Sort/Fields have not changed, or a new <see cref="Sort"/> if there
/// is a change </returns>
/// <exception cref="System.IO.IOException"> Can be thrown by the rewriting</exception>
public virtual Sort Rewrite(IndexSearcher searcher)
{
bool changed = false;
SortField[] rewrittenSortFields = new SortField[fields.Length];
for (int i = 0; i < fields.Length; i++)
{
rewrittenSortFields[i] = fields[i].Rewrite(searcher);
if (fields[i] != rewrittenSortFields[i])
{
changed = true;
}
}
return (changed) ? new Sort(rewrittenSortFields) : this;
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < fields.Length; i++)
{
buffer.Append(fields[i].ToString());
if ((i + 1) < fields.Length)
{
buffer.Append(',');
}
}
return buffer.ToString();
}
/// <summary>
/// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is Sort))
{
return false;
}
Sort other = (Sort)o;
return Arrays.Equals(this.fields, other.fields);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return 0x45aaf665 + Arrays.GetHashCode(fields);
}
/// <summary>
/// Returns <c>true</c> if the relevance score is needed to sort documents. </summary>
public virtual bool NeedsScores
{
get
{
foreach (SortField sortField in fields)
{
if (sortField.NeedsScores)
{
return true;
}
}
return false;
}
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
namespace HrdLib
{
partial class HrdDocument
{
private class StreamReader : IDisposable
{
private static readonly char[] CharStatement = "\"[]{}, \t=;/".ToCharArray(),
StatementDelimiters = " \t;".ToCharArray();
private readonly System.IO.StreamReader _innerReader;
private string _currentLine;
private int _linePosition;
private int _lineCounter;
private Statement _nextStatement;
public bool EndOfStream
{
get
{
return _innerReader.EndOfStream &&
(string.IsNullOrEmpty(_currentLine) || _linePosition >= _currentLine.Length);
}
}
public int LineCounter { get { return _lineCounter; } }
public StreamReader(Stream stream)
{
_innerReader = new System.IO.StreamReader(stream, Encoding.UTF8);
}
public Statement ReadNextStatement()
{
if (_nextStatement != null)
{
var stat = _nextStatement;
_nextStatement = null;
return stat;
}
if ((_currentLine == null || _linePosition >= _currentLine.Length) && !ReadNextLine())
return null;
var idx = _currentLine.IndexOfAny(CharStatement, _linePosition);
if (idx < 0 || idx > _linePosition)
{
string str;
if (idx < 0)
{
str = _currentLine.Substring(_linePosition);
_linePosition = _currentLine.Length;
}
else
{
int length = idx - _linePosition;
str = _currentLine.Substring(_linePosition, length);
_linePosition = idx;
}
var st = new Statement();
int intVal;
if (int.TryParse(str, out intVal))
{
st.Type = StatementType.Value;
st.IntValue = intVal;
}
else
{
st.Type = StatementType.Name;
st.Value = str;
}
return st;
}
var ch = _currentLine[idx];
if (ch == '/' && idx != _currentLine.Length - 1)
{
if (_currentLine[idx + 1] == '/')
{
_linePosition = _currentLine.Length;
return ReadNextStatement();
}
if (_currentLine[idx + 1] == '*')
{
const string endComment = "*/";
_linePosition += 2;
int endIdx;
do
{
if (_linePosition <= _currentLine.Length - 2)
endIdx = _currentLine.IndexOf(endComment, _linePosition);
else
endIdx = -1;
if (endIdx >= 0)
break;
} while (ReadNextLine());
if (endIdx < 0)
return null;
_linePosition = endIdx + endComment.Length;
return ReadNextStatement();
}
}
if (StatementDelimiters.Contains(ch))
{
do
{
idx++;
} while (idx < _currentLine.Length && StatementDelimiters.Contains(_currentLine[idx]));
_linePosition = idx;
return ReadNextStatement();
}
switch (ch)
{
case '[':
_linePosition = idx + 1;
return new Statement(StatementType.SquareBracketOpened, "[");
case ']':
_linePosition = idx + 1;
return new Statement(StatementType.SquareBracketClosed, "]");
case '}':
_linePosition = idx + 1;
return new Statement(StatementType.BraceClosed, "}");
case '{':
_linePosition = idx + 1;
return new Statement(StatementType.BraceOpened, "{");
case '\"':
_linePosition = idx + 1;
string str = ReadString();
// concatenation of strings
var statement = ReadNextStatement();
if (statement != null && statement.Type == StatementType.Value && statement.Value != null)
str += statement.Value;
else
_nextStatement = statement;
return new Statement(StatementType.Value, str);
case ',':
_linePosition = idx + 1;
return new Statement(StatementType.Comma, ",");
case '=':
_linePosition = idx + 1;
return new Statement(StatementType.EqualsSign, "=");
default:
return new Statement(StatementType.Unknown, ch.ToString());
}
}
private bool ReadNextLine()
{
while (true)
{
if (_innerReader.EndOfStream)
return false;
string line = _innerReader.ReadLine();
_lineCounter++;
if (string.IsNullOrEmpty(line))
continue;
_currentLine = line;
_linePosition = 0;
break;
}
return true;
}
private string ReadString()
{
char[] specialChar = new[] { '\"', '\\' };
var builder = new StringBuilder();
bool closed = false;
while (!closed)
{
if (_linePosition >= _currentLine.Length)
{
//builder.AppendLine();
if (!ReadNextLine())
throw new Exception("Suddenly! The end of file.");
continue;
}
int specialCharIdx = _currentLine.IndexOfAny(specialChar, _linePosition);
if (specialCharIdx < 0)
{
builder.Append(_currentLine.Substring(_linePosition));
_linePosition = _currentLine.Length;
continue;
}
int len = specialCharIdx - _linePosition;
if (len > 0)
builder.Append(_currentLine.Substring(_linePosition, specialCharIdx - _linePosition));
var ch = _currentLine[specialCharIdx];
if (ch == '"')
{
_linePosition = specialCharIdx + 1;
break;
}
//if(ch=='\')
if (specialCharIdx == _currentLine.Length - 1)
{
builder.AppendLine();
_linePosition = _currentLine.Length;
continue;
}
var nextCh = _currentLine[specialCharIdx + 1];
switch (nextCh)
{
case '"':
case '\\':
builder.Append(nextCh);
break;
case 'n':
builder.AppendLine();
break;
default:
builder.Append(nextCh);
break;
}
_linePosition = specialCharIdx + 2;
}
return builder.ToString();
}
public void Dispose()
{
if (_innerReader != null)
_innerReader.Dispose();
}
}
private class StreamWriter : IDisposable
{
private readonly System.IO.StreamWriter _innerWriter;
private char[] _tabChars;
private int _level;
public StreamWriter(Stream stream)
{
_innerWriter = new System.IO.StreamWriter(stream, Encoding.UTF8);
_tabChars = new char[4];
for (int i = 0; i < _tabChars.Length; i++)
_tabChars[i] = '\t';
}
public void WriteStatement(StatementType type)
{
switch (type)
{
case StatementType.Name:
case StatementType.Value:
throw new NotSupportedException(
"Name and value types is not supported by this method. Use WriteStatement(Statemnt) instead.");
case StatementType.BraceClosed:
_level--;
WriteNewLine();
_innerWriter.Write('}');
break;
case StatementType.BraceOpened:
WriteNewLine();
_level++;
_innerWriter.Write("{ ");
break;
case StatementType.Comma:
_innerWriter.Write(", ");
break;
case StatementType.EqualsSign:
_innerWriter.Write(" = ");
break;
case StatementType.SquareBracketClosed:
_level--;
WriteNewLine();
_innerWriter.Write(']');
break;
case StatementType.SquareBracketOpened:
WriteNewLine();
_level++;
_innerWriter.Write("[ ");
break;
default:
throw new Exception("Unknown statement.");
}
}
public void WriteStatement(Statement statement)
{
switch (statement.Type)
{
case StatementType.BraceClosed:
case StatementType.BraceOpened:
case StatementType.Comma:
case StatementType.EqualsSign:
case StatementType.SquareBracketClosed:
case StatementType.SquareBracketOpened:
WriteStatement(statement.Type);
break;
case StatementType.Name:
WriteNewLine();
_innerWriter.Write(statement.Value);
break;
case StatementType.Value:
if (statement.Value == null)
_innerWriter.Write(statement.IntValue.ToString());
else
WriteString(statement.Value);
break;
default:
throw new Exception("Unknown statement.");
}
}
private void WriteString(string str)
{
if (str == null)
str = string.Empty;
var builder = new StringBuilder(str.Length);
builder.Append('"');
foreach (var ch in str)
{
switch (ch)
{
case '\\':
builder.Append("\\\\");
break;
case '"':
builder.Append("\\\"");
break;
case '\n':
builder.AppendLine("\\");
break;
case '\r':
break;
default:
builder.Append(ch);
break;
}
}
builder.Append("\"");
_innerWriter.Write(builder.ToString());
}
private void WriteNewLine()
{
if (_level >= _tabChars.Length)
{
int oldLen = _tabChars.Length;
Array.Resize(ref _tabChars, oldLen * 2);
for (int i = oldLen; i < _tabChars.Length; i++)
_tabChars[i] = '\t';
}
_innerWriter.WriteLine();
if (_level > 0)
_innerWriter.Write(_tabChars, 0, _level);
}
public void Dispose()
{
if (_innerWriter != null)
_innerWriter.Dispose();
}
}
private class Statement
{
public StatementType Type { get; set; }
public string Value { get; set; }
public int IntValue { get; set; }
public Statement() { }
public Statement(StatementType type, string value)
{
Type = type;
Value = value;
}
}
private enum StatementType
{
Unknown,
Value,
Name,
SquareBracketOpened,
SquareBracketClosed,
BraceOpened,
BraceClosed,
Comma,
EqualsSign
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Runtime {
/// <summary>
/// Abstract base class used for optimized thread-safe dictionaries which have a set
/// of pre-defined string keys.
///
/// Implementers derive from this class and override the GetExtraKeys, TrySetExtraValue,
/// and TryGetExtraValue methods. When looking up a value first the extra keys will be
/// searched using the optimized Try*ExtraValue functions. If the value isn't found there
/// then the value is stored in the underlying .NET dictionary.
///
/// This dictionary can store object values in addition to string values. It also supports
/// null keys.
/// </summary>
public abstract class CustomStringDictionary :
#if CLR2
IValueEquality,
#endif
IDictionary, IDictionary<object, object> {
private Dictionary<object, object> _data;
private static readonly object _nullObject = new object();
protected CustomStringDictionary() {
}
/// <summary>
/// Gets a list of the extra keys that are cached by the the optimized implementation
/// of the module.
/// </summary>
public abstract string[] GetExtraKeys();
/// <summary>
/// Try to set the extra value and return true if the specified key was found in the
/// list of extra values.
/// </summary>
protected internal abstract bool TrySetExtraValue(string key, object value);
/// <summary>
/// Try to get the extra value and returns true if the specified key was found in the
/// list of extra values. Returns true even if the value is Uninitialized.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
protected internal abstract bool TryGetExtraValue(string key, out object value);
private void InitializeData() {
Debug.Assert(_data == null);
_data = new Dictionary<object, object>();
}
#region IDictionary<object, object> Members
void IDictionary<object, object>.Add(object key, object value) {
string strKey = key as string;
if (strKey != null) {
lock (this) {
if (_data == null) InitializeData();
if (TrySetExtraValue(strKey, value))
return;
_data.Add(strKey, value);
}
} else {
AddObjectKey(key, value);
}
}
private void AddObjectKey(object key, object value) {
if (_data == null) {
InitializeData();
}
_data[key] = value;
}
bool IDictionary<object, object>.ContainsKey(object key) {
lock (this) {
if (_data == null) {
return false;
}
object dummy;
return _data.TryGetValue(key, out dummy);
}
}
public ICollection<object> Keys {
get {
List<object> res = new List<object>();
lock (this) {
if (_data != null) {
res.AddRange(_data.Keys);
}
}
foreach (var key in GetExtraKeys()) {
object dummy;
if (TryGetExtraValue(key, out dummy) && dummy != Uninitialized.Instance) {
res.Add(key);
}
}
return res;
}
}
bool IDictionary<object, object>.Remove(object key) {
string strKey = key as string;
if (strKey != null) {
lock (this) {
if (TrySetExtraValue(strKey, Uninitialized.Instance)) return true;
if (_data == null) return false;
return _data.Remove(strKey);
}
}
return RemoveObjectKey(key);
}
private bool RemoveObjectKey(object key) {
return _data.Remove(key);
}
public bool TryGetValue(object key, out object value) {
string strKey = key as string;
if (strKey != null) {
lock (this) {
if (TryGetExtraValue(strKey, out value) && value != Uninitialized.Instance) return true;
if (_data == null) return false;
return _data.TryGetValue(strKey, out value);
}
}
return TryGetObjectValue(key, out value);
}
private bool TryGetObjectValue(object key, out object value) {
if (_data == null) {
value = null;
return false;
}
return _data.TryGetValue(key, out value);
}
ICollection<object> IDictionary<object, object>.Values {
get {
List<object> res = new List<object>();
lock (this) {
if (_data != null) {
res.AddRange(_data.Values);
}
}
foreach (var key in GetExtraKeys()) {
object value;
if (TryGetExtraValue(key, out value) && value != Uninitialized.Instance) {
res.Add(value);
}
}
return res;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public object this[object key] {
get {
string strKey = key as string;
object res;
if (strKey != null) {
lock (this) {
if (TryGetExtraValue(strKey, out res) && !(res is Uninitialized)) return res;
if (_data == null) {
throw new KeyNotFoundException(strKey);
}
return _data[strKey];
}
}
if (TryGetObjectValue(key, out res))
return res;
throw new KeyNotFoundException(key.ToString());
}
set {
string strKey = key as string;
if (strKey != null) {
lock (this) {
if (TrySetExtraValue(strKey, value)) return;
if (_data == null) InitializeData();
_data[strKey] = value;
}
} else {
AddObjectKey(key, value);
}
}
}
#endregion
#region ICollection<KeyValuePair<string,object>> Members
public void Add(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public void Clear() {
lock (this) {
foreach (var key in GetExtraKeys()) {
TrySetExtraValue(key, Uninitialized.Instance);
}
_data = null;
}
}
public bool Contains(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) {
ContractUtils.RequiresNotNull(array, "array");
ContractUtils.RequiresArrayRange(array, arrayIndex, Count, "araryIndex", "Count");
foreach (KeyValuePair<object, object> kvp in ((IEnumerable<KeyValuePair<object, object>>)this)) {
array[arrayIndex++] = kvp;
}
}
public int Count {
get {
int count = _data != null ? _data.Count : 0;
lock (this) {
foreach (var key in GetExtraKeys()) {
object dummy;
if (TryGetExtraValue(key, out dummy) && dummy != Uninitialized.Instance) count++;
}
}
return count;
}
}
public bool IsReadOnly {
get { return false; }
}
public bool Remove(KeyValuePair<object, object> item) {
throw new NotImplementedException();
}
public bool Remove(object key) {
string strKey = key as string;
if (strKey != null) {
if (TrySetExtraValue(strKey, Uninitialized.Instance)) {
return true;
}
lock (this) {
if (_data != null) {
return _data.Remove(strKey);
}
return false;
}
} else {
return RemoveObjectKey(key);
}
}
#endregion
#region IEnumerable<KeyValuePair<object,object>> Members
IEnumerator<KeyValuePair<object, object>> IEnumerable<KeyValuePair<object, object>>.GetEnumerator() {
if (_data != null) {
foreach (KeyValuePair<object, object> o in _data) {
yield return o;
}
}
foreach (var o in GetExtraKeys()) {
object val;
if (TryGetExtraValue(o, out val) && val != Uninitialized.Instance) {
yield return new KeyValuePair<object, object>(o, val);
}
}
}
#endregion
#region IEnumerable Members
public System.Collections.IEnumerator GetEnumerator() {
List<object> l = new List<object>(this.Keys);
for (int i = 0; i < l.Count; i++) {
object baseVal = l[i];
object nullVal = l[i] = CustomStringDictionary.ObjToNull(l[i]);
if (baseVal != nullVal) {
// we've transformed null, stop looking
break;
}
}
return l.GetEnumerator();
}
#endregion
#region IDictionary Members
void IDictionary.Add(object key, object value) {
((IDictionary<object, object>)this).Add(key, value);
}
public bool Contains(object key) {
object dummy;
return ((IDictionary<object, object>)this).TryGetValue(key, out dummy);
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
List<IDictionaryEnumerator> enums = new List<IDictionaryEnumerator>();
enums.Add(new ExtraKeyEnumerator(this));
if (_data != null) enums.Add(((IDictionary)_data).GetEnumerator());
return new DictionaryUnionEnumerator(enums);
}
public bool IsFixedSize {
get { return false; }
}
ICollection IDictionary.Keys {
get {
return new List<object>(((IDictionary<object, object>)this).Keys);
}
}
void IDictionary.Remove(object key) {
Remove(key);
}
ICollection IDictionary.Values {
get {
return new List<object>(((IDictionary<object, object>)this).Values);
}
}
#endregion
#region IValueEquality Members
public int GetValueHashCode() {
throw Error.DictionaryNotHashable();
}
public virtual bool ValueEquals(object other) {
if (Object.ReferenceEquals(this, other)) return true;
IDictionary<object, object> oth = other as IDictionary<object, object>;
IDictionary<object, object> ths = this as IDictionary<object, object>;
if (oth == null) return false;
if (oth.Count != ths.Count) return false;
foreach (KeyValuePair<object, object> o in ths) {
object res;
if (!oth.TryGetValue(o.Key, out res))
return false;
#if CLR2
IValueEquality ve = res as IValueEquality;
if (ve != null) {
if (!ve.ValueEquals(o.Value)) return false;
} else if ((ve = (o.Value as IValueEquality)) != null) {
if (!ve.Equals(res)) return false;
} else
#endif
if (res != null) {
if (!res.Equals(o.Value)) return false;
} else if (o.Value != null) {
if (!o.Value.Equals(res)) return false;
} // else both null and are equal
}
return true;
}
#endregion
public void CopyTo(Array array, int index) {
throw Error.MethodOrOperatorNotImplemented();
}
public bool IsSynchronized {
get {
return true;
}
}
public object SyncRoot {
get {
// TODO: Sync root shouldn't be this, it should be data.
return this;
}
}
public static object NullToObj(object o) {
if (o == null) return _nullObject;
return o;
}
public static object ObjToNull(object o) {
if (o == _nullObject) return null;
return o;
}
public static bool IsNullObject(object o) {
return o == _nullObject;
}
}
[Obsolete("Derive directly from CustomStringDictionary instead")]
public abstract class CustomSymbolDictionary : CustomStringDictionary {
}
}
| |
/*
* 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; //for [DebuggerNonUserCode]
using System.Reflection;
using System.Runtime.Remoting.Lifetime;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using log4net;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public class Executor
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Contains the script to execute functions in.
/// </summary>
protected IScript m_Script;
protected Dictionary<string, scriptEvents> m_eventFlagsMap = new Dictionary<string, scriptEvents>();
[Flags]
public enum scriptEvents : int
{
None = 0,
attach = 1,
collision = 16,
collision_end = 32,
collision_start = 64,
control = 128,
dataserver = 256,
email = 512,
http_response = 1024,
land_collision = 2048,
land_collision_end = 4096,
land_collision_start = 8192,
at_target = 16384,
at_rot_target = 16777216,
listen = 32768,
money = 65536,
moving_end = 131072,
moving_start = 262144,
not_at_rot_target = 524288,
not_at_target = 1048576,
remote_data = 8388608,
run_time_permissions = 268435456,
state_entry = 1073741824,
state_exit = 2,
timer = 4,
touch = 8,
touch_end = 536870912,
touch_start = 2097152,
transaction_result = 33554432,
object_rez = 4194304
}
// Cache functions by keeping a reference to them in a dictionary
private Dictionary<string, MethodInfo> Events = new Dictionary<string, MethodInfo>();
private Dictionary<string, scriptEvents> m_stateEvents = new Dictionary<string, scriptEvents>();
public Executor(IScript script)
{
m_Script = script;
initEventFlags();
}
public scriptEvents GetStateEventFlags(string state)
{
//m_log.Debug("Get event flags for " + state);
// Check to see if we've already computed the flags for this state
scriptEvents eventFlags = scriptEvents.None;
if (m_stateEvents.ContainsKey(state))
{
m_stateEvents.TryGetValue(state, out eventFlags);
return eventFlags;
}
Type type=m_Script.GetType();
// Fill in the events for this state, cache the results in the map
foreach (KeyValuePair<string, scriptEvents> kvp in m_eventFlagsMap)
{
string evname = state + "_event_" + kvp.Key;
//m_log.Debug("Trying event "+evname);
try
{
MethodInfo mi = type.GetMethod(evname);
if (mi != null)
{
//m_log.Debug("Found handler for " + kvp.Key);
eventFlags |= kvp.Value;
}
}
catch(Exception)
{
//m_log.Debug("Exeption in GetMethod:\n"+e.ToString());
}
}
// Save the flags we just computed and return the result
if (eventFlags != 0)
m_stateEvents.Add(state, eventFlags);
//m_log.Debug("Returning {0:x}", eventFlags);
return (eventFlags);
}
[DebuggerNonUserCode]
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
// IMPORTANT: Types and MemberInfo-derived objects require a LOT of memory.
// Instead use RuntimeTypeHandle, RuntimeFieldHandle and RunTimeHandle (IntPtr) instead!
string EventName = state + "_event_" + FunctionName;
//#if DEBUG
//m_log.Debug("ScriptEngine: Script event function name: " + EventName);
//#endif
if (Events.ContainsKey(EventName) == false)
{
// Not found, create
Type type = m_Script.GetType();
try
{
MethodInfo mi = type.GetMethod(EventName);
Events.Add(EventName, mi);
}
catch
{
// m_log.Error("Event "+EventName+" not found.");
// Event name not found, cache it as not found
Events.Add(EventName, null);
}
}
// Get event
MethodInfo ev = null;
Events.TryGetValue(EventName, out ev);
if (ev == null) // No event by that name!
{
//m_log.Debug("ScriptEngine Can not find any event named: \String.Empty + EventName + "\String.Empty);
return;
}
//cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
#if DEBUG
//m_log.Debug("ScriptEngine: Executing function name: " + EventName);
#endif
// Found
try
{
ev.Invoke(m_Script, args);
}
catch (TargetInvocationException tie)
{
// Grab the inner exception and rethrow it, unless the inner
// exception is an EventAbortException as this indicates event
// invocation termination due to a state change.
// DO NOT THROW JUST THE INNER EXCEPTION!
// FriendlyErrors depends on getting the whole exception!
//
if (!(tie.InnerException is EventAbortException))
{
throw;
}
}
}
protected void initEventFlags()
{
// Initialize the table if it hasn't already been done
if (m_eventFlagsMap.Count > 0)
{
return;
}
m_eventFlagsMap.Add("attach", scriptEvents.attach);
m_eventFlagsMap.Add("at_rot_target", scriptEvents.at_rot_target);
m_eventFlagsMap.Add("at_target", scriptEvents.at_target);
// m_eventFlagsMap.Add("changed",(long)scriptEvents.changed);
m_eventFlagsMap.Add("collision", scriptEvents.collision);
m_eventFlagsMap.Add("collision_end", scriptEvents.collision_end);
m_eventFlagsMap.Add("collision_start", scriptEvents.collision_start);
m_eventFlagsMap.Add("control", scriptEvents.control);
m_eventFlagsMap.Add("dataserver", scriptEvents.dataserver);
m_eventFlagsMap.Add("email", scriptEvents.email);
m_eventFlagsMap.Add("http_response", scriptEvents.http_response);
m_eventFlagsMap.Add("land_collision", scriptEvents.land_collision);
m_eventFlagsMap.Add("land_collision_end", scriptEvents.land_collision_end);
m_eventFlagsMap.Add("land_collision_start", scriptEvents.land_collision_start);
// m_eventFlagsMap.Add("link_message",scriptEvents.link_message);
m_eventFlagsMap.Add("listen", scriptEvents.listen);
m_eventFlagsMap.Add("money", scriptEvents.money);
m_eventFlagsMap.Add("moving_end", scriptEvents.moving_end);
m_eventFlagsMap.Add("moving_start", scriptEvents.moving_start);
m_eventFlagsMap.Add("not_at_rot_target", scriptEvents.not_at_rot_target);
m_eventFlagsMap.Add("not_at_target", scriptEvents.not_at_target);
// m_eventFlagsMap.Add("no_sensor",(long)scriptEvents.no_sensor);
// m_eventFlagsMap.Add("on_rez",(long)scriptEvents.on_rez);
m_eventFlagsMap.Add("remote_data", scriptEvents.remote_data);
m_eventFlagsMap.Add("run_time_permissions", scriptEvents.run_time_permissions);
// m_eventFlagsMap.Add("sensor",(long)scriptEvents.sensor);
m_eventFlagsMap.Add("state_entry", scriptEvents.state_entry);
m_eventFlagsMap.Add("state_exit", scriptEvents.state_exit);
m_eventFlagsMap.Add("timer", scriptEvents.timer);
m_eventFlagsMap.Add("touch", scriptEvents.touch);
m_eventFlagsMap.Add("touch_end", scriptEvents.touch_end);
m_eventFlagsMap.Add("touch_start", scriptEvents.touch_start);
m_eventFlagsMap.Add("transaction_result", scriptEvents.transaction_result);
m_eventFlagsMap.Add("object_rez", scriptEvents.object_rez);
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Actions.Wlb;
using XenAdmin.Core;
using XenAdmin.Wlb;
using XenAdmin.Controls;
namespace XenAdmin.Dialogs.Wlb
{
public partial class WlbReportSubscriptionDialog : XenAdmin.Dialogs.XenDialogBase
{
#region Variables
private Pool _pool;
private string _reportDisplayName;
private Dictionary<string, string> _rpParams;
private WlbReportSubscription _subscription;
private string _subId = String.Empty;
ToolTip InvalidParamToolTip = new ToolTip();
// Due to localization, changed email regex from @"^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)*[A-Z0-9-]+$"
// to match anything with an @ sign in the middle
private static readonly Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
#endregion
#region Constructors
// Create new subscription
public WlbReportSubscriptionDialog(string reportDisplayName, Dictionary<string, string> reportParams, Pool pool)
: base(pool.Connection)
{
_rpParams = reportParams;
_subscription = null;
_reportDisplayName = reportDisplayName;
_pool = pool;
init();
}
// Edit existing subscription
public WlbReportSubscriptionDialog(string reportDisplayName, WlbReportSubscription subscription, Pool pool)
: base(pool.Connection)
{
_subId = subscription.Id;
_rpParams = subscription.ReportParameters;
_subscription = subscription;
_reportDisplayName = reportDisplayName;
_pool = pool;
init();
}
#endregion
#region Private Methods
private void init()
{
InitializeComponent();
InitializeControls();
// Initialize InvalidParamToolTip
InvalidParamToolTip.IsBalloon = true;
InvalidParamToolTip.ToolTipIcon = ToolTipIcon.Warning;
InvalidParamToolTip.ToolTipTitle = Messages.INVALID_PARAMETER;
if (null != _subscription)
{
LoadSubscription();
}
}
private void InitializeControls()
{
this.Text = String.Concat(this.Text, this._reportDisplayName);
this.rpParamComboBox.SelectedIndex = 0;
this.rpRenderComboBox.SelectedIndex = 0;
this.schedDeliverComboBox.DataSource = new BindingSource(BuildDaysOfWeek(), null);
this.schedDeliverComboBox.ValueMember = "key";
this.schedDeliverComboBox.DisplayMember = "value"; ;
this.schedDeliverComboBox.SelectedIndex = 1;
this.dateTimePickerSchedEnd.Value = DateTime.Now.AddMonths(1);
this.dateTimePickerSchedStart.Value = DateTime.Now;
}
private Dictionary<int, string> BuildDaysOfWeek()
{
Dictionary<int, string> days = new Dictionary<int, string>();
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.All, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.All));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekends, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekends));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Sunday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Sunday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Monday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Monday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Thursday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Thursday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Friday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Friday));
days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Saturday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Saturday));
return days;
}
private string GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek daysOfWeek)
{
return WlbScheduledTask.DaysOfWeekL10N(daysOfWeek);
}
private void LoadSubscription()
{
// subscription name
this.subNameTextBox.Text = this._subscription.Description;
// report data range
int days = 0;
if (this._subscription.ReportParameters != null)
{
int.TryParse(this._subscription.ReportParameters["Start"], out days);
}
this.rpParamComboBox.SelectedIndex = (days-1)/-7 -1;
// email info
this.emailToTextBox.Text = this._subscription.EmailTo;
this.emailCcTextBox.Text = this._subscription.EmailCc;
this.emailBccTextBox.Text = this._subscription.EmailBcc;
this.emailReplyTextBox.Text = this._subscription.EmailReplyTo;
this.emailSubjectTextBox.Text = this._subscription.EmailSubject;
this.emailCommentRichTextBox.Text = this._subscription.EmailComment;
this.rpRenderComboBox.SelectedIndex = (int)this._subscription.ReportRenderFormat;
// convert utc days of week and utc execute time to local days of week and local execute time
DateTime localExecuteTime;
WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek;
WlbScheduledTask.GetLocalTaskTimes(this._subscription.DaysOfWeek, this._subscription.ExecuteTimeOfDay, out localDaysOfWeek, out localExecuteTime);
// subscription run time
this.dateTimePickerSubscriptionRunTime.Value = localExecuteTime;
// subscription delivery day
this.schedDeliverComboBox.SelectedValue = (int)localDaysOfWeek;
// subscription enable start and end dates
if (this._subscription.DisableDate != DateTime.MinValue)
{
this.dateTimePickerSchedEnd.Value = this._subscription.DisableDate.ToLocalTime();
}
if (this._subscription.EnableDate != DateTime.MinValue)
{
this.dateTimePickerSchedStart.Value = this._subscription.EnableDate.ToLocalTime();
}
}
#endregion //Private Methods
#region DateTimePicker and ComboBox Event Handler
private void rpParamComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.rpParamComboBox.SelectedIndex)
{
case 0:
this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-7);
break;
case 1:
this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-14);
break;
case 2:
this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-21);
break;
case 3:
this.dateTimePickerSchedStart.Value = DateTime.Now.AddMonths(-1);
break;
}
this.dateTimePickerSchedEnd.Value = DateTime.Now;
}
private void dateTimePickerSchedEnd_ValueChanged(object sender, EventArgs e)
{
if (this.dateTimePickerSchedEnd.Value < this.dateTimePickerSchedStart.Value)
{
this.dateTimePickerSchedStart.Value = this.dateTimePickerSchedEnd.Value;
}
}
private void dateTimePickerSchedStart_ValueChanged(object sender, EventArgs e)
{
if (this.dateTimePickerSchedStart.Value > this.dateTimePickerSchedEnd.Value)
{
this.dateTimePickerSchedEnd.Value = this.dateTimePickerSchedStart.Value;
}
}
#endregion //DateTimePicker and ComboBox Event Handler
#region Validators
private bool ValidToSave()
{
foreach (Control ctl in this.tableLayoutPanelSubscriptionName.Controls)
{
if (!IsValidControl(ctl))
{
HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip);
return false;
}
}
foreach (Control ctl in this.tableLayoutPanelDeliveryOptions.Controls)
{
if (!IsValidControl(ctl))
{
HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip);
return false;
}
}
return true;
}
private bool IsValidControl(Control ctl)
{
if (String.Compare(this.subNameTextBox.Name, ctl.Name) == 0)
{
return !String.IsNullOrEmpty(ctl.Text);
}
else if (String.Compare(this.emailToTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailReplyTextBox.Name, ctl.Name) == 0)
{
return IsValidEmail(ctl.Text);
}
else if (String.Compare(this.emailBccTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailCcTextBox.Name, ctl.Name) == 0)
{
if (!String.IsNullOrEmpty(ctl.Text))
{
return IsValidEmail(ctl.Text);
}
}
return true;
}
private static bool IsValidEmail(string emailAddress)
{
foreach (string address in emailAddress.Split(new char[] { ';' }))
{
if (!emailRegex.IsMatch(address))
{
return false;
}
}
return true;
}
#endregion
#region Button Click Event Handler
private void saveButton_Click(object sender, EventArgs e)
{
if (!ValidToSave())
{
this.DialogResult = DialogResult.None;
}
else
{
SaveSubscription();
InvalidParamToolTip.Dispose();
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
InvalidParamToolTip.Dispose();
}
#endregion
#region Private Methods
private string GetLoggedInAsText()
{
if (_pool.Connection == null)
{
// Shouldn't happen
return String.Empty;
}
Session session = _pool.Connection.Session;
if (session == null)
{
return String.Empty;
}
return session.UserFriendlyName();
}
private void SaveSubscription()
{
if (this._subscription == null)
{
_subscription = new WlbReportSubscription(String.Empty);
_subscription.SubscriberName = GetLoggedInAsText();
_subscription.Created = DateTime.UtcNow;
}
_subscription.Name = this.subNameTextBox.Text;
_subscription.Description = this.subNameTextBox.Text;
DateTime utcExecuteTime;
WlbScheduledTask.WlbTaskDaysOfWeek utcDaysOfWeek;
WlbScheduledTask.GetUTCTaskTimes((WlbScheduledTask.WlbTaskDaysOfWeek)this.schedDeliverComboBox.SelectedValue, this.dateTimePickerSubscriptionRunTime.Value, out utcDaysOfWeek, out utcExecuteTime);
_subscription.ExecuteTimeOfDay = utcExecuteTime;
_subscription.DaysOfWeek = utcDaysOfWeek;
if (_subscription.DaysOfWeek != WlbScheduledTask.WlbTaskDaysOfWeek.All)
{
_subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Weekly;
}
else
{
_subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Daily;
}
_subscription.Enabled = true;
_subscription.EnableDate = this.dateTimePickerSchedStart.Value == DateTime.MinValue ? DateTime.UtcNow : this.dateTimePickerSchedStart.Value.ToUniversalTime();
_subscription.DisableDate = this.dateTimePickerSchedEnd.Value == DateTime.MinValue ? DateTime.UtcNow.AddMonths(1) : this.dateTimePickerSchedEnd.Value.ToUniversalTime();
_subscription.LastTouched = DateTime.UtcNow;
_subscription.LastTouchedBy = GetLoggedInAsText();
// store email info
_subscription.EmailTo = this.emailToTextBox.Text.Trim();
_subscription.EmailCc = this.emailCcTextBox.Text.Trim();
_subscription.EmailBcc = this.emailBccTextBox.Text.Trim();
_subscription.EmailReplyTo = this.emailReplyTextBox.Text.Trim();
_subscription.EmailSubject = this.emailSubjectTextBox.Text.Trim();
_subscription.EmailComment = this.emailCommentRichTextBox.Text;
// store reoprt Info
//sub.ReportId = ;
_subscription.ReportRenderFormat = this.rpRenderComboBox.SelectedIndex;
Dictionary<string, string> rps = new Dictionary<string, string>();
foreach(string key in this._rpParams.Keys)
{
if (String.Compare(key, WlbReportSubscription.REPORT_NAME, true) == 0)
_subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME];
else
{
//Get start date range
if (String.Compare(key, "start", true) == 0)
{
rps.Add(key, ((this.rpParamComboBox.SelectedIndex + 1) * (-7)+1).ToString());
}
else
{
rps.Add(key, _rpParams[key]);
}
}
}
_subscription.ReportParameters = rps;
SendWlbConfigurationAction action = new SendWlbConfigurationAction(this._pool, _subscription.ToDictionary(), SendWlbConfigurationKind.SetReportSubscription);
using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
{
dialog.ShowCancel = true;
dialog.ShowDialog(this);
}
if (action.Succeeded)
{
DialogResult = DialogResult.OK;
this.Close();
}
else if(!action.Cancelled)
{
using (var dlg = new ErrorDialog(string.Format(Messages.WLB_SUBSCRIPTION_ERROR, _subscription.Description)))
{
dlg.ShowDialog(this);
}
//log.ErrorFormat("There was an error calling SendWlbConfigurationAction to SetReportSubscription {0}, Action Result: {1}.", _subscription.Description, action.Result);
DialogResult = DialogResult.None;
}
}
#endregion //Button Click Event Handler
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding {
/** Navmesh cutting is used for fast recast graph updates.
*
* Navmesh cutting is used to cut holes into an existing navmesh generated by a recast graph.
* Recast graphs usually only allow either just changing parameters on existing nodes (e.g make a whole triangle unwalkable) which is not very flexible or recalculate a whole tile which is pretty slow.
* With navmesh cutting you can remove (cut) parts of the navmesh that is blocked by obstacles such as a new building in an RTS game however you cannot add anything new to the navmesh or change
* the positions of the nodes.
*
* \htmlonly
* <iframe width="640" height="480" src="//www.youtube.com/embed/qXi5qhhGNIw" frameborder="0" allowfullscreen>
* </iframe>
* \endhtmlonly
*
* The NavmeshCut component uses a 2D shape to cut the navmesh with. A rectangle and circle shape is built in, but you can also specify a custom mesh to use.
* The custom mesh should be a flat 2D shape like in the image below. The script will then find the contour of that mesh and use that shape as the cut.
* Make sure that all normals are smooth and that the mesh contains no UV information. Otherwise Unity might split a vertex and then the script will not
* find the correct contour. You should not use a very high polygon mesh since that will create a lot of nodes in the navmesh graph and slow
* down pathfinding because of that. For very high polygon meshes it might even cause more suboptimal paths to be generated if it causes many
* thin triangles to be added to the navmesh.
* \shadowimage{navmeshcut_mesh.png}
*
* Note that the shape is not 3D so if you rotate the cut you will see that the 2D shape will be rotated and then just projected down on the XZ plane.
*
* To use a navmesh cut in your scene you need to have a TileHandlerHelper script somewhere in your scene. You should only have one though.
* That script will take care of checking all the NavmeshCut components to see if they need to update the navmesh.
*
* In the scene view the NavmeshCut looks like an extruded 2D shape because a navmesh cut also has a height. It will only cut the part of the
* navmesh which it touches. For performance it only checks the bounding boxes of the triangles in the navmesh, so it may cut triangles
* whoose bounding boxes it intersects even if the triangle does not intersect the extructed shape. However in most cases this does not make a large difference.
*
* It is also possible to set the navmesh cut to dual mode by setting the #isDual field to true. This will prevent it from cutting a hole in the navmesh
* and it will instead just split the navmesh along the border but keep both the interior and the exterior. This can be useful if you for example
* want to change the penalty of some region which does not neatly line up with the navmesh triangles. It is often combined with the GraphUpdateScene component
* (however note that the GraphUpdateScene component will not automatically reapply the penalty if the graph is updated again).
*
* By default the navmesh cut does not take rotation or scaling into account. If you want to do that, you can set the #useRotation field to true.
* This is a bit slower, but it is not a very large difference.
*
* \astarpro
* \see http://www.arongranberg.com/2013/08/navmesh-cutting/
*/
[AddComponentMenu("Pathfinding/Navmesh/Navmesh Cut")]
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_navmesh_cut.php")]
public class NavmeshCut : MonoBehaviour {
public enum MeshType {
Rectangle,
Circle,
CustomMesh
}
private static List<NavmeshCut> allCuts = new List<NavmeshCut>();
/** Called every time a NavmeshCut component is destroyed. */
public static event System.Action<NavmeshCut> OnDestroyCallback;
private static void AddCut (NavmeshCut obj) {
allCuts.Add(obj);
}
private static void RemoveCut (NavmeshCut obj) {
allCuts.Remove(obj);
}
/** Get all active instances which intersect the bounds */
public static List<NavmeshCut> GetAllInRange (Bounds b) {
List<NavmeshCut> cuts = Pathfinding.Util.ListPool<NavmeshCut>.Claim();
for (int i = 0; i < allCuts.Count; i++) {
if (allCuts[i].enabled && Intersects(b, allCuts[i].GetBounds())) {
cuts.Add(allCuts[i]);
}
}
return cuts;
}
/** True if \a b1 and \a b2 intersects.
*
* \note Faster than Unity's built in version. See http://forum.unity3d.com/threads/204243-Slow-Unity-Math-Please-Unity-Tech-keep-core-math-fast?p=1404070#post1404070
*/
private static bool Intersects (Bounds b1, Bounds b2) {
Vector3 min1 = b1.min;
Vector3 max1 = b1.max;
Vector3 min2 = b2.min;
Vector3 max2 = b2.max;
return min1.x <= max2.x && max1.x >= min2.x && min1.y <= max2.y && max1.y >= min2.y && min1.z <= max2.z && max1.z >= min2.z;
}
/** Returns a list with all NavmeshCut components in the scene.
* \warning Do not modify this array
*/
public static List<NavmeshCut> GetAll () {
return allCuts;
}
public MeshType type;
/** Custom mesh to use.
* The contour(s) of the mesh will be extracted.
* If you get the "max perturbations" error when cutting with this, check the normals on the mesh.
* They should all point in the same direction. Try flipping them if that does not help.
*/
public Mesh mesh;
/** Size of the rectangle */
public Vector2 rectangleSize = new Vector2(1, 1);
/** Radius of the circle */
public float circleRadius = 1;
/** Number of vertices on the circle */
public int circleResolution = 6;
public float height = 1;
/** Scale of the custom mesh, if used */
public float meshScale = 1;
public Vector3 center;
/** Distance between positions to require an update of the navmesh.
* A smaller distance gives better accuracy, but requires more updates when moving the object over time,
* so it is often slower.
*
* \note Dynamic updating requires a TileHandlerHelper somewhere in the scene.
*/
public float updateDistance = 0.4f;
/** Only makes a split in the navmesh, but does not remove the geometry to make a hole.
* This is slower than a normal cut
*/
public bool isDual;
/** Cuts geometry added by a NavmeshAdd component.
* You rarely need to change this
*/
public bool cutsAddedGeom = true;
/** How many degrees rotation that is required for an update to the navmesh.
* Should be between 0 and 180.
*
* \note Dynamic updating requires a Tile Handler Helper somewhere in the scene.
*/
public float updateRotationDistance = 10;
/** Includes rotation in calculations.
* This is slower since a lot more matrix multiplications are needed but gives more flexibility.
*/
public bool useRotation;
Vector3[][] contours;
/** cached transform component */
protected Transform tr;
Mesh lastMesh;
Vector3 lastPosition;
Quaternion lastRotation;
bool wasEnabled;
Bounds lastBounds;
public Bounds LastBounds {
get {
return lastBounds;
}
}
public void Awake () {
AddCut(this);
}
public void OnEnable () {
tr = transform;
lastPosition = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
lastRotation = tr.rotation;
}
public void OnDestroy () {
if (OnDestroyCallback != null) OnDestroyCallback(this);
RemoveCut(this);
}
/** Cached variable, to avoid allocations */
static readonly Dictionary<Int2, int> edges = new Dictionary<Int2, int>();
/** Cached variable, to avoid allocations */
static readonly Dictionary<int, int> pointers = new Dictionary<int, int>();
/** Forces this navmesh cut to update the navmesh.
*
* \note Dynamic updating requires a Tile Handler Helper somewhere in the scene.
* This update is not instant, it is done the next time the TileHandlerHelper checks this instance for
* if it needs updating.
*
* \see TileHandlerHelper.ForceUpdate()
*/
public void ForceUpdate () {
lastPosition = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
}
/** Returns true if this object has moved so much that it requires an update.
* When an update to the navmesh has been done, call NotifyUpdated to be able to get
* relavant output from this method again.
*/
public bool RequiresUpdate () {
return wasEnabled != enabled || (wasEnabled && ((tr.position-lastPosition).sqrMagnitude > updateDistance*updateDistance || (useRotation && (Quaternion.Angle(lastRotation, tr.rotation) > updateRotationDistance))));
}
/**
* Called whenever this navmesh cut is used to update the navmesh.
* Called once for each tile the navmesh cut is in.
* You can override this method to execute custom actions whenever this happens.
*/
public virtual void UsedForCut () {
}
/** Internal method to notify the NavmeshCut that it has just been used to update the navmesh */
public void NotifyUpdated () {
wasEnabled = enabled;
if (wasEnabled) {
lastPosition = tr.position;
lastBounds = GetBounds();
if (useRotation) {
lastRotation = tr.rotation;
}
}
}
void CalculateMeshContour () {
if (mesh == null) return;
edges.Clear();
pointers.Clear();
Vector3[] verts = mesh.vertices;
int[] tris = mesh.triangles;
for (int i = 0; i < tris.Length; i += 3) {
// Make sure it is clockwise
if (VectorMath.IsClockwiseXZ(verts[tris[i+0]], verts[tris[i+1]], verts[tris[i+2]])) {
int tmp = tris[i+0];
tris[i+0] = tris[i+2];
tris[i+2] = tmp;
}
edges[new Int2(tris[i+0], tris[i+1])] = i;
edges[new Int2(tris[i+1], tris[i+2])] = i;
edges[new Int2(tris[i+2], tris[i+0])] = i;
}
// Construct a list of pointers along all edges
for (int i = 0; i < tris.Length; i += 3) {
for (int j = 0; j < 3; j++) {
if (!edges.ContainsKey(new Int2(tris[i+((j+1)%3)], tris[i+((j+0)%3)]))) {
pointers[tris[i+((j+0)%3)]] = tris[i+((j+1)%3)];
}
}
}
var contourBuffer = new List<Vector3[]>();
List<Vector3> buffer = Pathfinding.Util.ListPool<Vector3>.Claim();
// Follow edge pointers to generate the contours
for (int i = 0; i < verts.Length; i++) {
if (pointers.ContainsKey(i)) {
buffer.Clear();
int s = i;
do {
int tmp = pointers[s];
//This path has been taken before
if (tmp == -1) break;
pointers[s] = -1;
buffer.Add(verts[s]);
s = tmp;
if (s == -1) {
Debug.LogError("Invalid Mesh '" + mesh.name + " in " + gameObject.name);
break;
}
} while (s != i);
if (buffer.Count > 0) contourBuffer.Add(buffer.ToArray());
}
}
// Return lists to the pool
Pathfinding.Util.ListPool<Vector3>.Release(buffer);
contours = contourBuffer.ToArray();
}
/** World space bounds of this cut */
public Bounds GetBounds () {
var bounds = new Bounds();
switch (type) {
case MeshType.Rectangle:
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
// Calculate the bounds by encapsulating each of the 8 corners in a bounds object
bounds = new Bounds(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, -height, -rectangleSize.y)*0.5f), Vector3.zero);
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, -height, -rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, -height, rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, -height, rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, height, -rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, height, -rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, height, rectangleSize.y)*0.5f));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, height, rectangleSize.y)*0.5f));
} else {
bounds = new Bounds(tr.position+center, new Vector3(rectangleSize.x, height, rectangleSize.y));
}
break;
case MeshType.Circle:
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
bounds = new Bounds(m.MultiplyPoint3x4(center), new Vector3(circleRadius*2, height, circleRadius*2));
} else {
bounds = new Bounds(transform.position+center, new Vector3(circleRadius*2, height, circleRadius*2));
}
break;
case MeshType.CustomMesh:
if (mesh == null) break;
Bounds b = mesh.bounds;
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
b.center *= meshScale;
b.size *= meshScale;
bounds = new Bounds(m.MultiplyPoint3x4(center + b.center), Vector3.zero);
Vector3 mx = b.max;
Vector3 mn = b.min;
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mx.x, mx.y, mx.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mn.x, mx.y, mx.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mn.x, mx.y, mn.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mx.x, mx.y, mn.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mx.x, mn.y, mx.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mn.x, mn.y, mx.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mn.x, mn.y, mn.z)));
bounds.Encapsulate(m.MultiplyPoint3x4(center + new Vector3(mx.x, mn.y, mn.z)));
Vector3 size = bounds.size;
size.y = Mathf.Max(size.y, height * tr.lossyScale.y);
bounds.size = size;
} else {
Vector3 size = b.size*meshScale;
size.y = Mathf.Max(size.y, height);
bounds = new Bounds(transform.position+center+b.center*meshScale, size);
}
break;
default:
throw new System.Exception("Invalid mesh type");
}
return bounds;
}
/**
* World space contour of the navmesh cut.
* Fills the specified buffer with all contours.
* The cut may contain several contours which is why the buffer is a list of lists.
*/
public void GetContour (List<List<Pathfinding.ClipperLib.IntPoint> > buffer) {
if (circleResolution < 3) circleResolution = 3;
Vector3 woffset = tr.position;
switch (type) {
case MeshType.Rectangle:
List<Pathfinding.ClipperLib.IntPoint> buffer0 = Pathfinding.Util.ListPool<Pathfinding.ClipperLib.IntPoint>.Claim();
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, 0, -rectangleSize.y)*0.5f)));
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, 0, -rectangleSize.y)*0.5f)));
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + new Vector3(rectangleSize.x, 0, rectangleSize.y)*0.5f)));
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + new Vector3(-rectangleSize.x, 0, rectangleSize.y)*0.5f)));
} else {
woffset += center;
buffer0.Add(V3ToIntPoint(woffset + new Vector3(-rectangleSize.x, 0, -rectangleSize.y)*0.5f));
buffer0.Add(V3ToIntPoint(woffset + new Vector3(rectangleSize.x, 0, -rectangleSize.y)*0.5f));
buffer0.Add(V3ToIntPoint(woffset + new Vector3(rectangleSize.x, 0, rectangleSize.y)*0.5f));
buffer0.Add(V3ToIntPoint(woffset + new Vector3(-rectangleSize.x, 0, rectangleSize.y)*0.5f));
}
buffer.Add(buffer0);
break;
case MeshType.Circle:
buffer0 = Pathfinding.Util.ListPool<Pathfinding.ClipperLib.IntPoint>.Claim(circleResolution);
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
for (int i = 0; i < circleResolution; i++) {
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + new Vector3(Mathf.Cos((i*2*Mathf.PI)/circleResolution), 0, Mathf.Sin((i*2*Mathf.PI)/circleResolution))*circleRadius)));
}
} else {
woffset += center;
for (int i = 0; i < circleResolution; i++) {
buffer0.Add(V3ToIntPoint(woffset + new Vector3(Mathf.Cos((i*2*Mathf.PI)/circleResolution), 0, Mathf.Sin((i*2*Mathf.PI)/circleResolution))*circleRadius));
}
}
buffer.Add(buffer0);
break;
case MeshType.CustomMesh:
if (mesh != lastMesh || contours == null) {
CalculateMeshContour();
lastMesh = mesh;
}
if (contours != null) {
woffset += center;
bool reverse = Vector3.Dot(tr.up, Vector3.up) < 0;
for (int i = 0; i < contours.Length; i++) {
Vector3[] contour = contours[i];
buffer0 = Pathfinding.Util.ListPool<Pathfinding.ClipperLib.IntPoint>.Claim(contour.Length);
if (useRotation) {
Matrix4x4 m = tr.localToWorldMatrix;
for (int x = 0; x < contour.Length; x++) {
buffer0.Add(V3ToIntPoint(m.MultiplyPoint3x4(center + contour[x]*meshScale)));
}
} else {
for (int x = 0; x < contour.Length; x++) {
buffer0.Add(V3ToIntPoint(woffset + contour[x]*meshScale));
}
}
if (reverse) buffer0.Reverse();
buffer.Add(buffer0);
}
}
break;
}
}
/** Converts a Vector3 to an IntPoint.
* This is a lossy conversion.
*/
public static Pathfinding.ClipperLib.IntPoint V3ToIntPoint (Vector3 p) {
var ip = (Int3)p;
return new Pathfinding.ClipperLib.IntPoint(ip.x, ip.z);
}
/** Converts an IntPoint to a Vector3.
* This is a lossy conversion.
*/
public static Vector3 IntPointToV3 (Pathfinding.ClipperLib.IntPoint p) {
var ip = new Int3((int)p.X, 0, (int)p.Y);
return (Vector3)ip;
}
public static readonly Color GizmoColor = new Color(37.0f/255, 184.0f/255, 239.0f/255);
public void OnDrawGizmos () {
if (tr == null) tr = transform;
var buffer = Pathfinding.Util.ListPool<List<Pathfinding.ClipperLib.IntPoint> >.Claim();
GetContour(buffer);
Gizmos.color = GizmoColor;
var bounds = GetBounds();
var ymin = bounds.min.y;
var yoffset = Vector3.up * (bounds.max.y - ymin);
// Draw all contours
for (int i = 0; i < buffer.Count; i++) {
List<Pathfinding.ClipperLib.IntPoint> cont = buffer[i];
for (int j = 0; j < cont.Count; j++) {
Vector3 p1 = IntPointToV3(cont[j]);
p1.y = ymin;
Vector3 p2 = IntPointToV3(cont[(j+1) % cont.Count]);
p2.y = ymin;
Gizmos.DrawLine(p1, p2);
Gizmos.DrawLine(p1+yoffset, p2+yoffset);
Gizmos.DrawLine(p1, p1+yoffset);
Gizmos.DrawLine(p2, p2+yoffset);
}
}
Pathfinding.Util.ListPool<List<Pathfinding.ClipperLib.IntPoint> >.Release(buffer);
}
public void OnDrawGizmosSelected () {
Gizmos.color = Color.Lerp(GizmoColor, new Color(1, 1, 1, 0.2f), 0.9f);
Bounds b = GetBounds();
Gizmos.DrawCube(b.center, b.size);
Gizmos.DrawWireCube(b.center, b.size);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryImports
{
public partial class RemoveUnnecessaryImportsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer(),
new CSharpRemoveUnnecessaryImportsCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNoReferences()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
}
}|]",
@"class Program
{
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestIdentifierReferenceInTypeContext()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}|]",
@"using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestGenericReferenceInTypeContext()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}|]",
@"using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMultipleReferences()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> list;
DateTime d;
}
}|]",
@"using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> list;
DateTime d;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestExtensionMethodReference()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args.Where(a => a.Length > 10);
}
}|]",
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args.Where(a => a.Length > 10);
}
}");
}
[WorkItem(541827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541827")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestExtensionMethodLinq()
{
// NOTE: Intentionally not running this test with Script options, because in Script,
// NOTE: class "Foo" is placed inside the script class, and can't be seen by the extension
// NOTE: method Select, which is not inside the script class.
await TestMissingAsync(
@"[|using System;
using System.Collections;
using SomeNS;
class Program
{
static void Main()
{
Foo qq = new Foo();
IEnumerable x = from q in qq
select q;
}
}
public class Foo
{
public Foo()
{
}
}
namespace SomeNS
{
public static class SomeClass
{
public static IEnumerable Select(this Foo o, Func<object, object> f)
{
return null;
}
}
}|]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAliasQualifiedAliasReference()
{
await TestAsync(
@"[|using System;
using G = System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
G::List<int> list;
}
}|]",
@"using G = System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
G::List<int> list;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestQualifiedAliasReference()
{
await TestAsync(
@"[|using System;
using G = System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
G.List<int> list;
}
}|]",
@"using G = System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
G.List<int> list;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUnusedUsings()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
namespace N
{
using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}|]",
@"namespace N
{
using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUsedUsings()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
namespace N
{
using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}
class F
{
DateTime d;
}|]",
@"using System;
namespace N
{
using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}
class F
{
DateTime d;
}");
}
[WorkItem(712656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/712656")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestNestedUsedUsings2()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
namespace N
{
[|using System;|]
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}
class F
{
DateTime d;
}",
@"using System;
namespace N
{
using System;
class Program
{
static void Main(string[] args)
{
DateTime d;
}
}
}
class F
{
DateTime d;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAttribute()
{
await TestMissingAsync(
@"[|using SomeNamespace;
[SomeAttr]
class Foo
{
}
namespace SomeNamespace
{
public class SomeAttrAttribute : System.Attribute
{
}
}|]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAttributeArgument()
{
await TestMissingAsync(
@"[|using foo;
[SomeAttribute(typeof(SomeClass))]
class Program
{
static void Main()
{
}
}
public class SomeAttribute : System.Attribute
{
public SomeAttribute(object f)
{
}
}
namespace foo
{
public class SomeClass
{
}
}|]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveAllWithSurroundingPreprocessor()
{
await TestAsync(
@"#if true
[|using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
}
}|]",
@"#if true
#endif
class Program
{
static void Main(string[] args)
{
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveFirstWithSurroundingPreprocessor()
{
await TestAsync(
@"#if true
[|using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}|]",
@"#if true
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveAllWithSurroundingPreprocessor2()
{
await TestAsync(
@"[|namespace N
{
#if true
using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
}
}
}|]",
@"namespace N
{
#if true
#endif
class Program
{
static void Main(string[] args)
{
}
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveOneWithSurroundingPreprocessor2()
{
await TestAsync(
@"[|namespace N
{
#if true
using System;
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}
}|]",
@"namespace N
{
#if true
using System.Collections.Generic;
#endif
class Program
{
static void Main(string[] args)
{
List<int> list;
}
}
}",
compareTokens: false);
}
[WorkItem(541817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541817")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestComments8718()
{
await TestAsync(
@"[|using Foo; using System.Collections.Generic; /*comment*/ using Foo2;
class Program
{
static void Main(string[] args)
{
Bar q;
Bar2 qq;
}
}
namespace Foo
{
public class Bar
{
}
}
namespace Foo2
{
public class Bar2
{
}
}|]",
@"using Foo;
using Foo2;
class Program
{
static void Main(string[] args)
{
Bar q;
Bar2 qq;
}
}
namespace Foo
{
public class Bar
{
}
}
namespace Foo2
{
public class Bar2
{
}
}",
compareTokens: false);
}
[WorkItem(528609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528609")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestComments()
{
await TestAsync(
@"//c1
/*c2*/
[|using/*c3*/ System/*c4*/; //c5
//c6
class Program
{
}
|]",
@"//c1
/*c2*/
//c6
class Program
{
}
",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedUsing()
{
await TestAsync(
@"[|using System.Collections.Generic;
class Program
{
static void Main()
{
}
}|]",
@"class Program
{
static void Main()
{
}
}",
compareTokens: false);
}
[WorkItem(541827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541827")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestSimpleQuery()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = from a in args
where a.Length > 21
select a;
}
}|]",
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
var q = from a in args
where a.Length > 21
select a;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessField1()
{
await TestAsync(
@"[|using SomeNS.Foo;
class Program
{
static void Main()
{
var q = x;
}
}
namespace SomeNS
{
static class Foo
{
public static int x;
}
}|]",
@"class Program
{
static void Main()
{
var q = x;
}
}
namespace SomeNS
{
static class Foo
{
public static int x;
}
}",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessField2()
{
await TestMissingAsync(
@"[|using static SomeNS.Foo;
class Program
{
static void Main()
{
var q = x;
}
}
namespace SomeNS
{
static class Foo
{
public static int x;
}
}|]");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessMethod1()
{
await TestAsync(
@"[|using SomeNS.Foo;
class Program
{
static void Main()
{
var q = X();
}
}
namespace SomeNS
{
static class Foo
{
public static int X()
{
return 42;
}
}
}|]",
@"[|class Program
{
static void Main()
{
var q = X();
}
}
namespace SomeNS
{
static class Foo
{
public static int X()
{
return 42;
}
}
}|]",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUsingStaticClassAccessMethod2()
{
await TestMissingAsync(
@"[|using static SomeNS.Foo;
class Program
{
static void Main()
{
var q = X();
}
}
namespace SomeNS
{
static class Foo
{
public static int X()
{
return 42;
}
}
}|]");
}
[WorkItem(8846, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedTypeImportIsRemoved()
{
await TestAsync(
@"[|using SomeNS.Foo;
class Program
{
static void Main()
{
}
}
namespace SomeNS
{
static class Foo
{
}
}|]",
@"class Program
{
static void Main()
{
}
}
namespace SomeNS
{
static class Foo
{
}
}");
}
[WorkItem(541817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541817")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveTrailingComment()
{
await TestAsync(
@"[|using System.Collections.Generic; // comment
class Program
{
static void Main(string[] args)
{
}
}
|]",
@"class Program
{
static void Main(string[] args)
{
}
}
",
compareTokens: false);
}
[WorkItem(541914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541914")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemovingUnbindableUsing()
{
await TestAsync(
@"[|using gibberish;
public static class Program
{
}|]",
@"public static class Program
{
}");
}
[WorkItem(541937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestAliasInUse()
{
await TestMissingAsync(
@"[|using GIBBERISH = Foo.Bar;
class Program
{
static void Main(string[] args)
{
GIBBERISH x;
}
}
namespace Foo
{
public class Bar
{
}
}|]");
}
[WorkItem(541914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541914")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveUnboundUsing()
{
await TestAsync(
@"[|using gibberish;
public static class Program
{
}|]",
@"public static class Program
{
}");
}
[WorkItem(542016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542016")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestLeadingNewlines1()
{
await TestAsync(
@"[|using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
}
}|]",
@"class Program
{
static void Main(string[] args)
{
}
}",
compareTokens: false);
}
[WorkItem(542016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542016")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveLeadingNewLines2()
{
await TestAsync(
@"[|namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
}
}
}|]",
@"namespace N
{
class Program
{
static void Main(string[] args)
{
}
}
}",
compareTokens: false);
}
[WorkItem(542134, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542134")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestImportedTypeUsedAsGenericTypeArgument()
{
await TestMissingAsync(
@"[|using GenericThingie;
public class GenericType<T>
{
}
namespace GenericThingie
{
public class Something
{
}
}
public class Program
{
void foo()
{
GenericType<Something> type;
}
}|]");
}
[WorkItem(542723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542723")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveCorrectUsing1()
{
await TestAsync(
@"[|using System.Collections.Generic;
namespace Foo
{
using Bar = Dictionary<string, string>;
}|]",
@"using System.Collections.Generic;
namespace Foo
{
}",
parseOptions: null);
}
[WorkItem(542723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542723")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestRemoveCorrectUsing2()
{
await TestMissingAsync(
@"[|using System.Collections.Generic;
namespace Foo
{
using Bar = Dictionary<string, string>;
class C
{
Bar b;
}
}|]",
parseOptions: null);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestSpan()
{
await TestSpansAsync(
@"[|namespace N
{
using System;
}|]",
@"namespace N
{
[|using System;|]
}");
}
[WorkItem(543000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543000")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingWhenErrorsWouldBeGenerated()
{
await TestMissingAsync(
@"[|using System;
using X;
using Y;
class B
{
static void Main()
{
Bar(x => x.Foo());
}
static void Bar(Action<int> x)
{
}
static void Bar(Action<string> x)
{
}
}
namespace X
{
public static class A
{
public static void Foo(this int x)
{
}
public static void Foo(this string x)
{
}
}
}
namespace Y
{
public static class B
{
public static void Foo(this int x)
{
}
}
}|]");
}
[WorkItem(544976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544976")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingWhenMeaningWouldChangeInLambda()
{
await TestMissingAsync(
@"[|using System;
using X;
using Y;
class B
{
static void Main()
{
Bar(x => x.Foo(), null); // Prints 1
}
static void Bar(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Bar(Action<int> x, string y)
{
Console.WriteLine(2);
}
}
namespace X
{
public static class A
{
public static void Foo(this int x)
{
}
public static void Foo(this string x)
{
}
}
}
namespace Y
{
public static class B
{
public static void Foo(this int x)
{
}
}
}|]");
}
[WorkItem(544976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544976")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestCasesWithLambdas1()
{
// NOTE: Y is used when speculatively binding "x => x.Foo()". As such, it is marked as
// used even though it isn't in the final bind, and could be removed. However, as we do
// not know if it was necessary to eliminate a speculative lambda bind, we must leave
// it.
await TestMissingAsync(
@"[|using System;
using X;
using Y;
class B
{
static void Main()
{
Bar(x => x.Foo(), null); // Prints 1
}
static void Bar(Action<string> x, object y)
{
}
}
namespace X
{
public static class A
{
public static void Foo(this string x)
{
}
}
}
namespace Y
{
public static class B
{
public static void Foo(this int x)
{
}
}
}|]");
}
[WorkItem(545646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545646")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestCasesWithLambdas2()
{
await TestMissingAsync(
@"[|using System;
using N; // Falsely claimed as unnecessary
static class C
{
static void Ex(this string x)
{
}
static void Inner(Action<string> x, string y)
{
}
static void Inner(Action<string> x, int y)
{
}
static void Inner(Action<int> x, int y)
{
}
static void Outer(Action<string> x, object y)
{
Console.WriteLine(1);
}
static void Outer(Action<int> x, string y)
{
Console.WriteLine(2);
}
static void Main()
{
Outer(y => Inner(x => x.Ex(), y), null);
}
}
namespace N
{
static class E
{
public static void Ex(this int x)
{
}
}
}|]");
}
[WorkItem(545741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545741")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestMissingOnAliasedVar()
{
await TestMissingAsync(
@"[|using var = var;
class var
{
}
class B
{
static void Main()
{
var a = 1;
}
}|]");
}
[WorkItem(546115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546115")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestBrokenCode()
{
await TestMissingAsync(
@"[|using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new[] { };
var expr2 = new[] { };
var query8 = from int i in expr1
join int fixed in expr2 on i equals fixed select new { i, fixed };
var query9 = from object i in expr1
join object fixed in expr2 on i equals fixed select new { i, fixed };
}
}|]");
}
[WorkItem(530980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestReferenceInCref()
{
// parsing doc comments as simple trivia; System is unnecessary
await TestAsync(
@"[|using System;
/// <summary><see cref=""String"" /></summary>
class C
{
}|]",
@"/// <summary><see cref=""String"" /></summary>
class C
{
}");
// fully parsing doc comments; System is necessary
await TestMissingAsync(
@"[|using System;
/// <summary><see cref=""String"" /></summary>
class C
{
}|]", Options.Regular.WithDocumentationMode(DocumentationMode.Diagnose));
}
[WorkItem(751283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751283")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)]
public async Task TestUnusedUsingOverLinq()
{
await TestAsync(
@"using System;
[|using System.Linq;
using System.Threading.Tasks;|]
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using Magecrawl.GameUI.Map.Requests;
using Magecrawl.Interfaces;
using Magecrawl.Keyboard.Requests;
using Magecrawl.Utilities;
namespace Magecrawl.Keyboard
{
// If true, don't reset the handler because we already set it to something new
internal delegate bool OnTargetSelection(Point selection);
[Export(typeof(IKeystrokeHandler))]
[ExportMetadata("RequireAllActionsMapped", "false")]
[ExportMetadata("HandlerName", "Target")]
internal class TargettingKeystrokeHandler : BaseKeystrokeHandler
{
internal enum TargettingType
{
None, Monster, Operatable, OpenFloor
}
private List<EffectivePoint> m_targetablePoints;
private OnTargetSelection m_selectionDelegate;
private NamedKey m_alternateSelectionKey;
private bool m_doNotResetHandler;
private TargettingType m_targettingType;
private ICharacter m_lastTargetted;
private Point SelectionPoint { get; set; }
public TargettingKeystrokeHandler()
{
m_targettingType = TargettingType.None;
m_lastTargetted = null;
}
public override void HandleKeystroke(NamedKey keystroke)
{
// If we match the alternate key, call Select()
if (m_alternateSelectionKey != NamedKey.Invalid && m_alternateSelectionKey == keystroke)
{
Select();
return;
}
MethodInfo action;
m_keyMappings.TryGetValue(keystroke, out action);
if (action != null)
{
try
{
action.Invoke(this, null);
}
catch (Exception e)
{
throw e.InnerException;
}
}
}
public override void NowPrimaried(object request)
{
TargettingKeystrokeRequest targettingRequest = (TargettingKeystrokeRequest)request;
m_targetablePoints = targettingRequest.TargetablePoints;
m_selectionDelegate = targettingRequest.SelectionDelegate;
if (m_selectionDelegate == null)
throw new ArgumentNullException("Selection delegate for targetting must not be null");
m_alternateSelectionKey = targettingRequest.AlternateSelectionKey;
m_targettingType = targettingRequest.TargettingType;
SelectionPoint = SetTargettingInitialSpot(m_engine);
EnablePlayerTargeting enableRequest = new EnablePlayerTargeting(true, m_targetablePoints);
if (targettingRequest.HaloDelegate != null)
enableRequest.HaloDelegate = x => targettingRequest.HaloDelegate(x);
m_gameInstance.SendPaintersRequest(enableRequest);
m_gameInstance.SendPaintersRequest(new EnableMapCursor(true, SelectionPoint));
// If we have no targetable points, just exit now
if (m_targetablePoints.Count == 0)
Escape();
m_gameInstance.UpdatePainters();
}
private void Select()
{
Attack();
}
private void Attack()
{
ICharacter possiblyTargettedMonster = m_engine.Map.Monsters.Where(x => x.Position == SelectionPoint).FirstOrDefault();
// Rememeber last targetted monster so we can target them again by default next turn.
if (m_targettingType == TargettingType.Monster && possiblyTargettedMonster != null)
m_lastTargetted = possiblyTargettedMonster;
m_doNotResetHandler = m_selectionDelegate(SelectionPoint);
Escape();
}
private void HandleDirection(Direction direction)
{
Point pointWantToGoTo = PointDirectionUtils.ConvertDirectionToDestinationPoint(SelectionPoint, direction);
Point resultPoint = TargetHandlerHelper.MoveSelectionToNewPoint(m_engine, pointWantToGoTo, direction, m_targetablePoints);
if (resultPoint != Point.Invalid)
SelectionPoint = resultPoint;
m_gameInstance.SendPaintersRequest(new ChangeCursorPosition(SelectionPoint));
m_gameInstance.UpdatePainters();
}
private void Escape()
{
m_gameInstance.SendPaintersRequest(new EnableMapCursor(false));
m_gameInstance.SendPaintersRequest(new EnablePlayerTargeting(false));
m_selectionDelegate = null;
m_gameInstance.UpdatePainters();
if (!m_doNotResetHandler)
m_gameInstance.ResetHandlerName();
m_doNotResetHandler = false;
}
private void North()
{
HandleDirection(Direction.North);
}
private void South()
{
HandleDirection(Direction.South);
}
private void East()
{
HandleDirection(Direction.East);
}
private void West()
{
HandleDirection(Direction.West);
}
private void Northeast()
{
HandleDirection(Direction.Northeast);
}
private void Northwest()
{
HandleDirection(Direction.Northwest);
}
private void Southeast()
{
HandleDirection(Direction.Southeast);
}
private void Southwest()
{
HandleDirection(Direction.Southwest);
}
private Point SetTargettingInitialSpot(IGameEngine engine)
{
if (!(bool)Preferences.Instance["DisableAutoTargetting"])
{
switch (m_targettingType)
{
case TargettingType.Monster:
{
if (m_lastTargetted != null && m_lastTargetted.IsAlive && EffectivePoint.PositionInTargetablePoints(m_lastTargetted.Position, m_targetablePoints))
return m_lastTargetted.Position;
List<ICharacter> monstersInRange = new List<ICharacter>();
foreach (ICharacter m in engine.Map.Monsters)
{
if (EffectivePoint.PositionInTargetablePoints(m.Position, m_targetablePoints))
monstersInRange.Add(m);
}
ICharacter lowestHPMonster = monstersInRange.OrderBy(x => x.CurrentHP / x.MaxHP).Reverse().FirstOrDefault();
if (lowestHPMonster != null)
{
m_lastTargetted = lowestHPMonster;
return lowestHPMonster.Position;
}
break;
}
case TargettingType.Operatable:
{
foreach (IMapObject m in engine.Map.MapObjects.Where(x => x.CanOperate))
{
if (EffectivePoint.PositionInTargetablePoints(m.Position, m_targetablePoints))
return m.Position;
}
break;
}
case TargettingType.OpenFloor:
{
foreach (Direction d in DirectionUtils.GenerateRandomDirectionList())
{
Point targetLocation = PointDirectionUtils.ConvertDirectionToDestinationPoint(engine.Player.Position, d);
if (engine.Map.GetTerrainAt(targetLocation) == TerrainType.Wall)
continue;
if (engine.Map.Monsters.Where(x => x.Position == targetLocation).Count() > 0)
continue;
if (engine.Map.MapObjects.Where(x => x.Position == targetLocation && x.IsSolid).Count() > 0)
continue;
return targetLocation;
}
break;
}
}
}
// If we can't find a better spot, use the player's position
return engine.Player.Position;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
using System.Drawing ;
using System.Diagnostics;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.PostEditor.ContentSources;
using OpenLiveWriter.BlogClient ;
using OpenLiveWriter.Extensibility.BlogClient;
namespace OpenLiveWriter.PostEditor.Configuration.Wizard
{
internal sealed class BlogProviderAccountWizard
{
public static IBlogProviderAccountWizardDescription[] InstalledAccountWizards
{
get
{
lock(_classLock)
{
if ( _installedAccountWizards == null )
{
ArrayList installedAccountWizards = new ArrayList();
// load account wizards from registered xml descriptors
// (disabled for now)
//installedAccountWizards.AddRange(LoadAccountWizardsFromXml()) ;
_installedAccountWizards = installedAccountWizards.ToArray(typeof(IBlogProviderAccountWizardDescription)) as IBlogProviderAccountWizardDescription[] ;
}
return _installedAccountWizards ;
}
}
}
private static IBlogProviderAccountWizardDescription[] _installedAccountWizards ;
private static ArrayList LoadAccountWizardsFromXml()
{
ArrayList accountWizardsFromXml = new ArrayList();
try
{
using ( SettingsPersisterHelper settingsKey = ApplicationEnvironment.UserSettingsRoot.GetSubSettings("AccountWizard\\Custom") )
{
foreach ( string customizationName in settingsKey.GetNames() )
{
IBlogProviderAccountWizardDescription wizardDescription = LoadAccountWizardFromXml(settingsKey.GetString(customizationName, String.Empty)) ;
if ( wizardDescription != null )
accountWizardsFromXml.Add(wizardDescription) ;
}
}
}
catch(Exception ex)
{
Trace.Fail("Unexpected exception in LoadAccountWizardsFromXml: " + ex.ToString());
}
return accountWizardsFromXml ;
}
private static IBlogProviderAccountWizardDescription LoadAccountWizardFromXml(string xmlDocumentPath)
{
try
{
return new BlogProviderAccountWizardDescriptionFromXml(xmlDocumentPath) ;
}
catch(Exception ex)
{
Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Unexpected exception loading account wizard {0}: {1}", xmlDocumentPath, ex.ToString()));
return null ;
}
}
private static readonly object _classLock = new object() ;
}
internal interface IBlogProviderAccountWizardDescription
{
// identification
string ServiceName { get; }
// welcome page
IBlogProviderWelcomePage WelcomePage { get; }
// account creation link
IBlogProviderAccountCreationLink AccountCreationLink { get; }
}
internal interface IBlogProviderWelcomePage
{
string Caption { get; }
string Text { get; }
}
internal interface IBlogProviderAccountCreationLink
{
Image Icon { get; }
string Text { get; }
string Url { get; }
}
internal class BlogProviderAccountWizardDescription : IBlogProviderAccountWizardDescription
{
protected BlogProviderAccountWizardDescription()
{
}
protected void Init(string serviceName, IBlogProviderWelcomePage welcomePage, IBlogProviderAccountCreationLink accountCreationLink)
{
if ( serviceName == null )
throw new ArgumentNullException("serviceName") ;
_serviceName = serviceName ;
_welcomePage = welcomePage ;
_accountCreationLink = accountCreationLink ;
}
public string ServiceName
{
get
{
return _serviceName ;
}
}
private string _serviceName ;
public IBlogProviderWelcomePage WelcomePage
{
get
{
return _welcomePage ;
}
}
private IBlogProviderWelcomePage _welcomePage ;
public IBlogProviderAccountCreationLink AccountCreationLink
{
get
{
return _accountCreationLink ;
}
}
private IBlogProviderAccountCreationLink _accountCreationLink ;
}
internal class BlogProviderWelcomePage : IBlogProviderWelcomePage
{
public BlogProviderWelcomePage( string caption, string text )
{
_caption = caption ;
_text = text ;
}
public string Caption
{
get
{
return _caption ;
}
}
private string _caption ;
public string Text
{
get
{
return _text;
}
}
private string _text ;
}
internal abstract class BlogProviderAccountCreationLink : IBlogProviderAccountCreationLink
{
public BlogProviderAccountCreationLink( string text, string url)
{
_text = text ;
_url = url ;
}
public abstract Image Icon
{
get ;
}
public string Text
{
get
{
return _text ;
}
}
private string _text;
public string Url
{
get
{
return _url ;
}
}
private string _url ;
}
internal class BlogProviderAccountCreationLinkFromResource : BlogProviderAccountCreationLink
{
public BlogProviderAccountCreationLinkFromResource( string imagePath, string text, string url)
: base(text, url)
{
_imagePath = imagePath ;
}
public override Image Icon
{
get
{
try
{
return ResourceHelper.LoadAssemblyResourceBitmap(_imagePath, true) ;
}
catch
{
Trace.Fail("accountCreationLink image path not found: " + _imagePath);
return null ;
}
}
}
private string _imagePath ;
}
internal class BlogProviderAccountCreationLinkFromFile : BlogProviderAccountCreationLink
{
public BlogProviderAccountCreationLinkFromFile( string imagePath, string text, string url)
: base(text, url)
{
_imagePath = imagePath ;
}
public override Image Icon
{
get
{
try
{
return new Bitmap(_imagePath) ;
}
catch
{
Trace.Fail("accountCreationLink image path not found: " + _imagePath);
return null ;
}
}
}
private string _imagePath ;
}
internal class BlogProviderAccountWizardDescriptionFromXml : BlogProviderAccountWizardDescription
{
public BlogProviderAccountWizardDescriptionFromXml( string wizardDocumentPath )
{
// load the xml document
XmlDocument wizardDocument = new XmlDocument() ;
wizardDocument.Load( wizardDocumentPath ) ;
// custom account wizard node
XmlNode customAccountWizardNode = wizardDocument.SelectSingleNode("//customAccountWizard") ;
if ( customAccountWizardNode == null )
throw new Exception("Required root element customAccountWizard not specified");
// service name
string serviceName = NodeText(customAccountWizardNode.SelectSingleNode("serviceName")) ;
if ( serviceName == String.Empty )
throw new Exception("Required element serviceName is not specified or empty") ;
// welcome page is optional
BlogProviderWelcomePage welcomePage = null ;
string welcomePageCaption = NodeText(customAccountWizardNode.SelectSingleNode("welcomePage/caption"));
string welcomePageText = NodeText(customAccountWizardNode.SelectSingleNode("welcomePage/text")) ;
if ( welcomePageCaption != String.Empty && welcomePageText != String.Empty )
welcomePage = new BlogProviderWelcomePage(welcomePageCaption, welcomePageText);
// account creation link is optional
BlogProviderAccountCreationLink accountCreationLink = null ;
string imagePath = NodeText(customAccountWizardNode.SelectSingleNode("accountCreationLink/imagePath")) ;
if ( imagePath != String.Empty )
{
if ( !Path.IsPathRooted(imagePath) )
imagePath = Path.Combine(Path.GetDirectoryName(wizardDocumentPath), imagePath) ;
}
string caption = NodeText(customAccountWizardNode.SelectSingleNode("accountCreationLink/caption")) ;
string link = NodeText(customAccountWizardNode.SelectSingleNode("accountCreationLink/link")) ;
if ( imagePath != String.Empty && caption != String.Empty && link != String.Empty )
accountCreationLink = new BlogProviderAccountCreationLinkFromFile(imagePath, caption, link);
// initialize
Init(serviceName, welcomePage, accountCreationLink) ;
}
private string NodeText(XmlNode node)
{
if ( node != null )
return node.InnerText.Trim();
else
return String.Empty ;
}
}
}
| |
// Track BuildR
// Available on the Unity3D Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public class TrackBuildREditorInspector
{
[SerializeField]
private static int selectedTexture;
[SerializeField]
private static RenderTexture pointPreviewTexture = null;
private static float aspect = 1.7777f;
private static Vector3 previewCameraHeight = new Vector3(0, 1.8f, 0);
private static int previewResolution = 800;
private static int pointTrackSelection = 0;
private static string[] pointTrackNames = new []{"Selected Point", "Track Wide"};
public static void OnInspectorGUI(TrackBuildR _trackBuildR, int selectedPointIndex, int selectedCurveIndex)
{
TrackBuildRTrack _track = _trackBuildR.track;
if (TrackBuildREditor._stageToolbarTexturesA == null)
return;
GUILayout.BeginVertical(GUILayout.Width(400));
//Track Preview Window
EditorGUILayout.Space();
RenderPreview(_trackBuildR);
EditorGUILayout.LabelField("Track Lap Length approx. " + (_track.trackLength / 1000).ToString("F2") + "km / " + (_track.trackLength / 1609.34f).ToString("F2") + " miles");
EditorGUILayout.LabelField("Track Polycount: "+_track.lastPolycount);
int currentTrackMode = (int)_trackBuildR.mode;
int currentTrackModeA = currentTrackMode < 5 ? currentTrackMode : -1;
int currentTrackModeB = currentTrackMode > 4 ? currentTrackMode - 5 : -1;
GUIContent[] guiContentA = new GUIContent[TrackBuildREditor.numberOfMenuOptionsA];
GUIContent[] guiContentB = new GUIContent[TrackBuildREditor.numberOfMenuOptionsB];
for (int i = 0; i < TrackBuildREditor.numberOfMenuOptionsA; i++)
guiContentA[i] = new GUIContent(TrackBuildREditor._stageToolbarTexturesA[i], TrackBuildREditor.trackModeString[i]);
for (int i = 0; i < TrackBuildREditor.numberOfMenuOptionsB; i++)
guiContentB[i] = new GUIContent(TrackBuildREditor._stageToolbarTexturesB[i], TrackBuildREditor.trackModeString[i]);
int newTrackModeA = GUILayout.Toolbar(currentTrackModeA, guiContentA, GUILayout.Width(400), GUILayout.Height(50));
int newTrackModeB = GUILayout.Toolbar(currentTrackModeB, guiContentB, GUILayout.Width(400), GUILayout.Height(50));
if (newTrackModeA != currentTrackModeA)
{
_trackBuildR.mode = (TrackBuildR.modes)newTrackModeA;
GUI.changed = true;
}
if (newTrackModeB != currentTrackModeB)
{
_trackBuildR.mode = (TrackBuildR.modes)newTrackModeB + 5;
GUI.changed = true;
}
if (_track.numberOfTextures == 0)
EditorGUILayout.HelpBox("There are no textures defined. Track will not render until this is done", MessageType.Error);
TrackBuildRPoint point = null;
if (_track.realNumberOfPoints > 0)
{
point = _trackBuildR.track[selectedPointIndex];
}
if(!_track.render)
EditorGUILayout.HelpBox("Track rendering is disabled", MessageType.Warning);
switch(_trackBuildR.mode)
{
case TrackBuildR.modes.track:
EditorGUILayout.Space();
Title("Track", TrackBuildRColours.GREEN);
bool trackloop = EditorGUILayout.Toggle("Is Looped", _track.loop);
if(_track.loop != trackloop)
{
Undo.RecordObject(_track, "Toggled Loop");
_track.loop = trackloop;
}
EditorGUILayout.BeginHorizontal();
if(_trackBuildR.pointMode != TrackBuildR.pointModes.add)
{
if(GUILayout.Button("Add New Point"))
_trackBuildR.pointMode = TrackBuildR.pointModes.add;
}
else
{
if(GUILayout.Button("Cancel Add New Point"))
_trackBuildR.pointMode = TrackBuildR.pointModes.transform;
}
EditorGUI.BeginDisabledGroup(_track.realNumberOfPoints < 3);
if(_trackBuildR.pointMode != TrackBuildR.pointModes.remove)
{
if(GUILayout.Button("Remove Point"))
_trackBuildR.pointMode = TrackBuildR.pointModes.remove;
}
else
{
if(GUILayout.Button("Cancel Remove Point"))
_trackBuildR.pointMode = TrackBuildR.pointModes.transform;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
if(!_track.drawMode)
{
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("Layout Track Points"))
{
if(EditorUtility.DisplayDialog("Discard Current Track?", "Do you wish to discard the current track layout?", "Yup", "Nope"))
{
_track.Clear();
_track.drawMode = true;
}
}
if(GUILayout.Button("?", GUILayout.Width(35)))
{
EditorUtility.DisplayDialog("Layout Track", "This allows you to click place points to define your track. It will erase the current track layout and start anew. Ideally used with a defined diagram to help you plot out the track", "Ok - got it!");
}
EditorGUILayout.EndHorizontal();
}
else
{
if(GUILayout.Button("Stop Layout Track"))
{
_track.drawMode = false;
}
EditorGUILayout.EndVertical();
return;
}
float meshResolution = _track.meshResolution;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Track Mesh Resolution", GUILayout.Width(140));
meshResolution = EditorGUILayout.Slider(meshResolution, 0.9f, 20.0f);
EditorGUILayout.LabelField("metres", GUILayout.Width(60));
EditorGUILayout.EndHorizontal();
if(meshResolution != _track.meshResolution)
{
_track.SetTrackDirty();
_track.meshResolution = meshResolution;
}
if(_track.realNumberOfPoints == 0)
{
EditorGUILayout.HelpBox("There are no track points defined, add nextNormIndex track point to begin", MessageType.Warning);
EditorGUILayout.EndVertical();
return;
}
EditorGUILayout.Space();
Title("Track Point", TrackBuildRColours.RED);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Point " + (selectedPointIndex + 1) + " selected");
if(GUILayout.Button("Goto Point"))
GotoScenePoint(point.position);
EditorGUILayout.EndHorizontal();
int currentMode = (int)_trackBuildR.pointMode;
int newStage = GUILayout.Toolbar(currentMode, TrackBuildREditor.pointModeString);
if(newStage != currentMode)
{
_trackBuildR.pointMode = (TrackBuildR.pointModes)newStage;
GUI.changed = true;
}
switch(_trackBuildR.pointMode)
{
case TrackBuildR.pointModes.transform:
Vector3 pointposition = EditorGUILayout.Vector3Field("Point Position", point.position);
if(pointposition != point.position)
{
Undo.RecordObject(point, "Position Modified");
point.position = pointposition;
}
break;
case TrackBuildR.pointModes.controlpoint:
bool pointsplitControlPoints = EditorGUILayout.Toggle("Split Control Points", point.splitControlPoints);
if(pointsplitControlPoints != point.splitControlPoints)
{
Undo.RecordObject(point, "Split Points Toggled");
point.splitControlPoints = pointsplitControlPoints;
}
Vector3 pointforwardControlPoint = EditorGUILayout.Vector3Field("Control Point Position", point.forwardControlPoint);
if(pointforwardControlPoint != point.forwardControlPoint)
{
Undo.RecordObject(point, "Forward Control Point Changed");
point.forwardControlPoint = pointforwardControlPoint;
}
break;
case TrackBuildR.pointModes.trackup:
//nothing to show - yet...
break;
case TrackBuildR.pointModes.trackpoint:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Point Crown");
float pointcrownAngle = EditorGUILayout.Slider(point.crownAngle, -45, 45);
if(pointcrownAngle != point.crownAngle)
{
point.isDirty = true;
Undo.RecordObject(point, "Crown Modified");
point.crownAngle = pointcrownAngle;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Point Width", GUILayout.Width(250));
float pointwidth = EditorGUILayout.FloatField(point.width);
if(pointwidth != point.width)
{
point.isDirty = true;
Undo.RecordObject(point, "Width Modified");
point.width = pointwidth;
}
EditorGUILayout.LabelField("metres", GUILayout.Width(75));
EditorGUILayout.EndHorizontal();
break;
}
break;
case TrackBuildR.modes.boundary:
EditorGUILayout.Space();
Title("Track Boundary", TrackBuildRColours.GREEN);
//Track Based Boundary Options
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Split Boundary from Track");
bool trackdisconnectBoundary = EditorGUILayout.Toggle(_track.disconnectBoundary, GUILayout.Width(25));
if(trackdisconnectBoundary != _track.disconnectBoundary)
{
Undo.RecordObject(_track, "disconnect boundary");
_track.disconnectBoundary = trackdisconnectBoundary;
GUI.changed = true;
_track.ReRenderTrack();
}
if(GUILayout.Button("Reset Boundary Points"))
{
Undo.RecordObject(_track, "reset boundary");
for(int i = 0; i < _track.numberOfPoints; i++)
{
_track[i].MatchBoundaryValues();
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Both Sides of Boundary");
bool renderBothSides = EditorGUILayout.Toggle(_track.renderBoundaryWallReverse, GUILayout.Width(50));
if(_track.renderBoundaryWallReverse != renderBothSides)
{
Undo.RecordObject(_track, "render reverse boundary");
_track.renderBoundaryWallReverse = renderBothSides;
GUI.changed = true;
_track.ReRenderTrack();
}
EditorGUILayout.EndHorizontal();
float newTrackColliderHeight = EditorGUILayout.FloatField("Track Collider Height", _track.trackColliderWallHeight);
if(newTrackColliderHeight != _track.trackColliderWallHeight)
{
Undo.RecordObject(_track, "trackCollider height");
_track.trackColliderWallHeight = newTrackColliderHeight;
_track.ReRenderTrack();
GUI.changed = true;
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Track Collider Should Have Roof");
bool newRoofCooliderValue = EditorGUILayout.Toggle(_track.includeColliderRoof, GUILayout.Width(50));
if(newRoofCooliderValue != _track.includeColliderRoof)
{
Undo.RecordObject(_track, "trackCollider roof");
_track.includeColliderRoof = newRoofCooliderValue;
_track.ReRenderTrack();
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
Title("Point Boundary", TrackBuildRColours.RED);
//Selected Point Boundary Options
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Point " + (selectedPointIndex + 1) + " selected");
if(GUILayout.Button("Goto Point"))
GotoScenePoint(point.position);
EditorGUILayout.EndHorizontal();
int currentBoundaryMode = (int)_trackBuildR.boundaryMode;
int newBoundaryMode = GUILayout.Toolbar(currentBoundaryMode, TrackBuildREditor.boundaryModeString);
if(newBoundaryMode != currentBoundaryMode)
{
_trackBuildR.boundaryMode = (TrackBuildR.boundaryModes)newBoundaryMode;
GUI.changed = true;
}
if(_track.realNumberOfPoints > 0)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Split Boundary Control Points");
bool pointSplitControlPoints = EditorGUILayout.Toggle(point.leftSplitControlPoints, GUILayout.Width(50));
if(point.leftSplitControlPoints != pointSplitControlPoints)
{
Undo.RecordObject(point, "split boundary");
point.leftSplitControlPoints = pointSplitControlPoints;
point.rightSplitControlPoints = pointSplitControlPoints;
GUI.changed = true;
_track.SetTrackDirty();
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.HelpBox("It is suggested that you disable the trackCollider bounding box when working on Track BuildR\nYou can do this by clicking on 'gizmos' above the scene view and deselecting 'Mesh Collider'", MessageType.Info);
break;
case TrackBuildR.modes.bumpers:
EditorGUILayout.Space();
Title("Track Bumpers", TrackBuildRColours.RED);
bool _tracktrackBumpers = EditorGUILayout.Toggle("Enable", _track.trackBumpers);
if(_track.trackBumpers != _tracktrackBumpers)
{
Undo.RecordObject(_track, "bumpers");
if(_tracktrackBumpers == false)
for(int i = 0; i < _track.numberOfCurves; i++)
_track[i].generateBumpers = false;
_track.trackBumpers = _tracktrackBumpers;
}
EditorGUI.BeginDisabledGroup(!_track.trackBumpers);
float bumperWidth = EditorGUILayout.Slider("Width", _track.bumperWidth, 0.1f, 2.0f);
if(bumperWidth != _track.bumperWidth)
{
Undo.RecordObject(_track, "bumper width");
GUI.changed = true;
_track.bumperWidth = bumperWidth;
}
float bumperHeight = EditorGUILayout.Slider("Height", _track.bumperHeight, 0.01f, 0.2f);
if(bumperHeight != _track.bumperHeight)
{
Undo.RecordObject(_track, "bumper height");
GUI.changed = true;
_track.bumperHeight = bumperHeight;
}
float bumperAngleThresold = EditorGUILayout.Slider("Threshold Angle", _track.bumperAngleThresold, 0.005f, 1.5f);
if(bumperAngleThresold != _track.bumperAngleThresold)
{
Undo.RecordObject(_track, "bumper threshold");
GUI.changed = true;
_track.bumperAngleThresold = bumperAngleThresold;
}
if(GUI.changed)//change on mouse up
{
_track.ReRenderTrack();
}
EditorGUI.EndDisabledGroup();
break;
case TrackBuildR.modes.textures:
EditorGUILayout.Space();
Title("Render Properties", TrackBuildRColours.BLUE);
pointTrackSelection = GUILayout.Toolbar(pointTrackSelection, pointTrackNames);
TrackBuildRPoint[] selectedCurves;
EditorGUILayout.BeginHorizontal();
switch(pointTrackSelection)
{
default:
selectedCurves = new TrackBuildRPoint[]{_track[selectedCurveIndex]};
Undo.RecordObjects(selectedCurves, "Curve Details Modified");
EditorGUILayout.LabelField("Selected Curve: " + selectedCurves[0].pointName);
if(GUILayout.Button("Goto Curve"))
GotoScenePoint(selectedCurves[0].center);
break;
case 1:
selectedCurves = _track.points;
Undo.RecordObjects(selectedCurves, "Curve Details Modified");
break;
}
EditorGUILayout.EndHorizontal();
TrackBuildRPoint selectedCurve = selectedCurves[0];
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Curve");
bool render = EditorGUILayout.Toggle(selectedCurve.render);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Boundaries");
bool renderBounds = EditorGUILayout.Toggle(selectedCurve.renderBounds);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Boundary Height");
float boundaryHeight = EditorGUILayout.Slider(selectedCurve.boundaryHeight, 0, 10);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Colliders");
bool trackCollider = EditorGUILayout.Toggle(selectedCurve.trackCollider);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Side Colliders");
bool colliderSides = EditorGUILayout.Toggle(selectedCurve.colliderSides);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Extrude Track");
bool extrudeTrack = EditorGUILayout.Toggle(selectedCurve.extrudeTrack);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Track Bottom");
bool extrudeTrackBottom = EditorGUILayout.Toggle(selectedCurve.extrudeTrackBottom);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Curve End");
bool extrudeCurveEnd = EditorGUILayout.Toggle(selectedCurve.extrudeCurveEnd);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Extrude Length");
float extrudeLength = EditorGUILayout.Slider(selectedCurve.extrudeLength, 0.1f, 25.0f);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Extrude Bevel");
float extrudeBevel = EditorGUILayout.Slider(selectedCurve.extrudeBevel, 0, 2);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Generate Bumpers");
bool generateBumpers = EditorGUILayout.Toggle(selectedCurve.generateBumpers);
EditorGUILayout.EndHorizontal();
if (selectedCurve.render != render)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.render = render;
if (selectedCurve.renderBounds != renderBounds)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.renderBounds = renderBounds;
if (selectedCurve.boundaryHeight != boundaryHeight)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.boundaryHeight = boundaryHeight;
if (selectedCurve.trackCollider != trackCollider)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.trackCollider = trackCollider;
if (selectedCurve.extrudeTrack != extrudeTrack)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.extrudeTrack = extrudeTrack;
if (selectedCurve.extrudeTrackBottom != extrudeTrackBottom)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.extrudeTrackBottom = extrudeTrackBottom;
if (selectedCurve.extrudeCurveEnd != extrudeCurveEnd)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.extrudeCurveEnd = extrudeCurveEnd;
if (selectedCurve.extrudeLength != extrudeLength)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.extrudeLength = extrudeLength;
if (selectedCurve.extrudeBevel != extrudeBevel)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.extrudeBevel = extrudeBevel;
if (selectedCurve.generateBumpers != generateBumpers)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.generateBumpers = generateBumpers;
if (selectedCurve.colliderSides != colliderSides)
foreach (TrackBuildRPoint selectedCurveArray in selectedCurves)
selectedCurveArray.colliderSides = colliderSides;
TrackBuildRTexture[] textures = _track.GetTexturesArray();
int numberOfTextures = textures.Length;
string[] textureNames = new string[numberOfTextures];
for(int t = 0; t < numberOfTextures; t++)
textureNames[t] = textures[t].customName;
if(numberOfTextures > 0)
{
int trackTextureStyleIndex = CurveTextureSelector(_track, selectedCurve.trackTextureStyleIndex, "Track Texture");
if(trackTextureStyleIndex != selectedCurve.trackTextureStyleIndex)
{
selectedCurve.trackTextureStyleIndex = trackTextureStyleIndex;
GUI.changed = true;
_track.ReRenderTrack();
}
int offroadTextureStyleIndex = CurveTextureSelector(_track, selectedCurve.offroadTextureStyleIndex, "Offroad Texture");
if(offroadTextureStyleIndex != selectedCurve.offroadTextureStyleIndex)
{
selectedCurve.offroadTextureStyleIndex = offroadTextureStyleIndex;
GUI.changed = true;
_track.ReRenderTrack();
}
int boundaryTextureStyleIndex = CurveTextureSelector(_track, selectedCurve.boundaryTextureStyleIndex, "Boundary Texture");
if(boundaryTextureStyleIndex != selectedCurve.boundaryTextureStyleIndex)
{
selectedCurve.boundaryTextureStyleIndex = boundaryTextureStyleIndex;
GUI.changed = true;
_track.ReRenderTrack();
}
int bumperTextureStyleIndex = CurveTextureSelector(_track, selectedCurve.bumperTextureStyleIndex, "Bumper Texture");
if(bumperTextureStyleIndex != selectedCurve.bumperTextureStyleIndex)
{
selectedCurve.bumperTextureStyleIndex = bumperTextureStyleIndex;
GUI.changed = true;
_track.ReRenderTrack();
}
int extrudeTextureStyleIndex = CurveTextureSelector(_track, selectedCurve.bottomTextureStyleIndex, "Track Extrude Texture");
if(extrudeTextureStyleIndex != selectedCurve.bottomTextureStyleIndex)
{
selectedCurve.bottomTextureStyleIndex = extrudeTextureStyleIndex;
GUI.changed = true;
_track.ReRenderTrack();
}
}
EditorGUILayout.Space();
Title("Track Texture Library", TrackBuildRColours.RED);
if(GUILayout.Button("Add New"))
{
_track.AddTexture();
numberOfTextures++;
selectedTexture = numberOfTextures - 1;
}
if(numberOfTextures == 0)
{
EditorGUILayout.HelpBox("There are no textures to show", MessageType.Info);
return;
}
if(numberOfTextures > 0)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Texture", GUILayout.Width(75));
selectedTexture = EditorGUILayout.Popup(selectedTexture, textureNames);
TrackBuildRTexture trackBuildRTexture = _track.Texture(selectedTexture);
if(GUILayout.Button("Remove Texture"))
{
_track.RemoveTexture(trackBuildRTexture);
numberOfTextures--;
selectedTexture = 0;
trackBuildRTexture = _track.Texture(selectedTexture);
return;
}
EditorGUILayout.EndHorizontal();
if(TextureGUI(ref trackBuildRTexture))
{
_track.ReRenderTrack();
}
}
break;
case TrackBuildR.modes.terrain:
Title("Terrain", TrackBuildRColours.RED);
EditorGUILayout.HelpBox("I'd love to hear feedback on this new feature.\nWhat works? What doesn't.\nLet me know!", MessageType.Info);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Terrain Mode", GUILayout.Width(90));
EditorGUI.BeginDisabledGroup(_trackBuildR.terrainMode == TrackBuildR.terrainModes.mergeTerrain);
if(GUILayout.Button("Merge Terrain"))
_trackBuildR.terrainMode = TrackBuildR.terrainModes.mergeTerrain;
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(_trackBuildR.terrainMode == TrackBuildR.terrainModes.conformTrack);
if(GUILayout.Button("Conform Track"))
_trackBuildR.terrainMode = TrackBuildR.terrainModes.conformTrack;
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
switch(_trackBuildR.terrainMode)
{
case TrackBuildR.terrainModes.mergeTerrain:
EditorGUILayout.BeginVertical("box");
Title("Terrain Merge", TrackBuildRColours.RED);
EditorGUILayout.LabelField("Selected Terrain");
EditorGUILayout.BeginHorizontal();
_track.mergeTerrain = (Terrain)EditorGUILayout.ObjectField(_track.mergeTerrain, typeof(Terrain), true);
if(GUILayout.Button("Find Terrain"))
_track.mergeTerrain = GameObject.FindObjectOfType<Terrain>();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Terrain Merge Width");
_track.terrainMergeWidth = EditorGUILayout.Slider(_track.terrainMergeWidth, 0, 100);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Terrain Match Accuracy");
_track.terrainAccuracy = EditorGUILayout.Slider(_track.terrainAccuracy, 0, 5);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Terrain Match Margin");
_track.terrainMergeMargin = EditorGUILayout.Slider(_track.terrainMergeMargin, 1, 5);
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Terrain Merge Curve");
_track.mergeCurve = EditorGUILayout.CurveField(_track.mergeCurve, GUILayout.Height(75));
EditorGUILayout.EndVertical();
if (_track.mergeTerrain == null)
EditorGUILayout.HelpBox("You have not selected a terrain in the scene", MessageType.Error);
if (_track.disconnectBoundary)
EditorGUILayout.HelpBox("Terrain Merge doesn't fully support tracks that have boundaries split", MessageType.Error);
EditorGUI.BeginDisabledGroup(_track.mergeTerrain == null);
if(GUILayout.Button("Merge Terrain", GUILayout.Height(50)))
{
if(_track.disconnectBoundary)
{
if (EditorUtility.DisplayDialog("Terrain Merge Warning", "Terrain Merge doesn't fully support tracks that have boundaries split", "Continue", "Cancel"))
{
Undo.RecordObject(_track.mergeTerrain.terrainData, "Merge Terrain");
TrackBuildRTerrain.MergeTerrain(_track, _track.mergeTerrain);
}
}
else
{
Undo.RecordObject(_track.mergeTerrain.terrainData, "Merge Terrain");
TrackBuildRTerrain.MergeTerrain(_track, _track.mergeTerrain);
}
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
break;
case TrackBuildR.terrainModes.conformTrack:
EditorGUILayout.BeginVertical("box");
Title("Conform Track to Terrain", TrackBuildRColours.RED);
EditorGUILayout.LabelField("Selected Terrain");
EditorGUILayout.BeginHorizontal();
_track.mergeTerrain = (Terrain)EditorGUILayout.ObjectField(_track.mergeTerrain, typeof(Terrain), true);
if(GUILayout.Button("Find Terrain"))
_track.mergeTerrain = GameObject.FindObjectOfType<Terrain>();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Track Conform Accuracy");
_track.conformAccuracy = EditorGUILayout.Slider(_track.conformAccuracy, 0, 25);
EditorGUILayout.EndVertical();
if (_track.mergeTerrain == null)
EditorGUILayout.HelpBox("You have not selected a terrain in the scene", MessageType.Error);
EditorGUI.BeginDisabledGroup(_track.mergeTerrain == null);
if(GUILayout.Button("Conform Track", GUILayout.Height(50)))
{
Undo.RecordObject(_track, "Conform Track");
TrackBuildRTerrain.ConformTrack(_track, _track.mergeTerrain);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
break;
}
break;
case TrackBuildR.modes.stunt:
EditorGUILayout.Space();
Title("Stunt", TrackBuildRColours.RED);
if(_track.realNumberOfPoints == 0)
{
EditorGUILayout.HelpBox("No Track to Apply Parts to",MessageType.Error);
return;
}
EditorGUILayout.BeginHorizontal("box");
EditorGUILayout.LabelField("Stunt Part Type");
_trackBuildR.stuntMode = (TrackBuildR.stuntModes)EditorGUILayout.EnumPopup(_trackBuildR.stuntMode, GUILayout.Width(160), GUILayout.Height(30));
EditorGUILayout.EndHorizontal();
switch(_trackBuildR.stuntMode)
{
case TrackBuildR.stuntModes.loop:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Loop Radius");
_track.loopRadius = EditorGUILayout.Slider(_track.loopRadius, 10, 100);
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Add Loop da Loop"))
{
Undo.RecordObject(_track, "Add Loop");
TrackBuildRStuntUtil.AddLoop(_track, selectedPointIndex);
GUI.changed = true;
}
break;
case TrackBuildR.stuntModes.jump:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Jump Height Radius");
_track.jumpHeight = EditorGUILayout.Slider(_track.jumpHeight, 0, 50);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Maximum Jump Length");
_track.maxJumpLength = EditorGUILayout.Slider(_track.maxJumpLength, 1, 100);
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Add Jump to Point"))
{
// Undo.RecordObject(_track, "Add Jump");
TrackBuildRStuntUtil.AddJump(_track, selectedPointIndex);
GUI.changed = true;
}
break;
case TrackBuildR.stuntModes.jumptwist:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Jump Height Radius");
_track.jumpHeight = EditorGUILayout.Slider(_track.jumpHeight, 0, 50);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Maximum Jump Length");
_track.maxJumpLength = EditorGUILayout.Slider(_track.maxJumpLength, 1, 100);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Jump Twist Angle");
_track.twistAngle = EditorGUILayout.Slider(_track.twistAngle, -90, 90);
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Add Jump Twist to Point"))
{
// Undo.RecordObject(_track, "Add Jump");
TrackBuildRStuntUtil.AddJumpTwist(_track, selectedPointIndex);
GUI.changed = true;
}
break;
// case TrackBuildR.stuntModes.twist:
//
// EditorGUILayout.BeginHorizontal();
// EditorGUILayout.LabelField("Twist Radius");
// _track.twistRadius = EditorGUILayout.Slider(_track.twistRadius, 0, 50);
// EditorGUILayout.EndHorizontal();
//
//
// EditorGUILayout.BeginHorizontal();
// EditorGUILayout.LabelField("Maximum Twist Length");
// _track.maxJumpLength = EditorGUILayout.Slider(_track.maxJumpLength, 1, 100);
// EditorGUILayout.EndHorizontal();
//
// if(GUILayout.Button("Add Twist to Point"))
// {
// // Undo.RecordObject(_track, "Add Jump");
// TrackBuildRStuntUtil.AddTwist(_track, selectedPointIndex);
// GUI.changed = true;
// }
//
// break;
}
break;
case TrackBuildR.modes.diagram:
_track.CheckDiagram();
EditorGUILayout.Space();
Title("Diagram Image", TrackBuildRColours.RED);
_track.showDiagram = EditorGUILayout.Toggle("Show Diagram", _track.showDiagram);
_track.diagramGO.renderer.enabled = _track.showDiagram;
EditorGUILayout.BeginHorizontal();
if(_track.diagramMaterial.mainTexture != null)
{
float height = _track.diagramMaterial.mainTexture.height * (200.0f / _track.diagramMaterial.mainTexture.width);
GUILayout.Label(_track.diagramMaterial.mainTexture, GUILayout.Width(200), GUILayout.Height(height));
}
EditorGUILayout.BeginVertical();
if(GUILayout.Button("Load Diagram"))
{
string newDiagramFilepath = EditorUtility.OpenFilePanel("Load Track Diagram", "/", "");
if(newDiagramFilepath != _track.diagramFilepath)
{
_track.diagramFilepath = newDiagramFilepath;
WWW www = new WWW("file:///" + newDiagramFilepath);
Texture2D newTexture = new Texture2D(100, 100);
www.LoadImageIntoTexture(newTexture);
_track.diagramMaterial.mainTexture = newTexture;
_track.diagramGO.transform.localScale = new Vector3(newTexture.width, 0, newTexture.height);
_track.showDiagram = true;
}
}
if(GUILayout.Button("Clear"))
{
_track.diagramFilepath = "";
_track.diagramMaterial.mainTexture = null;
_track.showDiagram = false;
}
GUILayout.Space(20);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Diagram Scale", GUILayout.Width(100));
float newScale = EditorGUILayout.FloatField(_track.scale, GUILayout.Width(40));
if(_track.scale != newScale)
{
_track.scale = newScale;
UpdateDiagram(_track);
}
EditorGUILayout.LabelField("metres", GUILayout.Width(50));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if(_track.assignedPoints == 0)
{
if(GUILayout.Button("Draw Scale"))
{
_track.assignedPoints = 1;
}
if(GUILayout.Button("?", GUILayout.Width(25)))
{
EditorUtility.DisplayDialog("Draw Scale", "Once you load a diagram, use this to define the start and end of the diagram scale (I do hope your diagram has a scale...)", "ok");
}
}
else
{
if(GUILayout.Button("Cancel Draw Scale"))
{
_track.assignedPoints = 0;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField(_track.diagramFilepath);
break;
case TrackBuildR.modes.options:
EditorGUILayout.Space();
Title("Generation Options", TrackBuildRColours.RED);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Render Track");
_track.render = EditorGUILayout.Toggle(_track.render, GUILayout.Width(15));
EditorGUILayout.EndHorizontal();
//Toggle showing the wireframe when we have selected the model.
EditorGUILayout.BeginHorizontal(GUILayout.Width(400));
EditorGUILayout.LabelField("Show Wireframe");
_track.showWireframe = EditorGUILayout.Toggle(_track.showWireframe, GUILayout.Width(15));
EditorGUILayout.EndHorizontal();
//Tangent calculation
EditorGUILayout.BeginHorizontal(GUILayout.Width(400));
EditorGUI.BeginDisabledGroup(_trackBuildR.tangentsGenerated);
if(GUILayout.Button("Build Tangents", GUILayout.Height(38)))
{
Undo.RecordObject(_trackBuildR, "Build Tangents");
_trackBuildR.GenerateTangents();
GUI.changed = false;
}
EditorGUI.EndDisabledGroup();
if(!_trackBuildR.tangentsGenerated)
EditorGUILayout.HelpBox("The model doesn't have tangents", MessageType.Warning);
EditorGUILayout.EndHorizontal();
//Lightmap rendering
EditorGUILayout.BeginHorizontal(GUILayout.Width(400));
EditorGUI.BeginDisabledGroup(_trackBuildR.lightmapGenerated);
if(GUILayout.Button("Build Lightmap UVs", GUILayout.Height(38)))
{
Undo.RecordObject(_trackBuildR, "Build Lightmap UVs");
_trackBuildR.GenerateSecondaryUVSet();
GUI.changed = false;
}
EditorGUI.EndDisabledGroup();
if(!_trackBuildR.lightmapGenerated)
EditorGUILayout.HelpBox("The model doesn't have lightmap UVs", MessageType.Warning);
EditorGUILayout.EndHorizontal();
//Mesh Optimisation
EditorGUILayout.BeginHorizontal(GUILayout.Width(400));
EditorGUI.BeginDisabledGroup(_trackBuildR.optimised);
if(GUILayout.Button("Optimise Mesh For Runtime", GUILayout.Height(38)))
{
Undo.RecordObject(_trackBuildR, "Optimise Meshes");
_trackBuildR.OptimseMeshes();
GUI.changed = false;
}
EditorGUI.EndDisabledGroup();
if(!_trackBuildR.optimised)
EditorGUILayout.HelpBox("The model is currently fully optimised for runtime", MessageType.Warning);
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Force Full Rebuild of Track"))
_trackBuildR.ForceFullRecalculation();
break;
case TrackBuildR.modes.export:
TrackBuildRExport.InspectorGUI(_trackBuildR);
break;
}
GUILayout.EndVertical();
}
/// <summary>
/// A GUI stub that displays the coloured titles in the inspector for Track BuildR
/// </summary>
/// <param customName="titleString">The title to display</param>
/// <param customName="colour">Colour of the background</param>
private static void Title(string titleString, Color colour)
{
//TITLE
GUIStyle title = new GUIStyle(GUI.skin.label);
title.fixedHeight = 60;
title.fixedWidth = 400;
title.alignment = TextAnchor.UpperCenter;
title.fontStyle = FontStyle.Bold;
title.normal.textColor = Color.white;
EditorGUILayout.LabelField(titleString, title);
Texture2D facadeTexture = new Texture2D(1, 1);
facadeTexture.SetPixel(0, 0, colour);
facadeTexture.Apply();
Rect sqrPos = new Rect(0, 0, 0, 0);
if (Event.current.type == EventType.Repaint)
sqrPos = GUILayoutUtility.GetLastRect();
GUI.DrawTexture(sqrPos, facadeTexture);
EditorGUI.LabelField(sqrPos, titleString, title);
}
private static void RenderPreview(TrackBuildR _trackBuildR)
{
if (!SystemInfo.supportsRenderTextures)
return;
if (EditorApplication.isPlaying)
return;
TrackBuildRTrack _track = _trackBuildR.track;
if (_track.realNumberOfPoints < 2)
return;
if (pointPreviewTexture == null)
pointPreviewTexture = new RenderTexture(previewResolution, Mathf.RoundToInt(previewResolution / aspect), 24, RenderTextureFormat.RGB565);
float previewpercent = (_trackBuildR.previewPercentage + _trackBuildR.previewStartPoint) % 1.0f;
if(!_trackBuildR.previewForward) previewpercent = 1.0f - previewpercent;
_track.diagramGO.renderer.enabled = false;
GameObject trackEditorPreview = _trackBuildR.trackEditorPreview;
Vector3 trackUp = _track.GetTrackUp(previewpercent) * Vector3.forward;
Vector3 trackDirection = _track.GetTrackDirection(previewpercent);
if (!_trackBuildR.previewForward) trackDirection = -trackDirection;
trackEditorPreview.transform.position = _track.GetTrackPosition(previewpercent) + (previewCameraHeight.y * trackUp) + _trackBuildR.transform.position;
trackEditorPreview.transform.rotation = Quaternion.LookRotation(trackDirection, trackUp);
trackEditorPreview.camera.targetTexture = pointPreviewTexture;
trackEditorPreview.camera.Render();
trackEditorPreview.camera.targetTexture = null;
_track.diagramGO.renderer.enabled = _track.showDiagram;
GUILayout.Label(pointPreviewTexture, GUILayout.Width(400), GUILayout.Height(225));
EditorGUILayout.BeginHorizontal();
string trackForwardText = _trackBuildR.previewForward ? "Track Preivew Direction Forward >>" : "<< Track Preivew Direction Backward";
if(GUILayout.Button(trackForwardText))
_trackBuildR.previewForward = !_trackBuildR.previewForward;
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Preview Track Percentage");
EditorGUILayout.BeginHorizontal();
_trackBuildR.previewPercentage = EditorGUILayout.Slider(_trackBuildR.previewPercentage, 0, 1);
EditorGUILayout.LabelField("0-1", GUILayout.Width(25));
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Preview Track Start Point");
EditorGUILayout.BeginHorizontal();
_trackBuildR.previewStartPoint = EditorGUILayout.Slider(_trackBuildR.previewStartPoint, 0, 1);
EditorGUILayout.LabelField("0-1", GUILayout.Width(25));
EditorGUILayout.EndHorizontal();
}
/// <summary>
/// The Texture display GUI
/// </summary>
/// <param customName="texture"></param>
/// <returns>True if this texture was modified</returns>
private static bool TextureGUI(ref TrackBuildRTexture texture)
{
if(texture.material == null)
texture.material = new Material(Shader.Find("Diffuse"));
bool isModified = false;
string textureName = texture.customName;
textureName = EditorGUILayout.TextField("Name", textureName);
if (texture.customName != textureName)
{
texture.customName = textureName;
}
texture.type = (TrackBuildRTexture.Types)EditorGUILayout.EnumPopup("Type", texture.type);
//Shader Time
Shader[] tempshaders = (Shader[])Resources.FindObjectsOfTypeAll(typeof(Shader));
List<string> shaderNames = new List<string>(ShaderProperties.NAMES);
foreach (Shader shader in tempshaders)
{
if (!string.IsNullOrEmpty(shader.name) && !shader.name.StartsWith("__") && !shader.name.Contains("hidden"))
shaderNames.Add(shader.name);
}
int selectedShaderIndex = shaderNames.IndexOf(texture.material.shader.name);
int newSelectedShaderIndex = EditorGUILayout.Popup("Shader", selectedShaderIndex, shaderNames.ToArray());
if (selectedShaderIndex != newSelectedShaderIndex)
{
texture.material.shader = Shader.Find(shaderNames[newSelectedShaderIndex]);
}
switch(texture.type)
{
case TrackBuildRTexture.Types.Basic:
Shader selectedShader = texture.material.shader;
int propertyCount = ShaderUtil.GetPropertyCount(selectedShader);
for (int s = 0; s < propertyCount; s++)
{
ShaderUtil.ShaderPropertyType propertyTpe = ShaderUtil.GetPropertyType(selectedShader, s);
string shaderPropertyName = ShaderUtil.GetPropertyName(selectedShader, s);
switch (propertyTpe)
{
case ShaderUtil.ShaderPropertyType.TexEnv:
Texture shaderTexture = texture.material.GetTexture(shaderPropertyName);
Texture newShaderTexture = (Texture)EditorGUILayout.ObjectField(shaderPropertyName, shaderTexture, typeof(Texture), false);
if (shaderTexture != newShaderTexture)
{
texture.material.SetTexture(shaderPropertyName, newShaderTexture);
}
break;
case ShaderUtil.ShaderPropertyType.Color:
Color shaderColor = texture.material.GetColor(shaderPropertyName);
Color newShaderColor = EditorGUILayout.ColorField(shaderPropertyName, shaderColor);
if (shaderColor != newShaderColor)
{
texture.material.SetColor(shaderPropertyName, newShaderColor);
}
break;
case ShaderUtil.ShaderPropertyType.Float:
float shaderFloat = texture.material.GetFloat(shaderPropertyName);
float newShaderFloat = EditorGUILayout.FloatField(shaderPropertyName, shaderFloat);
if (shaderFloat != newShaderFloat)
{
texture.material.SetFloat(shaderPropertyName, newShaderFloat);
}
break;
case ShaderUtil.ShaderPropertyType.Range:
float shaderRange = texture.material.GetFloat(shaderPropertyName);
float rangeMin = ShaderUtil.GetRangeLimits(selectedShader, s, 1);
float rangeMax = ShaderUtil.GetRangeLimits(selectedShader, s, 2);
float newShaderRange = EditorGUILayout.Slider(shaderPropertyName, shaderRange, rangeMin, rangeMax);
if (shaderRange != newShaderRange)
{
texture.material.SetFloat(shaderPropertyName, newShaderRange);
}
break;
case ShaderUtil.ShaderPropertyType.Vector:
Vector3 shaderVector = texture.material.GetVector(shaderPropertyName);
Vector3 newShaderVector = EditorGUILayout.Vector3Field(shaderPropertyName, shaderVector);
if (shaderVector != newShaderVector)
{
texture.material.SetVector(shaderPropertyName, newShaderVector);
}
break;
}
}
if(texture.texture == null)
return isModified;
bool textureflipped = EditorGUILayout.Toggle("Flip Clockwise", texture.flipped);
if(textureflipped != texture.flipped)
{
isModified = true;
texture.flipped = textureflipped;
}
Vector2 textureUnitSize = texture.textureUnitSize;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("trackTexture width", GUILayout.Width(75));//, GUILayout.Width(42));
float textureUnitSizex = EditorGUILayout.FloatField(texture.textureUnitSize.x, GUILayout.Width(25));
if(textureUnitSizex != textureUnitSize.x)
{
isModified = true;
textureUnitSize.x = textureUnitSizex;
}
EditorGUILayout.LabelField("metres", GUILayout.Width(40));//, GUILayout.Width(42));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("trackTexture height", GUILayout.Width(75));//, GUILayout.Width(42));
float textureUnitSizey = EditorGUILayout.FloatField(texture.textureUnitSize.y, GUILayout.Width(25));
if(textureUnitSizey != textureUnitSize.y)
{
isModified = true;
textureUnitSize.y = textureUnitSizey;
}
EditorGUILayout.LabelField("metres", GUILayout.Width(40));
EditorGUILayout.EndHorizontal();
texture.textureUnitSize = textureUnitSize;
const int previewTextureUnitSize = 120;
const int previewPadding = 25;
EditorGUILayout.LabelField("1 Metre Squared", GUILayout.Width(previewTextureUnitSize));
GUILayout.Space(previewPadding);
EditorGUILayout.Space();
Rect texturePreviewPostion = new Rect(0, 0, 0, 0);
if(Event.current.type == EventType.Repaint)
texturePreviewPostion = GUILayoutUtility.GetLastRect();
Rect previewRect = new Rect(texturePreviewPostion.x, texturePreviewPostion.y, previewTextureUnitSize, previewTextureUnitSize);
Rect sourceRect = new Rect(0, 0, (1.0f / textureUnitSize.x), (1.0f / textureUnitSize.y));
Graphics.DrawTexture(previewRect, texture.texture, sourceRect, 0, 0, 0, 0);
GUILayout.Space(previewTextureUnitSize);
break;
case TrackBuildRTexture.Types.Substance:
texture.proceduralMaterial = (ProceduralMaterial)EditorGUILayout.ObjectField("Procedural Material", texture.proceduralMaterial, typeof(ProceduralMaterial), false);
if (texture.proceduralMaterial != null)
{
ProceduralMaterial pMat = texture.proceduralMaterial;
GUILayout.Label(pMat.GetGeneratedTexture(pMat.mainTexture.name), GUILayout.Width(400));
}
else
EditorGUILayout.HelpBox("There is no substance material set.", MessageType.Error);
break;
case TrackBuildRTexture.Types.User:
texture.userMaterial = (Material)EditorGUILayout.ObjectField("User Material", texture.userMaterial, typeof(Material), false);
if (texture.userMaterial != null)
{
Material mat = texture.userMaterial;
GUILayout.Label(mat.mainTexture, GUILayout.Width(400));
}
else
EditorGUILayout.HelpBox("There is no substance material set.", MessageType.Error);
break;
}
if (isModified)
GUI.changed = true;
return isModified;
}
/// <summary>
/// Deals with modifing the diagram used in track building
/// </summary>
private static void UpdateDiagram(TrackBuildRTrack _track)
{
// Texture texture = _track.diagramMaterial.mainTexture;
float scaleSize = Vector3.Distance(_track.scalePointB, _track.scalePointA);
float diagramScale = _track.scale / scaleSize;
_track.diagramGO.transform.localScale *= diagramScale;
_track.scalePointA *= diagramScale;
_track.scalePointB *= diagramScale;
}
/// <summary>
/// A stub of GUI for selecting the texture for a specific part of the track on a specific curve
/// IE. The track texture, the wall texture, etc...
/// </summary>
/// <param customName="_track"></param>
/// <param customName="textureIndex"></param>
/// <param customName="label"></param>
/// <returns></returns>
private static int CurveTextureSelector(TrackBuildRTrack _track, int textureIndex, string label)
{
TrackBuildRTexture[] textures = _track.GetTexturesArray();
int numberOfTextures = textures.Length;
string[] textureNames = new string[numberOfTextures];
for (int t = 0; t < numberOfTextures; t++)
textureNames[t] = textures[t].customName;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField(label);
textureIndex = EditorGUILayout.Popup(textureIndex, textureNames);
TrackBuildRTexture tbrTexture = _track.Texture(textureIndex);
EditorGUILayout.EndVertical();
GUILayout.Label(tbrTexture.texture, GUILayout.Width(50), GUILayout.Height(50));
EditorGUILayout.EndHorizontal();
return textureIndex;
}
/// <summary>
/// Called to ensure we're not leaking stuff into the Editor
/// </summary>
public static void CleanUp()
{
if (pointPreviewTexture)
{
pointPreviewTexture.DiscardContents();
pointPreviewTexture.Release();
Object.DestroyImmediate(pointPreviewTexture);
}
}
/// <summary>
/// A little hacking of the Unity Editor to allow us to focus on an arbitrary point in 3D Space
/// We're replicating pressing the F button in scene view to focus on the selected object
/// Here we can focus on a 3D point
/// </summary>
/// <param customName="position">The 3D point we want to focus on</param>
private static void GotoScenePoint(Vector3 position)
{
Object[] intialFocus = Selection.objects;
GameObject tempFocusView = new GameObject("Temp Focus View");
tempFocusView.transform.position = position;
Selection.objects = new Object[] { tempFocusView };
SceneView.lastActiveSceneView.FrameSelected();
Selection.objects = intialFocus;
Object.DestroyImmediate(tempFocusView);
}
}
| |
// 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.Net.NetworkInformation;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Protocols.TestManager.Detector;
namespace Microsoft.Protocols.TestManager.RDPPlugin
{
public class RDPValueDetector : IValueDetector
{
#region Private Types
private enum EnvironmentType
{
Domain,
Workgroup,
}
#endregion Private Types
#region Variables
private EnvironmentType env = EnvironmentType.Workgroup;
private DetectionInfo detectionInfo = new DetectionInfo();
#endregion Variables
#region Constant
private const string tcComputerNameTitle = "SUT Name";
private const string isWindowsImplementationTitle = "IsWindowsImplementation";
private const string triggerMethodTitle = "Trigger RDP Client By";
private const string userNameInTCTitle = "SUT User Name \n* Only for PowerShell Trigger";
private const string userPwdInTCTitle = "SUT Password \n* Only for PowerShell Trigger";
private const string agentPortTitle = "Agent Listen Port \n* Only for Managed Trigger";
#endregion Constant
#region Implemented IValueDetector
/// <summary>
/// Sets selected test environment.
/// </summary>
/// <param name="Environment"></param>
public void SelectEnvironment(string NetworkEnvironment)
{
Enum.TryParse<EnvironmentType>(NetworkEnvironment, out env);
}
/// <summary>
/// Gets the prerequisites for auto-detection.
/// </summary>
/// <returns>A instance of Prerequisites class.</returns>
public Prerequisites GetPrerequisites()
{
Prerequisites prerequisites = new Prerequisites();
prerequisites.Title = "Remote Desktop";
prerequisites.Summary = "Please input the below info to detect SUT.";
Dictionary<string, List<string>> propertiesDic = new Dictionary<string, List<string>>();
//Retrieve values from *.ptfconfig file
string sutName = DetectorUtil.GetPropertyValue("SUTName");
string userNameInTC = DetectorUtil.GetPropertyValue("SUTUserName");
string userPwdInTC = DetectorUtil.GetPropertyValue("SUTUserPassword");
string isWindowsImplementation = DetectorUtil.GetPropertyValue("IsWindowsImplementation");
List<string> sutNames = new List<string>();
List<string> userNamesInTC = new List<string>();
List<string> userPwdsInTC = new List<string>();
List<string> isWindowsImplementationList = new List<string>();
if (string.IsNullOrWhiteSpace(sutName)
|| string.IsNullOrWhiteSpace(userNameInTC)
|| string.IsNullOrWhiteSpace(userPwdInTC)
|| string.IsNullOrWhiteSpace(isWindowsImplementation))
{
sutNames.Add("SUT01");
userNamesInTC.Add("administrator");
userPwdsInTC.Add("Password01!");
isWindowsImplementationList.Add("true");
isWindowsImplementationList.Add("false");
}
else
{
sutNames.Add(sutName);
userNamesInTC.Add(userNameInTC);
userPwdsInTC.Add(userPwdInTC);
isWindowsImplementationList.Add(isWindowsImplementation);
if (isWindowsImplementation.ToUpper().Equals("TRUE"))
{
isWindowsImplementationList.Add("false");
}
else
{
isWindowsImplementationList.Add("true");
}
}
propertiesDic.Add(tcComputerNameTitle, sutNames);
propertiesDic.Add(isWindowsImplementationTitle, isWindowsImplementationList);
propertiesDic.Add(triggerMethodTitle, new List<string>() { "Powershell", "Managed", "Interactive"});
propertiesDic.Add(userNameInTCTitle, userNamesInTC);
propertiesDic.Add(userPwdInTCTitle, userPwdsInTC);
propertiesDic.Add(agentPortTitle, new List<string>() {"4488"});
prerequisites.Properties = propertiesDic;
return prerequisites;
}
/// <summary>
/// Sets the values for the required properties.
/// </summary>
/// <param name="properties">Property name and values.</param>
/// <returns>
/// Return true if no other property needed. Return false means there are
/// other property required. PTF Tool will invoke GetPrerequisites and
/// pop up a dialog to set the value of the properties.
/// </returns>
public bool SetPrerequisiteProperties(Dictionary<string, string> properties)
{
// Save the prerequisites set by user
detectionInfo.SUTName = properties[tcComputerNameTitle];
detectionInfo.UserNameInTC = properties[userNameInTCTitle];
detectionInfo.UserPwdInTC = properties[userPwdInTCTitle];
detectionInfo.IsWindowsImplementation = properties[isWindowsImplementationTitle];
detectionInfo.TriggerMethod = TriggerMethod.Powershell;
if (properties[triggerMethodTitle] != null && properties[triggerMethodTitle].Equals("Interactive"))
{
detectionInfo.TriggerMethod = TriggerMethod.Manual;
}
else if (properties[triggerMethodTitle] != null && properties[triggerMethodTitle].Equals("Managed"))
{
detectionInfo.TriggerMethod = TriggerMethod.Managed;
}
detectionInfo.AgentListenPort = 4488;
if (properties[agentPortTitle] != null)
{
try
{
detectionInfo.AgentListenPort = Int32.Parse(properties[agentPortTitle]);
}
catch (Exception) { };
}
return true;
}
/// <summary>
/// Adds Detection steps to the log shown when detecting
/// </summary>
public List<DetectingItem> GetDetectionSteps()
{
List<DetectingItem> DetectingItems = new List<DetectingItem>();
DetectingItems.Add(new DetectingItem("Ping Target SUT", DetectingStatus.Pending, LogStyle.Default));
DetectingItems.Add(new DetectingItem("Establish RDP Connection with SUT", DetectingStatus.Pending, LogStyle.Default));
DetectingItems.Add(new DetectingItem("Check Specified features Support", DetectingStatus.Pending, LogStyle.Default));
DetectingItems.Add(new DetectingItem("Check Specified Protocols Support", DetectingStatus.Pending, LogStyle.Default));
return DetectingItems;
}
/// <summary>
/// Runs property autodetection.
/// </summary>
/// <returns>Return true if the function is succeeded.</returns>
public bool RunDetection()
{
if (!PingSUT())
{
return false;
}
RDPDetector detector = new RDPDetector(detectionInfo);
if (!detector.DetectRDPFeature())
{
detector.Dispose();
return false;
}
detector.Dispose();
return true;
}
/// <summary>
/// Gets the detect result.
/// </summary>
/// <param name="name">Property name</param>
/// <param name="value">Property value</param>
/// <returns>Return true if the property value is successfully got.</returns>
public bool GetDetectedProperty(out Dictionary<string, List<string>> propertiesDic)
{
propertiesDic = new Dictionary<string, List<string>>();
propertiesDic.Add("SUTName", new List<string>() { detectionInfo.SUTName });
propertiesDic.Add("SUTUserName", new List<string>() { detectionInfo.UserNameInTC });
propertiesDic.Add("SUTUserPassword", new List<string>() { detectionInfo.UserPwdInTC });
propertiesDic.Add("IsWindowsImplementation", new List<string>() { detectionInfo.IsWindowsImplementation });
propertiesDic.Add("RDP.Client.SupportAutoReconnect", new List<string>() { NullableBoolToString(detectionInfo.IsSupportAutoReconnect) });
propertiesDic.Add("RDP.Client.SupportServerRedirection", new List<string>() { NullableBoolToString(detectionInfo.IsSupportServerRedirection) });
propertiesDic.Add("RDP.Client.SupportRDPEFS", new List<string>() { NullableBoolToString(detectionInfo.IsSupportRDPEFS) });
propertiesDic.Add("SUTControl.AgentAddress", new List<string>() { detectionInfo.SUTName+":"+detectionInfo.AgentListenPort });
propertiesDic.Add("SUTControl.ClientSupportRDPFile", new List<string>() { detectionInfo.IsWindowsImplementation });
return true;
}
/// <summary>
/// Gets selected rules
/// </summary>
/// <returns>Selected rules</returns>
public List<CaseSelectRule> GetSelectedRules()
{
List<CaseSelectRule> caseList = new List<CaseSelectRule>();
caseList.Add(CreateRule("Priority.BVT", true));
caseList.Add(CreateRule("Priority.NonBVT", true));
#region Protocols
caseList.Add(CreateRule("Protocol.RDPBCGR", true));
caseList.Add(CreateRule("Protocol.RDPRFX", detectionInfo.IsSupportRDPRFX));
caseList.Add(CreateRule("Protocol.RDPEDISP", detectionInfo.IsSupportRDPEDISP));
caseList.Add(CreateRule("Protocol.RDPEGFX", detectionInfo.IsSupportRDPEGFX));
caseList.Add(CreateRule("Protocol.RDPEI", detectionInfo.IsSupportRDPEI));
bool isSupportMultitransport = false;
if (detectionInfo.IsSupportStaticVirtualChannel != null && detectionInfo.IsSupportStaticVirtualChannel.Value
&& ((detectionInfo.IsSupportTransportTypeUdpFECR != null && detectionInfo.IsSupportTransportTypeUdpFECR.Value)
|| (detectionInfo.IsSupportTransportTypeUdpFECL != null&& detectionInfo.IsSupportTransportTypeUdpFECL.Value)))
{
isSupportMultitransport = true;
}
caseList.Add(CreateRule("Protocol.RDPEMT", isSupportMultitransport));
caseList.Add(CreateRule("Protocol.RDPEUDP", isSupportMultitransport));
caseList.Add(CreateRule("Protocol.RDPEUSB", detectionInfo.IsSupportRDPEUSB));
caseList.Add(CreateRule("Protocol.RDPEVOR", detectionInfo.IsSupportRDPEVOR));
#endregion Protocols
caseList.Add(CreateRule("Specific Requirements.DeviceNeeded", false));
caseList.Add(CreateRule("Specific Requirements.Interactive", false));
caseList.Add(CreateRule("Enable Supported Feature.AutoReconnect", detectionInfo.IsSupportAutoReconnect));
caseList.Add(CreateRule("Enable Supported Feature.FastPathInput", true));
caseList.Add(CreateRule("Enable Supported Feature.HeartBeat", detectionInfo.IsSupportHeartbeatPdu));
caseList.Add(CreateRule("Enable Supported Feature.NetcharAutoDetect", detectionInfo.IsSupportNetcharAutoDetect));
caseList.Add(CreateRule("Enable Supported Feature.ServerRedirection", detectionInfo.IsSupportServerRedirection));
bool bothSupportSVCAndEFS = false;
if (detectionInfo.IsSupportRDPEFS != null && detectionInfo.IsSupportRDPEFS.Value
&& detectionInfo.IsSupportStaticVirtualChannel != null && detectionInfo.IsSupportStaticVirtualChannel.Value)
{
bothSupportSVCAndEFS = true;
}
caseList.Add(CreateRule("Enable Supported Feature.StaticVirtualChannel", bothSupportSVCAndEFS));
return caseList;
}
/// <summary>
/// Gets a summary of the detect result.
/// </summary>
/// <returns>Detect result.</returns>
public object GetSUTSummary()
{
DetectionResultControl SUTSummaryControl = new DetectionResultControl();
SUTSummaryControl.LoadDetectionInfo(detectionInfo);
return SUTSummaryControl;
}
/// <summary>
/// Gets the list of properties that will be hidder in the configure page.
/// </summary>
/// <param name="rules">Selected rules.</param>
/// <returns>The list of properties whick will not be shown in the configure page.</returns>
public List<string> GetHiddenProperties(List<CaseSelectRule> rules)
{
List<string> hiddenProp = new List<string>();
// Task name for SUT control adapter
hiddenProp.Add("RDPConnectWithNegotiationApproach_Task");
hiddenProp.Add("RDPConnectWithDirectTLS_Task");
hiddenProp.Add("RDPConnectWithDirectCredSSP_Task");
hiddenProp.Add("RDPConnectWithNegotiationApproachFullScreen_Task");
hiddenProp.Add("RDPConnectWithDirectTLSFullScreen_Task");
hiddenProp.Add("RDPConnectWithDirectCredSSPFullScreen_Task");
hiddenProp.Add("TriggerClientAutoReconnect_Task");
hiddenProp.Add("TriggerInputEvents_Task");
hiddenProp.Add("TriggerClientDisconnectAll_Task");
hiddenProp.Add("TriggerOneTouchEvent_Task");
hiddenProp.Add("TriggerMultiTouchEvent_Task");
hiddenProp.Add("TriggerSingleTouchPositionEvent_Task");
hiddenProp.Add("TriggerContinuousTouchEvent_Task");
hiddenProp.Add("TriggerTouchHoverEvent_Task");
hiddenProp.Add("MaximizeRDPClientWindow_Task");
// Image configure for RDPEDISP
hiddenProp.Add("RdpedispEndImage");
hiddenProp.Add("RdpedispOrientationChange1Image");
hiddenProp.Add("RdpedispOrientationChange2Image");
hiddenProp.Add("RdpedispOrientationChange3Image");
hiddenProp.Add("RdpedispOrientationChange4Image");
hiddenProp.Add("RdpedispMonitorAddImage");
hiddenProp.Add("RdpedispMonitorRemoveImage");
// Other properties should be hidden
hiddenProp.Add("IsTDI67289Fixed");
return hiddenProp;
}
/// <summary>
/// Returns false if check failed and set failed property in dictionary
/// </summary>
/// <param name="properties"></param>
/// <returns></returns>
public bool CheckConfigrationSettings(Dictionary<string, string> properties)
{
return true;
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
}
#endregion Implemented IValueDetector
#region Private Methods
private bool PingSUT()
{
DetectorUtil.WriteLog("Ping Target SUT...");
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
// Use the default TtL value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "0123456789ABCDEF0123456789ABCDEF";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 5000;
bool result = false;
List<PingReply> replys = new List<PingReply>();
try
{
for (int i = 0; i < 4; i++)
{
replys.Add(pingSender.Send(detectionInfo.SUTName, timeout, buffer, options));
}
}
catch
{
DetectorUtil.WriteLog("Error", false, LogStyle.Error);
//return false;
throw;
}
foreach (var reply in replys)
{
result |= (reply.Status == IPStatus.Success);
}
if (result)
{
DetectorUtil.WriteLog("Passed", false, LogStyle.StepPassed);
return true;
}
else
{
DetectorUtil.WriteLog("Failed", false, LogStyle.StepFailed);
DetectorUtil.WriteLog("Taget SUT don't respond.");
return false;
}
}
private CaseSelectRule CreateRule(string ruleCategoryName, bool? isSupported)
{
CaseSelectRule rule = null;
if (isSupported == null)
{
rule = new CaseSelectRule() { Name = ruleCategoryName, Status = RuleStatus.Unknown };
}
else
{
if (isSupported.Value)
{
rule = new CaseSelectRule() { Name = ruleCategoryName, Status = RuleStatus.Selected };
}
else
{
rule = new CaseSelectRule() { Name = ruleCategoryName, Status = RuleStatus.NotSupported };
}
}
return rule;
}
private string NullableBoolToString(bool? value)
{
if (value == null)
{
return "false";
}
return value.Value.ToString().ToLower();
}
#endregion Private Methods
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
// NOTE: define this if you want to test the output on US machine and ASCII
// characters
//#define TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
using System.Collections.Specialized;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
// interfaces for host interaction
namespace Microsoft.PowerShell.Commands.Internal.Format
{
#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
/// <summary>
/// test class to provide easily overridable behavior for testing on US machines
/// using US data.
/// NOTE: the class just forces any uppercase letter [A-Z] to be prepended
/// with an underscore (e.g. "A" becomes "_A", but "a" stays the same)
/// </summary>
internal class DisplayCellsTest : DisplayCells
{
internal override int Length(string str, int offset)
{
int len = 0;
for (int k = offset; k < str.Length; k++)
{
len += this.Length(str[k]);
}
return len;
}
internal override int Length(char character)
{
if (character >= 'A' && character <= 'Z')
return 2;
return 1;
}
internal override int GetHeadSplitLength(string str, int offset, int displayCells)
{
return GetSplitLengthInternalHelper(str, offset, displayCells, true);
}
internal override int GetTailSplitLength(string str, int offset, int displayCells)
{
return GetSplitLengthInternalHelper(str, offset, displayCells, false);
}
internal string GenerateTestString(string str)
{
StringBuilder sb = new StringBuilder();
for (int k = 0; k < str.Length; k++)
{
char ch = str[k];
if (this.Length(ch) == 2)
{
sb.Append('_');
}
sb.Append(ch);
}
return sb.ToString();
}
}
#endif
/// <summary>
/// Tear off class
/// </summary>
internal class DisplayCellsPSHost : DisplayCells
{
internal DisplayCellsPSHost(PSHostRawUserInterface rawUserInterface)
{
_rawUserInterface = rawUserInterface;
}
internal override int Length(string str, int offset)
{
Dbg.Assert(offset >= 0, "offset >= 0");
Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length");
try
{
return _rawUserInterface.LengthInBufferCells(str, offset);
}
catch (HostException)
{
//thrown when external host rawui is not implemented, in which case
//we will fallback to the default value.
}
return string.IsNullOrEmpty(str) ? 0 : str.Length - offset;
}
internal override int Length(string str)
{
try
{
return _rawUserInterface.LengthInBufferCells(str);
}
catch (HostException)
{
//thrown when external host rawui is not implemented, in which case
//we will fallback to the default value.
}
return string.IsNullOrEmpty(str) ? 0 : str.Length;
}
internal override int Length(char character)
{
try
{
return _rawUserInterface.LengthInBufferCells(character);
}
catch (HostException)
{
//thrown when external host rawui is not implemented, in which case
//we will fallback to the default value.
}
return 1;
}
internal override int GetHeadSplitLength(string str, int offset, int displayCells)
{
return GetSplitLengthInternalHelper(str, offset, displayCells, true);
}
internal override int GetTailSplitLength(string str, int offset, int displayCells)
{
return GetSplitLengthInternalHelper(str, offset, displayCells, false);
}
private PSHostRawUserInterface _rawUserInterface;
}
/// <summary>
/// Implementation of the LineOutput interface on top of Console and RawConsole
/// </summary>
internal sealed class ConsoleLineOutput : LineOutput
{
#region tracer
[TraceSource("ConsoleLineOutput", "ConsoleLineOutput")]
internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput");
#endregion tracer
#region LineOutput implementation
/// <summary>
/// the # of columns is just the width of the screen buffer (not the
/// width of the window)
/// </summary>
/// <value></value>
internal override int ColumnNumber
{
get
{
CheckStopProcessing();
PSHostRawUserInterface raw = _console.RawUI;
// IMPORTANT NOTE: we subtract one because
// we want to make sure the console's last column
// is never considered written. This causes the writing
// logic to always call WriteLine(), making sure a CR
// is inserted.
try
{
return _forceNewLine ? raw.BufferSize.Width - 1 : raw.BufferSize.Width;
}
catch (HostException)
{
//thrown when external host rawui is not implemented, in which case
//we will fallback to the default value.
}
return _forceNewLine ? _fallbackRawConsoleColumnNumber - 1 : _fallbackRawConsoleColumnNumber;
}
}
/// <summary>
/// the # of rows is the # of rows visible in the window (and not the # of
/// rows in the screen buffer)
/// </summary>
/// <value></value>
internal override int RowNumber
{
get
{
CheckStopProcessing();
PSHostRawUserInterface raw = _console.RawUI;
try
{
return raw.WindowSize.Height;
}
catch (HostException)
{
//thrown when external host rawui is not implemented, in which case
//we will fallback to the default value.
}
return _fallbackRawConsoleRowNumber;
}
}
/// <summary>
/// write a line to the output device
/// </summary>
/// <param name="s">line to write</param>
internal override void WriteLine(string s)
{
CheckStopProcessing();
// delegate the action to the helper,
// that will properly break the string into
// screen lines
_writeLineHelper.WriteLine(s, this.ColumnNumber);
}
internal override DisplayCells DisplayCells
{
get
{
CheckStopProcessing();
if (_displayCellsPSHost != null)
{
return _displayCellsPSHost;
}
// fall back if we do not have a Msh host specific instance
return _displayCellsPSHost;
}
}
#endregion
/// <summary>
/// constructor for the ConsoleLineOutput
/// </summary>
/// <param name="hostConsole">PSHostUserInterface to wrap</param>
/// <param name="paging">true if we require prompting for page breaks</param>
/// <param name="errorContext">error context to throw exceptions</param>
internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext)
{
if (hostConsole == null)
throw PSTraceSource.NewArgumentNullException("hostConsole");
if (errorContext == null)
throw PSTraceSource.NewArgumentNullException("errorContext");
_console = hostConsole;
_errorContext = errorContext;
if (paging)
{
tracer.WriteLine("paging is needed");
// if we need to do paging, instantiate a prompt handler
// that will take care of the screen interaction
string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt);
_prompt = new PromptHandler(promptString, this);
}
PSHostRawUserInterface raw = _console.RawUI;
if (raw != null)
{
tracer.WriteLine("there is a valid raw interface");
#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
// create a test instance with fake behavior
this._displayCellsPSHost = new DisplayCellsTest();
#else
// set only if we have a valid raw interface
_displayCellsPSHost = new DisplayCellsPSHost(raw);
#endif
}
// instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called
WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine);
WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite);
if (_forceNewLine)
{
_writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, null, this.DisplayCells);
}
else
{
_writeLineHelper = new WriteLineHelper(/*lineWrap*/false, wl, w, this.DisplayCells);
}
}
/// <summary>
/// callback to be called when ILineOutput.WriteLine() is called by WriteLineHelper
/// </summary>
/// <param name="s">string to write</param>
private void OnWriteLine(string s)
{
#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s);
#endif
// Do any default transcription.
_console.TranscribeResult(s);
switch (this.WriteStream)
{
case WriteStreamType.Error:
_console.WriteErrorLine(s);
break;
case WriteStreamType.Warning:
_console.WriteWarningLine(s);
break;
case WriteStreamType.Verbose:
_console.WriteVerboseLine(s);
break;
case WriteStreamType.Debug:
_console.WriteDebugLine(s);
break;
default:
// If the host is in "transcribe only"
// mode (due to an implicitly added call to Out-Default -Transcribe),
// then don't call the actual host API.
if (!_console.TranscribeOnly)
{
_console.WriteLine(s);
}
break;
}
LineWrittenEvent();
}
/// <summary>
/// callback to be called when ILineOutput.Write() is called by WriteLineHelper
/// This is called when the WriteLineHelper needs to write a line whose length
/// is the same as the width of the screen buffer
/// </summary>
/// <param name="s">string to write</param>
private void OnWrite(string s)
{
#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE
s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s);
#endif
switch (this.WriteStream)
{
case WriteStreamType.Error:
_console.WriteErrorLine(s);
break;
case WriteStreamType.Warning:
_console.WriteWarningLine(s);
break;
case WriteStreamType.Verbose:
_console.WriteVerboseLine(s);
break;
case WriteStreamType.Debug:
_console.WriteDebugLine(s);
break;
default:
_console.Write(s);
break;
}
LineWrittenEvent();
}
/// <summary>
/// called when a line was written to console
/// </summary>
private void LineWrittenEvent()
{
// check to avoid reentrancy from the prompt handler
// writing during the PromptUser() call
if (_disableLineWrittenEvent)
return;
// if there is no prompting, we are done
if (_prompt == null)
return;
// increment the count of lines written to the screen
_linesWritten++;
// check if we need to put out a prompt
if (this.NeedToPrompt)
{
// put out the prompt
_disableLineWrittenEvent = true;
PromptHandler.PromptResponse response = _prompt.PromptUser(_console);
_disableLineWrittenEvent = false;
switch (response)
{
case PromptHandler.PromptResponse.NextPage:
{
// reset the counter, since we are starting a new page
_linesWritten = 0;
}
break;
case PromptHandler.PromptResponse.NextLine:
{
// roll back the counter by one, since we allow one more line
_linesWritten--;
}
break;
case PromptHandler.PromptResponse.Quit:
// 1021203-2005/05/09-JonN
// HaltCommandException will cause the command
// to stop, but not be reported as an error.
throw new HaltCommandException();
}
}
}
/// <summary>
/// check if we need to put out a prompt
/// </summary>
/// <value>true if we need to prompt</value>
private bool NeedToPrompt
{
get
{
// NOTE: we recompute all the time to take into account screen resizing
int rawRowNumber = this.RowNumber;
if (rawRowNumber <= 0)
{
// something is wrong, there is no real estate, we suppress prompting
return false;
}
// the prompt will occupy some lines, so we need to subtract them form the total
// screen line count
int computedPromptLines = _prompt.ComputePromptLines(this.DisplayCells, this.ColumnNumber);
int availableLines = this.RowNumber - computedPromptLines;
if (availableLines <= 0)
{
tracer.WriteLine("No available Lines; suppress prompting");
// something is wrong, there is no real estate, we suppress prompting
return false;
}
return _linesWritten >= availableLines;
}
}
#region Private Members
/// <summary>
/// object to manage prompting
/// </summary>
private class PromptHandler
{
/// <summary>
/// prompt handler with the given prompt
/// </summary>
/// <param name="s">prompt string to be used</param>
/// <param name="cmdlet">the Cmdlet using this prompt handler</param>
internal PromptHandler(string s, ConsoleLineOutput cmdlet)
{
if (string.IsNullOrEmpty(s))
throw PSTraceSource.NewArgumentNullException("s");
_promptString = s;
_callingCmdlet = cmdlet;
}
/// <summary>
/// determine how many rows the prompt should take.
/// </summary>
/// <param name="cols">current number of columns on the screen</param>
/// <param name="displayCells">string manipulation helper</param>
/// <returns></returns>
internal int ComputePromptLines(DisplayCells displayCells, int cols)
{
// split the prompt string into lines
_actualPrompt = StringManipulationHelper.GenerateLines(displayCells, _promptString, cols, cols);
return _actualPrompt.Count;
}
/// <summary>
/// options returned by the PromptUser() call
/// </summary>
internal enum PromptResponse
{
NextPage,
NextLine,
Quit
}
/// <summary>
/// do the actual prompting
/// </summary>
/// <param name="console">PSHostUserInterface instance to prompt to</param>
internal PromptResponse PromptUser(PSHostUserInterface console)
{
// NOTE: assume the values passed to ComputePromptLines are still valid
// write out the prompt line(s). The last one will not have a new line
// at the end because we leave the prompt at the end of the line
for (int k = 0; k < _actualPrompt.Count; k++)
{
if (k < (_actualPrompt.Count - 1))
console.WriteLine(_actualPrompt[k]); // intermediate line(s)
else
console.Write(_actualPrompt[k]); // last line
}
while (true)
{
_callingCmdlet.CheckStopProcessing();
KeyInfo ki = console.RawUI.ReadKey(ReadKeyOptions.IncludeKeyUp | ReadKeyOptions.NoEcho);
char key = ki.Character;
if (key == 'q' || key == 'Q')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.Quit;
}
else if (key == ' ')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.NextPage;
}
else if (key == '\r')
{
// need to move to the next line since we accepted input, add a newline
console.WriteLine();
return PromptResponse.NextLine;
}
}
}
/// <summary>
/// cached string(s) valid during a sequence of ComputePromptLines()/PromptUser()
/// </summary>
private StringCollection _actualPrompt;
/// <summary>
/// prompt string as passed at initialization
/// </summary>
private string _promptString;
/// <summary>
/// The cmdlet that uses this prompt helper
/// </summary>
private ConsoleLineOutput _callingCmdlet = null;
}
/// <summary>
/// flag to force new lines in CMD.EXE by limiting the
/// usable width to N-1 (e.g. 80-1) and forcing a call
/// to WriteLine()
/// </summary>
private bool _forceNewLine = true;
/// <summary>
/// use this if IRawConsole is null;
/// </summary>
private int _fallbackRawConsoleColumnNumber = 80;
/// <summary>
/// use this if IRawConsole is null;
/// </summary>
private int _fallbackRawConsoleRowNumber = 40;
private WriteLineHelper _writeLineHelper;
/// <summary>
/// handler to prompt the user for page breaks
/// if this handler is not null, we have prompting
/// </summary>
private PromptHandler _prompt = null;
/// <summary>
/// conter for the # of lines written when prompting is on
/// </summary>
private long _linesWritten = 0;
/// <summary>
/// flag to avoid reentrancy on prompting
/// </summary>
private bool _disableLineWrittenEvent = false;
/// <summary>
/// refecence to the PSHostUserInterface interface we use
/// </summary>
private PSHostUserInterface _console = null;
/// <summary>
/// Msh host specific string manipulation helper
/// </summary>
private DisplayCells _displayCellsPSHost;
/// <summary>
/// reference to error context to throw Msh exceptions
/// </summary>
private TerminatingErrorContext _errorContext = null;
#endregion
}
}
| |
#region Header
//
// CmdWallLayerVolumes.cs - determine
// compound wall layer volumes
//
// Copyright (C) 2009-2021 by Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System.Collections.Generic;
using System.Diagnostics;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction(TransactionMode.ReadOnly)]
internal class CmdWallLayerVolumes : IExternalCommand
{
private const BuiltInParameter _bipArea
= BuiltInParameter.HOST_AREA_COMPUTED;
private const BuiltInParameter _bipVolume
= BuiltInParameter.HOST_VOLUME_COMPUTED;
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var app = commandData.Application;
var uidoc = app.ActiveUIDocument;
var doc = uidoc.Document;
// retrieve selected walls, or all walls,
// if nothing is selected:
var walls = new List<Element>();
if (!Util.GetSelectedElementsOrAll(
walls, uidoc, typeof(Wall)))
{
var sel = uidoc.Selection;
message = 0 < sel.GetElementIds().Count
? "Please select some wall elements."
: "No wall elements found.";
return Result.Failed;
}
// mapping of compound wall layers to total cumulated volume;
// the key is "<wall type name> : <wall layer function>",
// the value is its cumulated volume across all selected walls:
var totalVolumes
= new MapLayerToVolume();
foreach (Wall wall in walls) GetWallLayerVolumes(wall, ref totalVolumes);
var msg
= "Compound wall layer volumes formatted as '"
+ "wall type : layer function :"
+ " volume in cubic meters':\n";
var keys = new List<string>(
totalVolumes.Keys);
keys.Sort();
foreach (var key in keys)
msg += $"\n{key} : {Util.RealString(Util.CubicFootToCubicMeter(totalVolumes[key]))}";
Util.InfoMsg(msg);
return Result.Cancelled;
}
/// <summary>
/// Return the specified double parameter
/// value for the given wall.
/// </summary>
private double GetWallParameter(
Wall wall,
BuiltInParameter bip)
{
var p = wall.get_Parameter(bip);
Debug.Assert(null != p,
"expected wall to have "
+ "HOST_AREA_COMPUTED and "
+ "HOST_VOLUME_COMPUTED parameters");
return p.AsDouble();
}
/// <summary>
/// Cumulate the compound wall layer volumes for the given wall.
/// </summary>
private void GetWallLayerVolumes(
Wall wall,
ref MapLayerToVolume totalVolumes)
{
var wt = wall.WallType;
//CompoundStructure structure= wt.CompoundStructure; // 2011
var structure = wt.GetCompoundStructure(); // 2012
//CompoundStructureLayerArray layers = structure.Layers; // 2011
var layers = structure.GetLayers(); // 2012
//int i, n = layers.Size; // 2011
int i, n = layers.Count; // 2012
var area = GetWallParameter(wall, _bipArea);
var volume = GetWallParameter(wall, _bipVolume);
var thickness = wt.Width;
var desc = Util.ElementDescription(wall);
Debug.Print(
"{0} with thickness {1}"
+ " and volume {2}"
+ " has {3} layer{4}{5}",
desc,
Util.MmString(thickness),
Util.RealString(volume),
n, Util.PluralSuffix(n),
Util.DotOrColon(n));
// volume for entire wall:
var key = wall.WallType.Name;
totalVolumes.Cumulate(key, volume);
// volume for compound wall layers:
if (0 < n)
{
i = 0;
var total = 0.0;
double layerVolume;
foreach (var
layer in layers)
{
key = $"{wall.WallType.Name} : {layer.Function}";
//layerVolume = area * layer.Thickness; // 2011
layerVolume = area * layer.Width; // 2012
totalVolumes.Cumulate(key, layerVolume);
total += layerVolume;
Debug.Print(
" Layer {0}: function {1}, "
+ "thickness {2}, volume {3}",
++i, layer.Function,
Util.MmString(layer.Width),
Util.RealString(layerVolume));
}
Debug.Print("Wall volume = {0},"
+ " total layer volume = {1}",
Util.RealString(volume),
Util.RealString(total));
if (!Util.IsEqual(volume, total))
Debug.Print("Wall host volume parameter"
+ " value differs from sum of all layer"
+ " volumes: {0}",
volume - total);
}
}
/// <summary>
/// Enhance the standard Dictionary
/// class to have a Cumulate method.
/// </summary>
private class MapLayerToVolume
: Dictionary<string, double>
{
/// <summary>
/// Add cumulated value.
/// If seen for the first time for
/// this key, initialise with zero.
/// </summary>
public void Cumulate(
string key,
double value)
{
if (!ContainsKey(key)) this[key] = 0.0;
this[key] += value;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Connectors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RemoteGridServicesConnector")]
public class RemoteGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IGridService m_LocalGridService;
private IGridService m_RemoteGridService;
private RegionInfoCache m_RegionInfoCache = new RegionInfoCache();
public RemoteGridServicesConnector()
{
}
public RemoteGridServicesConnector(IConfigSource source)
{
InitialiseServices(source);
}
#region ISharedRegionmodule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "RemoteGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseServices(source);
m_Enabled = true;
m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled");
}
}
}
private void InitialiseServices(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string networkConnector = gridConfig.GetString("NetworkConnector", string.Empty);
if (networkConnector == string.Empty)
{
m_log.Error("[REMOTE GRID CONNECTOR]: Please specify a network connector under [GridService]");
return;
}
Object[] args = new Object[] { source };
m_RemoteGridService = ServerUtils.LoadPlugin<IGridService>(networkConnector, args);
m_LocalGridService = new LocalGridServicesConnector(source);
}
public void PostInitialise()
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).PostInitialise();
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
scene.RegisterModuleInterface<IGridService>(this);
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).AddRegion(scene);
}
public void RemoveRegion(Scene scene)
{
if (m_LocalGridService != null)
((ISharedRegionModule)m_LocalGridService).RemoveRegion(scene);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
string msg = m_LocalGridService.RegisterRegion(scopeID, regionInfo);
if (msg == String.Empty)
return m_RemoteGridService.RegisterRegion(scopeID, regionInfo);
return msg;
}
public bool DeregisterRegion(UUID regionID)
{
if (m_LocalGridService.DeregisterRegion(regionID))
return m_RemoteGridService.DeregisterRegion(regionID);
return false;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_RemoteGridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionID,out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByUUID(scopeID, regionID);
m_RegionInfoCache.Cache(scopeID,regionID,rinfo);
return rinfo;
}
// Get a region given its base world coordinates (in meters).
// NOTE: this is NOT 'get a region by some point in the region'. The coordinate MUST
// be the base coordinate of the region.
// The coordinates are world coords (meters), NOT region units.
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID, Util.RegionWorldLocToHandle((uint)x, (uint)y), out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByPosition(scopeID, x, y);
m_RegionInfoCache.Cache(rinfo);
return rinfo;
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
bool inCache = false;
GridRegion rinfo = m_RegionInfoCache.Get(scopeID,regionName, out inCache);
if (inCache)
return rinfo;
rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName);
if (rinfo == null)
rinfo = m_RemoteGridService.GetRegionByName(scopeID, regionName);
// can't cache negative results for name lookups
m_RegionInfoCache.Cache(rinfo);
return rinfo;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> rinfo = m_LocalGridService.GetRegionsByName(scopeID, name, maxNumber);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionsByName {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetRegionsByName(scopeID, name, maxNumber);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionsByName {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> rinfo = m_LocalGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetRegionRange {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetRegionRange {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetDefaultRegions(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetDefaultRegions(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetDefaultHypergridRegions(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetDefaultHypergridRegions(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetDefaultHypergridRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetDefaultHypergridRegions(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetDefaultHypergridRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<GridRegion> rinfo = m_LocalGridService.GetFallbackRegions(scopeID, x, y);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetFallbackRegions {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetFallbackRegions(scopeID, x, y);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetFallbackRegions {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
List<GridRegion> rinfo = m_LocalGridService.GetHyperlinks(scopeID);
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Local GetHyperlinks {0} found {1} regions", name, rinfo.Count);
List<GridRegion> grinfo = m_RemoteGridService.GetHyperlinks(scopeID);
if (grinfo != null)
{
//m_log.DebugFormat("[REMOTE GRID CONNECTOR]: Remote GetHyperlinks {0} found {1} regions", name, grinfo.Count);
foreach (GridRegion r in grinfo)
{
m_RegionInfoCache.Cache(r);
if (rinfo.Find(delegate(GridRegion gr) { return gr.RegionID == r.RegionID; }) == null)
rinfo.Add(r);
}
}
return rinfo;
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
int flags = m_LocalGridService.GetRegionFlags(scopeID, regionID);
if (flags == -1)
flags = m_RemoteGridService.GetRegionFlags(scopeID, regionID);
return flags;
}
#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.
/******************************************************************************
* 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 AndNotDouble()
{
var test = new SimpleBinaryOpTest__AndNotDouble();
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 SimpleBinaryOpTest__AndNotDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__AndNotDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.AndNot(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotDouble();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if ((~BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((~BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ArtifactSourcesOperations.
/// </summary>
public static partial class ArtifactSourcesOperationsExtensions
{
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<ArtifactSource> List(this IArtifactSourcesOperations operations, string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>))
{
return Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).ListAsync(labName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ArtifactSource>> ListAsync(this IArtifactSourcesOperations operations, string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(labName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=displayName)'
/// </param>
public static ArtifactSource Get(this IArtifactSourcesOperations operations, string labName, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).GetAsync(labName, name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example: 'properties($select=displayName)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ArtifactSource> GetAsync(this IArtifactSourcesOperations operations, string labName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(labName, name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// Properties of an artifact source.
/// </param>
public static ArtifactSource CreateOrUpdate(this IArtifactSourcesOperations operations, string labName, string name, ArtifactSource artifactSource)
{
return Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).CreateOrUpdateAsync(labName, name, artifactSource), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// Properties of an artifact source.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ArtifactSource> CreateOrUpdateAsync(this IArtifactSourcesOperations operations, string labName, string name, ArtifactSource artifactSource, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(labName, name, artifactSource, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
public static void Delete(this IArtifactSourcesOperations operations, string labName, string name)
{
Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).DeleteAsync(labName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete artifact source.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IArtifactSourcesOperations operations, string labName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(labName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Modify properties of artifact sources.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// Properties of an artifact source.
/// </param>
public static ArtifactSource Update(this IArtifactSourcesOperations operations, string labName, string name, ArtifactSourceFragment artifactSource)
{
return Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).UpdateAsync(labName, name, artifactSource), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Modify properties of artifact sources.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// Properties of an artifact source.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ArtifactSource> UpdateAsync(this IArtifactSourcesOperations operations, string labName, string name, ArtifactSourceFragment artifactSource, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(labName, name, artifactSource, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ArtifactSource> ListNext(this IArtifactSourcesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IArtifactSourcesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ArtifactSource>> ListNextAsync(this IArtifactSourcesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using System;
using System.Collections.Generic;
using Windows.UI.Popups;
using Microsoft.UI.Xaml;
namespace ArcGISRuntime.WinUI.Samples.ChangeStretchRenderer
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Stretch renderer",
category: "Layers",
description: "Use a stretch renderer to enhance the visual contrast of raster data for analysis.",
instructions: "Choose one of the stretch parameter types:",
tags: new[] { "analysis", "deviation", "histogram", "imagery", "interpretation", "min-max", "percent clip", "pixel", "raster", "stretch", "symbology", "visualization" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("95392f99970d4a71bd25951beb34a508")]
public partial class ChangeStretchRenderer
{
public ChangeStretchRenderer()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization
Initialize();
}
private async void Initialize()
{
// Initialize the GUI controls appearance
RendererTypes.Items.Add("Min Max");
RendererTypes.Items.Add("Percent Clip");
RendererTypes.Items.Add("Standard Deviation");
RendererTypes.SelectedIndex = 0;
// Add an imagery basemap
MyMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);
// Get the file name
string filepath = GetRasterPath();
// Load the raster file
Raster myRasterFile = new Raster(filepath);
// Create the layer
RasterLayer myRasterLayer = new RasterLayer(myRasterFile);
// Add the layer to the map
MyMapView.Map.OperationalLayers.Add(myRasterLayer);
try
{
// Wait for the layer to load
await myRasterLayer.LoadAsync();
// Set the viewpoint
await MyMapView.SetViewpointGeometryAsync(myRasterLayer.FullExtent);
}
catch (Exception e)
{
await new MessageDialog2(e.ToString(), "Error").ShowAsync();
}
}
private async void OnUpdateRendererClicked(object sender, RoutedEventArgs e)
{
// Convert the text to doubles and return if they're invalid.
double input1;
double input2;
try
{
input1 = Convert.ToDouble(FirstParameterInput.Text);
input2 = Convert.ToDouble(SecondParameterInput.Text);
}
catch (Exception ex)
{
await new MessageDialog2(ex.Message).ShowAsync();
return;
}
// Get the user choice for the raster stretch render
string myRendererTypeChoice = RendererTypes.SelectedValue.ToString();
// Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render
IEnumerable<double> myGammaValues = new List<double>();
// Create a color ramp for the stretch renderer
ColorRamp myColorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000);
// Create the place holder for the stretch renderer
StretchRenderer myStretchRenderer = null;
switch (myRendererTypeChoice)
{
case "Min Max":
// This section creates a stretch renderer based on a MinMaxStretchParameters
// TODO: Add you own logic to ensure that accurate min/max stretch values are used
// Create an IEnumerable from a list of double min stretch value doubles
IEnumerable<double> myMinValues = new List<double> { input1 };
// Create an IEnumerable from a list of double max stretch value doubles
IEnumerable<double> myMaxValues = new List<double> { input2 };
// Create a new MinMaxStretchParameters based on the user choice for min and max stretch values
MinMaxStretchParameters myMinMaxStretchParameters = new MinMaxStretchParameters(myMinValues, myMaxValues);
// Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp
myStretchRenderer = new StretchRenderer(myMinMaxStretchParameters, myGammaValues, true, myColorRamp);
break;
case "Percent Clip":
// This section creates a stretch renderer based on a PercentClipStretchParameters
// TODO: Add you own logic to ensure that accurate min/max percent clip values are used
// Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values
PercentClipStretchParameters myPercentClipStretchParameters = new PercentClipStretchParameters(input1, input2);
// Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp
myStretchRenderer = new StretchRenderer(myPercentClipStretchParameters, myGammaValues, true, myColorRamp);
break;
case "Standard Deviation":
// This section creates a stretch renderer based on a StandardDeviationStretchParameters
// TODO: Add you own logic to ensure that an accurate standard deviation value is used
// Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value
StandardDeviationStretchParameters myStandardDeviationStretchParameters = new StandardDeviationStretchParameters(input1);
// Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp
myStretchRenderer = new StretchRenderer(myStandardDeviationStretchParameters, myGammaValues, true, myColorRamp);
break;
}
// Get the existing raster layer in the map
RasterLayer myRasterLayer = (RasterLayer)MyMapView.Map.OperationalLayers[0];
// Apply the stretch renderer to the raster layer
myRasterLayer.Renderer = myStretchRenderer;
}
private void RendererTypes_SelectionChanged(object sender, Microsoft.UI.Xaml.Controls.SelectionChangedEventArgs e)
{
// Get the user choice for the raster stretch render
string myRendererTypeChoice = e.AddedItems[0].ToString();
switch (myRendererTypeChoice)
{
case "Min Max":
// This section displays/resets the user choice options for MinMaxStretchParameters
// Make sure all the GUI items are visible
FirstParameterLabel.Visibility = Visibility.Visible;
SecondParameterLabel.Visibility = Visibility.Visible;
FirstParameterInput.Visibility = Visibility.Visible;
SecondParameterInput.Visibility = Visibility.Visible;
// Define what values/options the user sees
FirstParameterLabel.Text = "Minimum value (0 - 255):";
SecondParameterLabel.Text = "Maximum value (0 - 255):";
FirstParameterInput.Text = "10";
SecondParameterInput.Text = "150";
break;
case "Percent Clip":
// This section displays/resets the user choice options for PercentClipStretchParameters
// Make sure all the GUI items are visible
FirstParameterLabel.Visibility = Visibility.Visible;
SecondParameterLabel.Visibility = Visibility.Visible;
FirstParameterInput.Visibility = Visibility.Visible;
SecondParameterInput.Visibility = Visibility.Visible;
// Define what values/options the user sees
FirstParameterLabel.Text = "Minimum (0 - 100):";
SecondParameterLabel.Text = "Maximum (0 - 100)";
FirstParameterInput.Text = "0";
SecondParameterInput.Text = "50";
break;
case "Standard Deviation":
// This section displays/resets the user choice options for StandardDeviationStretchParameters
// Make sure that only the necessary GUI items are visible
FirstParameterLabel.Visibility = Visibility.Visible;
SecondParameterLabel.Visibility = Visibility.Collapsed;
FirstParameterInput.Visibility = Visibility.Visible;
SecondParameterInput.Visibility = Visibility.Collapsed;
// Define what values/options the user sees
FirstParameterLabel.Text = "Factor (.25 to 4):";
FirstParameterInput.Text = "0.5";
break;
}
}
private static string GetRasterPath()
{
return DataManager.GetDataFolder("95392f99970d4a71bd25951beb34a508", "shasta", "ShastaBW.tif");
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmBarcodeScaleItem
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmBarcodeScaleItem() : base()
{
KeyPress += frmBarcodeScaleItem_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.TextBox withEventsField_txtQty;
public System.Windows.Forms.TextBox txtQty {
get { return withEventsField_txtQty; }
set {
if (withEventsField_txtQty != null) {
withEventsField_txtQty.KeyPress -= txtQty_KeyPress;
withEventsField_txtQty.Enter -= txtQty_Enter;
withEventsField_txtQty.Leave -= txtQty_Leave;
}
withEventsField_txtQty = value;
if (withEventsField_txtQty != null) {
withEventsField_txtQty.KeyPress += txtQty_KeyPress;
withEventsField_txtQty.Enter += txtQty_Enter;
withEventsField_txtQty.Leave += txtQty_Leave;
}
}
}
public System.Windows.Forms.TextBox txtPSize;
public System.Windows.Forms.TextBox txtPack;
private System.Windows.Forms.TextBox withEventsField_txtPriceS;
public System.Windows.Forms.TextBox txtPriceS {
get { return withEventsField_txtPriceS; }
set {
if (withEventsField_txtPriceS != null) {
withEventsField_txtPriceS.Enter -= txtPriceS_Enter;
withEventsField_txtPriceS.Leave -= txtPriceS_Leave;
}
withEventsField_txtPriceS = value;
if (withEventsField_txtPriceS != null) {
withEventsField_txtPriceS.Enter += txtPriceS_Enter;
withEventsField_txtPriceS.Leave += txtPriceS_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtQtyT;
public System.Windows.Forms.TextBox txtQtyT {
get { return withEventsField_txtQtyT; }
set {
if (withEventsField_txtQtyT != null) {
withEventsField_txtQtyT.KeyPress -= txtQtyT_KeyPress;
withEventsField_txtQtyT.Enter -= txtQtyT_Enter;
withEventsField_txtQtyT.Leave -= txtQtyT_Leave;
}
withEventsField_txtQtyT = value;
if (withEventsField_txtQtyT != null) {
withEventsField_txtQtyT.KeyPress += txtQtyT_KeyPress;
withEventsField_txtQtyT.Enter += txtQtyT_Enter;
withEventsField_txtQtyT.Leave += txtQtyT_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtPrice;
public System.Windows.Forms.TextBox txtPrice {
get { return withEventsField_txtPrice; }
set {
if (withEventsField_txtPrice != null) {
withEventsField_txtPrice.Enter -= txtPrice_Enter;
withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress;
withEventsField_txtPrice.Leave -= txtPrice_Leave;
}
withEventsField_txtPrice = value;
if (withEventsField_txtPrice != null) {
withEventsField_txtPrice.Enter += txtPrice_Enter;
withEventsField_txtPrice.KeyPress += txtPrice_KeyPress;
withEventsField_txtPrice.Leave += txtPrice_Leave;
}
}
}
public System.Windows.Forms.ComboBox cmbQuantity;
private System.Windows.Forms.Button withEventsField_cmdPack;
public System.Windows.Forms.Button cmdPack {
get { return withEventsField_cmdPack; }
set {
if (withEventsField_cmdPack != null) {
withEventsField_cmdPack.Click -= cmdPack_Click;
}
withEventsField_cmdPack = value;
if (withEventsField_cmdPack != null) {
withEventsField_cmdPack.Click += cmdPack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _LBL_6;
public System.Windows.Forms.Label _LBL_4;
public System.Windows.Forms.Label _LBL_2;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label lblPComp;
public System.Windows.Forms.Label lblSComp;
public System.Windows.Forms.Label lblStockItemS;
public System.Windows.Forms.Label _LBL_5;
public System.Windows.Forms.Label _LBL_0;
public System.Windows.Forms.Label _LBL_3;
public System.Windows.Forms.Label _LBL_1;
public System.Windows.Forms.Label lblStockItem;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
//Public WithEvents LBL As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this.txtQty = new System.Windows.Forms.TextBox();
this.txtPSize = new System.Windows.Forms.TextBox();
this.txtPack = new System.Windows.Forms.TextBox();
this.txtPriceS = new System.Windows.Forms.TextBox();
this.txtQtyT = new System.Windows.Forms.TextBox();
this.txtPrice = new System.Windows.Forms.TextBox();
this.cmbQuantity = new System.Windows.Forms.ComboBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdPack = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._LBL_6 = new System.Windows.Forms.Label();
this._LBL_4 = new System.Windows.Forms.Label();
this._LBL_2 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.lblPComp = new System.Windows.Forms.Label();
this.lblSComp = new System.Windows.Forms.Label();
this.lblStockItemS = new System.Windows.Forms.Label();
this._LBL_5 = new System.Windows.Forms.Label();
this._LBL_0 = new System.Windows.Forms.Label();
this._LBL_3 = new System.Windows.Forms.Label();
this._LBL_1 = new System.Windows.Forms.Label();
this.lblStockItem = new System.Windows.Forms.Label();
this.Shape1 = new _4PosBackOffice.NET.RectangleShapeArray(this.components);
this.picButtons.SuspendLayout();
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.SuspendLayout();
//
//ShapeContainer1
//
this.ShapeContainer1.Location = new System.Drawing.Point(0, 0);
this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0);
this.ShapeContainer1.Name = "ShapeContainer1";
this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] {
this._Shape1_0,
this._Shape1_2
});
this.ShapeContainer1.Size = new System.Drawing.Size(400, 145);
this.ShapeContainer1.TabIndex = 22;
this.ShapeContainer1.TabStop = false;
//
//_Shape1_0
//
this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_0.FillColor = System.Drawing.Color.Black;
this.Shape1.SetIndex(this._Shape1_0, Convert.ToInt16(0));
this._Shape1_0.Location = new System.Drawing.Point(7, 296);
this._Shape1_0.Name = "_Shape1_0";
this._Shape1_0.Size = new System.Drawing.Size(383, 56);
//
//_Shape1_2
//
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255)));
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this.Shape1.SetIndex(this._Shape1_2, Convert.ToInt16(2));
this._Shape1_2.Location = new System.Drawing.Point(7, 48);
this._Shape1_2.Name = "_Shape1_2";
this._Shape1_2.Size = new System.Drawing.Size(383, 88);
//
//txtQty
//
this.txtQty.AcceptsReturn = true;
this.txtQty.BackColor = System.Drawing.SystemColors.Window;
this.txtQty.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQty.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtQty.Location = new System.Drawing.Point(314, 102);
this.txtQty.MaxLength = 0;
this.txtQty.Name = "txtQty";
this.txtQty.ReadOnly = true;
this.txtQty.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtQty.Size = new System.Drawing.Size(67, 19);
this.txtQty.TabIndex = 20;
this.txtQty.Text = "0";
this.txtQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtQty.Visible = false;
//
//txtPSize
//
this.txtPSize.AcceptsReturn = true;
this.txtPSize.BackColor = System.Drawing.SystemColors.Window;
this.txtPSize.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPSize.Enabled = false;
this.txtPSize.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPSize.Location = new System.Drawing.Point(184, 101);
this.txtPSize.MaxLength = 0;
this.txtPSize.Name = "txtPSize";
this.txtPSize.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPSize.Size = new System.Drawing.Size(27, 19);
this.txtPSize.TabIndex = 19;
this.txtPSize.Text = "1";
this.txtPSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtPSize.Visible = false;
//
//txtPack
//
this.txtPack.AcceptsReturn = true;
this.txtPack.BackColor = System.Drawing.SystemColors.Window;
this.txtPack.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPack.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPack.Location = new System.Drawing.Point(352, 272);
this.txtPack.MaxLength = 0;
this.txtPack.Name = "txtPack";
this.txtPack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPack.Size = new System.Drawing.Size(41, 19);
this.txtPack.TabIndex = 16;
this.txtPack.Text = "0";
this.txtPack.Visible = false;
//
//txtPriceS
//
this.txtPriceS.AcceptsReturn = true;
this.txtPriceS.BackColor = System.Drawing.SystemColors.Window;
this.txtPriceS.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPriceS.Enabled = false;
this.txtPriceS.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPriceS.Location = new System.Drawing.Point(291, 346);
this.txtPriceS.MaxLength = 0;
this.txtPriceS.Name = "txtPriceS";
this.txtPriceS.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPriceS.Size = new System.Drawing.Size(91, 19);
this.txtPriceS.TabIndex = 8;
this.txtPriceS.Text = "0.00";
this.txtPriceS.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtPriceS.Visible = false;
//
//txtQtyT
//
this.txtQtyT.AcceptsReturn = true;
this.txtQtyT.BackColor = System.Drawing.SystemColors.Window;
this.txtQtyT.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQtyT.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtQtyT.Location = new System.Drawing.Point(79, 101);
this.txtQtyT.MaxLength = 0;
this.txtQtyT.Name = "txtQtyT";
this.txtQtyT.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtQtyT.Size = new System.Drawing.Size(75, 19);
this.txtQtyT.TabIndex = 0;
this.txtQtyT.Text = "0";
this.txtQtyT.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
//txtPrice
//
this.txtPrice.AcceptsReturn = true;
this.txtPrice.BackColor = System.Drawing.SystemColors.Window;
this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPrice.Enabled = false;
this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtPrice.Location = new System.Drawing.Point(301, 249);
this.txtPrice.MaxLength = 0;
this.txtPrice.Name = "txtPrice";
this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtPrice.Size = new System.Drawing.Size(91, 19);
this.txtPrice.TabIndex = 5;
this.txtPrice.Text = "0.00";
this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtPrice.Visible = false;
//
//cmbQuantity
//
this.cmbQuantity.BackColor = System.Drawing.SystemColors.Window;
this.cmbQuantity.Cursor = System.Windows.Forms.Cursors.Default;
this.cmbQuantity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbQuantity.ForeColor = System.Drawing.SystemColors.WindowText;
this.cmbQuantity.Location = new System.Drawing.Point(192, 248);
this.cmbQuantity.Name = "cmbQuantity";
this.cmbQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmbQuantity.Size = new System.Drawing.Size(79, 21);
this.cmbQuantity.TabIndex = 4;
this.cmbQuantity.Visible = false;
//
//picButtons
//
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Controls.Add(this.cmdPack);
this.picButtons.Controls.Add(this.cmdCancel);
this.picButtons.Controls.Add(this.cmdClose);
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.Name = "picButtons";
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Size = new System.Drawing.Size(400, 39);
this.picButtons.TabIndex = 1;
//
//cmdPack
//
this.cmdPack.BackColor = System.Drawing.SystemColors.Control;
this.cmdPack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPack.Location = new System.Drawing.Point(88, 3);
this.cmdPack.Name = "cmdPack";
this.cmdPack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPack.Size = new System.Drawing.Size(105, 29);
this.cmdPack.TabIndex = 22;
this.cmdPack.TabStop = false;
this.cmdPack.Text = "Break / Build P&ack";
this.cmdPack.UseVisualStyleBackColor = false;
this.cmdPack.Visible = false;
//
//cmdCancel
//
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Location = new System.Drawing.Point(8, 3);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.TabIndex = 15;
this.cmdCancel.TabStop = false;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.UseVisualStyleBackColor = false;
//
//cmdClose
//
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Location = new System.Drawing.Point(312, 3);
this.cmdClose.Name = "cmdClose";
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.TabIndex = 2;
this.cmdClose.TabStop = false;
this.cmdClose.Text = "E&xit";
this.cmdClose.UseVisualStyleBackColor = false;
//
//_LBL_6
//
this._LBL_6.AutoSize = true;
this._LBL_6.BackColor = System.Drawing.Color.Transparent;
this._LBL_6.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_6.Location = new System.Drawing.Point(257, 105);
this._LBL_6.Name = "_LBL_6";
this._LBL_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_6.Size = new System.Drawing.Size(53, 13);
this._LBL_6.TabIndex = 21;
this._LBL_6.Text = "Total Qty:";
this._LBL_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_6.Visible = false;
//
//_LBL_4
//
this._LBL_4.AutoSize = true;
this._LBL_4.BackColor = System.Drawing.Color.Transparent;
this._LBL_4.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_4.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._LBL_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_4.Location = new System.Drawing.Point(162, 102);
this._LBL_4.Name = "_LBL_4";
this._LBL_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_4.Size = new System.Drawing.Size(16, 16);
this._LBL_4.TabIndex = 18;
this._LBL_4.Text = "x";
this._LBL_4.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_4.Visible = false;
//
//_LBL_2
//
this._LBL_2.AutoSize = true;
this._LBL_2.BackColor = System.Drawing.Color.Transparent;
this._LBL_2.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_2.Location = new System.Drawing.Point(24, 104);
this._LBL_2.Name = "_LBL_2";
this._LBL_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_2.Size = new System.Drawing.Size(49, 13);
this._LBL_2.TabIndex = 17;
this._LBL_2.Text = "Item Qty:";
this._LBL_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//Label2
//
this.Label2.BackColor = System.Drawing.Color.Transparent;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.Label2.ForeColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(0)), Convert.ToInt32(Convert.ToByte(0)));
this.Label2.Location = new System.Drawing.Point(56, 272);
this.Label2.Name = "Label2";
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.Size = new System.Drawing.Size(296, 23);
this.Label2.TabIndex = 14;
this.Label2.Text = "Please verify products from both locations";
//
//lblPComp
//
this.lblPComp.BackColor = System.Drawing.Color.Transparent;
this.lblPComp.Cursor = System.Windows.Forms.Cursors.Default;
this.lblPComp.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblPComp.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblPComp.Location = new System.Drawing.Point(16, 152);
this.lblPComp.Name = "lblPComp";
this.lblPComp.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblPComp.Size = new System.Drawing.Size(352, 24);
this.lblPComp.TabIndex = 13;
this.lblPComp.Text = "Promotion Name:";
this.lblPComp.Visible = false;
//
//lblSComp
//
this.lblSComp.BackColor = System.Drawing.Color.Transparent;
this.lblSComp.Cursor = System.Windows.Forms.Cursors.Default;
this.lblSComp.Font = new System.Drawing.Font("Arial", 9.75f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblSComp.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblSComp.Location = new System.Drawing.Point(16, 304);
this.lblSComp.Name = "lblSComp";
this.lblSComp.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblSComp.Size = new System.Drawing.Size(360, 24);
this.lblSComp.TabIndex = 12;
this.lblSComp.Text = "Promotion Name:";
//
//lblStockItemS
//
this.lblStockItemS.BackColor = System.Drawing.SystemColors.Control;
this.lblStockItemS.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblStockItemS.Cursor = System.Windows.Forms.Cursors.Default;
this.lblStockItemS.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblStockItemS.Location = new System.Drawing.Point(98, 328);
this.lblStockItemS.Name = "lblStockItemS";
this.lblStockItemS.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblStockItemS.Size = new System.Drawing.Size(286, 17);
this.lblStockItemS.TabIndex = 11;
this.lblStockItemS.Text = "Label1";
//
//_LBL_5
//
this._LBL_5.AutoSize = true;
this._LBL_5.BackColor = System.Drawing.Color.Transparent;
this._LBL_5.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_5.Location = new System.Drawing.Point(10, 328);
this._LBL_5.Name = "_LBL_5";
this._LBL_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_5.Size = new System.Drawing.Size(92, 13);
this._LBL_5.TabIndex = 10;
this._LBL_5.Text = "Stock Item Name:";
this._LBL_5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//_LBL_0
//
this._LBL_0.AutoSize = true;
this._LBL_0.BackColor = System.Drawing.Color.Transparent;
this._LBL_0.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_0.Location = new System.Drawing.Point(260, 349);
this._LBL_0.Name = "_LBL_0";
this._LBL_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_0.Size = new System.Drawing.Size(34, 13);
this._LBL_0.TabIndex = 9;
this._LBL_0.Text = "Price:";
this._LBL_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_0.Visible = false;
//
//_LBL_3
//
this._LBL_3.AutoSize = true;
this._LBL_3.BackColor = System.Drawing.Color.Transparent;
this._LBL_3.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_3.Location = new System.Drawing.Point(270, 252);
this._LBL_3.Name = "_LBL_3";
this._LBL_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_3.Size = new System.Drawing.Size(34, 13);
this._LBL_3.TabIndex = 7;
this._LBL_3.Text = "Price:";
this._LBL_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._LBL_3.Visible = false;
//
//_LBL_1
//
this._LBL_1.AutoSize = true;
this._LBL_1.BackColor = System.Drawing.Color.Transparent;
this._LBL_1.Cursor = System.Windows.Forms.Cursors.Default;
this._LBL_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._LBL_1.Location = new System.Drawing.Point(24, 56);
this._LBL_1.Name = "_LBL_1";
this._LBL_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._LBL_1.Size = new System.Drawing.Size(92, 13);
this._LBL_1.TabIndex = 6;
this._LBL_1.Text = "Stock Item Name:";
this._LBL_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
//lblStockItem
//
this.lblStockItem.BackColor = System.Drawing.SystemColors.Control;
this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default;
this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblStockItem.Location = new System.Drawing.Point(24, 72);
this.lblStockItem.Name = "lblStockItem";
this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblStockItem.Size = new System.Drawing.Size(358, 25);
this.lblStockItem.TabIndex = 3;
this.lblStockItem.Text = "Label1";
//
//frmBarcodeScaleItem
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)));
this.ClientSize = new System.Drawing.Size(400, 145);
this.ControlBox = false;
this.Controls.Add(this.txtQty);
this.Controls.Add(this.txtPSize);
this.Controls.Add(this.txtPack);
this.Controls.Add(this.txtPriceS);
this.Controls.Add(this.txtQtyT);
this.Controls.Add(this.txtPrice);
this.Controls.Add(this.cmbQuantity);
this.Controls.Add(this.picButtons);
this.Controls.Add(this._LBL_6);
this.Controls.Add(this._LBL_4);
this.Controls.Add(this._LBL_2);
this.Controls.Add(this.Label2);
this.Controls.Add(this.lblPComp);
this.Controls.Add(this.lblSComp);
this.Controls.Add(this.lblStockItemS);
this.Controls.Add(this._LBL_5);
this.Controls.Add(this._LBL_0);
this.Controls.Add(this._LBL_3);
this.Controls.Add(this._LBL_1);
this.Controls.Add(this.lblStockItem);
this.Controls.Add(this.ShapeContainer1);
this.Cursor = System.Windows.Forms.Cursors.Default;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.KeyPreview = true;
this.Location = new System.Drawing.Point(3, 22);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmBarcodeScaleItem";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Scale Item - Barcode printing";
this.picButtons.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ThreadLocal.cs
//
//
// A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing
// thread; this provides an alternative to using a ThreadStatic static variable and having
// to check the variable prior to every access to see if it's been initialized.
//
//
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Threading
{
/// <summary>
/// Provides thread-local storage of data.
/// </summary>
/// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam>
/// <remarks>
/// <para>
/// With the exception of <see cref="Dispose()"/>, all public and protected members of
/// <see cref="ThreadLocal{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
public class ThreadLocal<T> : IDisposable
{
// a delegate that returns the created value, if null the created value will be default(T)
private Func<T> m_valueFactory;
//
// ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances
//
// So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T.
// The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in
// the ThreadLocal<T> instance.
//
[ThreadStatic]
static LinkedSlotVolatile[] ts_slotArray;
[ThreadStatic]
static FinalizationHelper ts_finalizationHelper;
// Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish
// between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or
// possibly due to a memory model issue in user code.
private int m_idComplement;
// This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor
// threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false
// when the instance is disposed.
private volatile bool m_initialized;
// IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock.
private static IdManager s_idManager = new IdManager();
// A linked list of all values associated with this ThreadLocal<T> instance.
// We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field.
private LinkedSlot m_linkedSlot = new LinkedSlot(null);
// Whether the Values property is supported
private bool m_trackAllValues;
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
public ThreadLocal()
{
Initialize(null, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param>
public ThreadLocal(bool trackAllValues)
{
Initialize(null, trackAllValues);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
Initialize(valueFactory, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory, bool trackAllValues)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
Initialize(valueFactory, trackAllValues);
}
private void Initialize(Func<T> valueFactory, bool trackAllValues)
{
m_valueFactory = valueFactory;
m_trackAllValues = trackAllValues;
// Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized
// in a finally block, to avoid a thread abort in between the two statements.
try { }
finally
{
m_idComplement = ~s_idManager.GetId();
// As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception
// occurred in the constructor.)
m_initialized = true;
}
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
~ThreadLocal()
{
// finalizer to return the type combination index to the pool
Dispose(false);
}
#region IDisposable Members
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <param name="disposing">
/// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>.
/// </param>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
int id;
using (LockHolder.Hold(s_idManager.m_lock))
{
id = ~m_idComplement;
m_idComplement = 0;
if (id < 0 || !m_initialized)
{
Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
}
m_initialized = false;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray;
if (slotArray == null)
{
// The thread that owns this slotArray has already finished.
continue;
}
// Remove the reference from the LinkedSlot to the slot table.
linkedSlot.SlotArray = null;
// And clear the references from the slot table to the linked slot and the value so that
// both can get garbage collected.
slotArray[id].Value.Value = default(T);
slotArray[id].Value = null;
}
}
m_linkedSlot = null;
s_idManager.ReturnId(id);
}
#endregion
/// <summary>Creates and returns a string representation of this instance for the current thread.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// Calling this method forces initialization for the current thread, as is the
/// case with accessing <see cref="Value"/> directly.
/// </remarks>
public override string ToString()
{
return Value.ToString();
}
/// <summary>
/// Gets or sets the value of this instance for the current thread.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// If this instance was not previously initialized for the current thread,
/// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was
/// supplied during the construction, that initialization will happen by invoking the function
/// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of
/// <typeparamref name="T"/> will be used.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to get the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
return slot.Value;
}
return GetValueSlow();
}
set
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to set the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
slot.Value = value;
}
else
{
SetValueSlow(value, slotArray);
}
}
}
private T GetValueSlow()
{
// If the object has been disposed, the id will be -1.
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
//Debugger.NotifyOfCrossThreadDependency();
// Determine the initial value
T value;
if (m_valueFactory == null)
{
value = default(T);
}
else
{
value = m_valueFactory();
if (IsValueCreated)
{
throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue);
}
}
// Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics).
Value = value;
return value;
}
private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray)
{
int id = ~m_idComplement;
// If the object has been disposed, id will be -1.
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
// If a slot array has not been created on this thread yet, create it.
if (slotArray == null)
{
slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)];
ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues);
ts_slotArray = slotArray;
}
// If the slot array is not big enough to hold this ID, increase the table size.
if (id >= slotArray.Length)
{
GrowTable(ref slotArray, id + 1);
ts_finalizationHelper.SlotArray = slotArray;
ts_slotArray = slotArray;
}
// If we are using the slot in this table for the first time, create a new LinkedSlot and add it into
// the linked list for this ThreadLocal instance.
if (slotArray[id].Value == null)
{
CreateLinkedSlot(slotArray, id, value);
}
else
{
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// that follows will not be reordered before the read of slotArray[id].
LinkedSlot slot = slotArray[id].Value;
// It is important to verify that the ThreadLocal instance has not been disposed. The check must come
// after capturing slotArray[id], but before assigning the value into the slot. This ensures that
// if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was
// created, we definitely won't assign the value into the wrong instance.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
slot.Value = value;
}
}
/// <summary>
/// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance.
/// </summary>
private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value)
{
// Create a LinkedSlot
var linkedSlot = new LinkedSlot(slotArray);
// Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array
using (LockHolder.Hold(s_idManager.m_lock))
{
// Check that the instance has not been disposed. It is important to check this under a lock, since
// Dispose also executes under a lock.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlot firstRealNode = m_linkedSlot.Next;
//
// Insert linkedSlot between nodes m_linkedSlot and firstRealNode.
// (m_linkedSlot is the dummy head node that should always be in the front.)
//
linkedSlot.Next = firstRealNode;
linkedSlot.Previous = m_linkedSlot;
linkedSlot.Value = value;
if (firstRealNode != null)
{
firstRealNode.Previous = linkedSlot;
}
m_linkedSlot.Next = linkedSlot;
// Assigning the slot under a lock prevents a race with Dispose (dispose also acquires the lock).
// Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created
// with the same ID, and the write would go to the wrong instance.
slotArray[id].Value = linkedSlot;
}
}
/// <summary>
/// Gets a list for all of the values currently stored by all of the threads that have accessed this instance.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public IList<T> Values
{
get
{
if (!m_trackAllValues)
{
throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable);
}
var list = GetValuesAsList(); // returns null if disposed
if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
return list;
}
}
/// <summary>Gets all of the threads' values in a list.</summary>
private LowLevelListWithIList<T> GetValuesAsList()
{
LowLevelListWithIList<T> valueList = new LowLevelListWithIList<T>();
int id = ~m_idComplement;
if (id == -1)
{
return null;
}
// Walk over the linked list of slots and gather the values associated with this ThreadLocal instance.
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
// We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot
// objects will never be assigned to another ThreadLocal instance.
valueList.Add(linkedSlot.Value);
}
return valueList;
}
/// <summary>Gets the number of threads that have data in this instance.</summary>
private int ValuesCountForDebugDisplay
{
get
{
int count = 0;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
count++;
}
return count;
}
}
/// <summary>
/// Gets whether <see cref="Value"/> is initialized on the current thread.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public bool IsValueCreated
{
get
{
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlotVolatile[] slotArray = ts_slotArray;
return slotArray != null && id < slotArray.Length && slotArray[id].Value != null;
}
}
/// <summary>Gets the value of the ThreadLocal<T> for debugging display purposes. It takes care of getting
/// the value for the current thread in the ThreadLocal mode.</summary>
internal T ValueForDebugDisplay
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
int id = ~m_idComplement;
LinkedSlot slot;
if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized)
return default(T);
return slot.Value;
}
}
/// <summary>Gets the values of all threads that accessed the ThreadLocal<T>.</summary>
internal IList<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed
{
get { return GetValuesAsList(); }
}
/// <summary>
/// Resizes a table to a certain length (or larger).
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
Contract.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen];
//
// The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all
// LinkedSlot instances referenced in the old table to reference the new table. Without locking,
// Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while
// the value continues to be referenced from the new (larger) array.
//
using (LockHolder.Hold(s_idManager.m_lock))
{
for (int i = 0; i < table.Length; i++)
{
LinkedSlot linkedSlot = table[i].Value;
if (linkedSlot != null && linkedSlot.SlotArray != null)
{
linkedSlot.SlotArray = newTable;
newTable[i] = table[i];
}
}
}
table = newTable;
}
const int MaxArrayLength = int.MaxValue;
/// <summary>
/// Chooses the next larger table size
/// </summary>
private static int GetNewTableSize(int minSize)
{
if ((uint)minSize > MaxArrayLength)
{
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
Contract.Assert(minSize > 0);
//
// Round up the size to the next power of 2
//
// The algorithm takes three steps:
// input -> subtract one -> propagate 1-bits to the right -> add one
//
// Let's take a look at the 3 steps in both interesting cases: where the input
// is (Example 1) and isn't (Example 2) a power of 2.
//
// Example 1: 100000 -> 011111 -> 011111 -> 100000
// Example 2: 011010 -> 011001 -> 011111 -> 100000
//
int newSize = minSize;
// Step 1: Decrement
newSize--;
// Step 2: Propagate 1-bits to the right.
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
// Step 3: Increment
newSize++;
// Don't set newSize to more than Array.MaxArrayLength
if ((uint)newSize > MaxArrayLength)
{
newSize = MaxArrayLength;
}
return newSize;
}
/// <summary>
/// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics
/// on array accesses.
/// </summary>
internal struct LinkedSlotVolatile
{
internal volatile LinkedSlot Value;
}
/// <summary>
/// A node in the doubly-linked list stored in the ThreadLocal instance.
///
/// The value is stored in one of two places:
///
/// 1. If SlotArray is not null, the value is in SlotArray.Table[id]
/// 2. If SlotArray is null, the value is in FinalValue.
/// </summary>
internal sealed class LinkedSlot
{
internal LinkedSlot(LinkedSlotVolatile[] slotArray)
{
SlotArray = slotArray;
}
// The next LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Next;
// The previous LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Previous;
// The SlotArray that stores this LinkedSlot at SlotArray.Table[id].
internal volatile LinkedSlotVolatile[] SlotArray;
// The value for this slot.
internal T Value;
}
/// <summary>
/// A manager class that assigns IDs to ThreadLocal instances
/// </summary>
private class IdManager
{
// The next ID to try
private int m_nextIdToTry = 0;
// Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager.
private LowLevelList<bool> m_freeIds = new LowLevelList<bool>();
internal Lock m_lock = new Lock();
internal int GetId()
{
using (LockHolder.Hold(m_lock))
{
int availableId = m_nextIdToTry;
while (availableId < m_freeIds.Count)
{
if (m_freeIds[availableId]) { break; }
availableId++;
}
if (availableId == m_freeIds.Count)
{
m_freeIds.Add(false);
}
else
{
m_freeIds[availableId] = false;
}
m_nextIdToTry = availableId + 1;
return availableId;
}
}
// Return an ID to the pool
internal void ReturnId(int id)
{
using (LockHolder.Hold(m_lock))
{
m_freeIds[id] = true;
if (id < m_nextIdToTry) m_nextIdToTry = id;
}
}
}
/// <summary>
/// A class that facilitates ThreadLocal cleanup after a thread exits.
///
/// After a thread with an associated thread-local table has exited, the FinalizationHelper
/// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper
/// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once
/// the thread has exited.
///
/// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table
/// (all those LinkedSlot instances can be found by following references from the table slots) and
/// releases the table so that it can get GC'd.
/// </summary>
internal class FinalizationHelper
{
internal LinkedSlotVolatile[] SlotArray;
private bool m_trackAllValues;
internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues)
{
SlotArray = slotArray;
m_trackAllValues = trackAllValues;
}
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
Contract.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
LinkedSlot linkedSlot = slotArray[i].Value;
if (linkedSlot == null)
{
// This slot in the table is empty
continue;
}
if (m_trackAllValues)
{
// Set the SlotArray field to null to release the slot array.
linkedSlot.SlotArray = null;
}
else
{
// Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to
// the table will be have been removed, and so the table can get GC'd.
using (LockHolder.Hold(s_idManager.m_lock))
{
if (linkedSlot.Next != null)
{
linkedSlot.Next.Previous = linkedSlot.Previous;
}
// Since the list uses a dummy head node, the Previous reference should never be null.
Contract.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
}
}
}
}
/// <summary>A debugger view of the ThreadLocal<T> to surface additional debugging properties and
/// to ensure that the ThreadLocal<T> does not become initialized if it was not already.</summary>
internal sealed class SystemThreading_ThreadLocalDebugView<T>
{
//The ThreadLocal object being viewed.
private readonly ThreadLocal<T> m_tlocal;
/// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary>
/// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param>
public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal)
{
m_tlocal = tlocal;
}
/// <summary>Returns whether the ThreadLocal object is initialized or not.</summary>
public bool IsValueCreated
{
get { return m_tlocal.IsValueCreated; }
}
/// <summary>Returns the value of the ThreadLocal object.</summary>
public T Value
{
get
{
return m_tlocal.ValueForDebugDisplay;
}
}
/// <summary>Return all values for all threads that have accessed this instance.</summary>
public IList<T> Values
{
get
{
return m_tlocal.ValuesForDebugDisplay;
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.Collections.Generic;
using System.ServiceModel;
using System.IO;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.ServiceModel.Security.Tokens;
using System.Threading;
using System.Globalization;
using System.ServiceModel.Diagnostics;
using System.Text;
using System.Xml;
using CanonicalFormWriter = System.IdentityModel.CanonicalFormWriter;
using SignatureResourcePool = System.IdentityModel.SignatureResourcePool;
using HashStream = System.IdentityModel.HashStream;
abstract class WSUtilitySpecificationVersion
{
internal static readonly string[] AcceptedDateTimeFormats = new string[]
{
"yyyy-MM-ddTHH:mm:ss.fffffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffffZ",
"yyyy-MM-ddTHH:mm:ss.fffffZ",
"yyyy-MM-ddTHH:mm:ss.ffffZ",
"yyyy-MM-ddTHH:mm:ss.fffZ",
"yyyy-MM-ddTHH:mm:ss.ffZ",
"yyyy-MM-ddTHH:mm:ss.fZ",
"yyyy-MM-ddTHH:mm:ssZ"
};
readonly XmlDictionaryString namespaceUri;
internal WSUtilitySpecificationVersion(XmlDictionaryString namespaceUri)
{
this.namespaceUri = namespaceUri;
}
public static WSUtilitySpecificationVersion Default
{
get { return OneDotZero; }
}
internal XmlDictionaryString NamespaceUri
{
get { return this.namespaceUri; }
}
public static WSUtilitySpecificationVersion OneDotZero
{
get { return WSUtilitySpecificationVersionOneDotZero.Instance; }
}
internal abstract bool IsReaderAtTimestamp(XmlDictionaryReader reader);
internal abstract SecurityTimestamp ReadTimestamp(XmlDictionaryReader reader, string digestAlgorithm, SignatureResourcePool resourcePool);
internal abstract void WriteTimestamp(XmlDictionaryWriter writer, SecurityTimestamp timestamp);
internal abstract void WriteTimestampCanonicalForm(Stream stream, SecurityTimestamp timestamp, byte[] buffer);
sealed class WSUtilitySpecificationVersionOneDotZero : WSUtilitySpecificationVersion
{
static readonly WSUtilitySpecificationVersionOneDotZero instance = new WSUtilitySpecificationVersionOneDotZero();
WSUtilitySpecificationVersionOneDotZero()
: base(XD.UtilityDictionary.Namespace)
{
}
public static WSUtilitySpecificationVersionOneDotZero Instance
{
get { return instance; }
}
internal override bool IsReaderAtTimestamp(XmlDictionaryReader reader)
{
return reader.IsStartElement(XD.UtilityDictionary.Timestamp, XD.UtilityDictionary.Namespace);
}
internal override SecurityTimestamp ReadTimestamp(XmlDictionaryReader reader, string digestAlgorithm, SignatureResourcePool resourcePool)
{
bool canonicalize = digestAlgorithm != null && reader.CanCanonicalize;
HashStream hashStream = null;
reader.MoveToStartElement(XD.UtilityDictionary.Timestamp, XD.UtilityDictionary.Namespace);
if (canonicalize)
{
hashStream = resourcePool.TakeHashStream(digestAlgorithm);
reader.StartCanonicalization(hashStream, false, null);
}
string id = reader.GetAttribute(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace);
reader.ReadStartElement();
reader.ReadStartElement(XD.UtilityDictionary.CreatedElement, XD.UtilityDictionary.Namespace);
DateTime creationTimeUtc = reader.ReadContentAsDateTime().ToUniversalTime();
reader.ReadEndElement();
DateTime expiryTimeUtc;
if (reader.IsStartElement(XD.UtilityDictionary.ExpiresElement, XD.UtilityDictionary.Namespace))
{
reader.ReadStartElement();
expiryTimeUtc = reader.ReadContentAsDateTime().ToUniversalTime();
reader.ReadEndElement();
}
else
{
expiryTimeUtc = SecurityUtils.MaxUtcDateTime;
}
reader.ReadEndElement();
byte[] digest;
if (canonicalize)
{
reader.EndCanonicalization();
digest = hashStream.FlushHashAndGetValue();
}
else
{
digest = null;
}
return new SecurityTimestamp(creationTimeUtc, expiryTimeUtc, id, digestAlgorithm, digest);
}
internal override void WriteTimestamp(XmlDictionaryWriter writer, SecurityTimestamp timestamp)
{
writer.WriteStartElement(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.Timestamp, XD.UtilityDictionary.Namespace);
writer.WriteAttributeString(XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, timestamp.Id);
writer.WriteStartElement(XD.UtilityDictionary.CreatedElement, XD.UtilityDictionary.Namespace);
char[] creationTime = timestamp.GetCreationTimeChars();
writer.WriteChars(creationTime, 0, creationTime.Length);
writer.WriteEndElement(); // wsu:Created
writer.WriteStartElement(XD.UtilityDictionary.ExpiresElement, XD.UtilityDictionary.Namespace);
char[] expiryTime = timestamp.GetExpiryTimeChars();
writer.WriteChars(expiryTime, 0, expiryTime.Length);
writer.WriteEndElement(); // wsu:Expires
writer.WriteEndElement();
}
internal override void WriteTimestampCanonicalForm(Stream stream, SecurityTimestamp timestamp, byte[] workBuffer)
{
TimestampCanonicalFormWriter.Instance.WriteCanonicalForm(
stream,
timestamp.Id, timestamp.GetCreationTimeChars(), timestamp.GetExpiryTimeChars(),
workBuffer);
}
}
sealed class TimestampCanonicalFormWriter : CanonicalFormWriter
{
const string timestamp = UtilityStrings.Prefix + ":" + UtilityStrings.Timestamp;
const string created = UtilityStrings.Prefix + ":" + UtilityStrings.CreatedElement;
const string expires = UtilityStrings.Prefix + ":" + UtilityStrings.ExpiresElement;
const string idAttribute = UtilityStrings.Prefix + ":" + UtilityStrings.IdAttribute;
const string ns = "xmlns:" + UtilityStrings.Prefix + "=\"" + UtilityStrings.Namespace + "\"";
const string xml1 = "<" + timestamp + " " + ns + " " + idAttribute + "=\"";
const string xml2 = "\"><" + created + ">";
const string xml3 = "</" + created + "><" + expires + ">";
const string xml4 = "</" + expires + "></" + timestamp + ">";
readonly byte[] fragment1;
readonly byte[] fragment2;
readonly byte[] fragment3;
readonly byte[] fragment4;
static readonly TimestampCanonicalFormWriter instance = new TimestampCanonicalFormWriter();
TimestampCanonicalFormWriter()
{
UTF8Encoding encoding = CanonicalFormWriter.Utf8WithoutPreamble;
this.fragment1 = encoding.GetBytes(xml1);
this.fragment2 = encoding.GetBytes(xml2);
this.fragment3 = encoding.GetBytes(xml3);
this.fragment4 = encoding.GetBytes(xml4);
}
public static TimestampCanonicalFormWriter Instance
{
get { return instance; }
}
public void WriteCanonicalForm(Stream stream, string id, char[] created, char[] expires, byte[] workBuffer)
{
stream.Write(this.fragment1, 0, this.fragment1.Length);
EncodeAndWrite(stream, workBuffer, id);
stream.Write(this.fragment2, 0, this.fragment2.Length);
EncodeAndWrite(stream, workBuffer, created);
stream.Write(this.fragment3, 0, this.fragment3.Length);
EncodeAndWrite(stream, workBuffer, expires);
stream.Write(this.fragment4, 0, this.fragment4.Length);
}
}
}
}
| |
// 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.
namespace System {
using System;
using System.Reflection;
using System.Runtime;
using System.Threading;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
[System.Security.SecurityCritical]
internal Object _target;
// MethodBase, either cached after first request or assigned from a DynamicMethod
// For open delegates to collectible types, this may be a LoaderAllocator object
[System.Security.SecurityCritical]
internal Object _methodBase;
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
[System.Security.SecurityCritical]
internal IntPtr _methodPtr;
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
// to _methodPtrAux.
[System.Security.SecurityCritical]
internal IntPtr _methodPtrAux;
// This constructor is called from the class generated by the
// compiler generated code
[System.Security.SecuritySafeCritical] // auto-generated
protected Delegate(Object target,String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
// the choice of target method ambiguous) for backwards
// compatibility. The name matching was case sensitive and we
// preserve that as well.
if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly))
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
[System.Security.SecuritySafeCritical] // auto-generated
protected unsafe Delegate(Type target,String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// The name matching was case insensitive (no idea why this is
// different from the constructor above) and we preserve that as
// well.
BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
DelegateBindingFlags.CaselessMatching);
}
// Protect the default constructor so you can't build a delegate
private Delegate()
{
}
public Object DynamicInvoke(params Object[] args)
{
// Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
// But to maintain backward compatibility we can't switch to calling an
// internal overload of DynamicInvokeImpl that takes a stack mark.
// Fortunately the stack walker skips all the reflection invocation frames including this one.
// So this method will never be returned by the stack walker as the caller.
// See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
return DynamicInvokeImpl(args);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj)
{
if (obj == null || !InternalEqualTypes(this, obj))
return false;
Delegate d = (Delegate) obj;
// do an optimistic check first. This is hopefully cheap enough to be worth
if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
return true;
// even though the fields were not all equals the delegates may still match
// When target carries the delegate itself the 2 targets (delegates) may be different instances
// but the delegates are logically the same
// It may also happen that the method pointer was not jitted when creating one delegate and jitted in the other
// if that's the case the delegates may still be equals but we need to make a more complicated check
if (_methodPtrAux.IsNull())
{
if (!d._methodPtrAux.IsNull())
return false; // different delegate kind
// they are both closed over the first arg
if (_target != d._target)
return false;
// fall through method handle check
}
else
{
if (d._methodPtrAux.IsNull())
return false; // different delegate kind
// Ignore the target as it will be the delegate instance, though it may be a different one
/*
if (_methodPtr != d._methodPtr)
return false;
*/
if (_methodPtrAux == d._methodPtrAux)
return true;
// fall through method handle check
}
// method ptrs don't match, go down long path
//
if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
return Delegate.InternalEqualMethodHandles(this, d);
else
return _methodBase.Equals(d._methodBase);
}
public override int GetHashCode()
{
//
// this is not right in the face of a method being jitted in one delegate and not in another
// in that case the delegate is the same and Equals will return true but GetHashCode returns a
// different hashcode which is not true.
/*
if (_methodPtrAux.IsNull())
return unchecked((int)((long)this._methodPtr));
else
return unchecked((int)((long)this._methodPtrAux));
*/
return GetType().GetHashCode();
}
public static Delegate Combine(Delegate a, Delegate b)
{
if ((Object)a == null) // cast to object for a more efficient test
return b;
return a.CombineImpl(b);
}
[System.Runtime.InteropServices.ComVisible(true)]
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d,delegates[i]);
return d;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
// This routine will return the method
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
[System.Security.SecuritySafeCritical] // auto-generated
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
if (!isStatic)
{
if (_methodPtrAux == (IntPtr)0)
{
// The target may be of a derived type that doesn't have visibility onto the
// target method. We don't want to call RuntimeType.GetMethodBase below with that
// or reflection can end up generating a MethodInfo where the ReflectedType cannot
// see the MethodInfo itself and that breaks an important invariant. But the
// target type could include important generic type information we need in order
// to work out what the exact instantiation of the method's declaring type is. So
// we'll walk up the inheritance chain (which will yield exactly instantiated
// types at each step) until we find the declaring type. Since the declaring type
// we get from the method is probably shared and those in the hierarchy we're
// walking won't be we compare using the generic type definition forms instead.
Type currentType = _target.GetType();
Type targetType = declaringType.GetGenericTypeDefinition();
while (currentType != null)
{
if (currentType.IsGenericType &&
currentType.GetGenericTypeDefinition() == targetType)
{
declaringType = currentType as RuntimeType;
break;
}
currentType = currentType.BaseType;
}
// RCWs don't need to be "strongly-typed" in which case we don't find a base type
// that matches the declaring type of the method. This is fine because interop needs
// to work with exact methods anyway so declaringType is never shared at this point.
BCLDebug.Assert(currentType != null || _target.GetType().IsCOMObject, "The class hierarchy should declare the method");
}
else
{
// it's an open one, need to fetch the first arg of the instantiation
MethodInfo invoke = this.GetType().GetMethod("Invoke");
declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
}
}
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
public Object Target
{
get
{
return GetTarget();
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
protected virtual Delegate CombineImpl(Delegate d)
{
throw new MulticastNotSupportedException(Environment.GetResourceString("Multicast_Combine"));
}
protected virtual Delegate RemoveImpl(Delegate d)
{
return (d.Equals(this)) ? null : this;
}
public virtual Object Clone()
{
return MemberwiseClone();
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
[System.Security.SecuritySafeCritical] // auto-generated
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
// We never generate a closed over null delegate and this is
// actually enforced via the check on target above, but we pass
// NeverCloseOverNull anyway just for clarity.
if (!d.BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly |
DelegateBindingFlags.NeverCloseOverNull |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
d = null;
}
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
{
return CreateDelegate(type, target, method, ignoreCase, true);
}
// V1 API.
[System.Security.SecuritySafeCritical] // auto-generated
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (rtTarget == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
// and don't allow relaxed signature matching (which could make the
// choice of target method ambiguous) for backwards compatibility.
if (!d.BindToMethodName(null, rtTarget, method,
DelegateBindingFlags.StaticMethodOnly |
DelegateBindingFlags.OpenDelegateOnly |
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
d = null;
}
return d;
}
// V1 API.
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
return d;
}
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
return CreateDelegate(type, firstArgument, method, true);
}
// V2 API.
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking. The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Delegate d = CreateDelegateInternal(
rtType,
rmi,
firstArgument,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
if (d == null && throwOnBindFailure)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
return d;
}
public static bool operator ==(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator != (Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
//
// Implementation of ISerializable
//
[System.Security.SecurityCritical]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException();
}
//
// internal implementation details (FCALLS and utilities)
//
// V2 internal API.
// This is Critical because it skips the security check when creating the delegate.
[System.Security.SecurityCritical] // auto-generated
internal unsafe static Delegate CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
// used by the dynamic method code to generate a wrapper delegate.
// Allow flexible binding options since the target method is
// unambiguously provided to us.
if (!d.BindToMethodInfo(target,
method.GetMethodInfo(),
RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
return d;
}
// Caution: this method is intended for deserialization only, no security checks are performed.
[System.Security.SecurityCritical] // auto-generated
internal static Delegate CreateDelegateNoSecurityCheck(RuntimeType type, Object firstArgument, MethodInfo method)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
if (!type.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
// target in a valid delegate) so we should bind with the most
// relaxed rules available (the result will never be ambiguous, it
// just increases the chance of success with minor (compatible)
// signature changes). We explicitly skip security checks here --
// we're not really constructing a delegate, we're cloning an
// existing instance which already passed its checks.
Delegate d = UnsafeCreateDelegate(type, rtMethod, firstArgument,
DelegateBindingFlags.SkipSecurityChecks |
DelegateBindingFlags.RelaxedSignature);
if (d == null)
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
return d;
}
// V1 API.
public static Delegate CreateDelegate(Type type, MethodInfo method)
{
return CreateDelegate(type, method, true);
}
[System.Security.SecuritySafeCritical]
internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags, ref StackCrawlMark stackMark)
{
Contract.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
#if FEATURE_APPX
bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
bool nonW8PType = (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
if (nonW8PMethod || nonW8PType)
{
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(
Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext",
nonW8PMethod ? rtMethod.FullName : rtType.FullName));
}
#endif
return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
}
[System.Security.SecurityCritical]
internal static Delegate UnsafeCreateDelegate(RuntimeType rtType, RuntimeMethodInfo rtMethod, Object firstArgument, DelegateBindingFlags flags)
{
Delegate d = InternalAlloc(rtType);
if (d.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags))
return d;
else
return null;
}
//
// internal implementation details (FCALLS and utilities)
//
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualTypes(object a, object b);
// Used by the ctor. Do not call directly.
// The name of this function will appear in managed stacktraces as delegate constructor.
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void DelegateConstruct(Object target, IntPtr slot);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetMulticastInvoke();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetInvokeMethod();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IRuntimeMethodInfo FindMethodHandle();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool InternalEqualMethodHandles(Delegate left, Delegate right);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr AdjustTarget(Object target, IntPtr methodPtr);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern IntPtr GetCallStub(IntPtr methodPtr);
[System.Security.SecuritySafeCritical]
internal virtual Object GetTarget()
{
return (_methodPtrAux.IsNull()) ? _target : null;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2);
}
// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in vm\comdelegate.h.
internal enum DelegateBindingFlags
{
StaticMethodOnly = 0x00000001, // Can only bind to static target methods
InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
}
}
| |
using System;
using System.IO;
using Enigma.Binary;
using Enigma.IO;
namespace Enigma.Serialization.PackedBinary
{
public class PackedDataReadVisitor : IReadVisitor
{
private readonly Stream _stream;
private readonly BinaryDataReader _reader;
private UInt32 _nextIndex;
private bool _endOfLevel;
public PackedDataReadVisitor(Stream stream)
{
_stream = stream;
_reader = new BinaryDataReader(stream);
}
private static bool SkipDataIndex(uint dataIndex, uint index)
{
return 0 < dataIndex && dataIndex < index;
}
private bool MoveToIndex(UInt32 index)
{
if (_endOfLevel) return false;
if (_nextIndex > index) return false;
if (_nextIndex > 0) {
var nextIndex = _nextIndex;
_nextIndex = 0;
if (nextIndex == index) return true;
}
UInt32 dataIndex;
while (SkipDataIndex(dataIndex = _reader.ReadZ(), index)) {
var byteLength = _reader.ReadByte();
if (byteLength == BinaryZPacker.Null) continue;
if (byteLength != BinaryZPacker.VariabelLength)
_reader.Skip(byteLength);
else {
var length = _reader.ReadUInt32();
_reader.Skip(length);
}
}
if (dataIndex == 0) {
_endOfLevel = true;
return false;
}
if (dataIndex > index) {
_nextIndex = dataIndex;
return false;
}
return true;
}
public ValueState TryVisit(VisitArgs args)
{
if (args.Type == LevelType.Root) return ValueState.Found;
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index))
return ValueState.NotFound;
var byteLength = _reader.ReadByte();
if (byteLength == BinaryZPacker.Null) return ValueState.Null;
if (byteLength != BinaryZPacker.VariabelLength)
throw new UnexpectedLengthException(args, byteLength);
_reader.Skip(4);
return ValueState.Found;
}
public void Leave(VisitArgs args)
{
if (_endOfLevel) {
_endOfLevel = false;
return;
}
if (args.Type == LevelType.Root) return;
if (args.Type.IsCollection()) return;
if (args.Type.IsDictionary()) return;
MoveToIndex(UInt32.MaxValue);
_endOfLevel = false;
}
public bool TryVisitValue(VisitArgs args, out byte? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Byte.FixedLength)
throw new UnexpectedLengthException(args, length);
value = (Byte)_stream.ReadByte();
return true;
}
public bool TryVisitValue(VisitArgs args, out short? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = (Int16)BinaryPV64Packer.UnpackS(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out int? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = (Int32)BinaryPV64Packer.UnpackS(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out long? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = BinaryPV64Packer.UnpackS(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out ushort? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = (UInt16)BinaryPV64Packer.UnpackU(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out uint? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = (UInt32)BinaryPV64Packer.UnpackU(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out ulong? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = BinaryPV64Packer.UnpackU(_stream, length);
return true;
}
public bool TryVisitValue(VisitArgs args, out bool? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Boolean.FixedLength)
throw new UnexpectedLengthException(args, length);
value = _reader.ReadBoolean();
return true;
}
public bool TryVisitValue(VisitArgs args, out float? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Single.FixedLength)
throw new UnexpectedLengthException(args, length);
value = _reader.ReadSingle();
return true;
}
public bool TryVisitValue(VisitArgs args, out double? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Double.FixedLength)
throw new UnexpectedLengthException(args, length);
value = _reader.ReadDouble();
return true;
}
public bool TryVisitValue(VisitArgs args, out decimal? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Decimal.FixedLength)
throw new UnexpectedLengthException(args, length);
value = _reader.ReadDecimal();
return true;
}
public bool TryVisitValue(VisitArgs args, out TimeSpan? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = new TimeSpan(BinaryPV64Packer.UnpackS(_stream, length));
return true;
}
public bool TryVisitValue(VisitArgs args, out DateTime? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
value = new DateTime(BinaryPV64Packer.UnpackS(_stream, length), DateTimeKind.Utc).ToLocalTime();
return true;
}
public bool TryVisitValue(VisitArgs args, out string value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
var lengthToRead = length == BinaryZPacker.VariabelLength ? _reader.ReadV() : length;
value = _reader.ReadString(lengthToRead);
return true;
}
public bool TryVisitValue(VisitArgs args, out Guid? value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
if (length != BinaryInformation.Guid.FixedLength)
throw new UnexpectedLengthException(args, length);
value = _reader.ReadGuid();
return true;
}
public bool TryVisitValue(VisitArgs args, out byte[] value)
{
if (args.Metadata.Index > 0 && !MoveToIndex(args.Metadata.Index)) {
value = null;
return false;
}
var length = _reader.ReadByte();
if (length == BinaryZPacker.Null) {
value = null;
return true;
}
var lengthToRead = length == BinaryZPacker.VariabelLength ? _reader.ReadV() : length;
value = _reader.ReadBlob(lengthToRead);
return true;
}
}
}
| |
/***************************************************************************\
*
* File: XamlStream.cs
*
* Purpose: Contains the Reader/Writer stream implementation for
* Doing async parsing on a separate thread.
*
* Todo: Make Sure Reader/Writer calls are on proper Threads
* Todo: Add logic to stop the Writer if buffer >> than
* What is being loaded into the Tree.
* Todo: Investigate if worthwhile keeping a cache of Buffers
* That get re-used instead of allocating one each time.
* Todo: Review if ReadByte needs to be optimized
* Todo: Need End Of File Markers so reader doesn't have to rely on
* getting the BamlEndRecord.
*
// History:
// 6/06/02: rogerg Created
// 5/27/03: peterost Ported to wcp
*
* Copyright (C) 2002 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.Xml;
using System.IO;
using System.Windows;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using MS.Utility;
#if PBTCOMPILER
namespace MS.Internal.Markup
#else
namespace System.Windows.Markup
#endif
{
/// <summary>
/// Main class for setting up Reader and Writer streams as well as
/// keeping common data and any synchronization work.
///
/// Writer is allowed write and seek back to any position in the file
/// until it calls UpdateReaderLength(position). The position passed in is
/// an absolute position in the file. After making this call the Writer is
/// only allowed to seek and write past this position.
///
/// The Reader only sees the part of the file that the Writer says is ready
/// to read. Initially the length of the Reader stream is zero. When the Writer
/// calls UpdateReaderLength(position)the length of the Reader stream is set
/// to that position. The Reader calls ReaderDoneWithFileUpToPosition(position) to indicate
/// it no longer needs the file up to and including that position. After this call
/// it is an error for the Reader to try read bits before the position.
/// </summary>
internal class ReadWriteStreamManager
{
#region Constructors
#if PBTCOMPILER
// The compiler only needs the class definition, and none of the implementation.
private ReadWriteStreamManager()
#else
internal ReadWriteStreamManager()
#endif
{
ReaderFirstBufferPosition = 0;
WriterFirstBufferPosition = 0;
ReaderBufferArrayList = new ArrayList();
WriterBufferArrayList = new ArrayList();
_writerStream = new WriterStream(this);
_readerStream = new ReaderStream(this);
_bufferLock = new ReaderWriterLock();
}
#endregion Constructors
#region WriterCallbacks
/// <summary>
/// Writes the counts of bytes into the stream.
/// </summary>
/// <param name="buffer">input buffer</param>
/// <param name="offset">starting offset into the buffer</param>
/// <param name="count">number of bytes to write</param>
internal void Write(byte[] buffer, int offset, int count)
{
int bufferOffset;
int bufferIndex;
#if DEBUG
Debug.Assert(!WriteComplete,"Write called after close");
#endif
Debug.Assert(null != buffer,"Null buffer past to the Writer");
// if nothing to write then just return.
if (0 == count)
{
return;
}
byte[] writeBuffer = GetBufferFromFilePosition(
WritePosition,false /*writer*/,
out bufferOffset, out bufferIndex);
Debug.Assert(null != writeBuffer,"Null writeBuffer returned");
// see how many bits fit into this buffer.
int availableBytesInBuffer = BufferSize - bufferOffset;
int leftOverBytes = 0;
int bufferWriteCount = 0;
// check if ther is enough room in the write buffer to meet the
// request or if there will be leftOverBytes.
if (count > availableBytesInBuffer)
{
bufferWriteCount = availableBytesInBuffer;
leftOverBytes = count - availableBytesInBuffer;
}
else
{
leftOverBytes = 0;
bufferWriteCount = count;
}
Debug.Assert(0 < bufferWriteCount,"Not writing any bytes to the buffer");
// now loop through writing out all or the number of bits that can fit in the buffer.
for (int loopCount = 0; loopCount < bufferWriteCount; loopCount++)
{
Debug.Assert(bufferOffset < BufferSize,"Trying to Read past bufer");
writeBuffer[bufferOffset++] = buffer[offset++];
}
// update the writePosition
WritePosition += bufferWriteCount;
// check if need to update length of the file that the writer sees.
if (WritePosition > WriteLength)
{
WriteLength = WritePosition;
}
// if we have any leftOver Bytes call Write Again.
if (leftOverBytes > 0)
{
Write(buffer,offset,leftOverBytes);
}
}
/// <summary>
/// Adjust the Writer's Seek Pointer.
/// Writer is not allowed to Seek before where the ReaderLength or
/// Seek past the writeLength.
/// </summary>
/// <param name="offset">seek offset</param>
/// <param name="loc">specifies how to interpret the seeek offset</param>
/// <returns></returns>
internal long WriterSeek(long offset, SeekOrigin loc)
{
switch(loc)
{
case SeekOrigin.Begin:
WritePosition = (int) offset;
break;
case SeekOrigin.Current:
WritePosition = (int) (WritePosition + offset);
break;
case SeekOrigin.End:
throw new NotSupportedException(SR.Get(SRID.ParserWriterNoSeekEnd));
default:
throw new ArgumentException(SR.Get(SRID.ParserWriterUnknownOrigin));
}
if( (!( WritePosition <= WriteLength ))
||
(!( WritePosition >= ReadLength )) )
{
throw new ArgumentOutOfRangeException( "offset" );
}
return WritePosition;
}
/// <summary>
/// Called by the Writer to indicate its okay for the reader to see
/// the file up to and including the position. Once the Writer calls
/// this it cannot go back and change the content.
/// </summary>
/// <param name="position">Absolute position in the stream</param>
internal void UpdateReaderLength(long position)
{
if(!(ReadLength <= position))
{
throw new ArgumentOutOfRangeException( "position" );
}
#if DEBUG
Debug.Assert(!WriteComplete,"UpdateReaderLength called after close");
#endif
ReadLength = position;
if(!(ReadLength <= WriteLength))
{
throw new ArgumentOutOfRangeException( "position" );
}
// safe for them to check and remove unused buffers.
CheckIfCanRemoveFromArrayList(position,WriterBufferArrayList,
ref _writerFirstBufferPosition);
}
/// <summary>
/// Closes the Writer Stream
/// </summary>
internal void WriterClose()
{
#if DEBUG
_writeComplete = true;
#endif
}
#endregion WriterCallbacks
#region ReaderCallbacks
/// <summary>
/// Reads the specified number of bytes into the buffer
/// </summary>
/// <param name="buffer">buffer to add the bytes</param>
/// <param name="offset">zero base starting offset</param>
/// <param name="count">number of bytes to read</param>
/// <returns></returns>
internal int Read(byte[] buffer, int offset, int count)
{
if(!(count + ReadPosition <= ReadLength))
{
throw new ArgumentOutOfRangeException( "count" );
}
int bufferOffset;
int bufferIndex;
byte[] readBuffer = GetBufferFromFilePosition(
ReadPosition,true /*reader*/,
out bufferOffset, out bufferIndex);
Debug.Assert(bufferOffset < BufferSize,"Calculated bufferOffset is greater than buffer");
// see how many bytes we can read from this buffer.
int availableBytesInBuffer = BufferSize - bufferOffset;
int leftOverBytes = 0;
int bufferReadCount = 0;
// check if ther is enough room in the write buffer to meet the
// request or if there will be leftOverBytes.
if (count > availableBytesInBuffer)
{
bufferReadCount = availableBytesInBuffer;
leftOverBytes = count - availableBytesInBuffer;
}
else
{
leftOverBytes = 0;
bufferReadCount = count;
}
Debug.Assert(0 < bufferReadCount,"Not reading any bytes to the buffer");
for (int loopCount = 0; loopCount < bufferReadCount; loopCount++)
{
// make sure not going over the buffer.
Debug.Assert(bufferOffset < BufferSize,"Trying ot read past buffer");
buffer[offset++] = readBuffer[bufferOffset++];
}
// update the read position
ReadPosition += bufferReadCount;
if (leftOverBytes > 0)
{
Read(buffer,offset,(int) leftOverBytes);
}
return count;
}
/// <summary>
/// Called to Read a Byte from the file. for now we allocate a byte
/// and call the standard Read method.
/// </summary>
/// <returns></returns>
internal int ReadByte()
{
// todo, make a better implementation.
byte[] buffer = new byte[1];
// uses Read to validate if reading past the end of the file.
Read(buffer,0,1);
return (int) buffer[0];
}
/// <summary>
/// Adjusts the Reader Seek position.
/// </summary>
/// <param name="offset">offset for the seek</param>
/// <param name="loc">defines relative offset </param>
/// <returns></returns>
internal long ReaderSeek(long offset, SeekOrigin loc)
{
switch(loc)
{
case SeekOrigin.Begin:
ReadPosition = (int) offset;
break;
case SeekOrigin.Current:
ReadPosition = (int) (ReadPosition + offset);
break;
case SeekOrigin.End:
throw new NotSupportedException(SR.Get(SRID.ParserWriterNoSeekEnd));
default:
throw new ArgumentException(SR.Get(SRID.ParserWriterUnknownOrigin));
}
// validate if at a good readPosition.
if((!(ReadPosition >= ReaderFirstBufferPosition))
||
(!(ReadPosition < ReadLength)))
{
throw new ArgumentOutOfRangeException( "offset" );
}
return ReadPosition;
}
/// <summary>
/// called by Reader to tell us it is done with everything
/// up to the given position. Once making this call the
/// Reader can no long reader at and before the position.
/// </summary>
/// <param name="position"></param>
internal void ReaderDoneWithFileUpToPosition(long position)
{
// call CheckIfCanRemove to update the readers BufferPositions
// and do any cleanup.
CheckIfCanRemoveFromArrayList(position,ReaderBufferArrayList,
ref _readerFirstBufferPosition);
}
#endregion ReaderCallbacks
#region PrivateMethods
/// <summary>
/// Given a position in the Stream returns the buffer and
/// start offset position in the buffer
/// </summary>
byte[] GetBufferFromFilePosition(long position,bool reader,
out int bufferOffset,out int bufferIndex)
{
byte[] buffer = null;
// get bufferArray and firstBuffer position based
// on if being called by the reader or the writer.
ArrayList bufferArray; // arraylist of buffers
long firstBufferPosition; // absolute file position of first buffer in the arrayList
// Ensure that while buffer and buffer position are stable while calculating
// buffer offsets and retrieving the buffer. The tokenizer thread can call
// CheckIfCanRemoveFromArrayList, which uses this same lock when modifying the
// writer buffer.
_bufferLock.AcquireWriterLock(-1);
if (reader)
{
bufferArray = ReaderBufferArrayList;
firstBufferPosition = ReaderFirstBufferPosition;
}
else
{
bufferArray = WriterBufferArrayList;
firstBufferPosition = WriterFirstBufferPosition;
}
// calc get the bufferIndex
bufferIndex = (int) ((position - firstBufferPosition)/BufferSize);
// calc the byte offset in the buffer for the position
bufferOffset =
(int) ((position - firstBufferPosition) - (bufferIndex*BufferSize));
Debug.Assert(bufferOffset < BufferSize,"Calculated bufferOffset is greater than buffer");
// check if we need to allocate a new buffer.
if (bufferArray.Count <= bufferIndex)
{
Debug.Assert(bufferArray.Count == bufferIndex,"Need to allocate more than one buffer");
Debug.Assert(false == reader,"Allocating a buffer on Read");
buffer = new byte[BufferSize];
// add to both the reader and writer ArrayLists.
ReaderBufferArrayList.Add(buffer);
WriterBufferArrayList.Add(buffer);
}
else
{
// just use the buffer that is there.
buffer = bufferArray[bufferIndex] as byte[];
}
_bufferLock.ReleaseWriterLock();
return buffer;
}
/// <summary>
/// helper function called by to check is any memory buffers
/// can be safely removed.
/// </summary>
/// <param name="position">Absolute File Position</param>
/// <param name="arrayList">ArrayList containing the Memory</param>
/// <param name="firstBufferPosition">If any arrays are cleaned up returns the
/// updated position that the first array in the buffer starts at</param>
void CheckIfCanRemoveFromArrayList(long position,ArrayList arrayList,ref long firstBufferPosition)
{
// see if there are any buffers we can get rid of.
int bufferIndex = (int) ((position - firstBufferPosition)/BufferSize);
if (bufferIndex > 0)
{
// we can safely remove all previous buffers from the ArrayList.
int numBuffersToRemove = bufferIndex;
// Ensure that while modifying the buffer position and buffer list that
// another thread can't get partially updated information while
// calling GetBufferFromFilePosition().
_bufferLock.AcquireWriterLock(-1);
// update buffer position offset for number of buffers to be
// removed.
firstBufferPosition += numBuffersToRemove*BufferSize;
arrayList.RemoveRange(0,bufferIndex);
_bufferLock.ReleaseWriterLock();
}
}
#endregion PrivateMethods
#region Properties
/// <summary>
/// WriterStream instance
/// </summary>
internal WriterStream WriterStream
{
get { return _writerStream; }
}
/// <summary>
/// ReaderStream instance
/// </summary>
internal ReaderStream ReaderStream
{
get { return _readerStream; }
}
/// <summary>
/// Current position inthe Reader stream
/// </summary>
internal long ReadPosition
{
get { return _readPosition; }
set { _readPosition = value; }
}
/// <summary>
/// Length of the Reader stream
/// </summary>
internal long ReadLength
{
get { return _readLength; }
set { _readLength = value; }
}
/// <summary>
/// Current position in the writer stream
/// </summary>
internal long WritePosition
{
get { return _writePosition ; }
set { _writePosition = value; }
}
/// <summary>
/// current length of the writer stream
/// </summary>
internal long WriteLength
{
get { return _writeLength ; }
set { _writeLength = value; }
}
/// <summary>
/// Constant Buffer size to be used for all allocated buffers
/// </summary>
int BufferSize
{
get { return _bufferSize; }
}
/// <summary>
/// File Position that the first buffer in the Readers array of buffer starts at
/// </summary>
long ReaderFirstBufferPosition
{
get { return _readerFirstBufferPosition ; }
set { _readerFirstBufferPosition = value; }
}
/// <summary>
/// File Position that the first buffer in the Writers array of buffer starts at
/// </summary>
long WriterFirstBufferPosition
{
get { return _writerFirstBufferPosition ; }
set { _writerFirstBufferPosition = value; }
}
/// <summary>
/// ArrayList containing all the buffers used by the Reader
/// </summary>
ArrayList ReaderBufferArrayList
{
get { return _readerBufferArrayList ; }
set { _readerBufferArrayList = value; }
}
/// <summary>
/// ArrayList of all the buffers used by the Writer.
/// </summary>
ArrayList WriterBufferArrayList
{
get { return _writerBufferArrayList ; }
set { _writerBufferArrayList = value; }
}
#if DEBUG
/// <summary>
/// Set when all bytes have been written
/// </summary>
internal bool WriteComplete
{
get { return _writeComplete; }
}
#endif
#endregion Properties
#region Data
long _readPosition;
long _readLength;
long _writePosition;
long _writeLength;
ReaderWriterLock _bufferLock;
WriterStream _writerStream;
ReaderStream _readerStream;
long _readerFirstBufferPosition;
long _writerFirstBufferPosition;
ArrayList _readerBufferArrayList;
ArrayList _writerBufferArrayList;
#if DEBUG
bool _writeComplete;
#endif
// size of each allocated buffer.
private const int _bufferSize = 4096;
#endregion Data
}
/// <summary>
/// Writer Stream class.
/// This is the Stream implementation the Writer sees.
/// </summary>
internal class WriterStream : Stream
{
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="streamManager">StreamManager that the writer stream should use</param>
internal WriterStream(ReadWriteStreamManager streamManager)
{
_streamManager = streamManager;
}
#endregion Constructor
#region overrides
/// <summary>
/// Override of Stream.CanRead
/// </summary>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Override of Stream.CanSeek
/// </summary>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// Override of Stream.CanWrite
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Override of Stream.Close
/// </summary>
public override void Close()
{
StreamManager.WriterClose();
}
/// <summary>
/// Override of Stream.Flush
/// </summary>
public override void Flush()
{
return; // nothing to Flush
}
/// <summary>
/// Override of Stream.Length
/// </summary>
public override long Length
{
get
{
return StreamManager.WriteLength;
}
}
/// <summary>
/// Override of Stream.Position
/// </summary>
public override long Position
{
get
{
return -1;
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Override of Stream.Read
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Override of Stream.ReadByte
/// </summary>
public override int ReadByte()
{
throw new NotSupportedException();
}
/// <summary>
/// Override of Stream.Seek
/// </summary>
public override long Seek(long offset, SeekOrigin loc)
{
return StreamManager.WriterSeek(offset,loc);
}
/// <summary>
/// Override of Stream.SetLength
/// </summary>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Override of Stream.Write
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
StreamManager.Write(buffer,offset,count);
}
#endregion overrides
#region Methods
/// <summary>
/// Called by the writer to say its okay to let the reader see what
/// it has written up to the position.
/// </summary>
/// <param name="position">Absolute position inthe file</param>
internal void UpdateReaderLength(long position)
{
StreamManager.UpdateReaderLength(position);
}
#endregion Methods
#region Properties
/// <summary>
/// StreamManager for the writer stream
/// </summary>
ReadWriteStreamManager StreamManager
{
get { return _streamManager; }
}
#endregion Properties
#region Data
ReadWriteStreamManager _streamManager;
#endregion Data
}
/// <summary>
/// Reader Stream class
/// This is the Stream implementation the Writer sees.
/// </summary>
internal class ReaderStream : Stream
{
#region Constructor
internal ReaderStream(ReadWriteStreamManager streamManager)
{
_streamManager = streamManager;
}
#endregion Constructor
#region overrides
/// <summary>
/// Override of Stream.CanRead
/// </summary>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// Override of Stream.CanSeek
/// </summary>
public override bool CanSeek
{
get { return true; }
}
/// <summary>
/// Override of Stream.CanWrite
/// </summary>
public override bool CanWrite
{
get { return false; }
}
/// <summary>
/// Override of Stream.Close
/// </summary>
public override void Close()
{
Debug.Assert(false,"Close called on ReaderStream");
}
/// <summary>
/// Override of Stream.Flush
/// </summary>
public override void Flush()
{
Debug.Assert(false,"Flush called on ReaderStream");
}
/// <summary>
/// Override of Stream.Length
/// </summary>
public override long Length
{
get
{
return StreamManager.ReadLength;
}
}
/// <summary>
/// Override of Stream.Position
/// </summary>
public override long Position
{
get
{
return StreamManager.ReadPosition;
}
set
{
StreamManager.ReaderSeek(value,SeekOrigin.Begin);
}
}
/// <summary>
/// Override of Stream.Read
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
return StreamManager.Read(buffer,offset,count);
}
/// <summary>
/// Override of Stream.ReadByte
/// </summary>
public override int ReadByte()
{
return StreamManager.ReadByte();
}
/// <summary>
/// Override of Stream.Seek
/// </summary>
public override long Seek(long offset, SeekOrigin loc)
{
return StreamManager.ReaderSeek(offset,loc);
}
/// <summary>
/// Override of Stream.SetLength
/// </summary>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Override of Stream.Write
/// </summary>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
#endregion Overrides
#region Methods
/// <summary>
/// Called by the reader to indicate all bytes up to and
/// including the position are no longer needed
/// After making this call the reader cannot go back and
/// read this data
/// </summary>
/// <param name="position"></param>
internal void ReaderDoneWithFileUpToPosition(long position)
{
StreamManager.ReaderDoneWithFileUpToPosition(position);
}
#if DEBUG
internal bool IsWriteComplete
{
get { return StreamManager.WriteComplete; }
}
#endif
#endregion Methods
#region Properties
/// <summary>
/// StreamManager that this class should use
/// </summary>
ReadWriteStreamManager StreamManager
{
get { return _streamManager; }
}
#endregion Properties
#region Data
ReadWriteStreamManager _streamManager;
#endregion Data
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.FaultHandling;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence.Repositories
{
//TODO: We need to get a readonly ISO code for the domain assigned
internal class DomainRepository : PetaPocoRepositoryBase<int, IDomain>, IDomainRepository
{
public DomainRepository(IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax)
: base(work, cache, logger, sqlSyntax)
{
}
protected override IRepositoryCachePolicy<IDomain, int> CreateCachePolicy(IRuntimeCacheProvider runtimeCache)
{
return new FullDataSetRepositoryCachePolicy<IDomain, int>(runtimeCache, GetEntityId, /*expires:*/ false);
}
protected override IDomain PerformGet(int id)
{
//use the underlying GetAll which will force cache all domains
return GetAll().FirstOrDefault(x => x.Id == id);
}
protected override IEnumerable<IDomain> PerformGetAll(params int[] ids)
{
var sql = GetBaseQuery(false).Where("umbracoDomains.id > 0");
if (ids.Any())
{
sql.Where("umbracoDomains.id in (@ids)", new { ids = ids });
}
return Database.Fetch<DomainDto>(sql).Select(ConvertFromDto);
}
protected override IEnumerable<IDomain> PerformGetByQuery(IQuery<IDomain> query)
{
throw new NotSupportedException("This repository does not support this method");
}
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<DomainDto>(SqlSyntax);
}
else
{
sql.Select("umbracoDomains.*, umbracoLanguage.languageISOCode")
.From<DomainDto>(SqlSyntax)
.LeftJoin<LanguageDto>(SqlSyntax)
.On<DomainDto, LanguageDto>(SqlSyntax, dto => dto.DefaultLanguage, dto => dto.Id);
}
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoDomains.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM umbracoDomains WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IDomain entity)
{
var exists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoDomains WHERE domainName = @domainName", new { domainName = entity.DomainName });
if (exists > 0) throw new DuplicateNameException(string.Format("The domain name {0} is already assigned", entity.DomainName));
if (entity.RootContentId.HasValue)
{
var contentExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM cmsContent WHERE nodeId = @id", new { id = entity.RootContentId.Value });
if (contentExists == 0) throw new NullReferenceException("No content exists with id " + entity.RootContentId.Value);
}
if (entity.LanguageId.HasValue)
{
var languageExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoLanguage WHERE id = @id", new { id = entity.LanguageId.Value });
if (languageExists == 0) throw new NullReferenceException("No language exists with id " + entity.LanguageId.Value);
}
((UmbracoDomain)entity).AddingEntity();
var factory = new DomainModelFactory();
var dto = factory.BuildDto(entity);
var id = Convert.ToInt32(Database.Insert(dto));
entity.Id = id;
//if the language changed, we need to resolve the ISO code!
if (entity.LanguageId.HasValue)
{
((UmbracoDomain)entity).LanguageIsoCode = Database.ExecuteScalar<string>("SELECT languageISOCode FROM umbracoLanguage WHERE id=@langId", new { langId = entity.LanguageId });
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IDomain entity)
{
((UmbracoDomain)entity).UpdatingEntity();
var exists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoDomains WHERE domainName = @domainName AND umbracoDomains.id <> @id",
new { domainName = entity.DomainName, id = entity.Id });
//ensure there is no other domain with the same name on another entity
if (exists > 0) throw new DuplicateNameException(string.Format("The domain name {0} is already assigned", entity.DomainName));
if (entity.RootContentId.HasValue)
{
var contentExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM cmsContent WHERE nodeId = @id", new { id = entity.RootContentId.Value });
if (contentExists == 0) throw new NullReferenceException("No content exists with id " + entity.RootContentId.Value);
}
if (entity.LanguageId.HasValue)
{
var languageExists = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoLanguage WHERE id = @id", new { id = entity.LanguageId.Value });
if (languageExists == 0) throw new NullReferenceException("No language exists with id " + entity.LanguageId.Value);
}
var factory = new DomainModelFactory();
var dto = factory.BuildDto(entity);
Database.Update(dto);
//if the language changed, we need to resolve the ISO code!
if (entity.WasPropertyDirty("LanguageId"))
{
((UmbracoDomain)entity).LanguageIsoCode = Database.ExecuteScalar<string>("SELECT languageISOCode FROM umbracoLanguage WHERE id=@langId", new {langId = entity.LanguageId});
}
entity.ResetDirtyProperties();
}
public IDomain GetByName(string domainName)
{
return GetAll().FirstOrDefault(x => x.DomainName.InvariantEquals(domainName));
}
public bool Exists(string domainName)
{
return GetAll().Any(x => x.DomainName.InvariantEquals(domainName));
}
public IEnumerable<IDomain> GetAll(bool includeWildcards)
{
return GetAll().Where(x => includeWildcards || x.IsWildcard == false);
}
public IEnumerable<IDomain> GetAssignedDomains(int contentId, bool includeWildcards)
{
return GetAll()
.Where(x => x.RootContentId == contentId)
.Where(x => includeWildcards || x.IsWildcard == false);
}
private IDomain ConvertFromDto(DomainDto dto)
{
var factory = new DomainModelFactory();
var entity = factory.BuildEntity(dto);
return entity;
}
internal class DomainModelFactory
{
public IDomain BuildEntity(DomainDto dto)
{
var domain = new UmbracoDomain(dto.DomainName, dto.IsoCode)
{
Id = dto.Id,
LanguageId = dto.DefaultLanguage,
RootContentId = dto.RootStructureId
};
//on initial construction we don't want to have dirty properties tracked
// http://issues.umbraco.org/issue/U4-1946
domain.ResetDirtyProperties(false);
return domain;
}
public DomainDto BuildDto(IDomain entity)
{
var dto = new DomainDto { DefaultLanguage = entity.LanguageId, DomainName = entity.DomainName, Id = entity.Id, RootStructureId = entity.RootContentId };
return dto;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.BigQuery.Storage.V1.Snippets
{
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedBigQueryReadClientSnippets
{
/// <summary>Snippet for CreateReadSession</summary>
public void CreateReadSessionRequestObject()
{
// Snippet: CreateReadSession(CreateReadSessionRequest, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 0,
};
// Make the request
ReadSession response = bigQueryReadClient.CreateReadSession(request);
// End snippet
}
/// <summary>Snippet for CreateReadSessionAsync</summary>
public async Task CreateReadSessionRequestObjectAsync()
{
// Snippet: CreateReadSessionAsync(CreateReadSessionRequest, CallSettings)
// Additional: CreateReadSessionAsync(CreateReadSessionRequest, CancellationToken)
// Create client
BigQueryReadClient bigQueryReadClient = await BigQueryReadClient.CreateAsync();
// Initialize request argument(s)
CreateReadSessionRequest request = new CreateReadSessionRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
ReadSession = new ReadSession(),
MaxStreamCount = 0,
};
// Make the request
ReadSession response = await bigQueryReadClient.CreateReadSessionAsync(request);
// End snippet
}
/// <summary>Snippet for CreateReadSession</summary>
public void CreateReadSession()
{
// Snippet: CreateReadSession(string, ReadSession, int, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
ReadSession readSession = new ReadSession();
int maxStreamCount = 0;
// Make the request
ReadSession response = bigQueryReadClient.CreateReadSession(parent, readSession, maxStreamCount);
// End snippet
}
/// <summary>Snippet for CreateReadSessionAsync</summary>
public async Task CreateReadSessionAsync()
{
// Snippet: CreateReadSessionAsync(string, ReadSession, int, CallSettings)
// Additional: CreateReadSessionAsync(string, ReadSession, int, CancellationToken)
// Create client
BigQueryReadClient bigQueryReadClient = await BigQueryReadClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
ReadSession readSession = new ReadSession();
int maxStreamCount = 0;
// Make the request
ReadSession response = await bigQueryReadClient.CreateReadSessionAsync(parent, readSession, maxStreamCount);
// End snippet
}
/// <summary>Snippet for CreateReadSession</summary>
public void CreateReadSessionResourceNames()
{
// Snippet: CreateReadSession(ProjectName, ReadSession, int, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
ReadSession readSession = new ReadSession();
int maxStreamCount = 0;
// Make the request
ReadSession response = bigQueryReadClient.CreateReadSession(parent, readSession, maxStreamCount);
// End snippet
}
/// <summary>Snippet for CreateReadSessionAsync</summary>
public async Task CreateReadSessionResourceNamesAsync()
{
// Snippet: CreateReadSessionAsync(ProjectName, ReadSession, int, CallSettings)
// Additional: CreateReadSessionAsync(ProjectName, ReadSession, int, CancellationToken)
// Create client
BigQueryReadClient bigQueryReadClient = await BigQueryReadClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
ReadSession readSession = new ReadSession();
int maxStreamCount = 0;
// Make the request
ReadSession response = await bigQueryReadClient.CreateReadSessionAsync(parent, readSession, maxStreamCount);
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRowsRequestObject()
{
// Snippet: ReadRows(ReadRowsRequest, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
ReadRowsRequest request = new ReadRowsRequest
{
ReadStreamAsReadStreamName = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]"),
Offset = 0L,
};
// Make the request, returning a streaming response
BigQueryReadClient.ReadRowsStream response = bigQueryReadClient.ReadRows(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRows()
{
// Snippet: ReadRows(string, long, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
string readStream = "projects/[PROJECT]/locations/[LOCATION]/sessions/[SESSION]/streams/[STREAM]";
long offset = 0L;
// Make the request, returning a streaming response
BigQueryReadClient.ReadRowsStream response = bigQueryReadClient.ReadRows(readStream, offset);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ReadRows</summary>
public async Task ReadRowsResourceNames()
{
// Snippet: ReadRows(ReadStreamName, long, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
ReadStreamName readStream = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]");
long offset = 0L;
// Make the request, returning a streaming response
BigQueryReadClient.ReadRowsStream response = bigQueryReadClient.ReadRows(readStream, offset);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<ReadRowsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ReadRowsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for SplitReadStream</summary>
public void SplitReadStreamRequestObject()
{
// Snippet: SplitReadStream(SplitReadStreamRequest, CallSettings)
// Create client
BigQueryReadClient bigQueryReadClient = BigQueryReadClient.Create();
// Initialize request argument(s)
SplitReadStreamRequest request = new SplitReadStreamRequest
{
ReadStreamName = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]"),
Fraction = 0,
};
// Make the request
SplitReadStreamResponse response = bigQueryReadClient.SplitReadStream(request);
// End snippet
}
/// <summary>Snippet for SplitReadStreamAsync</summary>
public async Task SplitReadStreamRequestObjectAsync()
{
// Snippet: SplitReadStreamAsync(SplitReadStreamRequest, CallSettings)
// Additional: SplitReadStreamAsync(SplitReadStreamRequest, CancellationToken)
// Create client
BigQueryReadClient bigQueryReadClient = await BigQueryReadClient.CreateAsync();
// Initialize request argument(s)
SplitReadStreamRequest request = new SplitReadStreamRequest
{
ReadStreamName = ReadStreamName.FromProjectLocationSessionStream("[PROJECT]", "[LOCATION]", "[SESSION]", "[STREAM]"),
Fraction = 0,
};
// Make the request
SplitReadStreamResponse response = await bigQueryReadClient.SplitReadStreamAsync(request);
// End snippet
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Buffers;
using System.Threading.Tasks;
using System.Reflection;
using System.Collections.Generic;
using SuperSocket;
using SuperSocket.Command;
using SuperSocket.ProtoBase;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
using SuperSocket.Server;
using System.Threading;
using SuperSocket.Tests.Command;
namespace SuperSocket.Tests
{
[Trait("Category", "Command")]
public class CommandTest : TestClassBase
{
public CommandTest(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
public async Task TestCommands(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
// register commands one by one
commandOptions.AddCommand<ADD>();
commandOptions.AddCommand<MULT>();
commandOptions.AddCommand<SUB>();
// register all commands in one assembly
//commandOptions.AddCommandAssembly(typeof(SUB).GetTypeInfo().Assembly);
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
await streamWriter.WriteAsync("ADD 1 2 3\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal("6", line);
await streamWriter.WriteAsync("MULT 2 5\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("10", line);
await streamWriter.WriteAsync("SUB 8 2\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("6", line);
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
public async Task TestCommandsFromAssembly(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
// register all commands in one assembly
commandOptions.AddCommandAssembly(typeof(MIN).GetTypeInfo().Assembly);
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
await streamWriter.WriteAsync("MIN 8 6 3\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal("3", line);
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
public async Task TestCommandsFromConfigAssembly(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
// register all commands in one assembly
commandOptions.Assemblies = new [] { new CommandAssemblyConfig { Name = "SuperSocket.Tests.Command" } };
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
await streamWriter.WriteAsync("MIN 8 6 3\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal("3", line);
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[Trait("Category", "JsonCommands")]
public async Task TestJsonCommands(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
// register commands one by one
commandOptions.AddCommand<POW>();
commandOptions.AddCommand<MAX>();
}).BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
await streamWriter.WriteAsync("POW { \"x\": 2, \"y\": 2 }\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal("4", line);
await streamWriter.WriteAsync("MAX { \"numbers\": [ 45, 77, 6, 88, 46 ] }\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("88", line);
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
public async Task TestCommandsWithCustomSession(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
// register commands one by one
/*
commandOptions.AddCommand<ADD>();
commandOptions.AddCommand<MULT>();
commandOptions.AddCommand<SUB>();
commandOptions.AddCommand<DIV>();
*/
// register all commands in one assembly
commandOptions.AddCommandAssembly(typeof(SUB).GetTypeInfo().Assembly);
})
.UseSession<MySession>()
.BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
await streamWriter.WriteAsync("ADD 1 2 3\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal("6", line);
await streamWriter.WriteAsync("MULT 2 5\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("10", line);
await streamWriter.WriteAsync("SUB 8 2\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("6", line);
await streamWriter.WriteAsync("DIV 8 2\r\n");
await streamWriter.FlushAsync();
line = await streamReader.ReadLineAsync();
Assert.Equal("4", line);
}
await server.StopAsync();
}
}
class HitCountCommandFilterAttribute : AsyncCommandFilterAttribute
{
private static int _total;
public static int Total
{
get { return _total; }
}
public override ValueTask OnCommandExecutedAsync(CommandExecutingContext commandContext)
{
Interlocked.Increment(ref _total);
return new ValueTask();
}
public override ValueTask<bool> OnCommandExecutingAsync(CommandExecutingContext commandContext)
{
return new ValueTask<bool>(true);
}
}
class IncreaseCountCommandFilterAttribute : AsyncCommandFilterAttribute
{
public override ValueTask OnCommandExecutedAsync(CommandExecutingContext commandContext)
{
return new ValueTask();
}
public override ValueTask<bool> OnCommandExecutingAsync(CommandExecutingContext commandContext)
{
var sessionState = commandContext.Session.DataContext as SessionState;
sessionState.ExecutionCount++;
return new ValueTask<bool>(true);
}
}
class DecreaseCountCommandFilterAttribute : CommandFilterAttribute
{
public override void OnCommandExecuted(CommandExecutingContext commandContext)
{
}
public override bool OnCommandExecuting(CommandExecutingContext commandContext)
{
var sessionState = commandContext.Session.DataContext as SessionState;
sessionState.ExecutionCount--;
return true;
}
}
[IncreaseCountCommandFilter]
class COUNT : IAsyncCommand<StringPackageInfo>
{
private IPackageEncoder<string> _encoder;
public COUNT(IPackageEncoder<string> encoder)
{
_encoder = encoder;
}
public async ValueTask ExecuteAsync(IAppSession session, StringPackageInfo package)
{
await session.SendAsync(_encoder, "OK\r\n");
}
}
[DecreaseCountCommandFilter]
class COUNTDOWN : IAsyncCommand<StringPackageInfo>
{
private IPackageEncoder<string> _encoder;
public COUNTDOWN(IPackageEncoder<string> encoder)
{
_encoder = encoder;
}
public async ValueTask ExecuteAsync(IAppSession session, StringPackageInfo package)
{
await session.SendAsync(_encoder, "OK\r\n");
}
}
class SessionState
{
public int ExecutionCount { get; set; }
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
public async Task TestCommandFilter(Type hostConfiguratorType)
{
var sessionState = new SessionState();
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator)
.UseCommand(commandOptions =>
{
commandOptions.AddCommand<COUNT>();
commandOptions.AddCommand<COUNTDOWN>();
commandOptions.AddGlobalCommandFilter<HitCountCommandFilterAttribute>();
})
.UseSessionHandler((s) =>
{
s.DataContext = sessionState;
return new ValueTask();
})
.BuildAsServer())
{
Assert.Equal("TestServer", server.Name);
Assert.True(await server.StartAsync());
OutputHelper.WriteLine("Server started.");
var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await client.ConnectAsync(hostConfigurator.GetServerEndPoint());
OutputHelper.WriteLine("Connected.");
using (var stream = await hostConfigurator.GetClientStream(client))
using (var streamReader = new StreamReader(stream, Utf8Encoding, true))
using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4))
{
var currentTotal = HitCountCommandFilterAttribute.Total;
for (var i = 1; i <= 100; i++)
{
await streamWriter.WriteAsync("COUNT\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal(i, sessionState.ExecutionCount);
}
Assert.Equal(currentTotal + 100, HitCountCommandFilterAttribute.Total);
for (var i = 99; i >= 0; i--)
{
await streamWriter.WriteAsync("COUNTDOWN\r\n");
await streamWriter.FlushAsync();
var line = await streamReader.ReadLineAsync();
Assert.Equal(i, sessionState.ExecutionCount);
}
Assert.Equal(currentTotal + 200, HitCountCommandFilterAttribute.Total);
}
await server.StopAsync();
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Linq;
using System.Collections.Generic;
[CustomEditor(typeof(tk2dStaticSpriteBatcher))]
class tk2dStaticSpriteBatcherEditor : Editor
{
tk2dStaticSpriteBatcher batcher { get { return (tk2dStaticSpriteBatcher)target; } }
// Like GetComponentsInChildren, but doesn't include self
T[] GetComponentsInChildrenExcludeSelf<T>(Transform root) where T : Component {
List<T> allTransforms = new List<T>( root.GetComponentsInChildren<T>() );
return (from t in allTransforms where t.transform != root select t).ToArray();
}
void DrawEditorGUI()
{
if (GUILayout.Button("Commit"))
{
// Select all children, EXCLUDING self
Transform[] allTransforms = batcher.transform.GetComponentsInChildren<Transform>();
allTransforms = (from t in allTransforms where t != batcher.transform select t).ToArray();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Renderer[] allRenderers = batcher.transform.GetComponentsInChildren<Renderer>();
allRenderers = (from r in allRenderers where r != batcher.GetComponent<Renderer>() select r).ToArray();
if (allRenderers.Length > 0) {
string sortingLayerName = allRenderers[0].sortingLayerName;
int sortingOrder = allRenderers[0].sortingOrder;
foreach (Renderer r in allRenderers) {
if (sortingLayerName != r.sortingLayerName ||
sortingOrder != r.sortingOrder) {
EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: Child objects use different sorting layer names and/or sorting orders.\n\nOnly one sorting layer and order is permitted in a static sprite batcher.", "Ok");
return;
}
}
}
#endif
// sort sprites, smaller to larger z
if (batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.SortToCamera)) {
tk2dCamera tk2dCam = tk2dCamera.CameraForLayer( batcher.gameObject.layer );
Camera cam = tk2dCam ? tk2dCam.GetComponent<Camera>() : Camera.main;
allTransforms = (from t in allTransforms orderby cam.WorldToScreenPoint((t.GetComponent<Renderer>() != null) ? t.GetComponent<Renderer>().bounds.center : t.position).z descending select t).ToArray();
}
else {
allTransforms = (from t in allTransforms orderby ((t.GetComponent<Renderer>() != null) ? t.GetComponent<Renderer>().bounds.center : t.position).z descending select t).ToArray();
}
// and within the z sort by material
if (allTransforms.Length == 0)
{
EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: No child objects found", "Ok");
return;
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
MeshCollider[] childMeshColliders = GetComponentsInChildrenExcludeSelf<MeshCollider>(batcher.transform);
BoxCollider[] childBoxColliders = GetComponentsInChildrenExcludeSelf<BoxCollider>(batcher.transform);
BoxCollider2D[] childBoxCollider2Ds = GetComponentsInChildrenExcludeSelf<BoxCollider2D>(batcher.transform);
EdgeCollider2D[] childEdgeCollider2Ds = GetComponentsInChildrenExcludeSelf<EdgeCollider2D>(batcher.transform);
PolygonCollider2D[] childPolygonCollider2Ds = GetComponentsInChildrenExcludeSelf<PolygonCollider2D>(batcher.transform);
if ((childMeshColliders.Length > 0 || childBoxColliders.Length > 0) && (childBoxCollider2Ds.Length > 0 || childEdgeCollider2Ds.Length > 0 || childPolygonCollider2Ds.Length > 0)) {
EditorUtility.DisplayDialog("StaticSpriteBatcher", "Error: Can't mix 2D and 3D colliders", "Ok");
return;
}
#endif
Dictionary<Transform, int> batchedSpriteLookup = new Dictionary<Transform, int>();
batchedSpriteLookup[batcher.transform] = -1;
Matrix4x4 batcherWorldToLocal = batcher.transform.worldToLocalMatrix;
batcher.spriteCollection = null;
batcher.batchedSprites = new tk2dBatchedSprite[allTransforms.Length];
List<tk2dTextMeshData> allTextMeshData = new List<tk2dTextMeshData>();
int currBatchedSprite = 0;
foreach (var t in allTransforms)
{
tk2dBaseSprite baseSprite = t.GetComponent<tk2dBaseSprite>();
tk2dTextMesh textmesh = t.GetComponent<tk2dTextMesh>();
tk2dBatchedSprite bs = new tk2dBatchedSprite();
bs.name = t.gameObject.name;
bs.position = t.localPosition;
bs.rotation = t.localRotation;
bs.relativeMatrix = batcherWorldToLocal * t.localToWorldMatrix;
if (baseSprite)
{
bs.baseScale = Vector3.one;
bs.localScale = new Vector3(t.localScale.x * baseSprite.scale.x, t.localScale.y * baseSprite.scale.y, t.localScale.z * baseSprite.scale.z);
FillBatchedSprite(bs, t.gameObject);
// temp redundant - just incase batcher expects to point to a valid one, somewhere we've missed
batcher.spriteCollection = baseSprite.Collection;
}
else if (textmesh)
{
bs.spriteCollection = null;
bs.type = tk2dBatchedSprite.Type.TextMesh;
bs.color = textmesh.color;
bs.baseScale = textmesh.scale;
bs.renderLayer = textmesh.SortingOrder;
bs.localScale = new Vector3(t.localScale.x * textmesh.scale.x, t.localScale.y * textmesh.scale.y, t.localScale.z * textmesh.scale.z);
bs.FormattedText = textmesh.FormattedText;
tk2dTextMeshData tmd = new tk2dTextMeshData();
tmd.font = textmesh.font;
tmd.text = textmesh.text;
tmd.color = textmesh.color;
tmd.color2 = textmesh.color2;
tmd.useGradient = textmesh.useGradient;
tmd.textureGradient = textmesh.textureGradient;
tmd.anchor = textmesh.anchor;
tmd.kerning = textmesh.kerning;
tmd.maxChars = textmesh.maxChars;
tmd.inlineStyling = textmesh.inlineStyling;
tmd.formatting = textmesh.formatting;
tmd.wordWrapWidth = textmesh.wordWrapWidth;
tmd.spacing = textmesh.Spacing;
tmd.lineSpacing = textmesh.LineSpacing;
bs.xRefId = allTextMeshData.Count;
allTextMeshData.Add(tmd);
}
else
{
// Empty GameObject
bs.spriteId = -1;
bs.baseScale = Vector3.one;
bs.localScale = t.localScale;
bs.type = tk2dBatchedSprite.Type.EmptyGameObject;
}
batchedSpriteLookup[t] = currBatchedSprite;
batcher.batchedSprites[currBatchedSprite++] = bs;
}
batcher.allTextMeshData = allTextMeshData.ToArray();
int idx = 0;
foreach (var t in allTransforms)
{
var bs = batcher.batchedSprites[idx];
bs.parentId = batchedSpriteLookup[t.parent];
t.parent = batcher.transform; // unparent
++idx;
}
Transform[] directChildren = (from t in allTransforms where t.parent == batcher.transform select t).ToArray();
foreach (var t in directChildren)
{
GameObject.DestroyImmediate(t.gameObject);
}
Vector3 inverseScale = new Vector3(1.0f / batcher.scale.x, 1.0f / batcher.scale.y, 1.0f / batcher.scale.z);
batcher.transform.localScale = Vector3.Scale( batcher.transform.localScale, inverseScale );
batcher.Build();
EditorUtility.SetDirty(target);
}
}
static void RestoreBoxColliderSettings( GameObject go, float offset, float extents ) {
BoxCollider boxCollider = go.GetComponent<BoxCollider>();
if (boxCollider != null) {
Vector3 p = boxCollider.center;
p.z = offset;
boxCollider.center = p;
p = boxCollider.size;
p.z = extents * 2;
boxCollider.size = p;
}
}
public static void FillBatchedSprite(tk2dBatchedSprite bs, GameObject go) {
tk2dSprite srcSprite = go.transform.GetComponent<tk2dSprite>();
tk2dTiledSprite srcTiledSprite = go.transform.GetComponent<tk2dTiledSprite>();
tk2dSlicedSprite srcSlicedSprite = go.transform.GetComponent<tk2dSlicedSprite>();
tk2dClippedSprite srcClippedSprite = go.transform.GetComponent<tk2dClippedSprite>();
tk2dBaseSprite baseSprite = go.GetComponent<tk2dBaseSprite>();
bs.spriteId = baseSprite.spriteId;
bs.spriteCollection = baseSprite.Collection;
bs.baseScale = baseSprite.scale;
bs.color = baseSprite.color;
bs.renderLayer = baseSprite.SortingOrder;
if (baseSprite.boxCollider != null)
{
bs.BoxColliderOffsetZ = baseSprite.boxCollider.center.z;
bs.BoxColliderExtentZ = baseSprite.boxCollider.size.z * 0.5f;
}
else {
bs.BoxColliderOffsetZ = 0.0f;
bs.BoxColliderExtentZ = 1.0f;
}
if (srcSprite) {
bs.type = tk2dBatchedSprite.Type.Sprite;
}
else if (srcTiledSprite) {
bs.type = tk2dBatchedSprite.Type.TiledSprite;
bs.Dimensions = srcTiledSprite.dimensions;
bs.anchor = srcTiledSprite.anchor;
bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcTiledSprite.CreateBoxCollider);
}
else if (srcSlicedSprite) {
bs.type = tk2dBatchedSprite.Type.SlicedSprite;
bs.Dimensions = srcSlicedSprite.dimensions;
bs.anchor = srcSlicedSprite.anchor;
bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcSlicedSprite.CreateBoxCollider);
bs.SetFlag(tk2dBatchedSprite.Flags.SlicedSprite_BorderOnly, srcSlicedSprite.BorderOnly);
bs.SlicedSpriteBorderBottomLeft = new Vector2(srcSlicedSprite.borderLeft, srcSlicedSprite.borderBottom);
bs.SlicedSpriteBorderTopRight = new Vector2(srcSlicedSprite.borderRight, srcSlicedSprite.borderTop);
}
else if (srcClippedSprite) {
bs.type = tk2dBatchedSprite.Type.ClippedSprite;
bs.ClippedSpriteRegionBottomLeft = srcClippedSprite.clipBottomLeft;
bs.ClippedSpriteRegionTopRight = srcClippedSprite.clipTopRight;
bs.SetFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider, srcClippedSprite.CreateBoxCollider);
}
}
// This is used by other parts of code
public static void RestoreBatchedSprite(GameObject go, tk2dBatchedSprite bs) {
tk2dBaseSprite baseSprite = null;
switch (bs.type) {
case tk2dBatchedSprite.Type.EmptyGameObject:
{
break;
}
case tk2dBatchedSprite.Type.Sprite:
{
tk2dSprite s = tk2dBaseSprite.AddComponent<tk2dSprite>(go, bs.spriteCollection, bs.spriteId);
baseSprite = s;
break;
}
case tk2dBatchedSprite.Type.TiledSprite:
{
tk2dTiledSprite s = tk2dBaseSprite.AddComponent<tk2dTiledSprite>(go, bs.spriteCollection, bs.spriteId);
baseSprite = s;
s.dimensions = bs.Dimensions;
s.anchor = bs.anchor;
s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider);
RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ);
break;
}
case tk2dBatchedSprite.Type.SlicedSprite:
{
tk2dSlicedSprite s = tk2dBaseSprite.AddComponent<tk2dSlicedSprite>(go, bs.spriteCollection, bs.spriteId);
baseSprite = s;
s.dimensions = bs.Dimensions;
s.anchor = bs.anchor;
s.BorderOnly = bs.CheckFlag(tk2dBatchedSprite.Flags.SlicedSprite_BorderOnly);
s.SetBorder(bs.SlicedSpriteBorderBottomLeft.x, bs.SlicedSpriteBorderBottomLeft.y, bs.SlicedSpriteBorderTopRight.x, bs.SlicedSpriteBorderTopRight.y);
s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider);
RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ);
break;
}
case tk2dBatchedSprite.Type.ClippedSprite:
{
tk2dClippedSprite s = tk2dBaseSprite.AddComponent<tk2dClippedSprite>(go, bs.spriteCollection, bs.spriteId);
baseSprite = s;
s.clipBottomLeft = bs.ClippedSpriteRegionBottomLeft;
s.clipTopRight = bs.ClippedSpriteRegionTopRight;
s.CreateBoxCollider = bs.CheckFlag(tk2dBatchedSprite.Flags.Sprite_CreateBoxCollider);
RestoreBoxColliderSettings(s.gameObject, bs.BoxColliderOffsetZ, bs.BoxColliderExtentZ);
break;
}
}
if (baseSprite != null) {
baseSprite.SortingOrder = bs.renderLayer;
baseSprite.scale = bs.baseScale;
baseSprite.color = bs.color;
}
}
void DrawInstanceGUI()
{
if (GUILayout.Button("Edit"))
{
Vector3 batcherPos = batcher.transform.position;
Quaternion batcherRotation = batcher.transform.rotation;
batcher.transform.position = Vector3.zero;
batcher.transform.rotation = Quaternion.identity;
batcher.transform.localScale = Vector3.Scale(batcher.transform.localScale, batcher.scale);
Dictionary<int, Transform> parents = new Dictionary<int, Transform>();
List<Transform> children = new List<Transform>();
List<GameObject> gos = new List<GameObject>();
int id;
id = 0;
foreach (var bs in batcher.batchedSprites)
{
GameObject go = new GameObject(bs.name);
go.layer = batcher.gameObject.layer;
parents[id++] = go.transform;
children.Add(go.transform);
gos.Add (go);
}
id = 0;
foreach (var bs in batcher.batchedSprites)
{
Transform parent = batcher.transform;
if (bs.parentId != -1)
parents.TryGetValue(bs.parentId, out parent);
children[id++].parent = parent;
}
id = 0;
bool overrideSortingOrder = false;
int overridenSortingOrder = 0;
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
string overridenSortingLayerName = "";
if (batcher.GetComponent<Renderer>()) {
overrideSortingOrder = true;
overridenSortingOrder = batcher.GetComponent<Renderer>().sortingOrder;
overridenSortingLayerName = batcher.GetComponent<Renderer>().sortingLayerName;
}
#endif
foreach (var bs in batcher.batchedSprites)
{
GameObject go = gos[id];
go.transform.localPosition = bs.position;
go.transform.localRotation = bs.rotation;
{
float sx = bs.localScale.x / ((Mathf.Abs (bs.baseScale.x) > Mathf.Epsilon) ? bs.baseScale.x : 1.0f);
float sy = bs.localScale.y / ((Mathf.Abs (bs.baseScale.y) > Mathf.Epsilon) ? bs.baseScale.y : 1.0f);
float sz = bs.localScale.z / ((Mathf.Abs (bs.baseScale.z) > Mathf.Epsilon) ? bs.baseScale.z : 1.0f);
go.transform.localScale = new Vector3(sx, sy, sz);
}
if (overrideSortingOrder) {
bs.renderLayer = overridenSortingOrder;
}
if (bs.type == tk2dBatchedSprite.Type.TextMesh) {
tk2dTextMesh s = go.AddComponent<tk2dTextMesh>();
if (batcher.allTextMeshData == null || bs.xRefId == -1) {
Debug.LogError("Unable to find text mesh ref");
}
else {
tk2dTextMeshData tmd = batcher.allTextMeshData[bs.xRefId];
s.font = tmd.font;
s.scale = bs.baseScale;
s.SortingOrder = bs.renderLayer;
s.text = tmd.text;
s.color = bs.color;
s.color2 = tmd.color2;
s.useGradient = tmd.useGradient;
s.textureGradient = tmd.textureGradient;
s.anchor = tmd.anchor;
s.scale = bs.baseScale;
s.kerning = tmd.kerning;
s.maxChars = tmd.maxChars;
s.inlineStyling = tmd.inlineStyling;
s.formatting = tmd.formatting;
s.wordWrapWidth = tmd.wordWrapWidth;
s.Spacing = tmd.spacing;
s.LineSpacing = tmd.lineSpacing;
s.Commit();
}
}
else {
RestoreBatchedSprite(go, bs);
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (go.GetComponent<Renderer>() != null && overrideSortingOrder) {
go.GetComponent<Renderer>().sortingLayerName = overridenSortingLayerName;
}
#endif
++id;
}
batcher.batchedSprites = null;
batcher.Build();
EditorUtility.SetDirty(target);
batcher.transform.position = batcherPos;
batcher.transform.rotation = batcherRotation;
}
batcher.scale = EditorGUILayout.Vector3Field("Scale", batcher.scale);
batcher.SetFlag(tk2dStaticSpriteBatcher.Flags.GenerateCollider, EditorGUILayout.Toggle("Generate Collider", batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.GenerateCollider)));
batcher.SetFlag(tk2dStaticSpriteBatcher.Flags.FlattenDepth, EditorGUILayout.Toggle("Flatten Depth", batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.FlattenDepth)));
batcher.SetFlag(tk2dStaticSpriteBatcher.Flags.SortToCamera, EditorGUILayout.Toggle("Sort to Camera", batcher.CheckFlag(tk2dStaticSpriteBatcher.Flags.SortToCamera)));
MeshFilter meshFilter = batcher.GetComponent<MeshFilter>();
MeshRenderer meshRenderer = batcher.GetComponent<MeshRenderer>();
if (meshRenderer != null) {
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", meshRenderer.sortingLayerName);
if (sortingLayerName != meshRenderer.sortingLayerName) {
tk2dUndo.RecordObject(meshRenderer, "Sorting Layer");
meshRenderer.sortingLayerName = sortingLayerName;
}
int sortingOrder = EditorGUILayout.IntField("Order In Layer", meshRenderer.sortingOrder);
if (sortingOrder != meshRenderer.sortingOrder) {
tk2dUndo.RecordObject(meshRenderer, "Order In Layer");
meshRenderer.sortingOrder = sortingOrder;
}
#endif
}
if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null) {
GUILayout.Label("Stats", EditorStyles.boldLabel);
int numIndices = 0;
Mesh mesh = meshFilter.sharedMesh;
for (int i = 0; i < mesh.subMeshCount; ++i) {
numIndices += mesh.GetTriangles(i).Length;
}
GUILayout.Label(string.Format("Triangles: {0}\nMaterials: {1}", numIndices / 3, meshRenderer.sharedMaterials.Length ));
}
}
public override void OnInspectorGUI()
{
if (batcher.batchedSprites == null || batcher.batchedSprites.Length == 0) {
DrawEditorGUI();
}
else {
DrawInstanceGUI();
}
}
[MenuItem(tk2dMenu.createBase + "Static Sprite Batcher", false, 13849)]
static void DoCreateSpriteObject()
{
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Static Sprite Batcher");
tk2dStaticSpriteBatcher batcher = go.AddComponent<tk2dStaticSpriteBatcher>();
batcher.version = tk2dStaticSpriteBatcher.CURRENT_VERSION;
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Static Sprite Batcher");
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SerializationInfo
**
**
** Purpose: The structure for holding all of the data needed
** for object serialization and deserialization.
**
**
===========================================================*/
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Remoting;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Proxies;
#endif
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Security;
#if FEATURE_CORECLR
using System.Runtime.CompilerServices;
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
{
private const int defaultSize = 4;
private const string s_mscorlibAssemblySimpleName = "mscorlib";
private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";
// Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
// Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
internal String[] m_members;
internal Object[] m_data;
internal Type[] m_types;
private Dictionary<string, int> m_nameToIndex;
internal int m_currMember;
internal IFormatterConverter m_converter;
private String m_fullTypeName;
private String m_assemName;
private Type objectType;
private bool isFullTypeNameSetExplicit;
private bool isAssemblyNameSetExplicit;
#if FEATURE_SERIALIZATION
private bool requireSameTokenInPartialTrust;
#endif
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter)
#if FEATURE_SERIALIZATION
: this(type, converter, false)
{
}
[CLSCompliant(false)]
public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust)
#endif
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
if (converter == null)
{
throw new ArgumentNullException("converter");
}
Contract.EndContractBlock();
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
m_members = new String[defaultSize];
m_data = new Object[defaultSize];
m_types = new Type[defaultSize];
m_nameToIndex = new Dictionary<string, int>();
m_converter = converter;
#if FEATURE_SERIALIZATION
this.requireSameTokenInPartialTrust = requireSameTokenInPartialTrust;
#endif
}
public String FullTypeName
{
get
{
return m_fullTypeName;
}
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
}
}
public String AssemblyName
{
get
{
return m_assemName;
}
#if FEATURE_SERIALIZATION
[SecuritySafeCritical]
#endif
set
{
if (null == value)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value);
}
#endif
m_assemName = value;
isAssemblyNameSetExplicit = true;
}
}
#if FEATURE_SERIALIZATION
[SecuritySafeCritical]
#endif
public void SetType(Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
#if FEATURE_SERIALIZATION
if (this.requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
}
#endif
if (!Object.ReferenceEquals(objectType, type))
{
objectType = type;
m_fullTypeName = type.FullName;
m_assemName = type.Module.Assembly.FullName;
isFullTypeNameSetExplicit = false;
isAssemblyNameSetExplicit = false;
}
}
private static bool Compare(byte[] a, byte[] b)
{
// if either or both assemblies do not have public key token, we should demand, hence, returning false will force a demand
if (a == null || b == null || a.Length == 0 || b.Length == 0 || a.Length != b.Length)
{
return false;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i]) return false;
}
return true;
}
}
[SecuritySafeCritical]
internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
{
if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
{
#if !MONO
CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
#endif
}
}
internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
{
if (originalAssemblyName == newAssemblyName)
{
return true;
}
AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
AssemblyName newAssembly = new AssemblyName(newAssemblyName);
// mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
// so setting the assembly name to mscorlib must always be protected by a demand
if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
}
public int MemberCount
{
get
{
return m_currMember;
}
}
public Type ObjectType
{
get
{
return objectType;
}
}
public bool IsFullTypeNameSetExplicit
{
get
{
return isFullTypeNameSetExplicit;
}
}
public bool IsAssemblyNameSetExplicit
{
get
{
return isAssemblyNameSetExplicit;
}
}
public SerializationInfoEnumerator GetEnumerator()
{
return new SerializationInfoEnumerator(m_members, m_data, m_types, m_currMember);
}
private void ExpandArrays()
{
int newSize;
Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");
newSize = (m_currMember * 2);
//
// In the pathological case, we may wrap
//
if (newSize < m_currMember)
{
if (Int32.MaxValue > m_currMember)
{
newSize = Int32.MaxValue;
}
}
//
// Allocate more space and copy the data
//
String[] newMembers = new String[newSize];
Object[] newData = new Object[newSize];
Type[] newTypes = new Type[newSize];
Array.Copy(m_members, newMembers, m_currMember);
Array.Copy(m_data, newData, m_currMember);
Array.Copy(m_types, newTypes, m_currMember);
//
// Assign the new arrys back to the member vars.
//
m_members = newMembers;
m_data = newData;
m_types = newTypes;
}
public void AddValue(String name, Object value, Type type)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
AddValueInternal(name, value, type);
}
public void AddValue(String name, Object value)
{
if (null == value)
{
AddValue(name, value, typeof(Object));
}
else
{
AddValue(name, value, value.GetType());
}
}
public void AddValue(String name, bool value)
{
AddValue(name, (Object)value, typeof(bool));
}
public void AddValue(String name, char value)
{
AddValue(name, (Object)value, typeof(char));
}
[CLSCompliant(false)]
public void AddValue(String name, sbyte value)
{
AddValue(name, (Object)value, typeof(sbyte));
}
public void AddValue(String name, byte value)
{
AddValue(name, (Object)value, typeof(byte));
}
public void AddValue(String name, short value)
{
AddValue(name, (Object)value, typeof(short));
}
[CLSCompliant(false)]
public void AddValue(String name, ushort value)
{
AddValue(name, (Object)value, typeof(ushort));
}
public void AddValue(String name, int value)
{
AddValue(name, (Object)value, typeof(int));
}
[CLSCompliant(false)]
public void AddValue(String name, uint value)
{
AddValue(name, (Object)value, typeof(uint));
}
public void AddValue(String name, long value)
{
AddValue(name, (Object)value, typeof(long));
}
[CLSCompliant(false)]
public void AddValue(String name, ulong value)
{
AddValue(name, (Object)value, typeof(ulong));
}
public void AddValue(String name, float value)
{
AddValue(name, (Object)value, typeof(float));
}
public void AddValue(String name, double value)
{
AddValue(name, (Object)value, typeof(double));
}
public void AddValue(String name, decimal value)
{
AddValue(name, (Object)value, typeof(decimal));
}
public void AddValue(String name, DateTime value)
{
AddValue(name, (Object)value, typeof(DateTime));
}
internal void AddValueInternal(String name, Object value, Type type)
{
if (m_nameToIndex.ContainsKey(name))
{
BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI.");
throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice"));
}
m_nameToIndex.Add(name, m_currMember);
//
// If we need to expand the arrays, do so.
//
if (m_currMember >= m_members.Length)
{
ExpandArrays();
}
//
// Add the data and then advance the counter.
//
m_members[m_currMember] = name;
m_data[m_currMember] = value;
m_types[m_currMember] = type;
m_currMember++;
}
/*=================================UpdateValue==================================
**Action: Finds the value if it exists in the current data. If it does, we replace
** the values, if not, we append it to the end. This is useful to the
** ObjectManager when it's performing fixups, but shouldn't be used by
** clients. Exposing out this functionality would allow children to overwrite
** their parent's values.
**Returns: void
**Arguments: name -- the name of the data to be updated.
** value -- the new value.
** type -- the type of the data being added.
**Exceptions: None. All error checking is done with asserts.
==============================================================================*/
internal void UpdateValue(String name, Object value, Type type)
{
Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");
int index = FindElement(name);
if (index < 0)
{
AddValueInternal(name, value, type);
}
else
{
m_data[index] = value;
m_types[index] = type;
}
}
private int FindElement(String name)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
Contract.EndContractBlock();
BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember);
int index;
if (m_nameToIndex.TryGetValue(name, out index))
{
return index;
}
return -1;
}
/*==================================GetElement==================================
**Action: Use FindElement to get the location of a particular member and then return
** the value of the element at that location. The type of the member is
** returned in the foundType field.
**Returns: The value of the element at the position associated with name.
**Arguments: name -- the name of the element to find.
** foundType -- the type of the element associated with the given name.
**Exceptions: None. FindElement does null checking and throws for elements not
** found.
==============================================================================*/
private Object GetElement(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
[System.Runtime.InteropServices.ComVisible(true)]
//
private Object GetElementNoThrow(String name, out Type foundType)
{
int index = FindElement(name);
if (index == -1)
{
foundType = null;
return null;
}
Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");
foundType = m_types[index];
Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
return m_data[index];
}
//
// The user should call one of these getters to get the data back in the
// form requested.
//
[System.Security.SecuritySafeCritical] // auto-generated
public Object GetValue(String name, Type type)
{
if ((object)type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
Type foundType;
Object value;
value = GetElement(name, out foundType);
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, rt))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
//
internal Object GetValueNoThrow(String name, Type type)
{
Type foundType;
Object value;
Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");
value = GetElementNoThrow(name, out foundType);
if (value == null)
return null;
#if FEATURE_REMOTING
if (RemotingServices.IsTransparentProxy(value))
{
RealProxy proxy = RemotingServices.GetRealProxy(value);
if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
return value;
}
else
#endif
if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
{
return value;
}
Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");
return m_converter.Convert(value, type);
}
public bool GetBoolean(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(bool)))
{
return (bool)value;
}
return m_converter.ToBoolean(value);
}
public char GetChar(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(char)))
{
return (char)value;
}
return m_converter.ToChar(value);
}
[CLSCompliant(false)]
public sbyte GetSByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(sbyte)))
{
return (sbyte)value;
}
return m_converter.ToSByte(value);
}
public byte GetByte(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(byte)))
{
return (byte)value;
}
return m_converter.ToByte(value);
}
public short GetInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(short)))
{
return (short)value;
}
return m_converter.ToInt16(value);
}
[CLSCompliant(false)]
public ushort GetUInt16(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ushort)))
{
return (ushort)value;
}
return m_converter.ToUInt16(value);
}
public int GetInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(int)))
{
return (int)value;
}
return m_converter.ToInt32(value);
}
[CLSCompliant(false)]
public uint GetUInt32(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(uint)))
{
return (uint)value;
}
return m_converter.ToUInt32(value);
}
public long GetInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(long)))
{
return (long)value;
}
return m_converter.ToInt64(value);
}
[CLSCompliant(false)]
public ulong GetUInt64(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(ulong)))
{
return (ulong)value;
}
return m_converter.ToUInt64(value);
}
public float GetSingle(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(float)))
{
return (float)value;
}
return m_converter.ToSingle(value);
}
public double GetDouble(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(double)))
{
return (double)value;
}
return m_converter.ToDouble(value);
}
public decimal GetDecimal(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(decimal)))
{
return (decimal)value;
}
return m_converter.ToDecimal(value);
}
public DateTime GetDateTime(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(DateTime)))
{
return (DateTime)value;
}
return m_converter.ToDateTime(value);
}
public String GetString(String name)
{
Type foundType;
Object value;
value = GetElement(name, out foundType);
if (Object.ReferenceEquals(foundType, typeof(String)) || value == null)
{
return (String)value;
}
return m_converter.ToString(value);
}
internal string[] MemberNames
{
get
{
return m_members;
}
}
internal object[] MemberValues
{
get
{
return m_data;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace GameLibrary.Dependencies.Entities
{
//Notes: Usage of unsafe or fixed would not do much in terms of performance
// In future maybe make ConcurrentBag concurrently modified through concurrentqueue? Too many concurrents?
// (2012-9-6) Squizzle : made Bag capable of using structs (Entity should be a struct)
public class Bag<E> : IEnumerable<E>
{
private E[] data;
private int size = 0;
/**
* Constructs an empty Bag with an initial capacity of 16.
*
*/
public Bag()
{
data = new E[16];
}
/**
* Constructs an empty Bag with the specified initial capacity.
*
* @param capacity
* the initial capacity of Bag
*/
public Bag(int capacity)
{
data = new E[capacity];
}
/**
* Removes the element at the specified position in this Bag. does this by
* overwriting it was last element then removing last element
*
* @param index
* the index of element to be removed
* @return element that was removed from the Bag
*/
public E Remove(int index)
{
E o = data[index]; // make copy of element to remove so it can be
// returned
data[index] = data[--size]; // overwrite item to remove with last
// element
data[size] = default(E); // null last element, so gc can do its work
return o;
}
/**
* Remove and return the last object in the bag.
*
* @return the last object in the bag, null if empty.
*/
public E RemoveLast()
{
if (size > 0)
{
E o = data[--size];
data[size] = default(E); // default(E) if class = null
return o;
}
return default(E);
}
/**
* Removes the first occurrence of the specified element from this Bag, if
* it is present. If the Bag does not contain the element, it is unchanged.
* does this by overwriting it was last element then removing last element
*
* @param o
* element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public bool Remove(E o)
{
for (int i = 0; i < size; i++)
{
Object o1 = data[i];
if (o.Equals(o1))
{
data[i] = data[--size]; // overwrite item to remove with last
// element
data[size] = default(E);
return true;
}
}
return false;
}
/**
* Check if bag contains this element.
*
* @param o
* @return
*/
public bool Contains(E o)
{
for (int i = 0; size > i; i++)
{
if (o.Equals(data[i]))
{
return true;
}
}
return false;
}
/**
* Removes from this Bag all of its elements that are contained in the
* specified Bag.
*
* @param bag
* Bag containing elements to be removed from this Bag
* @return {@code true} if this Bag changed as a result of the call
*/
public bool RemoveAll(Bag<E> bag)
{
bool modified = false;
for (int i = 0, bagSize = bag.Size; i < bagSize; i++)
{
Object o1 = bag.Get(i);
for (int j = 0; j < size; j++)
{
Object o2 = data[j];
if (o1 == o2)
{
//(2012-9-6) Squizzle : inlined method Remove(int)
{
E o = data[j];
data[j] = data[--size];
data[size] = default(E);
}
j--;
modified = true;
break;
}
}
}
return modified;
}
/**
* Returns the element at the specified position in Bag.
*
* @param index
* index of the element to return
* @return the element at the specified position in bag
*/
public E Get(int index)
{
if (index < data.Length)
return data[index];
else
return default(E);
}
/// <summary>
/// Returns the element at the specified position in Bag.
/// </summary>
/// <param name="index">index of the element to return</param>
/// <returns>the element at the specified position in Bag</returns>
public E this[int index]
{
get
{
return data[index];
}
set
{
if (index >= data.Length)
{
//(2012-9-6) Squizzle : inlined method Grow(int)
E[] oldData = data;
data = new E[index * 2];
Array.Copy(oldData, 0, data, 0, oldData.Length);
size = index + 1;
}
else if (index >= size)
{
size = index + 1;
}
data[index] = value;
}
}
/**
* Returns the number of elements in this bag.
*
* @return the number of elements in this bag
*/
public int Size
{
get
{
return size;
}
}
/**
* Returns the number of elements the bag can hold without growing.
*
* @return the number of elements the bag can hold without growing.
*/
public int Capacity
{
get { return data.Length; }
}
/**
* Returns true if this list contains no elements.
*
* @return true if this list contains no elements
*/
public bool IsEmpty
{
get { return size == 0; }
}
/**
* Adds the specified element to the end of this bag. if needed also
* increases the capacity of the bag.
*
* @param o
* element to be added to this list
*/
public void Add(E o) //TODO: ERROR
{
// is size greater than capacity increase capacity
if (size == data.Length)
{
Grow();
}
if(size < data.Length)
data[size++] = o;
}
/**
* Set element at specified index in the bag.
*
* @param index position of element
* @param o the element
*/
public void Set(int index, E o)
{
if (index >= data.Length)
{
//(2012-9-6) Squizzle : inlined method Grow(int)
E[] oldData = data;
data = new E[index * 2];
Array.Copy(oldData, 0, data, 0, oldData.Length);
size = index + 1;
}
else if (index >= size)
{
size = index + 1;
}
data[index] = o;
}
private void Grow()
{
int newCapacity = (data.Length * 3) / 2 + 1;
//(2012-9-6) Squizzle : inlined method Grow(int)
E[] oldData = data;
data = new E[newCapacity];
Array.Copy(oldData, 0, data, 0, oldData.Length);
}
private void Grow(int newCapacity)
{
E[] oldData = data;
data = new E[newCapacity];
Array.Copy(oldData, 0, data, 0, oldData.Length);
}
/**
* Removes all of the elements from this bag. The bag will be empty after
* this call returns.
*/
public void Clear()
{
// null all elements so gc can clean up
for (int i = 0; i < size; i++)
{
data[i] = default(E);
}
size = 0;
}
/**
* Add all items into this bag.
* @param added
*/
public void AddAll(Bag<E> items)
{
for (int i = 0, j = items.Size; j > i; i++)
{
//(2012-9-6) Squizzle : inlined method Add(E)
if (size == data.Length)
{
Grow();
}
data[size++] = items.Get(i);
}
}
IEnumerator<E> IEnumerable<E>.GetEnumerator()
{
return new BagEnumerator<E>(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new BagEnumerator<E>(this);
}
}
internal class BagEnumerator<E> : IEnumerator<E>
{
private Bag<E> bag;
private int i = -1;
public BagEnumerator(Bag<E> bag)
{
this.bag = bag;
}
public bool MoveNext()
{
i++;
return i < bag.Size;
}
public void Reset()
{
i = -1;
}
E IEnumerator<E>.Current
{
get { return bag.Get(i); }
}
public void Dispose()
{
this.bag = null;
}
object IEnumerator.Current
{
get { return bag.Get(i); }
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
#if !READ_ONLY
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageWriter : BinaryStreamWriter {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly TextMap text_map;
ImageDebugDirectory debug_directory;
byte [] debug_data;
RVA win32_rva;
ByteBuffer win32_resources;
ResourceDirectory win32_resources_directory;
const uint pe_header_size = 0x98u;
const uint section_header_size = 0x28u;
const uint file_alignment = 0x200;
const uint section_alignment = 0x2000;
const ulong image_base = 0x00400000;
internal const RVA text_rva = 0x2000;
readonly bool pe64;
readonly bool has_reloc;
readonly uint time_stamp;
internal Section text;
internal Section rsrc;
internal Section reloc;
ushort sections;
ImageWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
: base (stream)
{
this.module = module;
this.metadata = metadata;
this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64;
this.has_reloc = module.Architecture == TargetArchitecture.I386;
this.GetDebugHeader ();
this.GetWin32Resources ();
this.text_map = BuildTextMap ();
this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
this.time_stamp = (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
}
void GetDebugHeader ()
{
var symbol_writer = metadata.symbol_writer;
if (symbol_writer == null)
return;
if (!symbol_writer.GetDebugHeader (out debug_directory, out debug_data))
debug_data = Empty<byte>.Array;
}
void GetWin32Resources ()
{
if (module.Win32Resources != null)
{
win32_rva = module.Win32RVA;
win32_resources = new ByteBuffer(module.Win32Resources);
return;
}
if (module.Win32ResourceDirectory != null)
{
win32_resources_directory = module.Win32ResourceDirectory;
return;
}
var rsrc = GetImageResourceSection();
if (rsrc == null)
return;
var raw_resources = new byte [rsrc.Data.Length];
Buffer.BlockCopy (rsrc.Data, 0, raw_resources, 0, rsrc.Data.Length);
win32_rva = rsrc.VirtualAddress;
win32_resources = new ByteBuffer (raw_resources);
}
Section GetImageResourceSection ()
{
if (!module.HasImage)
return null;
const string rsrc_section = ".rsrc";
return module.Image.GetSection (rsrc_section);
}
public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream)
{
var writer = new ImageWriter (module, metadata, stream);
writer.BuildSections ();
return writer;
}
void BuildSections ()
{
if (win32_resources != null || win32_resources_directory != null)
sections++;
text = CreateSection (".text", text_map.GetLength (), null);
var previous = text;
if (win32_resources != null) {
rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
PatchWin32Resources (win32_resources);
previous = rsrc;
} else if (win32_resources_directory != null) {
rsrc = CreateSection(".rsrc", previous);
WriteWin32ResourcesDirectory(win32_resources_directory);
SetSectionSize(rsrc, (uint) win32_resources.length);
previous = rsrc;
}
if (has_reloc)
reloc = CreateSection (".reloc", 12u, previous);
}
Section CreateSection (string name, uint size, Section previous)
{
var ret = CreateSection(name, previous);
SetSectionSize(ret, size);
return ret;
}
void SetSectionSize(Section ret, uint size)
{
ret.VirtualSize = size;
ret.SizeOfRawData = Align(size, file_alignment);
}
Section CreateSection(string name, Section previous)
{
return new Section
{
Name = name,
VirtualAddress = previous != null
? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
: text_rva,
PointerToRawData = previous != null
? previous.PointerToRawData + previous.SizeOfRawData
: Align (GetHeaderSize (), file_alignment)
};
}
static uint Align (uint value, uint align)
{
align--;
return (value + align) & ~align;
}
void WriteDOSHeader ()
{
Write (new byte [] {
// dos header start
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// lfanew
0x80, 0x00, 0x00, 0x00,
// dos header end
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
});
}
ushort SizeOfOptionalHeader ()
{
return (ushort) (!pe64 ? 0xe0 : 0xf0);
}
void WritePEFileHeader ()
{
WriteUInt32 (0x00004550); // Magic
WriteUInt16 (GetMachine ()); // Machine
WriteUInt16 (sections); // NumberOfSections
WriteUInt32 (time_stamp);
WriteUInt32 (0); // PointerToSymbolTable
WriteUInt32 (0); // NumberOfSymbols
WriteUInt16 (SizeOfOptionalHeader ()); // SizeOfOptionalHeader
// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
characteristics |= 0x2000;
WriteUInt16 (characteristics); // Characteristics
}
ushort GetMachine ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 0x014c;
case TargetArchitecture.AMD64:
return 0x8664;
case TargetArchitecture.IA64:
return 0x0200;
case TargetArchitecture.ARMv7:
return 0x01c4;
}
throw new NotSupportedException ();
}
Section LastSection ()
{
if (reloc != null)
return reloc;
if (rsrc != null)
return rsrc;
return text;
}
void WriteOptionalHeaders ()
{
WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic
WriteByte (8); // LMajor
WriteByte (0); // LMinor
WriteUInt32 (text.SizeOfRawData); // CodeSize
WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0)
+ (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize
WriteUInt32 (0); // UninitializedDataSize
var startub_stub = text_map.GetRange (TextSegment.StartupStub);
WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA
WriteUInt32 (text_rva); // BaseOfCode
if (!pe64) {
WriteUInt32 (0); // BaseOfData
WriteUInt32 ((uint) image_base); // ImageBase
} else {
WriteUInt64 (image_base); // ImageBase
}
WriteUInt32 (section_alignment); // SectionAlignment
WriteUInt32 (file_alignment); // FileAlignment
WriteUInt16 (4); // OSMajor
WriteUInt16 (0); // OSMinor
WriteUInt16 (0); // UserMajor
WriteUInt16 (0); // UserMinor
WriteUInt16 (4); // SubSysMajor
WriteUInt16 (0); // SubSysMinor
WriteUInt32 (0); // Reserved
var last_section = LastSection();
WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize
WriteUInt32 (text.PointerToRawData); // HeaderSize
WriteUInt32 (0); // Checksum
WriteUInt16 (GetSubSystem ()); // SubSystem
WriteUInt16 ((ushort) module.Characteristics); // DLLFlags
const ulong stack_reserve = 0x100000;
const ulong stack_commit = 0x1000;
const ulong heap_reserve = 0x100000;
const ulong heap_commit = 0x1000;
if (!pe64) {
WriteUInt32 ((uint) stack_reserve);
WriteUInt32 ((uint) stack_commit);
WriteUInt32 ((uint) heap_reserve);
WriteUInt32 ((uint) heap_commit);
} else {
WriteUInt64 (stack_reserve);
WriteUInt64 (stack_commit);
WriteUInt64 (heap_reserve);
WriteUInt64 (heap_commit);
}
WriteUInt32 (0); // LoaderFlags
WriteUInt32 (16); // NumberOfDataDir
WriteZeroDataDirectory (); // ExportTable
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable
if (rsrc != null) { // ResourceTable
WriteUInt32 (rsrc.VirtualAddress);
WriteUInt32 (rsrc.VirtualSize);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // ExceptionTable
WriteZeroDataDirectory (); // CertificateTable
WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable
WriteUInt32 (reloc != null ? reloc.VirtualSize : 0);
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
WriteUInt32 (28u);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // Copyright
WriteZeroDataDirectory (); // GlobalPtr
WriteZeroDataDirectory (); // TLSTable
WriteZeroDataDirectory (); // LoadConfigTable
WriteZeroDataDirectory (); // BoundImport
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT
WriteZeroDataDirectory (); // DelayImportDesc
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader
WriteZeroDataDirectory (); // Reserved
}
void WriteZeroDataDirectory ()
{
WriteUInt32 (0);
WriteUInt32 (0);
}
ushort GetSubSystem ()
{
switch (module.Kind) {
case ModuleKind.Console:
case ModuleKind.Dll:
case ModuleKind.NetModule:
return 0x3;
case ModuleKind.Windows:
return 0x2;
default:
throw new ArgumentOutOfRangeException ();
}
}
void WriteSectionHeaders ()
{
WriteSection (text, 0x60000020);
if (rsrc != null)
WriteSection (rsrc, 0x40000040);
if (reloc != null)
WriteSection (reloc, 0x42000040);
}
void WriteSection (Section section, uint characteristics)
{
var name = new byte [8];
var sect_name = section.Name;
for (int i = 0; i < sect_name.Length; i++)
name [i] = (byte) sect_name [i];
WriteBytes (name);
WriteUInt32 (section.VirtualSize);
WriteUInt32 (section.VirtualAddress);
WriteUInt32 (section.SizeOfRawData);
WriteUInt32 (section.PointerToRawData);
WriteUInt32 (0); // PointerToRelocations
WriteUInt32 (0); // PointerToLineNumbers
WriteUInt16 (0); // NumberOfRelocations
WriteUInt16 (0); // NumberOfLineNumbers
WriteUInt32 (characteristics);
}
void MoveTo (uint pointer)
{
BaseStream.Seek (pointer, SeekOrigin.Begin);
}
void MoveToRVA (Section section, RVA rva)
{
BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
}
void MoveToRVA (TextSegment segment)
{
MoveToRVA (text, text_map.GetRVA (segment));
}
void WriteRVA (RVA rva)
{
if (!pe64)
WriteUInt32 (rva);
else
WriteUInt64 (rva);
}
void PrepareSection (Section section)
{
MoveTo (section.PointerToRawData);
const int buffer_size = 4096;
if (section.SizeOfRawData <= buffer_size) {
Write (new byte [section.SizeOfRawData]);
MoveTo (section.PointerToRawData);
return;
}
var written = 0;
var buffer = new byte [buffer_size];
while (written != section.SizeOfRawData) {
var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size);
Write (buffer, 0, write_size);
written += write_size;
}
MoveTo (section.PointerToRawData);
}
void WriteText ()
{
PrepareSection (text);
// ImportAddressTable
if (has_reloc) {
WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
WriteRVA (0);
}
// CLIHeader
WriteUInt32 (0x48);
WriteUInt16 (2);
WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
WriteUInt32 (GetMetadataLength ());
WriteUInt32 ((uint) module.Attributes);
WriteUInt32 (metadata.entry_point.ToUInt32 ());
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
WriteZeroDataDirectory (); // CodeManagerTable
WriteZeroDataDirectory (); // VTableFixups
WriteZeroDataDirectory (); // ExportAddressTableJumps
WriteZeroDataDirectory (); // ManagedNativeHeader
// Code
MoveToRVA (TextSegment.Code);
WriteBuffer (metadata.code);
// Resources
MoveToRVA (TextSegment.Resources);
WriteBuffer (metadata.resources);
// Data
if (metadata.data.length > 0) {
MoveToRVA (TextSegment.Data);
WriteBuffer (metadata.data);
}
// StrongNameSignature
// stays blank
// MetadataHeader
MoveToRVA (TextSegment.MetadataHeader);
WriteMetadataHeader ();
WriteMetadata ();
// DebugDirectory
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
MoveToRVA (TextSegment.DebugDirectory);
WriteDebugDirectory ();
}
if (!has_reloc)
return;
// ImportDirectory
MoveToRVA (TextSegment.ImportDirectory);
WriteImportDirectory ();
// StartupStub
MoveToRVA (TextSegment.StartupStub);
WriteStartupStub ();
}
uint GetMetadataLength ()
{
return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
}
void WriteMetadataHeader ()
{
WriteUInt32 (0x424a5342); // Signature
WriteUInt16 (1); // MajorVersion
WriteUInt16 (1); // MinorVersion
WriteUInt32 (0); // Reserved
var version = GetZeroTerminatedString (module.runtime_version);
WriteUInt32 ((uint) version.Length);
WriteBytes (version);
WriteUInt16 (0); // Flags
WriteUInt16 (GetStreamCount ());
uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
}
ushort GetStreamCount ()
{
return (ushort) (
1 // #~
+ 1 // #Strings
+ (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US
+ 1 // GUID
+ (metadata.blob_heap.IsEmpty ? 0 : 1)); // #Blob
}
void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
{
var length = (uint) text_map.GetLength (heap);
if (length == 0)
return;
WriteUInt32 (offset);
WriteUInt32 (length);
WriteBytes (GetZeroTerminatedString (name));
offset += length;
}
static byte [] GetZeroTerminatedString (string @string)
{
return GetString (@string, (@string.Length + 1 + 3) & ~3);
}
static byte [] GetSimpleString (string @string)
{
return GetString (@string, @string.Length);
}
static byte [] GetString (string @string, int length)
{
var bytes = new byte [length];
for (int i = 0; i < @string.Length; i++)
bytes [i] = (byte) @string [i];
return bytes;
}
void WriteMetadata ()
{
WriteHeap (TextSegment.TableHeap, metadata.table_heap);
WriteHeap (TextSegment.StringHeap, metadata.string_heap);
WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
WriteGuidHeap ();
WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
}
void WriteHeap (TextSegment heap, HeapBuffer buffer)
{
if (buffer.IsEmpty)
return;
MoveToRVA (heap);
WriteBuffer (buffer);
}
void WriteGuidHeap ()
{
MoveToRVA (TextSegment.GuidHeap);
WriteBytes (module.Mvid.ToByteArray ());
}
void WriteDebugDirectory ()
{
WriteInt32 (debug_directory.Characteristics);
WriteUInt32 (time_stamp);
WriteInt16 (debug_directory.MajorVersion);
WriteInt16 (debug_directory.MinorVersion);
WriteInt32 (debug_directory.Type);
WriteInt32 (debug_directory.SizeOfData);
WriteInt32 (debug_directory.AddressOfRawData);
WriteInt32 ((int) BaseStream.Position + 4);
WriteBytes (debug_data);
}
void WriteImportDirectory ()
{
WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable
WriteUInt32 (0); // DateTimeStamp
WriteUInt32 (0); // ForwarderChain
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
Advance (20);
// ImportLookupTable
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
// ImportHintNameTable
MoveToRVA (TextSegment.ImportHintNameTable);
WriteUInt16 (0); // Hint
WriteBytes (GetRuntimeMain ());
WriteByte (0);
WriteBytes (GetSimpleString ("mscoree.dll"));
WriteUInt16 (0);
}
byte [] GetRuntimeMain ()
{
return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
? GetSimpleString ("_CorDllMain")
: GetSimpleString ("_CorExeMain");
}
void WriteStartupStub ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt16 (0x25ff);
WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
return;
default:
throw new NotSupportedException ();
}
}
void WriteRsrc ()
{
PrepareSection (rsrc);
WriteBuffer (win32_resources);
}
void WriteReloc ()
{
PrepareSection (reloc);
var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
var page_rva = reloc_rva & ~0xfffu;
WriteUInt32 (page_rva); // PageRVA
WriteUInt32 (0x000c); // Block Size
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt32 (0x3000 + reloc_rva - page_rva);
break;
default:
throw new NotSupportedException();
}
}
public void WriteImage ()
{
WriteDOSHeader ();
WritePEFileHeader ();
WriteOptionalHeaders ();
WriteSectionHeaders ();
WriteText ();
if (rsrc != null)
WriteRsrc ();
if (reloc != null)
WriteReloc ();
}
TextMap BuildTextMap ()
{
var map = metadata.text_map;
map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
map.AddMap (TextSegment.Data, metadata.data.length, 4);
if (metadata.data.length > 0)
metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength ());
map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
map.AddMap (TextSegment.GuidHeap, 16);
map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
int debug_dir_len = 0;
if (!debug_data.IsNullOrEmpty ()) {
const int debug_dir_header_len = 28;
debug_directory.AddressOfRawData = (int) map.GetNextRVA (TextSegment.BlobHeap) + debug_dir_header_len;
debug_dir_len = debug_data.Length + debug_dir_header_len;
}
map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
if (!has_reloc) {
var start = map.GetNextRVA (TextSegment.DebugDirectory);
map.AddMap (TextSegment.ImportDirectory, new Range (start, 0));
map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0));
map.AddMap (TextSegment.StartupStub, new Range (start, 0));
return map;
}
RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
RVA import_hnt_rva = import_dir_rva + 48u;
import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
RVA startup_stub_rva = import_dir_rva + import_dir_len;
startup_stub_rva = module.Architecture == TargetArchitecture.IA64
? (startup_stub_rva + 15u) & ~15u
: 2 + ((startup_stub_rva + 3u) & ~3u);
map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
return map;
}
uint GetStartupStubLength ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 6;
default:
throw new NotSupportedException ();
}
}
int GetMetadataHeaderLength ()
{
return
// MetadataHeader
40
// #~ header
+ 12
// #Strings header
+ 20
// #US header
+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
// #GUID header
+ 16
// #Blob header
+ (metadata.blob_heap.IsEmpty ? 0 : 16);
}
int GetStrongNameLength ()
{
if (module.Assembly == null)
return 0;
var public_key = module.Assembly.Name.PublicKey;
if (public_key.IsNullOrEmpty ())
return 0;
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = public_key.Length;
if (size > 32)
return size - 32;
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
return 128; // default strongname signature size
}
public DataDirectory GetStrongNameSignatureDirectory ()
{
return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
}
public uint GetHeaderSize ()
{
return pe_header_size + SizeOfOptionalHeader () + (sections * section_header_size);
}
void PatchWin32Resources (ByteBuffer resources)
{
PatchResourceDirectoryTable (resources);
}
void PatchResourceDirectoryTable (ByteBuffer resources)
{
resources.Advance (12);
var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
for (int i = 0; i < entries; i++)
PatchResourceDirectoryEntry (resources);
}
void PatchResourceDirectoryEntry (ByteBuffer resources)
{
resources.Advance (4);
var child = resources.ReadUInt32 ();
var position = resources.position;
resources.position = (int) child & 0x7fffffff;
if ((child & 0x80000000) != 0)
PatchResourceDirectoryTable (resources);
else
PatchResourceDataEntry (resources);
resources.position = position;
}
void PatchResourceDataEntry (ByteBuffer resources)
{
var rva = resources.ReadUInt32 ();
resources.position -= 4;
resources.WriteUInt32 (rva - win32_rva + rsrc.VirtualAddress);
}
private static int GetDirectoryLength(ResourceDirectory dir)
{
int length = 16 + dir.Entries.Count * 8;
foreach (ResourceEntry entry in dir.Entries)
length += GetDirectoryLength(entry);
return length;
}
private static int GetDirectoryLength(ResourceEntry entry)
{
if (entry.Data != null)
return 16;
return GetDirectoryLength(entry.Directory);
}
private void WriteWin32ResourcesDirectory(ResourceDirectory directory)
{
win32_resources = new ByteBuffer();
if (directory.Entries.Count != 0)
{
int stringTableOffset = GetDirectoryLength(directory);
Dictionary<string, int> strings = new Dictionary<string, int>();
ByteBuffer stringTable = new ByteBuffer(16);
int offset = 16 + directory.Entries.Count * 8;
for (int pass = 0; pass < 3; pass++)
Write(directory, pass, 0, ref offset, strings, ref stringTableOffset, stringTable);
// the pecoff spec says that the string table is between the directory entries and the data entries,
// but the windows linker puts them after the data entries, so we do too.
stringTable.Align(4);
offset += stringTable.length;
WriteResourceDataEntries(directory, ref offset);
win32_resources.WriteBytes(stringTable);
WriteData(directory);
}
}
private void WriteResourceDataEntries(ResourceDirectory directory, ref int offset)
{
foreach (ResourceEntry entry in directory.Entries)
{
if (entry.Data != null)
{
win32_resources.WriteUInt32((uint) (rsrc.VirtualAddress + offset));
win32_resources.WriteInt32(entry.Data.Length);
win32_resources.WriteUInt32(entry.CodePage);
win32_resources.WriteUInt32(entry.Reserved);
offset += (entry.Data.Length + 3) & ~3;
}
else
{
WriteResourceDataEntries(entry.Directory, ref offset);
}
}
}
private void WriteData(ResourceDirectory directory)
{
foreach (ResourceEntry entry in directory.Entries)
{
if (entry.Data != null)
{
win32_resources.WriteBytes(entry.Data);
win32_resources.Align(4);
}
else
{
WriteData(entry.Directory);
}
}
}
private void Write(ResourceDirectory directory, int writeDepth, int currentDepth, ref int offset, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
if (currentDepth == writeDepth)
{
ushort namedEntries = directory.SortEntries();
// directory header
win32_resources.WriteUInt32(directory.Characteristics);
win32_resources.WriteUInt32(directory.TimeDateStamp);
win32_resources.WriteUInt16(directory.MajorVersion);
win32_resources.WriteUInt16(directory.MinVersion);
win32_resources.WriteUInt16(namedEntries);
win32_resources.WriteUInt16((ushort)(directory.Entries.Count - namedEntries));
foreach (ResourceEntry entry in directory.Entries)
{
WriteEntry(entry, ref offset, strings, ref stringTableOffset, stringTable);
}
}
else
{
foreach (ResourceEntry entry in directory.Entries)
{
Write(entry.Directory, writeDepth, currentDepth + 1, ref offset, strings, ref stringTableOffset, stringTable);
}
}
}
private void WriteEntry(ResourceEntry entry, ref int offset, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
WriteNameOrOrdinal(entry, strings, ref stringTableOffset, stringTable);
if (entry.Data == null)
{
win32_resources.WriteUInt32(0x80000000U | (uint)offset);
offset += entry.Directory.Entries.Count * 8;
}
else
{
win32_resources.WriteUInt32((uint)offset);
}
offset += 16;
}
private void WriteNameOrOrdinal(ResourceEntry entry, Dictionary<string, int> strings, ref int stringTableOffset, ByteBuffer stringTable)
{
if (entry.Name == null)
{
win32_resources.WriteUInt32(entry.Id);
}
else
{
int stringOffset;
if (!strings.TryGetValue(entry.Name, out stringOffset))
{
stringOffset = stringTableOffset;
strings.Add(entry.Name, stringOffset);
stringTableOffset += entry.Name.Length * 2 + 2;
stringTable.WriteUInt16((ushort)entry.Name.Length);
foreach (char c in entry.Name)
stringTable.WriteInt16((short)c);
}
win32_resources.WriteUInt32(0x80000000U | (uint)stringOffset);
}
}
}
}
#endif
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using GameLibrary.Dependencies.Physics.Collision;
using GameLibrary.Dependencies.Physics.Collision.Shapes;
using GameLibrary.Dependencies.Physics.Common;
using Microsoft.Xna.Framework;
using System;
using System.Diagnostics;
namespace GameLibrary.Dependencies.Physics.Dynamics.Contacts
{
public sealed class ContactConstraintPoint
{
public Vector2 LocalPoint;
public float NormalImpulse;
public float NormalMass;
public float TangentImpulse;
public float TangentMass;
public float VelocityBias;
public Vector2 rA;
public Vector2 rB;
}
public sealed class ContactConstraint
{
public PhysicsBody BodyA;
public PhysicsBody BodyB;
public float Friction;
public Mat22 K;
public Vector2 LocalNormal;
public Vector2 LocalPoint;
public Manifold Manifold;
public Vector2 Normal;
public Mat22 NormalMass;
public int PointCount;
public ContactConstraintPoint[] Points = new ContactConstraintPoint[Settings.MaxPolygonVertices];
public float RadiusA;
public float RadiusB;
public float Restitution;
public ManifoldType Type;
public ContactConstraint()
{
for (int i = 0; i < Settings.MaxManifoldPoints; i++)
{
Points[i] = new ContactConstraintPoint();
}
}
}
public class ContactSolver
{
public ContactConstraint[] Constraints;
private int _constraintCount; // collection can be bigger.
private Contact[] _contacts;
public void Reset(Contact[] contacts, int contactCount, float impulseRatio, bool warmstarting)
{
_contacts = contacts;
_constraintCount = contactCount;
// grow the array
if (Constraints == null || Constraints.Length < _constraintCount)
{
Constraints = new ContactConstraint[_constraintCount * 2];
for (int i = 0; i < Constraints.Length; i++)
{
Constraints[i] = new ContactConstraint();
}
}
// Initialize position independent portions of the constraints.
for (int i = 0; i < _constraintCount; ++i)
{
Contact contact = contacts[i];
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
Shape shapeA = fixtureA.Shape;
Shape shapeB = fixtureB.Shape;
float radiusA = shapeA.Radius;
float radiusB = shapeB.Radius;
PhysicsBody bodyA = fixtureA.Body;
PhysicsBody bodyB = fixtureB.Body;
Manifold manifold = contact.Manifold;
Debug.Assert(manifold.PointCount > 0);
ContactConstraint cc = Constraints[i];
cc.Friction = Settings.MixFriction(fixtureA.Friction, fixtureB.Friction);
cc.Restitution = Settings.MixRestitution(fixtureA.Restitution, fixtureB.Restitution);
cc.BodyA = bodyA;
cc.BodyB = bodyB;
cc.Manifold = manifold;
cc.Normal = Vector2.Zero;
cc.PointCount = manifold.PointCount;
cc.LocalNormal = manifold.LocalNormal;
cc.LocalPoint = manifold.LocalPoint;
cc.RadiusA = radiusA;
cc.RadiusB = radiusB;
cc.Type = manifold.Type;
for (int j = 0; j < cc.PointCount; ++j)
{
ManifoldPoint cp = manifold.Points[j];
ContactConstraintPoint ccp = cc.Points[j];
if (warmstarting)
{
ccp.NormalImpulse = impulseRatio * cp.NormalImpulse;
ccp.TangentImpulse = impulseRatio * cp.TangentImpulse;
}
else
{
ccp.NormalImpulse = 0.0f;
ccp.TangentImpulse = 0.0f;
}
ccp.LocalPoint = cp.LocalPoint;
ccp.rA = Vector2.Zero;
ccp.rB = Vector2.Zero;
ccp.NormalMass = 0.0f;
ccp.TangentMass = 0.0f;
ccp.VelocityBias = 0.0f;
}
cc.K.SetZero();
cc.NormalMass.SetZero();
}
}
public void InitializeVelocityConstraints()
{
for (int i = 0; i < _constraintCount; ++i)
{
ContactConstraint cc = Constraints[i];
float radiusA = cc.RadiusA;
float radiusB = cc.RadiusB;
PhysicsBody bodyA = cc.BodyA;
PhysicsBody bodyB = cc.BodyB;
Manifold manifold = cc.Manifold;
Vector2 vA = bodyA.LinearVelocity;
Vector2 vB = bodyB.LinearVelocity;
float wA = bodyA.AngularVelocity;
float wB = bodyB.AngularVelocity;
Debug.Assert(manifold.PointCount > 0);
FixedArray2<Vector2> points;
Collision.Collision.GetWorldManifold(ref manifold, ref bodyA.Xf, radiusA, ref bodyB.Xf, radiusB,
out cc.Normal, out points);
Vector2 tangent = new Vector2(cc.Normal.Y, -cc.Normal.X);
for (int j = 0; j < cc.PointCount; ++j)
{
ContactConstraintPoint ccp = cc.Points[j];
ccp.rA = points[j] - bodyA.Sweep.C;
ccp.rB = points[j] - bodyB.Sweep.C;
float rnA = ccp.rA.X * cc.Normal.Y - ccp.rA.Y * cc.Normal.X;
float rnB = ccp.rB.X * cc.Normal.Y - ccp.rB.Y * cc.Normal.X;
rnA *= rnA;
rnB *= rnB;
float kNormal = bodyA.InvMass + bodyB.InvMass + bodyA.InvI * rnA + bodyB.InvI * rnB;
if (kNormal <= Settings.Epsilon)
return;
ccp.NormalMass = 1.0f / kNormal;
float rtA = ccp.rA.X * tangent.Y - ccp.rA.Y * tangent.X;
float rtB = ccp.rB.X * tangent.Y - ccp.rB.Y * tangent.X;
rtA *= rtA;
rtB *= rtB;
float kTangent = bodyA.InvMass + bodyB.InvMass + bodyA.InvI * rtA + bodyB.InvI * rtB;
Debug.Assert(kTangent > Settings.Epsilon);
ccp.TangentMass = 1.0f / kTangent;
// Setup a velocity bias for restitution.
ccp.VelocityBias = 0.0f;
float vRel = cc.Normal.X * (vB.X + -wB * ccp.rB.Y - vA.X - -wA * ccp.rA.Y) +
cc.Normal.Y * (vB.Y + wB * ccp.rB.X - vA.Y - wA * ccp.rA.X);
if (vRel < -Settings.VelocityThreshold)
{
ccp.VelocityBias = -cc.Restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if (cc.PointCount == 2)
{
ContactConstraintPoint ccp1 = cc.Points[0];
ContactConstraintPoint ccp2 = cc.Points[1];
float invMassA = bodyA.InvMass;
float invIA = bodyA.InvI;
float invMassB = bodyB.InvMass;
float invIB = bodyB.InvI;
float rn1A = ccp1.rA.X * cc.Normal.Y - ccp1.rA.Y * cc.Normal.X;
float rn1B = ccp1.rB.X * cc.Normal.Y - ccp1.rB.Y * cc.Normal.X;
float rn2A = ccp2.rA.X * cc.Normal.Y - ccp2.rA.Y * cc.Normal.X;
float rn2B = ccp2.rB.X * cc.Normal.Y - ccp2.rB.Y * cc.Normal.X;
float k11 = invMassA + invMassB + invIA * rn1A * rn1A + invIB * rn1B * rn1B;
float k22 = invMassA + invMassB + invIA * rn2A * rn2A + invIB * rn2B * rn2B;
float k12 = invMassA + invMassB + invIA * rn1A * rn2A + invIB * rn1B * rn2B;
// Ensure a reasonable condition number.
const float k_maxConditionNumber = 100.0f;
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
{
// K is safe to invert.
cc.K.Col1.X = k11;
cc.K.Col1.Y = k12;
cc.K.Col2.X = k12;
cc.K.Col2.Y = k22;
float a = cc.K.Col1.X, b = cc.K.Col2.X, c = cc.K.Col1.Y, d = cc.K.Col2.Y;
float det = a * d - b * c;
if (det != 0.0f)
{
det = 1.0f / det;
}
cc.NormalMass.Col1.X = det * d;
cc.NormalMass.Col1.Y = -det * c;
cc.NormalMass.Col2.X = -det * b;
cc.NormalMass.Col2.Y = det * a;
}
else
{
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
cc.PointCount = 1;
}
}
}
}
public void WarmStart()
{
// Warm start.
for (int i = 0; i < _constraintCount; ++i)
{
ContactConstraint c = Constraints[i];
float tangentx = c.Normal.Y;
float tangenty = -c.Normal.X;
for (int j = 0; j < c.PointCount; ++j)
{
ContactConstraintPoint ccp = c.Points[j];
float px = ccp.NormalImpulse * c.Normal.X + ccp.TangentImpulse * tangentx;
float py = ccp.NormalImpulse * c.Normal.Y + ccp.TangentImpulse * tangenty;
c.BodyA.AngularVelocityInternal -= c.BodyA.InvI * (ccp.rA.X * py - ccp.rA.Y * px);
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * px;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * py;
c.BodyB.AngularVelocityInternal += c.BodyB.InvI * (ccp.rB.X * py - ccp.rB.Y * px);
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * px;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * py;
}
}
}
public void SolveVelocityConstraints()
{
for (int i = 0; i < _constraintCount; ++i)
{
ContactConstraint c = Constraints[i];
float wA = c.BodyA.AngularVelocityInternal;
float wB = c.BodyB.AngularVelocityInternal;
float tangentx = c.Normal.Y;
float tangenty = -c.Normal.X;
float friction = c.Friction;
Debug.Assert(c.PointCount == 1 || c.PointCount == 2);
// Solve tangent constraints
for (int j = 0; j < c.PointCount; ++j)
{
ContactConstraintPoint ccp = c.Points[j];
float lambda = ccp.TangentMass *
-((c.BodyB.LinearVelocityInternal.X + (-wB * ccp.rB.Y) -
c.BodyA.LinearVelocityInternal.X - (-wA * ccp.rA.Y)) * tangentx +
(c.BodyB.LinearVelocityInternal.Y + (wB * ccp.rB.X) -
c.BodyA.LinearVelocityInternal.Y - (wA * ccp.rA.X)) * tangenty);
// MathUtils.Clamp the accumulated force
float maxFriction = friction * ccp.NormalImpulse;
float newImpulse = Math.Max(-maxFriction, Math.Min(ccp.TangentImpulse + lambda, maxFriction));
lambda = newImpulse - ccp.TangentImpulse;
// Apply contact impulse
float px = lambda * tangentx;
float py = lambda * tangenty;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * px;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * py;
wA -= c.BodyA.InvI * (ccp.rA.X * py - ccp.rA.Y * px);
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * px;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * py;
wB += c.BodyB.InvI * (ccp.rB.X * py - ccp.rB.Y * px);
ccp.TangentImpulse = newImpulse;
}
// Solve normal constraints
if (c.PointCount == 1)
{
ContactConstraintPoint ccp = c.Points[0];
// Relative velocity at contact
// Compute normal impulse
float lambda = -ccp.NormalMass *
((c.BodyB.LinearVelocityInternal.X + (-wB * ccp.rB.Y) -
c.BodyA.LinearVelocityInternal.X - (-wA * ccp.rA.Y)) * c.Normal.X +
(c.BodyB.LinearVelocityInternal.Y + (wB * ccp.rB.X) -
c.BodyA.LinearVelocityInternal.Y -
(wA * ccp.rA.X)) * c.Normal.Y - ccp.VelocityBias);
// Clamp the accumulated impulse
float newImpulse = Math.Max(ccp.NormalImpulse + lambda, 0.0f);
lambda = newImpulse - ccp.NormalImpulse;
// Apply contact impulse
float px = lambda * c.Normal.X;
float py = lambda * c.Normal.Y;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * px;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * py;
wA -= c.BodyA.InvI * (ccp.rA.X * py - ccp.rA.Y * px);
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * px;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * py;
wB += c.BodyB.InvI * (ccp.rB.X * py - ccp.rB.Y * px);
ccp.NormalImpulse = newImpulse;
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn_0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = x' - a
//
// Plug into above equation:
//
// vn = A * x + b
// = A * (x' - a) + b
// = A * x' + b - A * a
// = A * x' + b'
// b' = b - A * a;
ContactConstraintPoint cp1 = c.Points[0];
ContactConstraintPoint cp2 = c.Points[1];
float ax = cp1.NormalImpulse;
float ay = cp2.NormalImpulse;
Debug.Assert(ax >= 0.0f && ay >= 0.0f);
// Relative velocity at contact
// Compute normal velocity
float vn1 = (c.BodyB.LinearVelocityInternal.X + (-wB * cp1.rB.Y) - c.BodyA.LinearVelocityInternal.X -
(-wA * cp1.rA.Y)) * c.Normal.X +
(c.BodyB.LinearVelocityInternal.Y + (wB * cp1.rB.X) - c.BodyA.LinearVelocityInternal.Y -
(wA * cp1.rA.X)) * c.Normal.Y;
float vn2 = (c.BodyB.LinearVelocityInternal.X + (-wB * cp2.rB.Y) - c.BodyA.LinearVelocityInternal.X -
(-wA * cp2.rA.Y)) * c.Normal.X +
(c.BodyB.LinearVelocityInternal.Y + (wB * cp2.rB.X) - c.BodyA.LinearVelocityInternal.Y -
(wA * cp2.rA.X)) * c.Normal.Y;
float bx = vn1 - cp1.VelocityBias - (c.K.Col1.X * ax + c.K.Col2.X * ay);
float by = vn2 - cp2.VelocityBias - (c.K.Col1.Y * ax + c.K.Col2.Y * ay);
float xx = -(c.NormalMass.Col1.X * bx + c.NormalMass.Col2.X * by);
float xy = -(c.NormalMass.Col1.Y * bx + c.NormalMass.Col2.Y * by);
while (true)
{
//
// Case 1: vn = 0
//
// 0 = A * x' + b'
//
// Solve for x':
//
// x' = - inv(A) * b'
//
if (xx >= 0.0f && xy >= 0.0f)
{
// Resubstitute for the incremental impulse
float dx = xx - ax;
float dy = xy - ay;
// Apply incremental impulse
float p1x = dx * c.Normal.X;
float p1y = dx * c.Normal.Y;
float p2x = dy * c.Normal.X;
float p2y = dy * c.Normal.Y;
float p12x = p1x + p2x;
float p12y = p1y + p2y;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * p12x;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * p12y;
wA -= c.BodyA.InvI * ((cp1.rA.X * p1y - cp1.rA.Y * p1x) + (cp2.rA.X * p2y - cp2.rA.Y * p2x));
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * p12x;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * p12y;
wB += c.BodyB.InvI * ((cp1.rB.X * p1y - cp1.rB.Y * p1x) + (cp2.rB.X * p2y - cp2.rB.Y * p2x));
// Accumulate
cp1.NormalImpulse = xx;
cp2.NormalImpulse = xy;
#if B2_DEBUG_SOLVER
float k_errorTol = 1e-3f;
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(MathUtils.Abs(vn1 - cp1.velocityBias) < k_errorTol);
Debug.Assert(MathUtils.Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1' + a12 * 0 + b1'
// vn2 = a21 * x1' + a22 * 0 + b2'
//
xx = -cp1.NormalMass * bx;
xy = 0.0f;
vn1 = 0.0f;
vn2 = c.K.Col1.Y * xx + by;
if (xx >= 0.0f && vn2 >= 0.0f)
{
// Resubstitute for the incremental impulse
float dx = xx - ax;
float dy = xy - ay;
// Apply incremental impulse
float p1x = dx * c.Normal.X;
float p1y = dx * c.Normal.Y;
float p2x = dy * c.Normal.X;
float p2y = dy * c.Normal.Y;
float p12x = p1x + p2x;
float p12y = p1y + p2y;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * p12x;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * p12y;
wA -= c.BodyA.InvI * ((cp1.rA.X * p1y - cp1.rA.Y * p1x) + (cp2.rA.X * p2y - cp2.rA.Y * p2x));
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * p12x;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * p12y;
wB += c.BodyB.InvI * ((cp1.rB.X * p1y - cp1.rB.Y * p1x) + (cp2.rB.X * p2y - cp2.rB.Y * p2x));
// Accumulate
cp1.NormalImpulse = xx;
cp2.NormalImpulse = xy;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
Debug.Assert(MathUtils.Abs(vn1 - cp1.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2' + b1'
// 0 = a21 * 0 + a22 * x2' + b2'
//
xx = 0.0f;
xy = -cp2.NormalMass * by;
vn1 = c.K.Col2.X * xy + bx;
vn2 = 0.0f;
if (xy >= 0.0f && vn1 >= 0.0f)
{
// Resubstitute for the incremental impulse
float dx = xx - ax;
float dy = xy - ay;
// Apply incremental impulse
float p1x = dx * c.Normal.X;
float p1y = dx * c.Normal.Y;
float p2x = dy * c.Normal.X;
float p2y = dy * c.Normal.Y;
float p12x = p1x + p2x;
float p12y = p1y + p2y;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * p12x;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * p12y;
wA -= c.BodyA.InvI * ((cp1.rA.X * p1y - cp1.rA.Y * p1x) + (cp2.rA.X * p2y - cp2.rA.Y * p2x));
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * p12x;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * p12y;
wB += c.BodyB.InvI * ((cp1.rB.X * p1y - cp1.rB.Y * p1x) + (cp2.rB.X * p2y - cp2.rB.Y * p2x));
// Accumulate
cp1.NormalImpulse = xx;
cp2.NormalImpulse = xy;
#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);
Debug.Assert(MathUtils.Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
xx = 0.0f;
xy = 0.0f;
vn1 = bx;
vn2 = by;
if (vn1 >= 0.0f && vn2 >= 0.0f)
{
// Resubstitute for the incremental impulse
float dx = xx - ax;
float dy = xy - ay;
// Apply incremental impulse
float p1x = dx * c.Normal.X;
float p1y = dx * c.Normal.Y;
float p2x = dy * c.Normal.X;
float p2y = dy * c.Normal.Y;
float p12x = p1x + p2x;
float p12y = p1y + p2y;
c.BodyA.LinearVelocityInternal.X -= c.BodyA.InvMass * p12x;
c.BodyA.LinearVelocityInternal.Y -= c.BodyA.InvMass * p12y;
wA -= c.BodyA.InvI * ((cp1.rA.X * p1y - cp1.rA.Y * p1x) + (cp2.rA.X * p2y - cp2.rA.Y * p2x));
c.BodyB.LinearVelocityInternal.X += c.BodyB.InvMass * p12x;
c.BodyB.LinearVelocityInternal.Y += c.BodyB.InvMass * p12y;
wB += c.BodyB.InvI * ((cp1.rB.X * p1y - cp1.rB.Y * p1x) + (cp2.rB.X * p2y - cp2.rB.Y * p2x));
// Accumulate
cp1.NormalImpulse = xx;
cp2.NormalImpulse = xy;
break;
}
// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}
c.BodyA.AngularVelocityInternal = wA;
c.BodyB.AngularVelocityInternal = wB;
}
}
public void StoreImpulses()
{
for (int i = 0; i < _constraintCount; ++i)
{
ContactConstraint c = Constraints[i];
Manifold m = c.Manifold;
for (int j = 0; j < c.PointCount; ++j)
{
ManifoldPoint pj = m.Points[j];
ContactConstraintPoint cp = c.Points[j];
pj.NormalImpulse = cp.NormalImpulse;
pj.TangentImpulse = cp.TangentImpulse;
m.Points[j] = pj;
}
c.Manifold = m;
_contacts[i].Manifold = m;
}
}
public bool SolvePositionConstraints(float baumgarte)
{
float minSeparation = 0.0f;
for (int i = 0; i < _constraintCount; ++i)
{
ContactConstraint c = Constraints[i];
PhysicsBody bodyA = c.BodyA;
PhysicsBody bodyB = c.BodyB;
float invMassA = bodyA.Mass * bodyA.InvMass;
float invIA = bodyA.Mass * bodyA.InvI;
float invMassB = bodyB.Mass * bodyB.InvMass;
float invIB = bodyB.Mass * bodyB.InvI;
// Solve normal constraints
for (int j = 0; j < c.PointCount; ++j)
{
Vector2 normal;
Vector2 point;
float separation;
Solve(c, j, out normal, out point, out separation);
float rax = point.X - bodyA.Sweep.C.X;
float ray = point.Y - bodyA.Sweep.C.Y;
float rbx = point.X - bodyB.Sweep.C.X;
float rby = point.Y - bodyB.Sweep.C.Y;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = Math.Max(-Settings.MaxLinearCorrection,
Math.Min(baumgarte * (separation + Settings.LinearSlop), 0.0f));
// Compute the effective mass.
float rnA = rax * normal.Y - ray * normal.X;
float rnB = rbx * normal.Y - rby * normal.X;
float K = invMassA + invMassB + invIA * rnA * rnA + invIB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
float px = impulse * normal.X;
float py = impulse * normal.Y;
bodyA.Sweep.C.X -= invMassA * px;
bodyA.Sweep.C.Y -= invMassA * py;
bodyA.Sweep.A -= invIA * (rax * py - ray * px);
bodyB.Sweep.C.X += invMassB * px;
bodyB.Sweep.C.Y += invMassB * py;
bodyB.Sweep.A += invIB * (rbx * py - rby * px);
bodyA.SynchronizeTransform();
bodyB.SynchronizeTransform();
}
}
// We can't expect minSpeparation >= -Settings.b2_linearSlop because we don't
// push the separation above -Settings.b2_linearSlop.
return minSeparation >= -1.5f * Settings.LinearSlop;
}
private static void Solve(ContactConstraint cc, int index, out Vector2 normal, out Vector2 point,
out float separation)
{
Debug.Assert(cc.PointCount > 0);
normal = Vector2.Zero;
switch (cc.Type)
{
case ManifoldType.Circles:
{
Vector2 pointA = cc.BodyA.GetWorldPoint(ref cc.LocalPoint);
Vector2 pointB = cc.BodyB.GetWorldPoint(ref cc.Points[0].LocalPoint);
float a = (pointA.X - pointB.X) * (pointA.X - pointB.X) +
(pointA.Y - pointB.Y) * (pointA.Y - pointB.Y);
if (a > Settings.Epsilon * Settings.Epsilon)
{
Vector2 normalTmp = pointB - pointA;
float factor = 1f / (float)Math.Sqrt(normalTmp.X * normalTmp.X + normalTmp.Y * normalTmp.Y);
normal.X = normalTmp.X * factor;
normal.Y = normalTmp.Y * factor;
}
else
{
normal.X = 1;
normal.Y = 0;
}
point = 0.5f * (pointA + pointB);
separation = (pointB.X - pointA.X) * normal.X + (pointB.Y - pointA.Y) * normal.Y - cc.RadiusA -
cc.RadiusB;
}
break;
case ManifoldType.FaceA:
{
normal = cc.BodyA.GetWorldVector(ref cc.LocalNormal);
Vector2 planePoint = cc.BodyA.GetWorldPoint(ref cc.LocalPoint);
Vector2 clipPoint = cc.BodyB.GetWorldPoint(ref cc.Points[index].LocalPoint);
separation = (clipPoint.X - planePoint.X) * normal.X + (clipPoint.Y - planePoint.Y) * normal.Y -
cc.RadiusA - cc.RadiusB;
point = clipPoint;
}
break;
case ManifoldType.FaceB:
{
normal = cc.BodyB.GetWorldVector(ref cc.LocalNormal);
Vector2 planePoint = cc.BodyB.GetWorldPoint(ref cc.LocalPoint);
Vector2 clipPoint = cc.BodyA.GetWorldPoint(ref cc.Points[index].LocalPoint);
separation = (clipPoint.X - planePoint.X) * normal.X + (clipPoint.Y - planePoint.Y) * normal.Y -
cc.RadiusA - cc.RadiusB;
point = clipPoint;
// Ensure normal points from A to B
normal = -normal;
}
break;
default:
point = Vector2.Zero;
separation = 0.0f;
break;
}
}
}
}
| |
namespace Petstore
{
using System.Linq;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// The Storage Management Client.
/// </summary>
public partial class StorageManagementClient : Microsoft.Rest.ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.StorageAccounts = new StorageAccountsOperations(this);
this.Usage = new UsageOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.ApiVersion = "2015-06-15";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Hatfield.EnviroData.MVC.Areas.HelpPage.Models;
namespace Hatfield.EnviroData.MVC.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;
using Object = UnityEngine.Object;
namespace Thinksquirrel.Development.Integration
{
struct Parameter
{
#region Public API
public object obj;
public Type parameterType;
public Parameter(object obj)
{
this.obj = obj;
parameterType = obj == null ? typeof(object) : obj.GetType();
}
public Parameter(object obj, Type type)
{
this.obj = obj;
parameterType = type;
}
#endregion
}
static class ReflectionHelpers
{
internal static T Cast<T>(this object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
var type = typeof(T);
return (T)Cast(obj, type);
}
internal static object Cast(this object obj, Type type)
{
if (obj == null) throw new ArgumentNullException("obj");
if (type == null) throw new ArgumentNullException("type");
if (type.IsEnum)
{
return Enum.ToObject(type, obj);
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return Convert.ChangeType(obj, Nullable.GetUnderlyingType(type));
}
return Convert.ChangeType(obj, type);
}
internal static Type GetEditorType(string typeName)
{
if (typeName == null) throw new ArgumentNullException("typeName");
return GetTypeInAssembly(typeof(Editor), string.Format("UnityEditor.{0}", typeName));
}
internal static FieldInfo GetField(this object obj, string fieldName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (fieldName == null) throw new ArgumentNullException("fieldName");
var t = obj.GetType();
while (t != null)
{
var candidate = t.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return candidate;
t = t.BaseType;
}
return null;
}
internal static Type GetFieldType(this Type type, string fieldName)
{
if (type == null) throw new ArgumentNullException("type");
if (fieldName == null) throw new ArgumentNullException("fieldName");
var t = type;
while (t != null)
{
var candidate = t.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return candidate.FieldType;
t = t.BaseType;
}
return null;
}
internal static Type GetFieldType(this object obj, string fieldName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (fieldName == null) throw new ArgumentNullException("fieldName");
return GetFieldType(obj.GetType(), fieldName);
}
internal static object GetFieldValue(this Type type, string fieldName)
{
if (type == null) throw new ArgumentNullException("type");
if (fieldName == null) throw new ArgumentNullException("fieldName");
return GetFieldValue<object>(type, null, fieldName);
}
internal static T GetFieldValue<T>(this Type type, string fieldName)
{
if (type == null) throw new ArgumentNullException("type");
if (fieldName == null) throw new ArgumentNullException("fieldName");
return GetFieldValue<T>(type, null, fieldName);
}
internal static object GetFieldValue(this object obj, string fieldName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (fieldName == null) throw new ArgumentNullException("fieldName");
return GetFieldValue<object>(obj.GetType(), obj, fieldName);
}
internal static T GetFieldValue<T>(this object obj, string fieldName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (fieldName == null) throw new ArgumentNullException("fieldName");
return GetFieldValue<T>(obj.GetType(), obj, fieldName);
}
internal static MethodInfo GetMethod(this object obj, string methodName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (methodName == null) throw new ArgumentNullException("methodName");
var t = obj.GetType();
while (t != null)
{
var candidate = t.GetMethod(methodName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return candidate;
t = t.BaseType;
}
return null;
}
internal static PropertyInfo GetProperty(this object obj, string propertyName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (propertyName == null) throw new ArgumentNullException("propertyName");
var t = obj.GetType();
while (t != null)
{
var candidate = t.GetProperty(propertyName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return candidate;
t = t.BaseType;
}
return null;
}
internal static Type GetPropertyType(this Type type, string propertyName)
{
if (type == null) throw new ArgumentNullException("type");
if (propertyName == null) throw new ArgumentNullException("propertyName");
var t = type;
while (t != null)
{
var candidate = t.GetProperty(propertyName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return candidate.PropertyType;
t = t.BaseType;
}
return null;
}
internal static Type GetPropertyType(this object obj, string propertyName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (propertyName == null) throw new ArgumentNullException("propertyName");
return GetPropertyType(obj.GetType(), propertyName);
}
internal static object GetPropertyValue(this Type type, string propertyName)
{
if (type == null) throw new ArgumentNullException("type");
if (propertyName == null) throw new ArgumentNullException("propertyName");
return GetPropertyValue<object>(type, null, propertyName);
}
internal static T GetPropertyValue<T>(this Type type, string propertyName)
{
if (type == null) throw new ArgumentNullException("type");
if (propertyName == null) throw new ArgumentNullException("propertyName");
return GetPropertyValue<T>(type, null, propertyName);
}
internal static object GetPropertyValue(this object obj, string propertyName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (propertyName == null) throw new ArgumentNullException("propertyName");
return GetPropertyValue<object>(obj.GetType(), obj, propertyName);
}
internal static T GetPropertyValue<T>(this object obj, string propertyName)
{
if (obj == null) throw new ArgumentNullException("obj");
if (propertyName == null) throw new ArgumentNullException("propertyName");
return GetPropertyValue<T>(obj.GetType(), obj, propertyName);
}
internal static Type GetRuntimeType(string typeName)
{
if (typeName == null) throw new ArgumentNullException("typeName");
return GetTypeInAssembly(typeof(Object), string.Format("UnityEngine.{0}", typeName));
}
internal static Type GetTypeInAssembly(this Type type, string typeName)
{
if (type == null) throw new ArgumentNullException("type");
if (typeName == null) throw new ArgumentNullException("typeName");
return type.Assembly.GetType(typeName);
}
internal static object Invoke(this Type type, string methodName, params Parameter[] parameters)
{
if (type == null) throw new ArgumentNullException("type");
if (methodName == null) throw new ArgumentNullException("methodName");
return Invoke<object>(type, null, methodName, parameters);
}
internal static T Invoke<T>(this Type type, string methodName, params Parameter[] parameters)
{
if (type == null) throw new ArgumentNullException("type");
if (methodName == null) throw new ArgumentNullException("methodName");
return Invoke<T>(type, null, methodName, parameters);
}
internal static object Invoke(this object obj, string methodName, params Parameter[] parameters)
{
if (obj == null) throw new ArgumentNullException("obj");
if (methodName == null) throw new ArgumentNullException("methodName");
return Invoke<object>(obj.GetType(), obj, methodName, parameters);
}
internal static T Invoke<T>(this object obj, string methodName, params Parameter[] parameters)
{
if (obj == null) throw new ArgumentNullException("obj");
if (methodName == null) throw new ArgumentNullException("methodName");
return Invoke<T>(obj.GetType(), obj, methodName, parameters);
}
internal static Type NestedType(this Type type, string typeName)
{
if (type == null) throw new ArgumentNullException("type");
if (typeName == null) throw new ArgumentNullException("typeName");
return type.GetNestedType(typeName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
}
internal static Parameter Param(this object obj)
{
if (obj == null) throw new ArgumentNullException("obj");
return new Parameter(obj);
}
internal static void SetFieldValue(this Type type, string fieldName, object value)
{
if (type == null) throw new ArgumentNullException("type");
if (fieldName == null) throw new ArgumentNullException("fieldName");
SetFieldValue(type, null, fieldName, value);
}
internal static void SetFieldValue(this object obj, string fieldName, object value)
{
if (obj == null) throw new ArgumentNullException("obj");
if (fieldName == null) throw new ArgumentNullException("fieldName");
SetFieldValue(obj.GetType(), obj, fieldName, value);
}
internal static void SetPropertyValue(this Type type, string propertyName, object value)
{
if (type == null) throw new ArgumentNullException("type");
if (propertyName == null) throw new ArgumentNullException("propertyName");
SetPropertyValue(type, null, propertyName, value);
}
internal static void SetPropertyValue(this object obj, string propertyName, object value)
{
if (obj == null) throw new ArgumentNullException("obj");
if (propertyName == null) throw new ArgumentNullException("propertyName");
SetPropertyValue(obj.GetType(), obj, propertyName, value);
}
internal static object Create(this Type type, params Parameter[] parameters)
{
return Create<object>(type, parameters);
}
internal static T Create<T>(this Type type, params Parameter[] parameters)
{
if (type == null) throw new ArgumentNullException("type");
return
(T)
type.GetConstructor(
BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
parameters.Select(p => p.parameterType).ToArray(), null)
.Invoke(parameters.Select(p => p.obj).ToArray());
}
static T GetFieldValue<T>(Type type, object obj, string fieldName)
{
var t = type;
while (t != null)
{
var candidate = t.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return (T)candidate.GetValue(obj);
t = t.BaseType;
}
return default(T);
}
static T GetPropertyValue<T>(Type type, object obj, string propertyName)
{
var t = type;
while (t != null)
{
var candidate = t.GetProperty(propertyName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null) return (T)candidate.GetValue(obj, null);
t = t.BaseType;
}
return default(T);
}
static T Invoke<T>(Type type, object obj, string methodName, params Parameter[] parameters)
{
var t = type;
while (t != null)
{
var candidate = t.GetMethod(methodName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public, null, parameters.Select(p => p.parameterType).ToArray(),
null);
if (candidate != null) return (T)candidate.Invoke(obj, parameters.Select(p => p.obj).ToArray());
t = t.BaseType;
}
return default(T);
}
static void SetFieldValue(Type type, object obj, string fieldName, object value)
{
var t = type;
while (t != null)
{
var candidate = t.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null)
{
candidate.SetValue(obj, value);
return;
}
t = t.BaseType;
}
}
static void SetPropertyValue(Type type, object obj, string propertyName, object value)
{
var t = type;
while (t != null)
{
var candidate = t.GetProperty(propertyName,
BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
if (candidate != null)
{
candidate.SetValue(obj, value, null);
return;
}
t = t.BaseType;
}
}
}
}
| |
/* ====================================================================
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.IO;
using NPOI.POIFS.EventFileSystem;
using NPOI.Util;
namespace NPOI.POIFS.Crypt
{
using System;
using System.Text;
using NPOI.POIFS.Crypt.Standard;
using NPOI.POIFS.FileSystem;
public class DataSpaceMapUtils
{
public static void AddDefaultDataSpace(DirectoryEntry dir)
{
DataSpaceMapEntry dsme = new DataSpaceMapEntry(
new int[] { 0 }
, new String[] { Decryptor.DEFAULT_POIFS_ENTRY }
, "StrongEncryptionDataSpace"
);
DataSpaceMap dsm = new DataSpaceMap(new DataSpaceMapEntry[] { dsme });
CreateEncryptionEntry(dir, "\u0006DataSpaces/DataSpaceMap", dsm);
DataSpaceDefInition dsd = new DataSpaceDefInition(new String[] { "StrongEncryptionTransform" });
CreateEncryptionEntry(dir, "\u0006DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace", dsd);
TransformInfoHeader tih = new TransformInfoHeader(
1
, "{FF9A3F03-56EF-4613-BDD5-5A41C1D07246}"
, "Microsoft.Container.EncryptionTransform"
, 1, 0, 1, 0, 1, 0
);
IRMDSTransformInfo irm = new IRMDSTransformInfo(tih, 0, null);
CreateEncryptionEntry(dir, "\u0006DataSpaces/TransformInfo/StrongEncryptionTransform/\u0006Primary", irm);
DataSpaceVersionInfo dsvi = new DataSpaceVersionInfo("Microsoft.Container.DataSpaces", 1, 0, 1, 0, 1, 0);
CreateEncryptionEntry(dir, "\u0006DataSpaces/Version", dsvi);
}
public static DocumentEntry CreateEncryptionEntry(DirectoryEntry dir, String path, EncryptionRecord out1)
{
String[] parts = path.Split("/".ToCharArray());
for (int i = 0; i < parts.Length - 1; i++)
{
dir = dir.HasEntry(parts[i])
? (DirectoryEntry)dir.GetEntry(parts[i])
: dir.CreateDirectory(parts[i]);
}
byte[] buf = new byte[5000];
LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0);
out1.Write(bos);
String fileName = parts[parts.Length - 1];
if (dir.HasEntry(fileName))
{
dir.GetEntry(fileName).Delete();
}
return dir.CreateDocument(fileName, bos.WriteIndex, new POIFSWriterListenerImpl(buf));
}
public class POIFSWriterListenerImpl : POIFSWriterListener
{
byte[] buf;
public POIFSWriterListenerImpl(byte[] buf)
{
this.buf = buf;
}
public void ProcessPOIFSWriterEvent(POIFSWriterEvent event1)
{
try
{
event1.Stream.Write(buf, 0, event1.Limit);
}
catch (IOException e)
{
throw new EncryptedDocumentException(e);
}
}
}
public class DataSpaceMap : EncryptionRecord
{
DataSpaceMapEntry[] entries;
public DataSpaceMap(DataSpaceMapEntry[] entries)
{
this.entries = entries;
}
public DataSpaceMap(ILittleEndianInput is1)
{
//@SuppressWarnings("unused")
int length = is1.ReadInt();
int entryCount = is1.ReadInt();
entries = new DataSpaceMapEntry[entryCount];
for (int i = 0; i < entryCount; i++)
{
entries[i] = new DataSpaceMapEntry(is1);
}
}
public void Write(LittleEndianByteArrayOutputStream os)
{
os.WriteInt(8);
os.WriteInt(entries.Length);
foreach (DataSpaceMapEntry dsme in entries)
{
dsme.Write(os);
}
}
}
public class DataSpaceMapEntry : EncryptionRecord
{
int[] referenceComponentType;
String[] referenceComponent;
String dataSpaceName;
public DataSpaceMapEntry(int[] referenceComponentType, String[] referenceComponent, String dataSpaceName)
{
this.referenceComponentType = referenceComponentType;
this.referenceComponent = referenceComponent;
this.dataSpaceName = dataSpaceName;
}
public DataSpaceMapEntry(ILittleEndianInput is1)
{
int length = is1.ReadInt();
int referenceComponentCount = is1.ReadInt();
referenceComponentType = new int[referenceComponentCount];
referenceComponent = new String[referenceComponentCount];
for (int i = 0; i < referenceComponentCount; i++)
{
referenceComponentType[i] = is1.ReadInt();
referenceComponent[i] = ReadUnicodeLPP4(is1);
}
dataSpaceName = ReadUnicodeLPP4(is1);
}
public void Write(LittleEndianByteArrayOutputStream os)
{
int start = os.WriteIndex;
ILittleEndianOutput sizeOut = os.CreateDelayedOutput(LittleEndianConsts.INT_SIZE);
os.WriteInt(referenceComponent.Length);
for (int i = 0; i < referenceComponent.Length; i++)
{
os.WriteInt(referenceComponentType[i]);
WriteUnicodeLPP4(os, referenceComponent[i]);
}
WriteUnicodeLPP4(os, dataSpaceName);
sizeOut.WriteInt(os.WriteIndex - start);
}
}
public class DataSpaceDefInition : EncryptionRecord
{
String[] transformer;
public DataSpaceDefInition(String[] transformer)
{
this.transformer = transformer;
}
public DataSpaceDefInition(ILittleEndianInput is1)
{
int headerLength = is1.ReadInt();
int transformReferenceCount = is1.ReadInt();
transformer = new String[transformReferenceCount];
for (int i = 0; i < transformReferenceCount; i++)
{
transformer[i] = ReadUnicodeLPP4(is1);
}
}
public void Write(LittleEndianByteArrayOutputStream bos)
{
bos.WriteInt(8);
bos.WriteInt(transformer.Length);
foreach (String str in transformer)
{
WriteUnicodeLPP4(bos, str);
}
}
}
public class IRMDSTransformInfo : EncryptionRecord
{
TransformInfoHeader transformInfoHeader;
int extensibilityHeader;
String xrMLLicense;
public IRMDSTransformInfo(TransformInfoHeader transformInfoHeader, int extensibilityHeader, String xrMLLicense)
{
this.transformInfoHeader = transformInfoHeader;
this.extensibilityHeader = extensibilityHeader;
this.xrMLLicense = xrMLLicense;
}
public IRMDSTransformInfo(ILittleEndianInput is1)
{
transformInfoHeader = new TransformInfoHeader(is1);
extensibilityHeader = is1.ReadInt();
xrMLLicense = ReadUtf8LPP4(is1);
// finish with 0x04 (int) ???
}
public void Write(LittleEndianByteArrayOutputStream bos)
{
transformInfoHeader.Write(bos);
bos.WriteInt(extensibilityHeader);
WriteUtf8LPP4(bos, xrMLLicense);
bos.WriteInt(4); // where does this 4 come from???
}
}
public class TransformInfoHeader : EncryptionRecord
{
int transformType;
String transformerId;
String transformerName;
int readerVersionMajor = 1, readerVersionMinor = 0;
int updaterVersionMajor = 1, updaterVersionMinor = 0;
int writerVersionMajor = 1, writerVersionMinor = 0;
public TransformInfoHeader(
int transformType,
String transformerId,
String transformerName,
int readerVersionMajor, int readerVersionMinor,
int updaterVersionMajor, int updaterVersionMinor,
int writerVersionMajor, int writerVersionMinor
)
{
this.transformType = transformType;
this.transformerId = transformerId;
this.transformerName = transformerName;
this.readerVersionMajor = readerVersionMajor;
this.readerVersionMinor = readerVersionMinor;
this.updaterVersionMajor = updaterVersionMajor;
this.updaterVersionMinor = updaterVersionMinor;
this.writerVersionMajor = writerVersionMajor;
this.writerVersionMinor = writerVersionMinor;
}
public TransformInfoHeader(ILittleEndianInput is1)
{
int length = is1.ReadInt();
transformType = is1.ReadInt();
transformerId = ReadUnicodeLPP4(is1);
transformerName = ReadUnicodeLPP4(is1);
readerVersionMajor = is1.ReadShort();
readerVersionMinor = is1.ReadShort();
updaterVersionMajor = is1.ReadShort();
updaterVersionMinor = is1.ReadShort();
writerVersionMajor = is1.ReadShort();
writerVersionMinor = is1.ReadShort();
}
public void Write(LittleEndianByteArrayOutputStream bos)
{
int start = bos.WriteIndex;
ILittleEndianOutput sizeOut = bos.CreateDelayedOutput(LittleEndianConsts.INT_SIZE);
bos.WriteInt(transformType);
WriteUnicodeLPP4(bos, transformerId);
sizeOut.WriteInt(bos.WriteIndex - start);
WriteUnicodeLPP4(bos, transformerName);
bos.WriteShort(readerVersionMajor);
bos.WriteShort(readerVersionMinor);
bos.WriteShort(updaterVersionMajor);
bos.WriteShort(updaterVersionMinor);
bos.WriteShort(writerVersionMajor);
bos.WriteShort(writerVersionMinor);
}
}
public class DataSpaceVersionInfo : EncryptionRecord
{
String featureIdentifier;
int readerVersionMajor = 1, readerVersionMinor = 0;
int updaterVersionMajor = 1, updaterVersionMinor = 0;
int writerVersionMajor = 1, writerVersionMinor = 0;
public DataSpaceVersionInfo(ILittleEndianInput is1)
{
featureIdentifier = ReadUnicodeLPP4(is1);
readerVersionMajor = is1.ReadShort();
readerVersionMinor = is1.ReadShort();
updaterVersionMajor = is1.ReadShort();
updaterVersionMinor = is1.ReadShort();
writerVersionMajor = is1.ReadShort();
writerVersionMinor = is1.ReadShort();
}
public DataSpaceVersionInfo(
String featureIdentifier,
int readerVersionMajor, int readerVersionMinor,
int updaterVersionMajor, int updaterVersionMinor,
int writerVersionMajor, int writerVersionMinor
)
{
this.featureIdentifier = featureIdentifier;
this.readerVersionMajor = readerVersionMajor;
this.readerVersionMinor = readerVersionMinor;
this.updaterVersionMajor = updaterVersionMajor;
this.updaterVersionMinor = updaterVersionMinor;
this.writerVersionMajor = writerVersionMajor;
this.writerVersionMinor = writerVersionMinor;
}
public void Write(LittleEndianByteArrayOutputStream bos)
{
WriteUnicodeLPP4(bos, featureIdentifier);
bos.WriteShort(readerVersionMajor);
bos.WriteShort(readerVersionMinor);
bos.WriteShort(updaterVersionMajor);
bos.WriteShort(updaterVersionMinor);
bos.WriteShort(writerVersionMajor);
bos.WriteShort(writerVersionMinor);
}
}
public static String ReadUnicodeLPP4(ILittleEndianInput is1)
{
int length = is1.ReadInt();
if (length % 2 != 0)
{
throw new EncryptedDocumentException(
"UNICODE-LP-P4 structure is a multiple of 4 bytes. "
+ "If PAdding is present, it MUST be exactly 2 bytes long");
}
String result = StringUtil.ReadUnicodeLE(is1, length / 2);
if (length % 4 == 2)
{
// PAdding (variable): A Set of bytes that MUST be of the correct size such that the size of the
// UNICODE-LP-P4 structure is a multiple of 4 bytes. If PAdding is present, it MUST be exactly
// 2 bytes long, and each byte MUST be 0x00.
is1.ReadShort();
}
return result;
}
public static void WriteUnicodeLPP4(ILittleEndianOutput os, String string1)
{
byte[] buf = StringUtil.GetToUnicodeLE(string1);
os.WriteInt(buf.Length);
os.Write(buf);
if (buf.Length % 4 == 2)
{
os.WriteShort(0);
}
}
public static String ReadUtf8LPP4(ILittleEndianInput is1)
{
int length = is1.ReadInt();
if (length == 0 || length == 4)
{
//@SuppressWarnings("unused")
int skip = is1.ReadInt(); // ignore
return length == 0 ? null : "";
}
byte[] data = new byte[length];
is1.ReadFully(data);
// Padding (variable): A set of bytes that MUST be of correct size such that the size of the UTF-8-LP-P4
// structure is a multiple of 4 bytes. If PAdding is present, each byte MUST be 0x00. If
// the length is exactly 0x00000000, this specifies a null string, and the entire structure uses
// exactly 4 bytes. If the length is exactly 0x00000004, this specifies an empty string, and the
// entire structure also uses exactly 4 bytes
int scratchedBytes = length % 4;
if (scratchedBytes > 0)
{
for (int i = 0; i < (4 - scratchedBytes); i++)
{
is1.ReadByte();
}
}
return Encoding.UTF8.GetString(data, 0, data.Length);
//return new String(data, 0, data.length, Charset.forName("UTF-8"));
}
public static void WriteUtf8LPP4(ILittleEndianOutput os, String str)
{
if (str == null || "".Equals(str))
{
os.WriteInt(str == null ? 0 : 4);
os.WriteInt(0);
}
else
{
byte[] buf = Encoding.UTF8.GetBytes(str);// str.GetBytes(Charset.ForName("UTF-8"));
os.WriteInt(buf.Length);
os.Write(buf);
int scratchBytes = buf.Length % 4;
if (scratchBytes > 0)
{
for (int i = 0; i < (4 - scratchBytes); i++)
{
os.WriteByte(0);
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
namespace Test
{
public class ToDictionaryTests
{
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.ToDictionary(x => x * 2),
p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.ToDictionary(x => x, y => y * 2),
p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_ElementSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.ToDictionary(x => x * 2, new ModularCongruenceComparer(count * 2)),
p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.ToDictionary(x => x, y => y * 2, new ModularCongruenceComparer(count)),
p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); });
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_ElementSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_UniqueKeys_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
if (count > 2)
{
AggregateException e = Assert.Throws<AggregateException>(() => query.ToDictionary(x => x, new ModularCongruenceComparer(2)));
Assert.IsType<ArgumentException>(e.InnerException);
}
else if (count == 1 || count == 2)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (KeyValuePair<int, int> entry in query.ToDictionary(x => x, new ModularCongruenceComparer(2)))
{
seen.Add(entry.Key);
Assert.Equal(entry.Key, entry.Value);
}
seen.AssertComplete();
}
else
{
Assert.Empty(query.ToDictionary(x => x, new ModularCongruenceComparer(2)));
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_UniqueKeys_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_UniqueKeys_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector_UniqueKeys_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
if (count > 2)
{
AggregateException e = Assert.Throws<AggregateException>(() => query.ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
Assert.IsType<ArgumentException>(e.InnerException);
}
else if (count == 1 || count == 2)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (KeyValuePair<int, int> entry in query.ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)))
{
seen.Add(entry.Key);
Assert.Equal(entry.Key, entry.Value);
}
seen.AssertComplete();
}
else
{
Assert.Empty(query.ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
}
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_ElementSelector_UniqueKeys_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_ElementSelector_UniqueKeys_CustomComparator(labeled, count);
}
[Fact]
public static void ToDictionary_DuplicateKeys()
{
AggregateException e = Assert.Throws<AggregateException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x));
Assert.IsType<ArgumentException>(e.InnerException);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_DuplicateKeys_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
AggregateException e = Assert.Throws<AggregateException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, y => y));
Assert.IsType<ArgumentException>(e.InnerException);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_DuplicateKeys_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_DuplicateKeys_ElementSelector(labeled, count);
}
[Fact]
public static void ToDictionary_DuplicateKeys_CustomComparator()
{
AggregateException e = Assert.Throws<AggregateException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, new ModularCongruenceComparer(2)));
Assert.IsType<ArgumentException>(e.InnerException);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_DuplicateKeys_ElementSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
AggregateException e = Assert.Throws<AggregateException>(() => ParallelEnumerable.Repeat(0, 2).ToDictionary(x => x, y => y, new ModularCongruenceComparer(2)));
Assert.IsType<ArgumentException>(e.InnerException);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024 * 4, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_DuplicateKeys_ElementSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToDictionary_DuplicateKeys_ElementSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToDictionary(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToDictionary(x => x, EqualityComparer<int>.Default));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToDictionary(x => x, y => y));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).ToDictionary(x => x, y => y, EqualityComparer<int>.Default));
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void ToDictionary_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary((Func<int, int>)(x => { throw new DeliberateTestException(); }), y => y, EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, (Func<int, int>)(y => { throw new DeliberateTestException(); }), EqualityComparer<int>.Default));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, new FailingEqualityComparer<int>()));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.ToDictionary(x => x, y => y, new FailingEqualityComparer<int>()));
}
[Fact]
public static void ToDictionary_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToDictionary(x => x));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToDictionary(x => x, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToDictionary(x => x, y => y));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).ToDictionary(x => x, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, y => y));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary((Func<int, int>)null, y => y, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary(x => x, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<int>().ToDictionary(x => x, (Func<int, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using MonoTouch.CoreAnimation;
using System.Linq;
namespace ClanceysLib
{
namespace DayCalendar
{
internal class Block
{
internal ArrayList Columns;
public List<CalendarDayEventView> events = new List<CalendarDayEventView> ();
internal Block ()
{
}
internal void Add (CalendarDayEventView ev)
{
events.Add (ev);
arrangeColumns ();
}
private BlockColumn createColumn ()
{
BlockColumn col = new BlockColumn ();
this.Columns.Add (col);
col.Block = this;
return col;
}
private void arrangeColumns ()
{
// cleanup
this.Columns = new ArrayList ();
foreach (CalendarDayEventView e in events)
e.Column = null;
// there always will be at least one column because arrangeColumns is called only from Add()
createColumn ();
foreach (CalendarDayEventView e in events)
{
foreach (BlockColumn col in Columns)
{
if (col.CanAdd (e))
{
col.Add (e);
break;
}
}
// it wasn't placed
if (e.Column == null)
{
BlockColumn col = createColumn ();
col.Add (e);
}
}
}
internal bool OverlapsWith (CalendarDayEventView e)
{
if (events.Count == 0)
return false;
return (this.BoxStart < e.BoxEnd && this.BoxEnd > e.startDate);
}
internal DateTime BoxStart {
get { return (from e in events.ToArray ()select e.BoxStart).Min (); }
}
internal DateTime BoxEnd {
get { return (from e in events.ToArray ()select e.BoxEnd).Max (); }
}
}
internal class BlockColumn
{
private ArrayList events = new ArrayList ();
internal Block Block;
private bool isLastInBlock {
get { return Block.Columns[Block.Columns.Count - 1] == this; }
}
internal BlockColumn ()
{
}
internal bool CanAdd (CalendarDayEventView e)
{
foreach (CalendarDayEventView ev in events)
{
if (ev.OverlapsWith (e))
return false;
}
return true;
}
internal void Add (CalendarDayEventView e)
{
if (e.Column != null)
throw new ApplicationException ("This Event was already placed into a Column.");
events.Add (e);
e.Column = this;
}
/// <summary>
/// Gets the order number of the column.
/// </summary>
public int Number {
get {
if (Block == null)
throw new ApplicationException ("This Column doesn't belong to any Block.");
return Block.Columns.IndexOf (this);
}
}
}
public class CalendarDayEventView : UIView
{
private static float HORIZONTAL_OFFSET = 4.0f;
private static float VERTICAL_OFFSET = 5.0f;
private static float VERTICAL_DIFF = 50.0f;
private static float FONT_SIZE = 12.0f;
public int id { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public string Title { get; set; }
public string Location { get; set; }
internal BlockColumn Column { get; set; }
public CalendarDayEventView ()
{
this.Frame = new RectangleF (0, 0, 320, 400);
setupCustomInitialisation ();
}
public CalendarDayEventView (RectangleF frame)
{
this.Frame = frame;
setupCustomInitialisation ();
}
public DateTime BoxStart {
get {
if (startDate.Minute >= 30)
return new DateTime (startDate.Year, startDate.Month, startDate.Day, startDate.Hour, 30, 0);
else
return new DateTime (startDate.Year, startDate.Month, startDate.Day, startDate.Hour, 0, 0);
}
}
public bool OverlapsWith (CalendarDayEventView e)
{
return (this.BoxStart < e.BoxEnd && this.BoxEnd > e.startDate);
}
public DateTime BoxEnd {
get {
if (endDate.Minute > 30)
{
DateTime hourPlus = endDate.AddHours (1);
return new DateTime (hourPlus.Year, hourPlus.Month, hourPlus.Day, hourPlus.Hour, 0, 0);
}
else if (endDate.Minute > 0)
{
return new DateTime (endDate.Year, endDate.Month, endDate.Day, endDate.Hour, 30, 0);
}
else
{
return new DateTime (endDate.Year, endDate.Month, endDate.Day, endDate.Hour, 0, 0);
}
}
}
public void setupCustomInitialisation ()
{
this.BackgroundColor = UIColor.Purple;
this.Alpha = 0.8f;
CALayer layer = this.Layer;
layer.MasksToBounds = true;
layer.CornerRadius = 5.0f;
// You can even add a border
layer.BorderWidth = 0.5f;
layer.BorderColor = UIColor.LightGray.CGColor;
}
public override void Draw (RectangleF rect)
{
// Retrieve the graphics context
var context = UIGraphics.GetCurrentContext ();
//CGContextRef context = new UIGraphicsGetCurrentContext();
// Save the context state
context.SaveState ();
// Set shadow
context.SetShadowWithColor (new SizeF (0.0f, 1.0f), 0.7f, UIColor.Black.CGColor);
// Set text color
UIColor.White.SetColor ();
RectangleF titleRect = new RectangleF (this.Bounds.X + HORIZONTAL_OFFSET, this.Bounds.Y + VERTICAL_OFFSET, this.Bounds.Width - 2 * HORIZONTAL_OFFSET, FONT_SIZE + 4.0f);
RectangleF locationRect = new RectangleF (this.Bounds.X + HORIZONTAL_OFFSET, this.Bounds.Y + VERTICAL_OFFSET + FONT_SIZE + 4.0f, this.Bounds.Width - 2 * HORIZONTAL_OFFSET, FONT_SIZE + 4.0f);
// Drawing code
if (this.Bounds.Height > VERTICAL_DIFF)
{
// Draw both title and location
if (!string.IsNullOrEmpty (this.Title))
{
DrawString (Title, titleRect, UIFont.BoldSystemFontOfSize (FONT_SIZE), UILineBreakMode.TailTruncation, UITextAlignment.Left);
}
if (!string.IsNullOrEmpty (Location))
{
DrawString (Location, locationRect, UIFont.SystemFontOfSize (FONT_SIZE), UILineBreakMode.TailTruncation, UITextAlignment.Left);
}
}
else
{
// Draw only title
if (!string.IsNullOrEmpty (Title))
{
DrawString (Title, titleRect, UIFont.BoldSystemFontOfSize (FONT_SIZE), UILineBreakMode.TailTruncation, UITextAlignment.Left);
}
}
// Restore the context state
context.RestoreState ();
}
}
public class CalendarDaytimelineView : UIView
{
//////
public static float HORIZONTAL_OFFSET = 3.0f;
public static float VERTICAL_OFFSET = 5.0f;
public static float TIME_WIDTH = 20.0f;
public static float PERIOD_WIDTH = 26.0f;
private static float VERTICAL_DIFF = 50.0f;
public static float FONT_SIZE = 14.0f;
public static float HORIZONTAL_LINE_DIFF = 10.0f;
public static float TIMELINE_HEIGHT = (24 * VERTICAL_OFFSET) + (23 * VERTICAL_DIFF);
public static float EVENT_VERTICAL_DIFF = 0.0f;
public static float EVENT_HORIZONTAL_DIFF = 2.0f;
public List<CalendarDayEventView> Events;
public DateTime currentDate;
private UIScrollView scrollView;
private TimeLineView timelineView;
// The designated initializer. Override to perform setup that is required before the view is loaded.
// Only when xibless (interface buildder)
public CalendarDaytimelineView (RectangleF rect)
{
this.Frame = rect;
this.BackgroundColor = UIColor.White;
setupCustomInitialisation ();
}
public CalendarDaytimelineView ()
{
this.Frame = new RectangleF (0, 0, 320, 400);
setupCustomInitialisation ();
}
public void setupCustomInitialisation ()
{
// Initialization code
Events = new List<CalendarDayEventView> ();
currentDate = DateTime.Today;
// Add main scroll view
this.AddSubview (getScrollView ());
// Add timeline view inside scrollview
scrollView.AddSubview (getTimeLineView ());
}
private UIScrollView getScrollView ()
{
if (scrollView == null)
{
scrollView = new UIScrollView (this.Bounds);
scrollView.ContentSize = new SizeF (this.Bounds.Size.Width, TIMELINE_HEIGHT);
scrollView.ScrollEnabled = true;
scrollView.BackgroundColor = UIColor.White;
scrollView.AlwaysBounceVertical = true;
}
return scrollView;
}
private TimeLineView getTimeLineView ()
{
if (timelineView == null)
{
timelineView = new TimeLineView (new RectangleF (this.Bounds.X, this.Bounds.Y, this.Bounds.Size.Width, TIMELINE_HEIGHT));
timelineView.BackgroundColor = UIColor.White;
}
return timelineView;
}
public override void MovedToWindow ()
{
if (Window != null)
this.reloadDay ();
}
private void reloadDay ()
{
// If no current day was given
// Make it today
if (currentDate != null)
{
// Dont' want to inform the observer
currentDate = DateTime.Today;
}
// Remove all previous view event
foreach (var view in this.scrollView.Subviews)
{
if (view is TimeLineView)
{
view.Frame = Frame;
}
else
{
view.RemoveFromSuperview ();
}
}
// Ask the delgate about the events that correspond
// the the currently displayed day view
if (Events != null)
{
Events = Events.OrderBy (x => x.startDate).ThenByDescending (x => x.endDate).ToList ();
List<Block> blocks = new List<Block> ();
Block lastBlock = new Block ();
foreach (CalendarDayEventView e in Events)
{
// if there is no block, create the first one
if (blocks.Count == 0)
{
lastBlock = new Block ();
blocks.Add (lastBlock);
}
// or if the event doesn't overlap with the last block, create a new block
else if (!lastBlock.OverlapsWith (e))
{
lastBlock = new Block ();
blocks.Add (lastBlock);
}
// any case, add it to some block
lastBlock.Add (e);
}
foreach (Block theBlock in blocks)
{
foreach (CalendarDayEventView theEvent in theBlock.events)
{
// Making sure delgate sending date that match current day
if (theEvent.startDate.Date == currentDate)
{
// Get the hour start position
Int32 hourStart = theEvent.startDate.Hour;
float hourStartPosition = (float)Math.Round ((hourStart * VERTICAL_DIFF) + VERTICAL_OFFSET + ((FONT_SIZE + 4.0f) / 2.0f));
// Get the minute start position
// Round minute to each 5
Int32 minuteStart = theEvent.startDate.Minute;
minuteStart = Convert.ToInt32 (Math.Round (minuteStart / 5.0f) * 5);
float minuteStartPosition = (float)Math.Round ((minuteStart < 30) ? 0 : VERTICAL_DIFF / 2.0);
// Get the hour end position
Int32 hourEnd = theEvent.endDate.Hour;
if (theEvent.startDate.Date != theEvent.endDate.Date)
{
hourEnd = 23;
}
float hourEndPosition = (float)Math.Round ((hourEnd * VERTICAL_DIFF) + VERTICAL_OFFSET + ((FONT_SIZE + 4.0f) / 2.0f));
// Get the minute end position
// Round minute to each 5
Int32 minuteEnd = theEvent.endDate.Minute;
if (theEvent.startDate.Date != theEvent.endDate.Date)
{
minuteEnd = 55;
}
minuteEnd = Convert.ToInt32 (Math.Round (minuteEnd / 5.0) * 5);
float minuteEndPosition = (float)Math.Round ((minuteEnd < 30) ? 0 : VERTICAL_DIFF / 2.0f);
float eventHeight = 0.0f;
if (minuteStartPosition == minuteEndPosition || hourEnd == 23)
{
// Starting and ending date position are the same
// Take all half hour space
// Or hour is at the end
eventHeight = (VERTICAL_DIFF / 2) - (2 * EVENT_VERTICAL_DIFF);
}
else
{
// Take all hour space
eventHeight = VERTICAL_DIFF - (2 * EVENT_VERTICAL_DIFF);
}
if (hourStartPosition != hourEndPosition)
{
eventHeight += (hourEndPosition + minuteEndPosition) - hourStartPosition - minuteStartPosition;
}
var availableWidth = this.Bounds.Size.Width - (HORIZONTAL_OFFSET + TIME_WIDTH + PERIOD_WIDTH + HORIZONTAL_LINE_DIFF) - HORIZONTAL_LINE_DIFF - EVENT_HORIZONTAL_DIFF;
var currentWidth = availableWidth / theBlock.Columns.Count;
var currentInt = theEvent.Column.Number;
var x = HORIZONTAL_OFFSET + TIME_WIDTH + PERIOD_WIDTH + HORIZONTAL_LINE_DIFF + EVENT_HORIZONTAL_DIFF + (currentWidth * currentInt);
var y = hourStartPosition + minuteStartPosition + EVENT_VERTICAL_DIFF;
RectangleF eventFrame = new RectangleF (x, y, currentWidth, eventHeight);
theEvent.Frame = eventFrame;
//event.delegate = self;
theEvent.SetNeedsDisplay ();
this.scrollView.AddSubview (theEvent);
// Log the extracted date values
Console.WriteLine ("hourStart: {0} minuteStart: {1}", hourStart, minuteStart);
}
}
}
}
}
public class TimeLineView : UIView
{
string[] _times;
string[] _periods;
// The designated initializer. Override to perform setup that is required before the view is loaded.
// Only when xibless (interface buildder)
public TimeLineView (RectangleF rect)
{
this.Frame = rect;
setupCustomInitialisation ();
}
public void setupCustomInitialisation ()
{
// Initialization code
}
// Setup array consisting of string
// representing time aka 12 (12 am), 1 (1 am) ... 25 x
public string[] times {
get {
if (_times == null)
{
_times = new string[] { "12", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"10", "11", "Noon", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12", "" };
}
return _times;
}
}
// Setup array consisting of string
// representing time periods aka AM or PM
// Matching the array of times 25 x
public string[] periods {
get {
if (_periods == null)
{
_periods = new string[] { "AM", "AM", "AM", "AM", "AM", "AM", "AM", "AM", "AM", "AM",
"AM", "AM", "", "PM", "PM", "PM", "PM", "PM", "PM", "PM",
"PM", "PM", "PM", "PM", "AM", "" };
}
return _periods;
}
}
public override void Draw (RectangleF rect)
{
// Drawing code
// Here Draw timeline from 12 am to noon to 12 am next day
// Times appearance
UIFont timeFont = UIFont.BoldSystemFontOfSize (FONT_SIZE);
UIColor timeColor = UIColor.Black;
// Periods appearance
UIFont periodFont = UIFont.SystemFontOfSize (FONT_SIZE);
UIColor periodColor = UIColor.Gray;
// Draw each times string
for (Int32 i = 0; i < this.times.Length; i++)
{
// Draw time
timeColor.SetStroke ();
string time = this.times[i];
RectangleF timeRect = new RectangleF (HORIZONTAL_OFFSET, VERTICAL_OFFSET + i * VERTICAL_DIFF, TIME_WIDTH, FONT_SIZE + 4.0f);
// Find noon
if (i == 24 / 2)
{
timeRect = new RectangleF (HORIZONTAL_OFFSET, VERTICAL_OFFSET + i * VERTICAL_DIFF, TIME_WIDTH + PERIOD_WIDTH, FONT_SIZE + 4.0f);
}
DrawString (time, timeRect, timeFont, UILineBreakMode.WordWrap, UITextAlignment.Right);
// Draw period
// Only if it is not noon
if (i != 24 / 2)
{
periodColor.SetStroke ();
string period = this.periods[i];
DrawString (period, new RectangleF (HORIZONTAL_OFFSET + TIME_WIDTH, VERTICAL_OFFSET + i * VERTICAL_DIFF, PERIOD_WIDTH, FONT_SIZE + 4.0f), periodFont, UILineBreakMode.WordWrap, UITextAlignment.Right);
var context = UIGraphics.GetCurrentContext ();
// Save the context state
context.SaveState ();
context.SetStrokeColorWithColor (UIColor.LightGray.CGColor);
// Draw line with a black stroke color
// Draw line with a 1.0 stroke width
context.SetLineWidth (0.5f);
// Translate context for clear line
context.TranslateCTM (-0.5f, -0.5f);
context.BeginPath ();
context.MoveTo (HORIZONTAL_OFFSET + TIME_WIDTH + PERIOD_WIDTH + HORIZONTAL_LINE_DIFF, VERTICAL_OFFSET + i * VERTICAL_DIFF + (float)Math.Round (((FONT_SIZE + 4.0) / 2.0)));
context.AddLineToPoint (this.Bounds.Size.Width, VERTICAL_OFFSET + i * VERTICAL_DIFF + (float)Math.Round ((FONT_SIZE + 4.0) / 2.0));
context.StrokePath ();
if (i != this.times.Length - 1)
{
context.BeginPath ();
context.MoveTo (HORIZONTAL_OFFSET + TIME_WIDTH + PERIOD_WIDTH + HORIZONTAL_LINE_DIFF, VERTICAL_OFFSET + i * VERTICAL_DIFF + (float)Math.Round (((FONT_SIZE + 4.0f) / 2.0f)) + (float)Math.Round ((VERTICAL_DIFF / 2.0f)));
context.AddLineToPoint (this.Bounds.Size.Width, VERTICAL_OFFSET + i * VERTICAL_DIFF + (float)Math.Round (((FONT_SIZE + 4.0f) / 2.0f)) + (float)Math.Round ((VERTICAL_DIFF / 2.0f)));
float[] dash1 = { 2.0f, 1.0f };
context.SetLineDash (0.0f, dash1, 2);
context.StrokePath ();
}
// Restore the context state
context.RestoreState ();
}
}
}
///////
}
}
}
}
| |
// <copyright file="OtlpTraceExporterTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient;
using OpenTelemetry.Resources;
using OpenTelemetry.Tests;
using OpenTelemetry.Trace;
using Xunit;
using OtlpCollector = Opentelemetry.Proto.Collector.Trace.V1;
using OtlpCommon = Opentelemetry.Proto.Common.V1;
using OtlpTrace = Opentelemetry.Proto.Trace.V1;
using Status = OpenTelemetry.Trace.Status;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests
{
public class OtlpTraceExporterTests : Http2UnencryptedSupportTests
{
static OtlpTraceExporterTests()
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
var listener = new ActivityListener
{
ShouldListenTo = _ => true,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
};
ActivitySource.AddActivityListener(listener);
}
[Fact]
public void OtlpExporter_BadArgs()
{
TracerProviderBuilder builder = null;
Assert.Throws<ArgumentNullException>(() => builder.AddOtlpExporter());
}
[Fact]
public void UserHttpFactoryCalled()
{
OtlpExporterOptions options = new OtlpExporterOptions();
var defaultFactory = options.HttpClientFactory;
int invocations = 0;
options.Protocol = OtlpExportProtocol.HttpProtobuf;
options.HttpClientFactory = () =>
{
invocations++;
return defaultFactory();
};
using (var exporter = new OtlpTraceExporter(options))
{
Assert.Equal(1, invocations);
}
using (var provider = Sdk.CreateTracerProviderBuilder()
.AddOtlpExporter(o =>
{
o.Protocol = OtlpExportProtocol.HttpProtobuf;
o.HttpClientFactory = options.HttpClientFactory;
})
.Build())
{
Assert.Equal(2, invocations);
}
options.HttpClientFactory = null;
Assert.Throws<InvalidOperationException>(() =>
{
using var exporter = new OtlpTraceExporter(options);
});
options.HttpClientFactory = () => null;
Assert.Throws<InvalidOperationException>(() =>
{
using var exporter = new OtlpTraceExporter(options);
});
}
[Fact]
public void ServiceProviderHttpClientFactoryInvoked()
{
IServiceCollection services = new ServiceCollection();
services.AddHttpClient();
int invocations = 0;
services.AddHttpClient("OtlpTraceExporter", configureClient: (client) => invocations++);
services.AddOpenTelemetryTracing(builder => builder.AddOtlpExporter(
o => o.Protocol = OtlpExportProtocol.HttpProtobuf));
using var serviceProvider = services.BuildServiceProvider();
var tracerProvider = serviceProvider.GetRequiredService<TracerProvider>();
Assert.Equal(1, invocations);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ToOtlpResourceSpansTest(bool includeServiceNameInResource)
{
var evenTags = new[] { new KeyValuePair<string, object>("k0", "v0") };
var oddTags = new[] { new KeyValuePair<string, object>("k1", "v1") };
var sources = new[]
{
new ActivitySource("even", "2.4.6"),
new ActivitySource("odd", "1.3.5"),
};
var resourceBuilder = ResourceBuilder.CreateEmpty();
if (includeServiceNameInResource)
{
resourceBuilder.AddAttributes(
new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>(ResourceSemanticConventions.AttributeServiceName, "service-name"),
new KeyValuePair<string, object>(ResourceSemanticConventions.AttributeServiceNamespace, "ns1"),
});
}
var builder = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(resourceBuilder)
.AddSource(sources[0].Name)
.AddSource(sources[1].Name);
using var openTelemetrySdk = builder.Build();
var exportedItems = new List<Activity>();
var processor = new BatchActivityExportProcessor(new InMemoryExporter<Activity>(exportedItems));
const int numOfSpans = 10;
bool isEven;
for (var i = 0; i < numOfSpans; i++)
{
isEven = i % 2 == 0;
var source = sources[i % 2];
var activityKind = isEven ? ActivityKind.Client : ActivityKind.Server;
var activityTags = isEven ? evenTags : oddTags;
using Activity activity = source.StartActivity($"span-{i}", activityKind, parentContext: default, activityTags);
processor.OnEnd(activity);
}
processor.Shutdown();
var batch = new Batch<Activity>(exportedItems.ToArray(), exportedItems.Count);
RunTest(batch);
void RunTest(Batch<Activity> batch)
{
var request = new OtlpCollector.ExportTraceServiceRequest();
request.AddBatch(resourceBuilder.Build().ToOtlpResource(), batch);
Assert.Single(request.ResourceSpans);
var oltpResource = request.ResourceSpans.First().Resource;
if (includeServiceNameInResource)
{
Assert.Contains(oltpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceName && kvp.Value.StringValue == "service-name");
Assert.Contains(oltpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceNamespace && kvp.Value.StringValue == "ns1");
}
else
{
Assert.Contains(oltpResource.Attributes, (kvp) => kvp.Key == ResourceSemanticConventions.AttributeServiceName && kvp.Value.ToString().Contains("unknown_service:"));
}
foreach (var instrumentationLibrarySpans in request.ResourceSpans.First().InstrumentationLibrarySpans)
{
Assert.Equal(numOfSpans / 2, instrumentationLibrarySpans.Spans.Count);
Assert.NotNull(instrumentationLibrarySpans.InstrumentationLibrary);
var expectedSpanNames = new List<string>();
var start = instrumentationLibrarySpans.InstrumentationLibrary.Name == "even" ? 0 : 1;
for (var i = start; i < numOfSpans; i += 2)
{
expectedSpanNames.Add($"span-{i}");
}
var otlpSpans = instrumentationLibrarySpans.Spans;
Assert.Equal(expectedSpanNames.Count, otlpSpans.Count);
var kv0 = new OtlpCommon.KeyValue { Key = "k0", Value = new OtlpCommon.AnyValue { StringValue = "v0" } };
var kv1 = new OtlpCommon.KeyValue { Key = "k1", Value = new OtlpCommon.AnyValue { StringValue = "v1" } };
var expectedTag = instrumentationLibrarySpans.InstrumentationLibrary.Name == "even"
? kv0
: kv1;
foreach (var otlpSpan in otlpSpans)
{
Assert.Contains(otlpSpan.Name, expectedSpanNames);
Assert.Contains(expectedTag, otlpSpan.Attributes);
}
}
}
}
[Fact]
public void ToOtlpSpanTest()
{
using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));
using var rootActivity = activitySource.StartActivity("root", ActivityKind.Producer);
var attributes = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("bool", true),
new KeyValuePair<string, object>("long", 1L),
new KeyValuePair<string, object>("string", "text"),
new KeyValuePair<string, object>("double", 3.14),
new KeyValuePair<string, object>("int", 1),
new KeyValuePair<string, object>("datetime", DateTime.UtcNow),
new KeyValuePair<string, object>("bool_array", new bool[] { true, false }),
new KeyValuePair<string, object>("int_array", new int[] { 1, 2 }),
new KeyValuePair<string, object>("double_array", new double[] { 1.0, 2.09 }),
new KeyValuePair<string, object>("string_array", new string[] { "a", "b" }),
};
foreach (var kvp in attributes)
{
rootActivity.SetTag(kvp.Key, kvp.Value);
}
var startTime = new DateTime(2020, 02, 20, 20, 20, 20, DateTimeKind.Utc);
DateTimeOffset dateTimeOffset;
dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(0);
var expectedUnixTimeTicks = (ulong)(startTime.Ticks - dateTimeOffset.Ticks);
var duration = TimeSpan.FromMilliseconds(1555);
rootActivity.SetStartTime(startTime);
rootActivity.SetEndTime(startTime + duration);
Span<byte> traceIdSpan = stackalloc byte[16];
rootActivity.TraceId.CopyTo(traceIdSpan);
var traceId = traceIdSpan.ToArray();
var otlpSpan = rootActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
Assert.Equal("root", otlpSpan.Name);
Assert.Equal(OtlpTrace.Span.Types.SpanKind.Producer, otlpSpan.Kind);
Assert.Equal(traceId, otlpSpan.TraceId);
Assert.Empty(otlpSpan.ParentSpanId);
Assert.Null(otlpSpan.Status);
Assert.Empty(otlpSpan.Events);
Assert.Empty(otlpSpan.Links);
OtlpTestHelpers.AssertOtlpAttributes(attributes, otlpSpan.Attributes);
var expectedStartTimeUnixNano = 100 * expectedUnixTimeTicks;
Assert.Equal(expectedStartTimeUnixNano, otlpSpan.StartTimeUnixNano);
var expectedEndTimeUnixNano = expectedStartTimeUnixNano + (duration.TotalMilliseconds * 1_000_000);
Assert.Equal(expectedEndTimeUnixNano, otlpSpan.EndTimeUnixNano);
var childLinks = new List<ActivityLink> { new ActivityLink(rootActivity.Context, new ActivityTagsCollection(attributes)) };
var childActivity = activitySource.StartActivity(
"child",
ActivityKind.Client,
rootActivity.Context,
links: childLinks);
childActivity.SetStatus(Status.Error);
var childEvents = new List<ActivityEvent> { new ActivityEvent("e0"), new ActivityEvent("e1", default, new ActivityTagsCollection(attributes)) };
childActivity.AddEvent(childEvents[0]);
childActivity.AddEvent(childEvents[1]);
Span<byte> parentIdSpan = stackalloc byte[8];
rootActivity.Context.SpanId.CopyTo(parentIdSpan);
var parentId = parentIdSpan.ToArray();
otlpSpan = childActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
Assert.Equal("child", otlpSpan.Name);
Assert.Equal(OtlpTrace.Span.Types.SpanKind.Client, otlpSpan.Kind);
Assert.Equal(traceId, otlpSpan.TraceId);
Assert.Equal(parentId, otlpSpan.ParentSpanId);
// Assert.Equal(OtlpTrace.Status.Types.StatusCode.NotFound, otlpSpan.Status.Code);
Assert.Equal(Status.Error.Description ?? string.Empty, otlpSpan.Status.Message);
Assert.Empty(otlpSpan.Attributes);
Assert.Equal(childEvents.Count, otlpSpan.Events.Count);
for (var i = 0; i < childEvents.Count; i++)
{
Assert.Equal(childEvents[i].Name, otlpSpan.Events[i].Name);
OtlpTestHelpers.AssertOtlpAttributes(childEvents[i].Tags.ToList(), otlpSpan.Events[i].Attributes);
}
childLinks.Reverse();
Assert.Equal(childLinks.Count, otlpSpan.Links.Count);
for (var i = 0; i < childLinks.Count; i++)
{
OtlpTestHelpers.AssertOtlpAttributes(childLinks[i].Tags.ToList(), otlpSpan.Links[i].Attributes);
}
}
[Fact]
public void ToOtlpSpanActivitiesWithNullArrayTest()
{
using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));
using var rootActivity = activitySource.StartActivity("root", ActivityKind.Client);
Assert.NotNull(rootActivity);
var stringArr = new string[] { "test", string.Empty, null };
rootActivity.SetTag("stringArray", stringArr);
var otlpSpan = rootActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
var stringArray = otlpSpan.Attributes.Where(kvp => kvp.Key == "stringArray").ToList();
Assert.NotNull(stringArray);
Assert.Equal(3, stringArray.Count());
Assert.Equal("test", stringArray[0].Value.StringValue);
Assert.Equal(string.Empty, stringArray[1].Value.StringValue);
Assert.Null(stringArray[2].Value);
}
[Fact]
public void ToOtlpSpanPeerServiceTest()
{
using var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));
using var rootActivity = activitySource.StartActivity("root", ActivityKind.Client);
rootActivity.SetTag(SemanticConventions.AttributeHttpHost, "opentelemetry.io");
var otlpSpan = rootActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
var peerService = otlpSpan.Attributes.FirstOrDefault(kvp => kvp.Key == SemanticConventions.AttributePeerService);
Assert.NotNull(peerService);
Assert.Equal("opentelemetry.io", peerService.Value.StringValue);
}
[Fact]
public void UseOpenTelemetryProtocolActivityExporterWithCustomActivityProcessor()
{
if (Environment.Version.Major == 3)
{
// Adding the OtlpExporter creates a GrpcChannel.
// This switch must be set before creating a GrpcChannel when calling an insecure HTTP/2 endpoint.
// See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
}
const string ActivitySourceName = "otlp.test";
TestActivityProcessor testActivityProcessor = new TestActivityProcessor();
bool startCalled = false;
bool endCalled = false;
testActivityProcessor.StartAction =
(a) =>
{
startCalled = true;
};
testActivityProcessor.EndAction =
(a) =>
{
endCalled = true;
};
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource(ActivitySourceName)
.AddProcessor(testActivityProcessor)
.AddOtlpExporter()
.Build();
using var source = new ActivitySource(ActivitySourceName);
var activity = source.StartActivity("Test Otlp Activity");
activity?.Stop();
Assert.True(startCalled);
Assert.True(endCalled);
}
[Fact]
public void Shutdown_ClientShutdownIsCalled()
{
var exportClientMock = new Mock<IExportClient<OtlpCollector.ExportTraceServiceRequest>>();
var exporter = new OtlpTraceExporter(new OtlpExporterOptions(), exportClientMock.Object);
var result = exporter.Shutdown();
exportClientMock.Verify(m => m.Shutdown(It.IsAny<int>()), Times.Once());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class PlaneTests
{
// A test for Equals (Plane)
[Fact]
public void PlaneEqualsTest1()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Equals (object)
[Fact]
public void PlaneEqualsTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
}
// A test for operator != (Plane, Plane)
[Fact]
public void PlaneInequalityTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Plane, Plane)
[Fact]
public void PlaneEqualityTest()
{
Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.Equal(expected, actual);
// case 2: compare between different values
b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z);
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for GetHashCode ()
[Fact]
public void PlaneGetHashCodeTest()
{
Plane target = new Plane(1.0f, 2.0f, 3.0f, 4.0f);
int expected = target.Normal.GetHashCode() + target.D.GetHashCode();
int actual = target.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Plane (float, float, float, float)
[Fact]
public void PlaneConstructorTest1()
{
float a = 1.0f, b = 2.0f, c = 3.0f, d = 4.0f;
Plane target = new Plane(a, b, c, d);
Assert.True(
target.Normal.X == a && target.Normal.Y == b && target.Normal.Z == c && target.D == d,
"Plane.cstor did not return the expected value.");
}
// A test for Plane.CreateFromVertices
[Fact]
public void PlaneCreateFromVerticesTest()
{
Vector3 point1 = new Vector3(0.0f, 1.0f, 1.0f);
Vector3 point2 = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 point3 = new Vector3(1.0f, 0.0f, 1.0f);
Plane target = Plane.CreateFromVertices(point1, point2, point3);
Plane expected = new Plane(new Vector3(0, 0, 1), -1.0f);
Assert.Equal(target, expected);
}
// A test for Plane.CreateFromVertices
[Fact]
public void PlaneCreateFromVerticesTest2()
{
Vector3 point1 = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 point2 = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 point3 = new Vector3(1.0f, 1.0f, 0.0f);
Plane target = Plane.CreateFromVertices(point1, point2, point3);
float invRoot2 = (float)(1 / Math.Sqrt(2));
Plane expected = new Plane(new Vector3(invRoot2, 0, invRoot2), -invRoot2);
Assert.True(MathHelper.Equal(target, expected), "Plane.cstor did not return the expected value.");
}
// A test for Plane (Vector3f, float)
[Fact]
public void PlaneConstructorTest3()
{
Vector3 normal = new Vector3(1, 2, 3);
float d = 4;
Plane target = new Plane(normal, d);
Assert.True(
target.Normal == normal && target.D == d,
"Plane.cstor did not return the expected value.");
}
// A test for Plane (Vector4f)
[Fact]
public void PlaneConstructorTest()
{
Vector4 value = new Vector4(1.0f, 2.0f, 3.0f, 4.0f);
Plane target = new Plane(value);
Assert.True(
target.Normal.X == value.X && target.Normal.Y == value.Y && target.Normal.Z == value.Z && target.D == value.W,
"Plane.cstor did not return the expected value.");
}
[Fact]
public void PlaneDotTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector4 value = new Vector4(5, 4, 3, 2);
float expected = 10 + 12 + 12 + 10;
float actual = Plane.Dot(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Dot returns unexpected value.");
}
[Fact]
public void PlaneDotCoordinateTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector3 value = new Vector3(5, 4, 3);
float expected = 10 + 12 + 12 + 5;
float actual = Plane.DotCoordinate(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value.");
}
[Fact]
public void PlaneDotNormalTest()
{
Plane target = new Plane(2, 3, 4, 5);
Vector3 value = new Vector3(5, 4, 3);
float expected = 10 + 12 + 12;
float actual = Plane.DotNormal(target, value);
Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value.");
}
[Fact]
public void PlaneNormalizeTest()
{
Plane target = new Plane(1, 2, 3, 4);
float f = target.Normal.LengthSquared();
float invF = 1.0f / (float)Math.Sqrt(f);
Plane expected = new Plane(target.Normal * invF, target.D * invF);
Plane actual = Plane.Normalize(target);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value.");
// normalize, normalized normal.
actual = Plane.Normalize(actual);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value.");
}
[Fact]
// Transform by matrix
public void PlaneTransformTest1()
{
Plane target = new Plane(1, 2, 3, 4);
target = Plane.Normalize(target);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Plane expected = new Plane();
Matrix4x4 inv;
Matrix4x4.Invert(m, out inv);
Matrix4x4 itm = Matrix4x4.Transpose(inv);
float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D;
expected.Normal = new Vector3(
x * itm.M11 + y * itm.M21 + z * itm.M31 + w * itm.M41,
x * itm.M12 + y * itm.M22 + z * itm.M32 + w * itm.M42,
x * itm.M13 + y * itm.M23 + z * itm.M33 + w * itm.M43);
expected.D = x * itm.M14 + y * itm.M24 + z * itm.M34 + w * itm.M44;
Plane actual;
actual = Plane.Transform(target, m);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value.");
}
[Fact]
// Transform by quaternion
public void PlaneTransformTest2()
{
Plane target = new Plane(1, 2, 3, 4);
target = Plane.Normalize(target);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Plane expected = new Plane();
float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D;
expected.Normal = new Vector3(
x * m.M11 + y * m.M21 + z * m.M31 + w * m.M41,
x * m.M12 + y * m.M22 + z * m.M32 + w * m.M42,
x * m.M13 + y * m.M23 + z * m.M33 + w * m.M43);
expected.D = x * m.M14 + y * m.M24 + z * m.M34 + w * m.M44;
Plane actual;
actual = Plane.Transform(target, q);
Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value.");
}
// A test for Plane comparison involving NaN values
[Fact]
public void PlaneEqualsNanTest()
{
Plane a = new Plane(float.NaN, 0, 0, 0);
Plane b = new Plane(0, float.NaN, 0, 0);
Plane c = new Plane(0, 0, float.NaN, 0);
Plane d = new Plane(0, 0, 0, float.NaN);
Assert.False(a == new Plane(0, 0, 0, 0));
Assert.False(b == new Plane(0, 0, 0, 0));
Assert.False(c == new Plane(0, 0, 0, 0));
Assert.False(d == new Plane(0, 0, 0, 0));
Assert.True(a != new Plane(0, 0, 0, 0));
Assert.True(b != new Plane(0, 0, 0, 0));
Assert.True(c != new Plane(0, 0, 0, 0));
Assert.True(d != new Plane(0, 0, 0, 0));
Assert.False(a.Equals(new Plane(0, 0, 0, 0)));
Assert.False(b.Equals(new Plane(0, 0, 0, 0)));
Assert.False(c.Equals(new Plane(0, 0, 0, 0)));
Assert.False(d.Equals(new Plane(0, 0, 0, 0)));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.False(a.Equals(a));
Assert.False(b.Equals(b));
Assert.False(c.Equals(c));
Assert.False(d.Equals(d));
}
/* Enable when size of Vector3 is correct
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void PlaneSizeofTest()
{
Assert.Equal(16, sizeof(Plane));
Assert.Equal(32, sizeof(Plane_2x));
Assert.Equal(20, sizeof(PlanePlusFloat));
Assert.Equal(40, sizeof(PlanePlusFloat_2x));
}
*/
[StructLayout(LayoutKind.Sequential)]
struct Plane_2x
{
Plane a;
Plane b;
}
[StructLayout(LayoutKind.Sequential)]
struct PlanePlusFloat
{
Plane v;
float f;
}
[StructLayout(LayoutKind.Sequential)]
struct PlanePlusFloat_2x
{
PlanePlusFloat a;
PlanePlusFloat b;
}
//// A test to make sure the fields are laid out how we expect
//[Fact]
//public unsafe void PlaneFieldOffsetTest()
//{
// Plane* ptr = (Plane*)0;
// Assert.Equal(new IntPtr(0), new IntPtr(&ptr->Normal));
// Assert.Equal(new IntPtr(12), new IntPtr(&ptr->D));
//}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The Test abstract class represents a test within the framework.
/// </summary>
public abstract class Test : ITest, IComparable
{
#region Fields
/// <summary>
/// Static value to seed ids. It's started at 1000 so any
/// uninitialized ids will stand out.
/// </summary>
private static int _nextID = 1000;
/// <summary>
/// Used to cache the declaring type for this MethodInfo
/// </summary>
protected ITypeInfo DeclaringTypeInfo;
/// <summary>
/// Method property backing field
/// </summary>
private IMethodInfo _method;
#endregion
#region Construction
/// <summary>
/// Constructs a test given its name
/// </summary>
/// <param name="name">The name of the test</param>
protected Test( string name )
{
Guard.ArgumentNotNullOrEmpty(name, "name");
Initialize(name);
}
/// <summary>
/// Constructs a test given the path through the
/// test hierarchy to its parent and a name.
/// </summary>
/// <param name="pathName">The parent tests full name</param>
/// <param name="name">The name of the test</param>
protected Test( string pathName, string name )
{
Initialize(name);
if (!string.IsNullOrEmpty(pathName))
FullName = pathName + "." + name;
}
/// <summary>
/// TODO: Documentation needed for constructor
/// </summary>
/// <param name="typeInfo"></param>
protected Test(ITypeInfo typeInfo)
{
Initialize(typeInfo.GetDisplayName());
string nspace = typeInfo.Namespace;
if (nspace != null && nspace != "")
FullName = nspace + "." + Name;
TypeInfo = typeInfo;
}
/// <summary>
/// Construct a test from a MethodInfo
/// </summary>
/// <param name="method"></param>
protected Test(IMethodInfo method)
{
Initialize(method.Name);
Method = method;
TypeInfo = method.TypeInfo;
FullName = method.TypeInfo.FullName + "." + Name;
}
private void Initialize(string name)
{
FullName = Name = name;
Id = GetNextId();
Properties = new PropertyBag();
RunState = RunState.Runnable;
SetUpMethods = new MethodInfo[0];
TearDownMethods = new MethodInfo[0];
}
private static string GetNextId()
{
return IdPrefix + unchecked(_nextID++);
}
#endregion
#region ITest Members
/// <summary>
/// Gets or sets the id of the test
/// </summary>
/// <value></value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the name of the test
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the fully qualified name of the test
/// </summary>
/// <value></value>
public string FullName { get; set; }
/// <summary>
/// Gets the name of the class where this test was declared.
/// Returns null if the test is not associated with a class.
/// </summary>
public string ClassName
{
get
{
ITypeInfo typeInfo = TypeInfo;
if (Method != null)
{
if (DeclaringTypeInfo == null)
DeclaringTypeInfo = new TypeWrapper(Method.MethodInfo.DeclaringType);
typeInfo = DeclaringTypeInfo;
}
if (typeInfo == null)
return null;
return typeInfo.IsGenericType
? typeInfo.GetGenericTypeDefinition().FullName
: typeInfo.FullName;
}
}
/// <summary>
/// Gets the name of the method implementing this test.
/// Returns null if the test is not implemented as a method.
/// </summary>
public virtual string MethodName
{
get { return null; }
}
/// <summary>
/// The arguments to use in creating the test or empty array if none required.
/// </summary>
public abstract object[] Arguments { get; }
/// <summary>
/// Gets the TypeInfo of the fixture used in running this test
/// or null if no fixture type is associated with it.
/// </summary>
public ITypeInfo TypeInfo { get; private set; }
/// <summary>
/// Gets a MethodInfo for the method implementing this test.
/// Returns null if the test is not implemented as a method.
/// </summary>
public IMethodInfo Method
{
get { return _method; }
set
{
DeclaringTypeInfo = null;
_method = value;
}
} // public setter needed by NUnitTestCaseBuilder
/// <summary>
/// Whether or not the test should be run
/// </summary>
public RunState RunState { get; set; }
/// <summary>
/// Gets the name used for the top-level element in the
/// XML representation of this test
/// </summary>
public abstract string XmlElementName { get; }
/// <summary>
/// Gets a string representing the type of test. Used as an attribute
/// value in the XML representation of a test and has no other
/// function in the framework.
/// </summary>
public virtual string TestType
{
get { return this.GetType().Name; }
}
/// <summary>
/// Gets a count of test cases represented by
/// or contained under this test.
/// </summary>
public virtual int TestCaseCount
{
get { return 1; }
}
/// <summary>
/// Gets the properties for this test
/// </summary>
public IPropertyBag Properties { get; private set; }
/// <summary>
/// Returns true if this is a TestSuite
/// </summary>
public bool IsSuite
{
get { return this is TestSuite; }
}
/// <summary>
/// Gets a bool indicating whether the current test
/// has any descendant tests.
/// </summary>
public abstract bool HasChildren { get; }
/// <summary>
/// Gets the parent as a Test object.
/// Used by the core to set the parent.
/// </summary>
public ITest Parent { get; set; }
/// <summary>
/// Gets this test's child tests
/// </summary>
/// <value>A list of child tests</value>
public abstract IList<ITest> Tests { get; }
/// <summary>
/// Gets or sets a fixture object for running this test.
/// </summary>
public virtual object Fixture { get; set; }
#endregion
#region Other Public Properties
/// <summary>
/// Static prefix used for ids in this AppDomain.
/// Set by FrameworkController.
/// </summary>
public static string IdPrefix { get; set; }
/// <summary>
/// Gets or Sets the Int value representing the seed for the RandomGenerator
/// </summary>
/// <value></value>
public int Seed { get; set; }
/// <summary>
/// The SetUp methods.
/// </summary>
public MethodInfo[] SetUpMethods { get; protected set; }
/// <summary>
/// The teardown methods
/// </summary>
public MethodInfo[] TearDownMethods { get; protected set; }
#endregion
#region Internal Properties
internal bool RequiresThread { get; set; }
private ITestAction[] _actions;
internal ITestAction[] Actions
{
get
{
if (_actions == null)
{
// For fixtures, we use special rules to get actions
// Otherwise we just get the attributes
_actions = Method == null && TypeInfo != null
? GetActionsForType(TypeInfo.Type)
: GetCustomAttributes<ITestAction>(false);
}
return _actions;
}
}
#endregion
#region Other Public Methods
/// <summary>
/// Creates a TestResult for this test.
/// </summary>
/// <returns>A TestResult suitable for this type of test.</returns>
public abstract TestResult MakeTestResult();
#if PORTABLE || NETSTANDARD1_6
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied ICustomAttributeProvider, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
/// <param name="provider">An object deriving from MemberInfo</param>
public void ApplyAttributesToTest(MemberInfo provider)
{
foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>(true))
iApply.ApplyToTest(this);
}
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied ICustomAttributeProvider, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
/// <param name="provider">An object deriving from MemberInfo</param>
public void ApplyAttributesToTest(Assembly provider)
{
foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>())
iApply.ApplyToTest(this);
}
#else
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied ICustomAttributeProvider, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
/// <param name="provider">An object implementing ICustomAttributeProvider</param>
public void ApplyAttributesToTest(ICustomAttributeProvider provider)
{
foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true))
iApply.ApplyToTest(this);
}
#endif
/// <summary>
/// Mark the test as Invalid (not runnable) specifying a reason
/// </summary>
/// <param name="reason">The reason the test is not runnable</param>
public void MakeInvalid(string reason)
{
Guard.ArgumentNotNullOrEmpty(reason, "reason");
RunState = RunState.NotRunnable;
Properties.Add(PropertyNames.SkipReason, reason);
}
/// <summary>
/// Get custom attributes applied to a test
/// </summary>
public virtual TAttr[] GetCustomAttributes<TAttr>(bool inherit) where TAttr : class
{
if (Method != null)
#if PORTABLE || NETSTANDARD1_6
return Method.GetCustomAttributes<TAttr>(inherit).ToArray();
#else
return (TAttr[])Method.MethodInfo.GetCustomAttributes(typeof(TAttr), inherit);
#endif
if (TypeInfo != null)
return TypeInfo.GetCustomAttributes<TAttr>(inherit).ToArray();
return new TAttr[0];
}
#endregion
#region Protected Methods
/// <summary>
/// Add standard attributes and members to a test node.
/// </summary>
/// <param name="thisNode"></param>
/// <param name="recursive"></param>
protected void PopulateTestNode(TNode thisNode, bool recursive)
{
thisNode.AddAttribute("id", this.Id.ToString());
thisNode.AddAttribute("name", this.Name);
thisNode.AddAttribute("fullname", this.FullName);
if (this.MethodName != null)
thisNode.AddAttribute("methodname", this.MethodName);
if (this.ClassName != null)
thisNode.AddAttribute("classname", this.ClassName);
thisNode.AddAttribute("runstate", this.RunState.ToString());
if (Properties.Keys.Count > 0)
Properties.AddToXml(thisNode, recursive);
}
#endregion
#region Private Methods
private static ITestAction[] GetActionsForType(Type type)
{
var actions = new List<ITestAction>();
if (type != null && type != typeof(object))
{
actions.AddRange(GetActionsForType(type.GetTypeInfo().BaseType));
#if PORTABLE || NETSTANDARD1_6
foreach (Type interfaceType in TypeHelper.GetDeclaredInterfaces(type))
actions.AddRange(interfaceType.GetTypeInfo().GetAttributes<ITestAction>(false).ToArray());
actions.AddRange(type.GetTypeInfo().GetAttributes<ITestAction>(false).ToArray());
#else
foreach (Type interfaceType in TypeHelper.GetDeclaredInterfaces(type))
actions.AddRange((ITestAction[])interfaceType.GetTypeInfo().GetCustomAttributes(typeof(ITestAction), false));
actions.AddRange((ITestAction[])type.GetTypeInfo().GetCustomAttributes(typeof(ITestAction), false));
#endif
}
return actions.ToArray();
}
#endregion
#region IXmlNodeBuilder Members
/// <summary>
/// Returns the Xml representation of the test
/// </summary>
/// <param name="recursive">If true, include child tests recursively</param>
/// <returns></returns>
public TNode ToXml(bool recursive)
{
return AddToXml(new TNode("dummy"), recursive);
}
/// <summary>
/// Returns an XmlNode representing the current result after
/// adding it as a child of the supplied parent node.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public abstract TNode AddToXml(TNode parentNode, bool recursive);
#endregion
#region IComparable Members
/// <summary>
/// Compares this test to another test for sorting purposes
/// </summary>
/// <param name="obj">The other test</param>
/// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
public int CompareTo(object obj)
{
Test other = obj as Test;
if (other == null)
return -1;
return this.FullName.CompareTo(other.FullName);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Product Groups.
/// </summary>
internal partial class ProductGroupsOperations : IServiceOperations<ApiManagementClient>, IProductGroupsOperations
{
/// <summary>
/// Initializes a new instance of the ProductGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ProductGroupsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Assigns group to product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> AddAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all Product Groups.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, string pid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all Product Groups.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Removes group assignement from product.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the Group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RemoveAsync(string resourceGroupName, string serviceName, string pid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (pid == null)
{
throw new ArgumentNullException("pid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("pid", pid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/products/";
url = url + Uri.EscapeDataString(pid);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-10-10");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition.Hosting.Core;
using System.Globalization;
using System.Reflection;
using Xunit;
namespace System.Composition.Runtime.Tests
{
public class CompositionContractTests
{
[Theory]
[InlineData(typeof(int))]
public void Ctor_ContractType(Type contractType)
{
var contract = new CompositionContract(contractType);
Assert.Equal(contractType, contract.ContractType);
Assert.Null(contract.ContractName);
Assert.Null(contract.MetadataConstraints);
}
[Theory]
[InlineData(typeof(int), null)]
[InlineData(typeof(object), "contractName")]
public void Ctor_ContractType(Type contractType, string contractName)
{
var contract = new CompositionContract(contractType, contractName);
Assert.Equal(contractType, contract.ContractType);
Assert.Equal(contractName, contract.ContractName);
Assert.Null(contract.MetadataConstraints);
}
public static IEnumerable<object[]> Ctor_ContractType_ContractName_MetadataConstraints_TestData()
{
yield return new object[] { typeof(int), null, null };
yield return new object[] { typeof(object), "contractName", new Dictionary<string, object> { { "key", "value" } } };
}
[Theory]
[MemberData(nameof(Ctor_ContractType_ContractName_MetadataConstraints_TestData))]
public void Ctor_ContractType_MetadataConstraints(Type contractType, string contractName, IDictionary<string, object> metadataConstraints)
{
var contract = new CompositionContract(contractType, contractName, metadataConstraints);
Assert.Equal(contractType, contract.ContractType);
Assert.Equal(contractName, contract.ContractName);
Assert.Equal(metadataConstraints, contract.MetadataConstraints);
}
[Fact]
public void Ctor_NullContractType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("contractType", () => new CompositionContract(null));
AssertExtensions.Throws<ArgumentNullException>("contractType", () => new CompositionContract(null, "contractName"));
AssertExtensions.Throws<ArgumentNullException>("contractType", () => new CompositionContract(null, "contractName", new Dictionary<string, object>()));
}
[Fact]
public void Ctor_EmptyMetadataConstraints_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("metadataConstraints", () => new CompositionContract(typeof(string), "contractName", new Dictionary<string, object>()));
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new CompositionContract(typeof(int)), new CompositionContract(typeof(int)), true };
yield return new object[] { new CompositionContract(typeof(int)), new CompositionContract(typeof(string)), false };
yield return new object[] { new CompositionContract(typeof(int)), new CompositionContract(typeof(int), "contractName"), false };
yield return new object[] { new CompositionContract(typeof(int)), new CompositionContract(typeof(int), null, new Dictionary<string, object> { { "key", "value" } }), false };
yield return new object[] { new CompositionContract(typeof(int), "contractName"), new CompositionContract(typeof(int), "contractName"), true };
yield return new object[] { new CompositionContract(typeof(int), "contractName"), new CompositionContract(typeof(int), "ContractName"), false };
yield return new object[] { new CompositionContract(typeof(int), "contractName"), new CompositionContract(typeof(int)), false };
yield return new object[] { new CompositionContract(typeof(int)), new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }), false };
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
true
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", 1 } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", 1 } }),
true
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[] { "1", null } } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new object[] { "1", null } } }),
true
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[] { "1", null } } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new object[] { "1", new object() } } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" }, { "key2", "value2" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" }, { "key2", "value2" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key2", "value" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value2" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[0] } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[1] } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[0] } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new string[0] } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new object() } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", "value" } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } }),
false
};
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", new object[0] } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } }),
false
};
if (!PlatformDetection.IsFullFramework)
{
yield return new object[]
{
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } }),
new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } }),
true
};
}
yield return new object[] { new CompositionContract(typeof(int)), new object(), false };
yield return new object[] { new CompositionContract(typeof(int)), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(CompositionContract contract, object other, bool expected)
{
Assert.Equal(expected, contract.Equals(other));
Assert.Equal(contract.GetHashCode(), contract.GetHashCode());
}
[Fact]
public void ChangeType_ValidType_Success()
{
var dictionary = new Dictionary<string, object> { { "key", "value" } };
var contract = new CompositionContract(typeof(int), "contractName", dictionary);
CompositionContract newContract = contract.ChangeType(typeof(string));
Assert.Equal(typeof(int), contract.ContractType);
Assert.Equal(typeof(string), newContract.ContractType);
Assert.Equal("contractName", newContract.ContractName);
Assert.Same(dictionary, newContract.MetadataConstraints);
}
[Fact]
public void ChangeType_NullNewContractType_ThrowsArgumentNullException()
{
var contract = new CompositionContract(typeof(int));
AssertExtensions.Throws<ArgumentNullException>("newContractType", () => contract.ChangeType(null));
}
[Fact]
public void TryUnwrapMetadataConstraint_NullConstraints_ReturnsFalse()
{
var contract = new CompositionContract(typeof(int));
Assert.False(contract.TryUnwrapMetadataConstraint("constraintName", out int constraintValue, out CompositionContract remainingContract));
Assert.Equal(0, constraintValue);
Assert.Null(remainingContract);
}
[Fact]
public void TryUnwrapMetadataConstraint_NoSuchConstraintName_ReturnsFalse()
{
var contract = new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "constraint", 1 } });
Assert.False(contract.TryUnwrapMetadataConstraint("constraintName", out int constraintValue, out CompositionContract remainingContract));
Assert.Equal(0, constraintValue);
Assert.Null(remainingContract);
}
[Fact]
public void TryUnwrapMetadataConstraint_IncorrectConstraintNameType_ReturnsFalse()
{
var contract = new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "constraintName", "value" } });
Assert.False(contract.TryUnwrapMetadataConstraint("constraintName", out int constraintValue, out CompositionContract remainingContract));
Assert.Equal(0, constraintValue);
Assert.Null(remainingContract);
}
[Fact]
public void TryUnwrapMetadataConstraint_UnwrapAllConstraints_ReturnsTrue()
{
var originalContract = new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "constraintName1", 1 }, { "constraintName2", 2 } });
Assert.True(originalContract.TryUnwrapMetadataConstraint("constraintName1", out int constraintValue1, out CompositionContract remainingContract1));
Assert.Equal(1, constraintValue1);
Assert.Equal(originalContract.ContractType, remainingContract1.ContractType);
Assert.Equal(originalContract.ContractName, remainingContract1.ContractName);
Assert.Equal(new Dictionary<string, object> { { "constraintName2", 2 } }, remainingContract1.MetadataConstraints);
Assert.NotEqual(originalContract.MetadataConstraints, remainingContract1.MetadataConstraints);
Assert.True(remainingContract1.TryUnwrapMetadataConstraint("constraintName2", out int constraintValue2, out CompositionContract remainingContract2));
Assert.Equal(2, constraintValue2);
Assert.Equal(originalContract.ContractType, remainingContract2.ContractType);
Assert.Equal(originalContract.ContractName, remainingContract2.ContractName);
Assert.Null(remainingContract2.MetadataConstraints);
Assert.NotEqual(originalContract.MetadataConstraints, remainingContract2.MetadataConstraints);
}
[Fact]
public void TryUnwrapMetadataConstraint_NullContractName_ThrowsArgumentNullException()
{
var contract = new CompositionContract(typeof(int));
AssertExtensions.Throws<ArgumentNullException>("constraintName", () => contract.TryUnwrapMetadataConstraint(null, out int unusedValue, out CompositionContract unusedContract));
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { new CompositionContract(typeof(int)), "Int32" };
yield return new object[] { new CompositionContract(typeof(int), "contractName"), "Int32 \"contractName\"" };
yield return new object[] { new CompositionContract(typeof(List<>), "contractName", new Dictionary<string, object> { { "key1", "value" }, { "key2", 2 } }), "List`1 \"contractName\" { key1 = \"value\", key2 = 2 }" };
yield return new object[] { new CompositionContract(typeof(List<string>), "contractName", new Dictionary<string, object> { { "key1", "value" }, { "key2", 2 } }), "List<String> \"contractName\" { key1 = \"value\", key2 = 2 }" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public void ToString_Get_ReturnsExpected(CompositionContract contract, string expected)
{
Assert.Equal(expected, contract.ToString());
}
[Fact]
public void ToString_NullValueInDictionary_ThrowsArgumentNullException()
{
var contract = new CompositionContract(typeof(int), "contractName", new Dictionary<string, object> { { "key", null } });
AssertExtensions.Throws<ArgumentNullException>("value", () => contract.ToString());
}
[Fact]
public void ToString_NullTypeInGenericTypeArguments_ThrowsArgumentNullException()
{
var contract = new CompositionContract(new SubType() { GenericTypeArgumentsOverride = new Type[] { null } });
AssertExtensions.Throws<ArgumentNullException>("type", () => contract.ToString());
}
private class SubType : Type
{
public override Assembly Assembly => throw new NotImplementedException();
public override string AssemblyQualifiedName => throw new NotImplementedException();
public override Type BaseType => throw new NotImplementedException();
public override string FullName => throw new NotImplementedException();
public override Guid GUID => throw new NotImplementedException();
public override Module Module => throw new NotImplementedException();
public override string Namespace => throw new NotImplementedException();
public override Type UnderlyingSystemType => throw new NotImplementedException();
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) => throw new NotImplementedException();
public override object[] GetCustomAttributes(bool inherit) => throw new NotImplementedException();
public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new NotImplementedException();
public override Type GetElementType() => throw new NotImplementedException();
public override EventInfo GetEvent(string name, BindingFlags bindingAttr) => throw new NotImplementedException();
public override EventInfo[] GetEvents(BindingFlags bindingAttr) => throw new NotImplementedException();
public override FieldInfo GetField(string name, BindingFlags bindingAttr) => throw new NotImplementedException();
public override FieldInfo[] GetFields(BindingFlags bindingAttr) => throw new NotImplementedException();
public override Type GetInterface(string name, bool ignoreCase) => throw new NotImplementedException();
public override Type[] GetInterfaces() => throw new NotImplementedException();
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) => throw new NotImplementedException();
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) => throw new NotImplementedException();
public override Type GetNestedType(string name, BindingFlags bindingAttr) => throw new NotImplementedException();
public override Type[] GetNestedTypes(BindingFlags bindingAttr) => throw new NotImplementedException();
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => throw new NotImplementedException();
public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) => throw new NotImplementedException();
public override bool IsDefined(Type attributeType, bool inherit) => throw new NotImplementedException();
protected override TypeAttributes GetAttributeFlagsImpl() => throw new NotImplementedException();
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotImplementedException();
protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotImplementedException();
protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) => throw new NotImplementedException();
protected override bool HasElementTypeImpl() => throw new NotImplementedException();
protected override bool IsArrayImpl() => throw new NotImplementedException();
protected override bool IsByRefImpl() => throw new NotImplementedException();
protected override bool IsCOMObjectImpl() => throw new NotImplementedException();
protected override bool IsPointerImpl() => throw new NotImplementedException();
protected override bool IsPrimitiveImpl() => throw new NotImplementedException();
public override string Name => "Name`1";
public override bool IsConstructedGenericType => true;
public Type[] GenericTypeArgumentsOverride { get; set; }
public override Type[] GenericTypeArguments => GenericTypeArgumentsOverride;
}
}
}
| |
using System.Windows.Forms;
using VersionOne.ServiceHost.ConfigurationTool.Entities;
namespace VersionOne.ServiceHost.ConfigurationTool.UI.Controls {
partial class JiraPageControl {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose (bool disposing) {
if(disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent () {
this.components = new System.ComponentModel.Container();
this.chkDisabled = new System.Windows.Forms.CheckBox();
this.grpVersionOneDefectAttributes = new System.Windows.Forms.GroupBox();
this.cboSourceFieldValue = new System.Windows.Forms.ComboBox();
this.txtJiraUrlTitle = new System.Windows.Forms.TextBox();
this.lblJiraUrlTitle = new System.Windows.Forms.Label();
this.txtJiraUrlTempl = new System.Windows.Forms.TextBox();
this.lblJiraUrlTempl = new System.Windows.Forms.Label();
this.lblSourceFieldValue = new System.Windows.Forms.Label();
this.lblMinutes = new System.Windows.Forms.Label();
this.lblTimerInterval = new System.Windows.Forms.Label();
this.nmdInterval = new System.Windows.Forms.NumericUpDown();
this.txtCreateDefectFilterId = new System.Windows.Forms.TextBox();
this.lblCreateDefectFilterId = new System.Windows.Forms.Label();
this.txtDefectLinkFieldId = new System.Windows.Forms.TextBox();
this.lblDefectLinkFieldId = new System.Windows.Forms.Label();
this.grpConnection = new System.Windows.Forms.GroupBox();
this.lblConnectionValidation = new System.Windows.Forms.Label();
this.btnVerify = new System.Windows.Forms.Button();
this.txtPassword = new System.Windows.Forms.TextBox();
this.lblPassword = new System.Windows.Forms.Label();
this.txtUserName = new System.Windows.Forms.TextBox();
this.lblUserName = new System.Windows.Forms.Label();
this.txtUrl = new System.Windows.Forms.TextBox();
this.lblUrl = new System.Windows.Forms.Label();
this.grpUpdate = new System.Windows.Forms.GroupBox();
this.lblAssigneeStateChanged = new System.Windows.Forms.Label();
this.txtAssigneeStateChanged = new System.Windows.Forms.TextBox();
this.lblProgressWorkflow = new System.Windows.Forms.Label();
this.txtProgressWorkflow = new System.Windows.Forms.TextBox();
this.lblProgressWorkflowClosed = new System.Windows.Forms.Label();
this.txtProgressWorkflowClosed = new System.Windows.Forms.TextBox();
this.lblCommentCloseFieldId = new System.Windows.Forms.Label();
this.lblCommentCreateFieldId = new System.Windows.Forms.Label();
this.lblCreateFieldId = new System.Windows.Forms.Label();
this.txtCreateFieldId = new System.Windows.Forms.TextBox();
this.lblCreateFieldValue = new System.Windows.Forms.Label();
this.txtCreateFieldValue = new System.Windows.Forms.TextBox();
this.lblCloseFieldId = new System.Windows.Forms.Label();
this.txtCloseFieldId = new System.Windows.Forms.TextBox();
this.lblCloseFieldValue = new System.Windows.Forms.Label();
this.txtCloseFieldValue = new System.Windows.Forms.TextBox();
this.grpSearch = new System.Windows.Forms.GroupBox();
this.chkDefectFilterDisabled = new System.Windows.Forms.CheckBox();
this.lblCreateStoryFilterId = new System.Windows.Forms.Label();
this.txtCreateStoryFilterId = new System.Windows.Forms.TextBox();
this.chkStoryFilterDisabled = new System.Windows.Forms.CheckBox();
this.grpProjectMappings = new System.Windows.Forms.GroupBox();
this.btnDeleteProjectMapping = new System.Windows.Forms.Button();
this.grdProjectMappings = new System.Windows.Forms.DataGridView();
this.colVersionOneProject = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.colJiraProject = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.bsProjectMappings = new System.Windows.Forms.BindingSource(this.components);
this.bsPriorityMappings = new System.Windows.Forms.BindingSource(this.components);
this.tcJiraData = new System.Windows.Forms.TabControl();
this.tpSettings = new System.Windows.Forms.TabPage();
this.tpMappings = new System.Windows.Forms.TabPage();
this.grpPriorityMappings = new System.Windows.Forms.GroupBox();
this.lblPriorityValidationNote = new System.Windows.Forms.Label();
this.btnDeletePriorityMapping = new System.Windows.Forms.Button();
this.grdPriorityMappings = new System.Windows.Forms.DataGridView();
this.colVersionOnePriority = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.colJiraPriority = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.grpVersionOneDefectAttributes.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nmdInterval)).BeginInit();
this.grpConnection.SuspendLayout();
this.grpUpdate.SuspendLayout();
this.grpSearch.SuspendLayout();
this.grpProjectMappings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).BeginInit();
this.tcJiraData.SuspendLayout();
this.tpSettings.SuspendLayout();
this.tpMappings.SuspendLayout();
this.grpPriorityMappings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).BeginInit();
this.SuspendLayout();
//
// chkDisabled
//
this.chkDisabled.AutoSize = true;
this.chkDisabled.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkDisabled.Location = new System.Drawing.Point(405, 11);
this.chkDisabled.Name = "chkDisabled";
this.chkDisabled.Size = new System.Drawing.Size(67, 17);
this.chkDisabled.TabIndex = 0;
this.chkDisabled.Text = "Disabled";
this.chkDisabled.UseVisualStyleBackColor = true;
//
// grpVersionOneDefectAttributes
//
this.grpVersionOneDefectAttributes.Controls.Add(this.cboSourceFieldValue);
this.grpVersionOneDefectAttributes.Controls.Add(this.txtJiraUrlTitle);
this.grpVersionOneDefectAttributes.Controls.Add(this.lblJiraUrlTitle);
this.grpVersionOneDefectAttributes.Controls.Add(this.txtJiraUrlTempl);
this.grpVersionOneDefectAttributes.Controls.Add(this.lblJiraUrlTempl);
this.grpVersionOneDefectAttributes.Controls.Add(this.lblSourceFieldValue);
this.grpVersionOneDefectAttributes.Location = new System.Drawing.Point(12, 134);
this.grpVersionOneDefectAttributes.Name = "grpVersionOneDefectAttributes";
this.grpVersionOneDefectAttributes.Size = new System.Drawing.Size(502, 108);
this.grpVersionOneDefectAttributes.TabIndex = 1;
this.grpVersionOneDefectAttributes.TabStop = false;
this.grpVersionOneDefectAttributes.Text = "VersionOne Workitem attributes";
//
// cboSourceFieldValue
//
this.cboSourceFieldValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboSourceFieldValue.FormattingEnabled = true;
this.cboSourceFieldValue.Location = new System.Drawing.Point(129, 19);
this.cboSourceFieldValue.Name = "cboSourceFieldValue";
this.cboSourceFieldValue.Size = new System.Drawing.Size(327, 21);
this.cboSourceFieldValue.TabIndex = 1;
//
// txtJiraUrlTitle
//
this.txtJiraUrlTitle.Location = new System.Drawing.Point(129, 76);
this.txtJiraUrlTitle.Name = "txtJiraUrlTitle";
this.txtJiraUrlTitle.Size = new System.Drawing.Size(327, 20);
this.txtJiraUrlTitle.TabIndex = 5;
//
// lblJiraUrlTitle
//
this.lblJiraUrlTitle.AutoSize = true;
this.lblJiraUrlTitle.Location = new System.Drawing.Point(12, 79);
this.lblJiraUrlTitle.Name = "lblJiraUrlTitle";
this.lblJiraUrlTitle.Size = new System.Drawing.Size(52, 13);
this.lblJiraUrlTitle.TabIndex = 4;
this.lblJiraUrlTitle.Text = "URL Title";
//
// txtJiraUrlTempl
//
this.txtJiraUrlTempl.Location = new System.Drawing.Point(129, 48);
this.txtJiraUrlTempl.Name = "txtJiraUrlTempl";
this.txtJiraUrlTempl.Size = new System.Drawing.Size(327, 20);
this.txtJiraUrlTempl.TabIndex = 3;
//
// lblJiraUrlTempl
//
this.lblJiraUrlTempl.AutoSize = true;
this.lblJiraUrlTempl.Location = new System.Drawing.Point(12, 51);
this.lblJiraUrlTempl.Name = "lblJiraUrlTempl";
this.lblJiraUrlTempl.Size = new System.Drawing.Size(76, 13);
this.lblJiraUrlTempl.TabIndex = 2;
this.lblJiraUrlTempl.Text = "URL Template";
//
// lblSourceFieldValue
//
this.lblSourceFieldValue.AutoSize = true;
this.lblSourceFieldValue.Location = new System.Drawing.Point(12, 22);
this.lblSourceFieldValue.Name = "lblSourceFieldValue";
this.lblSourceFieldValue.Size = new System.Drawing.Size(41, 13);
this.lblSourceFieldValue.TabIndex = 0;
this.lblSourceFieldValue.Text = "Source";
//
// lblMinutes
//
this.lblMinutes.AutoSize = true;
this.lblMinutes.Location = new System.Drawing.Point(199, 255);
this.lblMinutes.Name = "lblMinutes";
this.lblMinutes.Size = new System.Drawing.Size(43, 13);
this.lblMinutes.TabIndex = 4;
this.lblMinutes.Text = "minutes";
//
// lblTimerInterval
//
this.lblTimerInterval.AutoSize = true;
this.lblTimerInterval.Location = new System.Drawing.Point(24, 255);
this.lblTimerInterval.Name = "lblTimerInterval";
this.lblTimerInterval.Size = new System.Drawing.Size(62, 13);
this.lblTimerInterval.TabIndex = 2;
this.lblTimerInterval.Text = "Poll Interval";
//
// nmdInterval
//
this.nmdInterval.Location = new System.Drawing.Point(141, 251);
this.nmdInterval.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nmdInterval.Name = "nmdInterval";
this.nmdInterval.Size = new System.Drawing.Size(52, 20);
this.nmdInterval.TabIndex = 3;
this.nmdInterval.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// txtCreateDefectFilterId
//
this.txtCreateDefectFilterId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCreateDefectFilterId.Location = new System.Drawing.Point(130, 19);
this.txtCreateDefectFilterId.Name = "txtCreateDefectFilterId";
this.txtCreateDefectFilterId.Size = new System.Drawing.Size(115, 20);
this.txtCreateDefectFilterId.TabIndex = 1;
//
// lblCreateDefectFilterId
//
this.lblCreateDefectFilterId.AutoSize = true;
this.lblCreateDefectFilterId.Location = new System.Drawing.Point(12, 23);
this.lblCreateDefectFilterId.Name = "lblCreateDefectFilterId";
this.lblCreateDefectFilterId.Size = new System.Drawing.Size(112, 13);
this.lblCreateDefectFilterId.TabIndex = 0;
this.lblCreateDefectFilterId.Text = "Create Defect Filter ID";
//
// txtDefectLinkFieldId
//
this.txtDefectLinkFieldId.Location = new System.Drawing.Point(154, 18);
this.txtDefectLinkFieldId.Name = "txtDefectLinkFieldId";
this.txtDefectLinkFieldId.Size = new System.Drawing.Size(302, 20);
this.txtDefectLinkFieldId.TabIndex = 1;
//
// lblDefectLinkFieldId
//
this.lblDefectLinkFieldId.AutoSize = true;
this.lblDefectLinkFieldId.Location = new System.Drawing.Point(12, 22);
this.lblDefectLinkFieldId.Name = "lblDefectLinkFieldId";
this.lblDefectLinkFieldId.Size = new System.Drawing.Size(136, 13);
this.lblDefectLinkFieldId.TabIndex = 0;
this.lblDefectLinkFieldId.Text = "Link to VersionOne Field ID";
//
// grpConnection
//
this.grpConnection.Controls.Add(this.lblConnectionValidation);
this.grpConnection.Controls.Add(this.btnVerify);
this.grpConnection.Controls.Add(this.txtPassword);
this.grpConnection.Controls.Add(this.lblPassword);
this.grpConnection.Controls.Add(this.txtUserName);
this.grpConnection.Controls.Add(this.lblUserName);
this.grpConnection.Controls.Add(this.txtUrl);
this.grpConnection.Controls.Add(this.lblUrl);
this.grpConnection.Location = new System.Drawing.Point(12, 5);
this.grpConnection.Name = "grpConnection";
this.grpConnection.Size = new System.Drawing.Size(502, 121);
this.grpConnection.TabIndex = 0;
this.grpConnection.TabStop = false;
this.grpConnection.Text = "Connection";
//
// lblConnectionValidation
//
this.lblConnectionValidation.AutoSize = true;
this.lblConnectionValidation.Location = new System.Drawing.Point(74, 89);
this.lblConnectionValidation.Name = "lblConnectionValidation";
this.lblConnectionValidation.Size = new System.Drawing.Size(81, 13);
this.lblConnectionValidation.TabIndex = 6;
this.lblConnectionValidation.Text = "Validation result";
this.lblConnectionValidation.Visible = false;
//
// btnVerify
//
this.btnVerify.Location = new System.Drawing.Point(389, 82);
this.btnVerify.Name = "btnVerify";
this.btnVerify.Size = new System.Drawing.Size(67, 27);
this.btnVerify.TabIndex = 7;
this.btnVerify.Text = "Validate";
this.btnVerify.UseVisualStyleBackColor = true;
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(330, 49);
this.txtPassword.Name = "txtPassword";
this.txtPassword.Size = new System.Drawing.Size(126, 20);
this.txtPassword.TabIndex = 5;
//
// lblPassword
//
this.lblPassword.AutoSize = true;
this.lblPassword.Location = new System.Drawing.Point(268, 52);
this.lblPassword.Name = "lblPassword";
this.lblPassword.Size = new System.Drawing.Size(53, 13);
this.lblPassword.TabIndex = 4;
this.lblPassword.Text = "Password";
//
// txtUserName
//
this.txtUserName.Location = new System.Drawing.Point(77, 49);
this.txtUserName.Name = "txtUserName";
this.txtUserName.Size = new System.Drawing.Size(130, 20);
this.txtUserName.TabIndex = 3;
//
// lblUserName
//
this.lblUserName.AutoSize = true;
this.lblUserName.Location = new System.Drawing.Point(12, 52);
this.lblUserName.Name = "lblUserName";
this.lblUserName.Size = new System.Drawing.Size(55, 13);
this.lblUserName.TabIndex = 2;
this.lblUserName.Text = "Username";
//
// txtUrl
//
this.txtUrl.Location = new System.Drawing.Point(77, 20);
this.txtUrl.Name = "txtUrl";
this.txtUrl.Size = new System.Drawing.Size(379, 20);
this.txtUrl.TabIndex = 1;
//
// lblUrl
//
this.lblUrl.AutoSize = true;
this.lblUrl.Location = new System.Drawing.Point(12, 23);
this.lblUrl.Name = "lblUrl";
this.lblUrl.Size = new System.Drawing.Size(48, 13);
this.lblUrl.TabIndex = 0;
this.lblUrl.Text = "JIRA URL";
//
// grpUpdate
//
this.grpUpdate.Controls.Add(this.lblDefectLinkFieldId);
this.grpUpdate.Controls.Add(this.txtDefectLinkFieldId);
this.grpUpdate.Controls.Add(this.lblAssigneeStateChanged);
this.grpUpdate.Controls.Add(this.txtAssigneeStateChanged);
this.grpUpdate.Controls.Add(this.lblProgressWorkflow);
this.grpUpdate.Controls.Add(this.txtProgressWorkflow);
this.grpUpdate.Controls.Add(this.lblProgressWorkflowClosed);
this.grpUpdate.Controls.Add(this.txtProgressWorkflowClosed);
this.grpUpdate.Controls.Add(this.lblCommentCloseFieldId);
this.grpUpdate.Controls.Add(this.lblCommentCreateFieldId);
this.grpUpdate.Controls.Add(this.lblCreateFieldId);
this.grpUpdate.Controls.Add(this.txtCreateFieldId);
this.grpUpdate.Controls.Add(this.lblCreateFieldValue);
this.grpUpdate.Controls.Add(this.txtCreateFieldValue);
this.grpUpdate.Controls.Add(this.lblCloseFieldId);
this.grpUpdate.Controls.Add(this.txtCloseFieldId);
this.grpUpdate.Controls.Add(this.lblCloseFieldValue);
this.grpUpdate.Controls.Add(this.txtCloseFieldValue);
this.grpUpdate.Location = new System.Drawing.Point(11, 374);
this.grpUpdate.Name = "grpUpdate";
this.grpUpdate.Size = new System.Drawing.Size(502, 209);
this.grpUpdate.TabIndex = 3;
this.grpUpdate.TabStop = false;
this.grpUpdate.Text = "Update JIRA Issue";
//
// lblAssigneeStateChanged
//
this.lblAssigneeStateChanged.AutoSize = true;
this.lblAssigneeStateChanged.Location = new System.Drawing.Point(12, 145);
this.lblAssigneeStateChanged.Name = "lblAssigneeStateChanged";
this.lblAssigneeStateChanged.Size = new System.Drawing.Size(124, 13);
this.lblAssigneeStateChanged.TabIndex = 12;
this.lblAssigneeStateChanged.Text = "Assignee State Changed";
//
// txtAssigneeStateChanged
//
this.txtAssigneeStateChanged.Location = new System.Drawing.Point(154, 141);
this.txtAssigneeStateChanged.Name = "txtAssigneeStateChanged";
this.txtAssigneeStateChanged.Size = new System.Drawing.Size(302, 20);
this.txtAssigneeStateChanged.TabIndex = 8;
//
// lblProgressWorkflow
//
this.lblProgressWorkflow.AutoSize = true;
this.lblProgressWorkflow.Location = new System.Drawing.Point(12, 178);
this.lblProgressWorkflow.Name = "lblProgressWorkflow";
this.lblProgressWorkflow.Size = new System.Drawing.Size(136, 13);
this.lblProgressWorkflow.TabIndex = 14;
this.lblProgressWorkflow.Text = "Progress Workflow Created";
//
// txtProgressWorkflow
//
this.txtProgressWorkflow.Location = new System.Drawing.Point(154, 174);
this.txtProgressWorkflow.Name = "txtProgressWorkflow";
this.txtProgressWorkflow.Size = new System.Drawing.Size(53, 20);
this.txtProgressWorkflow.TabIndex = 10;
//
// lblProgressWorkflowClosed
//
this.lblProgressWorkflowClosed.AutoSize = true;
this.lblProgressWorkflowClosed.Location = new System.Drawing.Point(269, 178);
this.lblProgressWorkflowClosed.Name = "lblProgressWorkflowClosed";
this.lblProgressWorkflowClosed.Size = new System.Drawing.Size(131, 13);
this.lblProgressWorkflowClosed.TabIndex = 16;
this.lblProgressWorkflowClosed.Text = "Progress Workflow Closed";
//
// txtProgressWorkflowClosed
//
this.txtProgressWorkflowClosed.Location = new System.Drawing.Point(403, 174);
this.txtProgressWorkflowClosed.Name = "txtProgressWorkflowClosed";
this.txtProgressWorkflowClosed.Size = new System.Drawing.Size(53, 20);
this.txtProgressWorkflowClosed.TabIndex = 15;
//
// lblCommentCloseFieldId
//
this.lblCommentCloseFieldId.AutoSize = true;
this.lblCommentCloseFieldId.BackColor = System.Drawing.SystemColors.Control;
this.lblCommentCloseFieldId.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblCommentCloseFieldId.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.lblCommentCloseFieldId.Location = new System.Drawing.Point(12, 120);
this.lblCommentCloseFieldId.Name = "lblCommentCloseFieldId";
this.lblCommentCloseFieldId.Size = new System.Drawing.Size(157, 14);
this.lblCommentCloseFieldId.TabIndex = 9;
this.lblCommentCloseFieldId.Text = "\"customfield_\" plus numeric id";
//
// lblCommentCreateFieldId
//
this.lblCommentCreateFieldId.AutoSize = true;
this.lblCommentCreateFieldId.BackColor = System.Drawing.SystemColors.Control;
this.lblCommentCreateFieldId.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblCommentCreateFieldId.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.lblCommentCreateFieldId.Location = new System.Drawing.Point(12, 75);
this.lblCommentCreateFieldId.Name = "lblCommentCreateFieldId";
this.lblCommentCreateFieldId.Size = new System.Drawing.Size(157, 14);
this.lblCommentCreateFieldId.TabIndex = 4;
this.lblCommentCreateFieldId.Text = "\"customfield_\" plus numeric id";
//
// lblCreateFieldId
//
this.lblCreateFieldId.AutoSize = true;
this.lblCreateFieldId.Location = new System.Drawing.Point(12, 57);
this.lblCreateFieldId.Name = "lblCreateFieldId";
this.lblCreateFieldId.Size = new System.Drawing.Size(77, 13);
this.lblCreateFieldId.TabIndex = 0;
this.lblCreateFieldId.Text = "Create Field ID";
//
// txtCreateFieldId
//
this.txtCreateFieldId.Location = new System.Drawing.Point(93, 53);
this.txtCreateFieldId.Name = "txtCreateFieldId";
this.txtCreateFieldId.Size = new System.Drawing.Size(114, 20);
this.txtCreateFieldId.TabIndex = 1;
//
// lblCreateFieldValue
//
this.lblCreateFieldValue.AutoSize = true;
this.lblCreateFieldValue.Location = new System.Drawing.Point(264, 57);
this.lblCreateFieldValue.Name = "lblCreateFieldValue";
this.lblCreateFieldValue.Size = new System.Drawing.Size(93, 13);
this.lblCreateFieldValue.TabIndex = 2;
this.lblCreateFieldValue.Text = "Create Field Value";
//
// txtCreateFieldValue
//
this.txtCreateFieldValue.Location = new System.Drawing.Point(368, 53);
this.txtCreateFieldValue.Name = "txtCreateFieldValue";
this.txtCreateFieldValue.Size = new System.Drawing.Size(88, 20);
this.txtCreateFieldValue.TabIndex = 3;
//
// lblCloseFieldId
//
this.lblCloseFieldId.AutoSize = true;
this.lblCloseFieldId.Location = new System.Drawing.Point(12, 101);
this.lblCloseFieldId.Name = "lblCloseFieldId";
this.lblCloseFieldId.Size = new System.Drawing.Size(72, 13);
this.lblCloseFieldId.TabIndex = 5;
this.lblCloseFieldId.Text = "Close Field ID";
//
// txtCloseFieldId
//
this.txtCloseFieldId.Location = new System.Drawing.Point(93, 97);
this.txtCloseFieldId.Name = "txtCloseFieldId";
this.txtCloseFieldId.Size = new System.Drawing.Size(114, 20);
this.txtCloseFieldId.TabIndex = 6;
//
// lblCloseFieldValue
//
this.lblCloseFieldValue.AutoSize = true;
this.lblCloseFieldValue.Location = new System.Drawing.Point(264, 101);
this.lblCloseFieldValue.Name = "lblCloseFieldValue";
this.lblCloseFieldValue.Size = new System.Drawing.Size(88, 13);
this.lblCloseFieldValue.TabIndex = 7;
this.lblCloseFieldValue.Text = "Close Field Value";
//
// txtCloseFieldValue
//
this.txtCloseFieldValue.Location = new System.Drawing.Point(368, 97);
this.txtCloseFieldValue.Name = "txtCloseFieldValue";
this.txtCloseFieldValue.Size = new System.Drawing.Size(88, 20);
this.txtCloseFieldValue.TabIndex = 8;
//
// grpSearch
//
this.grpSearch.Controls.Add(this.lblCreateDefectFilterId);
this.grpSearch.Controls.Add(this.txtCreateDefectFilterId);
this.grpSearch.Controls.Add(this.chkDefectFilterDisabled);
this.grpSearch.Controls.Add(this.lblCreateStoryFilterId);
this.grpSearch.Controls.Add(this.txtCreateStoryFilterId);
this.grpSearch.Controls.Add(this.chkStoryFilterDisabled);
this.grpSearch.Location = new System.Drawing.Point(12, 280);
this.grpSearch.Name = "grpSearch";
this.grpSearch.Size = new System.Drawing.Size(502, 86);
this.grpSearch.TabIndex = 2;
this.grpSearch.TabStop = false;
this.grpSearch.Text = "Find JIRA Issues";
//
// chkDefectFilterDisabled
//
this.chkDefectFilterDisabled.AutoSize = true;
this.chkDefectFilterDisabled.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkDefectFilterDisabled.Location = new System.Drawing.Point(293, 21);
this.chkDefectFilterDisabled.Name = "chkDefectFilterDisabled";
this.chkDefectFilterDisabled.Size = new System.Drawing.Size(67, 17);
this.chkDefectFilterDisabled.TabIndex = 2;
this.chkDefectFilterDisabled.Text = "Disabled";
this.chkDefectFilterDisabled.UseVisualStyleBackColor = true;
//
// lblCreateStoryFilterId
//
this.lblCreateStoryFilterId.AutoSize = true;
this.lblCreateStoryFilterId.Location = new System.Drawing.Point(12, 54);
this.lblCreateStoryFilterId.Name = "lblCreateStoryFilterId";
this.lblCreateStoryFilterId.Size = new System.Drawing.Size(104, 13);
this.lblCreateStoryFilterId.TabIndex = 3;
this.lblCreateStoryFilterId.Text = "Create Story Filter ID";
//
// txtCreateStoryFilterId
//
this.txtCreateStoryFilterId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCreateStoryFilterId.Location = new System.Drawing.Point(130, 50);
this.txtCreateStoryFilterId.Name = "txtCreateStoryFilterId";
this.txtCreateStoryFilterId.Size = new System.Drawing.Size(115, 20);
this.txtCreateStoryFilterId.TabIndex = 4;
//
// chkStoryFilterDisabled
//
this.chkStoryFilterDisabled.AutoSize = true;
this.chkStoryFilterDisabled.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.chkStoryFilterDisabled.Location = new System.Drawing.Point(293, 52);
this.chkStoryFilterDisabled.Name = "chkStoryFilterDisabled";
this.chkStoryFilterDisabled.Size = new System.Drawing.Size(67, 17);
this.chkStoryFilterDisabled.TabIndex = 5;
this.chkStoryFilterDisabled.Text = "Disabled";
this.chkStoryFilterDisabled.UseVisualStyleBackColor = true;
//
// grpProjectMappings
//
this.grpProjectMappings.Controls.Add(this.btnDeleteProjectMapping);
this.grpProjectMappings.Controls.Add(this.grdProjectMappings);
this.grpProjectMappings.Location = new System.Drawing.Point(6, 9);
this.grpProjectMappings.Name = "grpProjectMappings";
this.grpProjectMappings.Size = new System.Drawing.Size(508, 236);
this.grpProjectMappings.TabIndex = 0;
this.grpProjectMappings.TabStop = false;
this.grpProjectMappings.Text = "Project Mappings";
//
// btnDeleteProjectMapping
//
this.btnDeleteProjectMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon;
this.btnDeleteProjectMapping.Location = new System.Drawing.Point(330, 195);
this.btnDeleteProjectMapping.Name = "btnDeleteProjectMapping";
this.btnDeleteProjectMapping.Size = new System.Drawing.Size(132, 26);
this.btnDeleteProjectMapping.TabIndex = 1;
this.btnDeleteProjectMapping.Text = "Delete selected row";
this.btnDeleteProjectMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnDeleteProjectMapping.UseVisualStyleBackColor = true;
//
// grdProjectMappings
//
this.grdProjectMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdProjectMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colVersionOneProject,
this.colJiraProject});
this.grdProjectMappings.Location = new System.Drawing.Point(15, 20);
this.grdProjectMappings.MultiSelect = false;
this.grdProjectMappings.Name = "grdProjectMappings";
this.grdProjectMappings.Size = new System.Drawing.Size(447, 169);
this.grdProjectMappings.TabIndex = 0;
//
// colVersionOneProject
//
this.colVersionOneProject.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.colVersionOneProject.DataPropertyName = "VersionOneProjectToken";
this.colVersionOneProject.HeaderText = "VersionOne Project";
this.colVersionOneProject.MinimumWidth = 110;
this.colVersionOneProject.Name = "colVersionOneProject";
//
// colJiraProject
//
this.colJiraProject.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.colJiraProject.DataPropertyName = "JiraProjectName";
this.colJiraProject.HeaderText = "JIRA Project";
this.colJiraProject.MinimumWidth = 100;
this.colJiraProject.Name = "colJiraProject";
//
// tcJiraData
//
this.tcJiraData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tcJiraData.Controls.Add(this.tpSettings);
this.tcJiraData.Controls.Add(this.tpMappings);
this.tcJiraData.Location = new System.Drawing.Point(0, 34);
this.tcJiraData.Name = "tcJiraData";
this.tcJiraData.SelectedIndex = 0;
this.tcJiraData.Size = new System.Drawing.Size(564, 673);
this.tcJiraData.TabIndex = 1;
//
// tpSettings
//
this.tpSettings.Controls.Add(this.grpConnection);
this.tpSettings.Controls.Add(this.lblMinutes);
this.tpSettings.Controls.Add(this.grpVersionOneDefectAttributes);
this.tpSettings.Controls.Add(this.lblTimerInterval);
this.tpSettings.Controls.Add(this.grpUpdate);
this.tpSettings.Controls.Add(this.nmdInterval);
this.tpSettings.Controls.Add(this.grpSearch);
this.tpSettings.Location = new System.Drawing.Point(4, 22);
this.tpSettings.Name = "tpSettings";
this.tpSettings.Padding = new System.Windows.Forms.Padding(3);
this.tpSettings.Size = new System.Drawing.Size(556, 647);
this.tpSettings.TabIndex = 0;
this.tpSettings.Text = "JIRA Settings";
this.tpSettings.UseVisualStyleBackColor = true;
//
// tpMappings
//
this.tpMappings.Controls.Add(this.grpPriorityMappings);
this.tpMappings.Controls.Add(this.grpProjectMappings);
this.tpMappings.Location = new System.Drawing.Point(4, 22);
this.tpMappings.Name = "tpMappings";
this.tpMappings.Padding = new System.Windows.Forms.Padding(3);
this.tpMappings.Size = new System.Drawing.Size(556, 647);
this.tpMappings.TabIndex = 1;
this.tpMappings.Text = "Project and Priority Mappings";
this.tpMappings.UseVisualStyleBackColor = true;
//
// grpPriorityMappings
//
this.grpPriorityMappings.Controls.Add(this.lblPriorityValidationNote);
this.grpPriorityMappings.Controls.Add(this.btnDeletePriorityMapping);
this.grpPriorityMappings.Controls.Add(this.grdPriorityMappings);
this.grpPriorityMappings.Location = new System.Drawing.Point(12, 251);
this.grpPriorityMappings.Name = "grpPriorityMappings";
this.grpPriorityMappings.Size = new System.Drawing.Size(502, 254);
this.grpPriorityMappings.TabIndex = 1;
this.grpPriorityMappings.TabStop = false;
this.grpPriorityMappings.Text = "Priority Mappings";
this.grdPriorityMappings.EditMode = DataGridViewEditMode.EditOnEnter;
//
// lblPriorityValidationNote
//
this.lblPriorityValidationNote.AutoSize = true;
this.lblPriorityValidationNote.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.lblPriorityValidationNote.ForeColor = System.Drawing.SystemColors.ControlDark;
this.lblPriorityValidationNote.Location = new System.Drawing.Point(15, 196);
this.lblPriorityValidationNote.Name = "lblPriorityValidationNote";
this.lblPriorityValidationNote.Size = new System.Drawing.Size(310, 13);
this.lblPriorityValidationNote.TabIndex = 2;
this.lblPriorityValidationNote.Text = "*Please validate connection to JIRA for proper priority assignment.";
//
// btnDeletePriorityMapping
//
this.btnDeletePriorityMapping.Image = global::VersionOne.ServiceHost.ConfigurationTool.Resources.DeleteIcon;
this.btnDeletePriorityMapping.Location = new System.Drawing.Point(324, 222);
this.btnDeletePriorityMapping.Name = "btnDeletePriorityMapping";
this.btnDeletePriorityMapping.Size = new System.Drawing.Size(132, 26);
this.btnDeletePriorityMapping.TabIndex = 1;
this.btnDeletePriorityMapping.Text = "Delete selected row";
this.btnDeletePriorityMapping.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnDeletePriorityMapping.UseVisualStyleBackColor = true;
//
// grdPriorityMappings
//
this.grdPriorityMappings.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdPriorityMappings.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colVersionOnePriority,
this.colJiraPriority});
this.grdPriorityMappings.Location = new System.Drawing.Point(15, 20);
this.grdPriorityMappings.MultiSelect = false;
this.grdPriorityMappings.Name = "grdPriorityMappings";
this.grdPriorityMappings.Size = new System.Drawing.Size(441, 169);
this.grdPriorityMappings.TabIndex = 0;
//
// colVersionOnePriority
//
this.colVersionOnePriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.colVersionOnePriority.DataPropertyName = "VersionOnePriorityId";
this.colVersionOnePriority.HeaderText = "VersionOne Priority";
this.colVersionOnePriority.MinimumWidth = 100;
this.colVersionOnePriority.Name = "colVersionOnePriority";
//
// colJiraPriority
//
this.colJiraPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.colJiraPriority.DataPropertyName = "JiraPriorityId";
this.colJiraPriority.HeaderText = "JIRA Priority";
this.colJiraPriority.MinimumWidth = 100;
this.colJiraPriority.Name = "colJiraPriority";
//
// JiraPageControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tcJiraData);
this.Controls.Add(this.chkDisabled);
this.Name = "JiraPageControl";
this.Size = new System.Drawing.Size(540, 742);
this.grpVersionOneDefectAttributes.ResumeLayout(false);
this.grpVersionOneDefectAttributes.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nmdInterval)).EndInit();
this.grpConnection.ResumeLayout(false);
this.grpConnection.PerformLayout();
this.grpUpdate.ResumeLayout(false);
this.grpUpdate.PerformLayout();
this.grpSearch.ResumeLayout(false);
this.grpSearch.PerformLayout();
this.grpProjectMappings.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grdProjectMappings)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bsProjectMappings)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.bsPriorityMappings)).EndInit();
this.tcJiraData.ResumeLayout(false);
this.tpSettings.ResumeLayout(false);
this.tpSettings.PerformLayout();
this.tpMappings.ResumeLayout(false);
this.grpPriorityMappings.ResumeLayout(false);
this.grpPriorityMappings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.grdPriorityMappings)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.CheckBox chkDisabled;
private System.Windows.Forms.GroupBox grpVersionOneDefectAttributes;
private System.Windows.Forms.Label lblMinutes;
private System.Windows.Forms.Label lblTimerInterval;
private System.Windows.Forms.NumericUpDown nmdInterval;
private System.Windows.Forms.ComboBox cboSourceFieldValue;
private System.Windows.Forms.TextBox txtJiraUrlTitle;
private System.Windows.Forms.Label lblJiraUrlTitle;
private System.Windows.Forms.TextBox txtJiraUrlTempl;
private System.Windows.Forms.Label lblJiraUrlTempl;
private System.Windows.Forms.TextBox txtCreateDefectFilterId;
private System.Windows.Forms.Label lblCreateDefectFilterId;
private System.Windows.Forms.TextBox txtDefectLinkFieldId;
private System.Windows.Forms.Label lblDefectLinkFieldId;
private System.Windows.Forms.Label lblSourceFieldValue;
private System.Windows.Forms.GroupBox grpConnection;
private System.Windows.Forms.Label lblConnectionValidation;
private System.Windows.Forms.Button btnVerify;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.Label lblPassword;
private System.Windows.Forms.TextBox txtUserName;
private System.Windows.Forms.Label lblUserName;
private System.Windows.Forms.TextBox txtUrl;
private System.Windows.Forms.Label lblUrl;
private System.Windows.Forms.GroupBox grpUpdate;
private System.Windows.Forms.GroupBox grpSearch;
private System.Windows.Forms.GroupBox grpProjectMappings;
private System.Windows.Forms.DataGridView grdProjectMappings;
private System.Windows.Forms.Button btnDeleteProjectMapping;
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.BindingSource bsProjectMappings;
private System.Windows.Forms.BindingSource bsPriorityMappings;
private TabControl tcJiraData;
private TabPage tpSettings;
private TabPage tpMappings;
private GroupBox grpPriorityMappings;
private Button btnDeletePriorityMapping;
private DataGridView grdPriorityMappings;
private Label lblPriorityValidationNote;
private DataGridViewComboBoxColumn colVersionOneProject;
private DataGridViewTextBoxColumn colJiraProject;
private DataGridViewComboBoxColumn colVersionOnePriority;
private DataGridViewComboBoxColumn colJiraPriority;
private CheckBox chkStoryFilterDisabled;
private Label lblCreateStoryFilterId;
private TextBox txtCreateStoryFilterId;
private CheckBox chkDefectFilterDisabled;
private Label lblAssigneeStateChanged;
private TextBox txtAssigneeStateChanged;
private Label lblProgressWorkflow;
private TextBox txtProgressWorkflow;
private Label lblProgressWorkflowClosed;
private TextBox txtProgressWorkflowClosed;
private Label lblCommentCloseFieldId;
private Label lblCommentCreateFieldId;
private Label lblCreateFieldId;
private Label lblCreateFieldValue;
private TextBox txtCreateFieldId;
private Label lblCloseFieldId;
private TextBox txtCreateFieldValue;
private Label lblCloseFieldValue;
private TextBox txtCloseFieldId;
private TextBox txtCloseFieldValue;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Runtime
{
public static class TaskHelpers
{
//This replaces the Wait<TException>(this Task task) method as we want to await and not Wait()
public static async Task AsyncWait<TException>(this Task task)
{
try
{
await task;
}
catch
{
throw Fx.Exception.AsError<TException>(task.Exception);
}
}
// Helper method when implementing an APM wrapper around a Task based async method which returns a result.
// In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync:
// return MethodAsync(params).ToApm(callback, state);
// In the EndMethod, you would use ToApmEnd<TResult> to ensure the correct exception handling
// This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided
// state object
public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback callback, object state)
{
// When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This
// is so the callback can regain state. If the incoming task already holds the state object, there's no need
// to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object.
// This is a performance optimization for this special case.
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith((antecedent, obj) =>
{
var callbackObj = obj as AsyncCallback;
callbackObj(antecedent);
}, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
}
return task;
}
// Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value.
var tcs = new TaskCompletionSource<TResult>(state);
var continuationState = Tuple.Create(tcs, callback);
task.ContinueWith((antecedent, obj) =>
{
var tuple = obj as Tuple<TaskCompletionSource<TResult>, AsyncCallback>;
var tcsObj = tuple.Item1;
var callbackObj = tuple.Item2;
if (antecedent.IsFaulted) tcsObj.TrySetException(antecedent.Exception.InnerException);
else if (antecedent.IsCanceled) tcsObj.TrySetCanceled();
else tcsObj.TrySetResult(antecedent.Result);
if (callbackObj != null)
{
callbackObj(tcsObj.Task);
}
}, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
return tcs.Task;
}
// Helper method when implementing an APM wrapper around a Task based async method which returns a result.
// In the BeginMethod method, you would call use ToApm to wrap a call to MethodAsync:
// return MethodAsync(params).ToApm(callback, state);
// In the EndMethod, you would use ToApmEnd to ensure the correct exception handling
// This will handle throwing exceptions in the correct place and ensure the IAsyncResult contains the provided
// state object
public static Task ToApm(this Task task, AsyncCallback callback, object state)
{
// When using APM, the returned IAsyncResult must have the passed in state object stored in AsyncState. This
// is so the callback can regain state. If the incoming task already holds the state object, there's no need
// to create a TaskCompletionSource to ensure the returned (IAsyncResult)Task has the right state object.
// This is a performance optimization for this special case.
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith((antecedent, obj) =>
{
var callbackObj = obj as AsyncCallback;
callbackObj(antecedent);
}, callback, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
}
return task;
}
// Need to create a TaskCompletionSource so that the returned Task object has the correct AsyncState value.
// As we intend to create a task with no Result value, we don't care what result type the TCS holds as we
// won't be using it. As Task<TResult> derives from Task, the returned Task is compatible.
var tcs = new TaskCompletionSource<object>(state);
var continuationState = Tuple.Create(tcs, callback);
task.ContinueWith((antecedent, obj) =>
{
var tuple = obj as Tuple<TaskCompletionSource<object>, AsyncCallback>;
var tcsObj = tuple.Item1;
var callbackObj = tuple.Item2;
if (antecedent.IsFaulted)
{
tcsObj.TrySetException(antecedent.Exception.InnerException);
}
else if (antecedent.IsCanceled)
{
tcsObj.TrySetCanceled();
}
else
{
tcsObj.TrySetResult(null);
}
if (callbackObj != null)
{
callbackObj(tcsObj.Task);
}
}, continuationState, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);
return tcs.Task;
}
// Helper method to implement the End method of an APM method pair which is wrapping a Task based
// async method when the Task returns a result. By using task.GetAwaiter.GetResult(), the exception
// handling conventions are the same as when await'ing a task, i.e. this throws the first exception
// and doesn't wrap it in an AggregateException. It also throws the right exception if the task was
// cancelled.
public static TResult ToApmEnd<TResult>(this IAsyncResult iar)
{
Task<TResult> task = iar as Task<TResult>;
Contract.Assert(task != null, "IAsyncResult must be an instance of Task<TResult>");
return task.GetAwaiter().GetResult();
}
// Helper method to implement the End method of an APM method pair which is wrapping a Task based
// async method when the Task does not return result.
public static void ToApmEnd(this IAsyncResult iar)
{
Task task = iar as Task;
Contract.Assert(task != null, "IAsyncResult must be an instance of Task");
task.GetAwaiter().GetResult();
}
// Awaitable helper to await a maximum amount of time for a task to complete. If the task doesn't
// complete in the specified amount of time, returns false. This does not modify the state of the
// passed in class, but instead is a mechanism to allow interrupting awaiting a task if a timeout
// period passes.
public static async Task<bool> AwaitWithTimeout(this Task task, TimeSpan timeout)
{
if (task.IsCompleted)
{
return true;
}
using (CancellationTokenSource cts = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token));
if (completedTask == task)
{
cts.Cancel();
return true;
}
else
{
return (task.IsCompleted);
}
}
}
// Task.GetAwaiter().GetResult() calls an internal variant of Wait() which doesn't wrap exceptions in
// an AggregateException.
public static void WaitForCompletion(this Task task)
{
task.GetAwaiter().GetResult();
}
public static TResult WaitForCompletion<TResult>(this Task<TResult> task)
{
return task.GetAwaiter().GetResult();
}
// Used by WebSocketTransportDuplexSessionChannel on the sync code path.
// TODO: Try and switch as many code paths as possible which use this to async
public static void Wait(this Task task, TimeSpan timeout, Action<Exception, TimeSpan, string> exceptionConverter, string operationType)
{
bool timedOut = false;
try
{
if (timeout > TimeoutHelper.MaxWait)
{
task.Wait();
}
else
{
timedOut = !task.Wait(timeout);
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex) || exceptionConverter == null)
{
throw;
}
exceptionConverter(ex, timeout, operationType);
}
if (timedOut)
{
throw Fx.Exception.AsError(new TimeoutException(InternalSR.TaskTimedOutError(timeout)));
}
}
public static Task CompletedTask()
{
return Task.FromResult(true);
}
public static DefaultTaskSchedulerAwaiter EnsureDefaultTaskScheduler()
{
return DefaultTaskSchedulerAwaiter.Singleton;
}
public static Action<object> OnAsyncCompletionCallback = OnAsyncCompletion;
// Method to act as callback for asynchronous code which uses AsyncCompletionResult as the return type when used within
// a Task based async method. These methods require a callback which is called in the case of the IO completing asynchronously.
// This pattern still requires an allocation, whereas the purpose of using the AsyncCompletionResult enum is to avoid allocation.
// In the future, this pattern should be replaced with a reusable awaitable object, potentially with a global pool.
private static void OnAsyncCompletion(object state)
{
var tcs = state as TaskCompletionSource<bool>;
Contract.Assert(state != null, "Async state should be of type TaskCompletionSource<bool>");
tcs.TrySetResult(true);
}
}
// This awaiter causes an awaiting async method to continue on the same thread if using the
// default task scheduler, otherwise it posts the continuation to the ThreadPool. While this
// does a similar function to Task.ConfigureAwait, this code doesn't require a Task to function.
// With Task.ConfigureAwait, you would need to call it on the first task on each potential code
// path in a method. This could mean calling ConfigureAwait multiple times in a single method.
// This awaiter can be awaited on at the beginning of a method a single time and isn't dependant
// on running other awaitable code.
public struct DefaultTaskSchedulerAwaiter : INotifyCompletion
{
public static DefaultTaskSchedulerAwaiter Singleton = new DefaultTaskSchedulerAwaiter();
// If the current TaskScheduler is the default, if we aren't currently running inside a task and
// the default SynchronizationContext isn't current, when a Task starts, it will change the TaskScheduler
// to one based off the current SynchronizationContext. Also, any async api's that WCF consumes will
// post back to the same SynchronizationContext as they were started in which could cause WCF to deadlock
// on our Sync code path.
public bool IsCompleted
{
get
{
return (TaskScheduler.Current == TaskScheduler.Default) &&
(SynchronizationContext.Current == null ||
(SynchronizationContext.Current.GetType() == typeof(SynchronizationContext)));
}
}
// Only called when IsCompleted returns false, otherwise the caller will call the continuation
// directly causing it to stay on the same thread.
public void OnCompleted(Action continuation)
{
Task.Run(continuation);
}
// Awaiter is only used to control where subsequent awaitable's run so GetResult needs no
// implementation. Normally any exceptions would be thrown here, but we have nothing to throw
// as we don't run anything, only control where other code runs.
public void GetResult() { }
public DefaultTaskSchedulerAwaiter GetAwaiter()
{
return this;
}
}
// Async methods can't take an out (or ref) argument. This wrapper allows passing in place of an out argument
// and can be used to return a value via a method argument.
public class OutWrapper<T> where T : class
{
public OutWrapper()
{
Value = null;
}
public T Value { get; set; }
public static implicit operator T(OutWrapper<T> wrapper)
{
return wrapper.Value;
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Displays beatmap metadata inside <see cref="PlayerLoader"/>
/// </summary>
public class BeatmapMetadataDisplay : Container
{
private readonly WorkingBeatmap beatmap;
private readonly Bindable<IReadOnlyList<Mod>> mods;
private readonly Drawable logoFacade;
private LoadingSpinner loading;
public IBindable<IReadOnlyList<Mod>> Mods => mods;
public bool Loading
{
set
{
if (value)
loading.Show();
else
loading.Hide();
}
}
public BeatmapMetadataDisplay(WorkingBeatmap beatmap, Bindable<IReadOnlyList<Mod>> mods, Drawable logoFacade)
{
this.beatmap = beatmap;
this.logoFacade = logoFacade;
this.mods = new Bindable<IReadOnlyList<Mod>>();
this.mods.BindTo(mods);
}
private IBindable<StarDifficulty?> starDifficulty;
private FillFlowContainer versionFlow;
private StarRatingDisplay starRatingDisplay;
[BackgroundDependencyLoader]
private void load(BeatmapDifficultyCache difficultyCache)
{
var metadata = beatmap.BeatmapInfo.Metadata;
AutoSizeAxes = Axes.Both;
Children = new Drawable[]
{
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
Direction = FillDirection.Vertical,
Children = new[]
{
logoFacade.With(d =>
{
d.Anchor = Anchor.TopCentre;
d.Origin = Anchor.TopCentre;
}),
new OsuSpriteText
{
Text = new RomanisableString(metadata.TitleUnicode, metadata.Title),
Font = OsuFont.GetFont(size: 36, italics: true),
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
Margin = new MarginPadding { Top = 15 },
},
new OsuSpriteText
{
Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist),
Font = OsuFont.GetFont(size: 26, italics: true),
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
},
new Container
{
Size = new Vector2(300, 60),
Margin = new MarginPadding(10),
Origin = Anchor.TopCentre,
Anchor = Anchor.TopCentre,
CornerRadius = 10,
Masking = true,
Children = new Drawable[]
{
new Sprite
{
RelativeSizeAxes = Axes.Both,
Texture = beatmap?.Background,
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
FillMode = FillMode.Fill,
},
loading = new LoadingLayer(true)
}
},
versionFlow = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Direction = FillDirection.Vertical,
Spacing = new Vector2(5f),
Margin = new MarginPadding { Bottom = 40 },
Children = new Drawable[]
{
new OsuSpriteText
{
Text = beatmap?.BeatmapInfo?.Version,
Font = OsuFont.GetFont(size: 26, italics: true),
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
},
starRatingDisplay = new StarRatingDisplay(default)
{
Alpha = 0f,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
}
}
},
new GridContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
AutoSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
},
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new MetadataLineLabel("Source"),
new MetadataLineInfo(metadata.Source)
},
new Drawable[]
{
new MetadataLineLabel("Mapper"),
new MetadataLineInfo(metadata.AuthorString)
}
}
},
new ModDisplay
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Margin = new MarginPadding { Top = 20 },
Current = mods
},
},
}
};
starDifficulty = difficultyCache.GetBindableDifficulty(beatmap.BeatmapInfo);
Loading = true;
}
protected override void LoadComplete()
{
base.LoadComplete();
if (starDifficulty.Value != null)
{
starRatingDisplay.Current.Value = starDifficulty.Value.Value;
starRatingDisplay.Show();
}
else
{
starRatingDisplay.Hide();
starDifficulty.ValueChanged += d =>
{
Debug.Assert(d.NewValue != null);
starRatingDisplay.Current.Value = d.NewValue.Value;
versionFlow.AutoSizeDuration = 300;
versionFlow.AutoSizeEasing = Easing.OutQuint;
starRatingDisplay.FadeIn(300, Easing.InQuint);
};
}
}
private class MetadataLineLabel : OsuSpriteText
{
public MetadataLineLabel(string text)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Margin = new MarginPadding { Right = 5 };
Colour = OsuColour.Gray(0.8f);
Text = text;
}
}
private class MetadataLineInfo : OsuSpriteText
{
public MetadataLineInfo(string text)
{
Margin = new MarginPadding { Left = 5 };
Text = string.IsNullOrEmpty(text) ? @"-" : text;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
public class AggregateExportProvider : ExportProvider , IDisposable
{
private readonly ReadOnlyCollection<ExportProvider> _readOnlyProviders;
private readonly ExportProvider[] _providers;
private volatile int _isDisposed = 0;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
/// </summary>
/// <param name="providers">The prioritized list of export providers.</param>
/// <exception cref="ArgumentException">
/// <paramref name="providers"/> contains an element that is <see langword="null"/>.
/// </exception>
/// <remarks>
/// <para>
/// The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
/// executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
/// </para>
/// <para>
/// The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
/// That is, it will not try to dispose of any of them when it gets disposed.
/// </para>
/// </remarks>
public AggregateExportProvider(params ExportProvider[] providers)
{
// NOTE : we optimize for the array case here, because the collection of providers is typically tiny
// Arrays are much more compact to store and much faster to create and enumerate
ExportProvider[] copiedProviders = null;
if (providers != null)
{
copiedProviders = new ExportProvider[providers.Length];
for (int i = 0; i < providers.Length; i++)
{
ExportProvider provider = providers[i];
if (provider == null)
{
throw ExceptionBuilder.CreateContainsNullElement(nameof(providers));
}
copiedProviders[i] = provider;
provider.ExportsChanged += OnExportChangedInternal;
provider.ExportsChanging += OnExportChangingInternal;
}
}
else
{
copiedProviders = Array.Empty<ExportProvider>();
}
_providers = copiedProviders;
_readOnlyProviders = new ReadOnlyCollection<ExportProvider>(_providers);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateExportProvider"/> class.
/// </summary>
/// <param name="providers">The prioritized list of export providers. The providers are consulted in order in which they are supplied.</param>
/// <remarks>
/// <para>
/// The <see cref="AggregateExportProvider"/> will consult the providers in the order they have been specfied when
/// executing <see cref="ExportProvider.GetExports(ImportDefinition,AtomicComposition)"/>.
/// </para>
/// <para>
/// The <see cref="AggregateExportProvider"/> does not take ownership of the specified providers.
/// That is, it will not try to dispose of any of them when it gets disposed.
/// </para>
/// </remarks>
public AggregateExportProvider(IEnumerable<ExportProvider> providers)
: this((providers!= null) ? providers.AsArray() : null)
{
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
{
foreach (ExportProvider provider in _providers)
{
provider.ExportsChanged -= OnExportChangedInternal;
provider.ExportsChanging -= OnExportChangingInternal;
}
}
}
}
/// <summary>
/// Gets the export providers which the aggregate export provider aggregates.
/// </summary>
/// <value>
/// A <see cref="ReadOnlyCollection{T}"/> of <see cref="ExportProvider"/> objects
/// which the <see cref="AggregateExportProvider"/> aggregates.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="AggregateExportProvider"/> has been disposed of.
/// </exception>
public ReadOnlyCollection<ExportProvider> Providers
{
get
{
ThrowIfDisposed();
Debug.Assert(_readOnlyProviders != null);
return _readOnlyProviders;
}
}
/// <summary>
/// Returns all exports that match the conditions of the specified import.
/// </summary>
/// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="Export"/> to get.</param>
/// <returns></returns>
/// <result>
/// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
/// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
/// empty <see cref="IEnumerable{T}"/>.
/// </result>
/// <remarks>
/// <note type="inheritinfo">
/// The implementers should not treat the cardinality-related mismatches as errors, and are not
/// expected to throw exceptions in those cases.
/// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
if (definition.Cardinality == ImportCardinality.ZeroOrMore)
{
var exports = new List<Export>();
foreach (var provider in _providers)
{
foreach (var export in provider.GetExports(definition, atomicComposition))
{
exports.Add(export);
}
}
return exports;
}
else
{
IEnumerable<Export> allExports = null;
// if asked for "one or less", the prioriry is at play - the first provider that agrees to return the value
// which best complies with the request, wins.
foreach (ExportProvider provider in _providers)
{
IEnumerable<Export> exports;
bool cardinalityCheckResult = provider.TryGetExports(definition, atomicComposition, out exports);
bool anyExports = exports.FastAny();
if (cardinalityCheckResult && anyExports)
{
// NOTE : if the provider returned nothing, we need to proceed, even if it indicated that the
// cardinality is correct - when asked for "one or less", the provider might - correctly -
// return an empty sequence, but we shouldn't be satisfied with that as providers down the list
// might have a value we are interested in.
return exports;
}
else
{
// This is a sneaky thing that we do - if in the end no provider returns the exports with the right cardinality
// we simply return the aggregation of all exports they have returned. This way the end result is still not what we want
// but no information is lost.
if (anyExports)
{
allExports = (allExports != null) ? allExports.Concat(exports) : exports;
}
}
}
return allExports;
}
}
private void OnExportChangedInternal(object sender, ExportsChangeEventArgs e)
{
OnExportsChanged(e);
}
private void OnExportChangingInternal(object sender, ExportsChangeEventArgs e)
{
OnExportsChanging(e);
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed == 1)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "EventNotification", IsSet = false)]
public class EventNotification : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(EventNotification));
private ActionResultSequenceType actionResult_;
private bool actionResult_present;
private AlarmAckRule alarmAcknowledgmentRule_;
private bool alarmAcknowledgmentRule_present;
private EC_State currentState_;
private bool currentState_present;
private ObjectName eventConditionName_;
private ObjectName eventEnrollmentName_;
private bool notificationLost_;
private Severity severity_;
private EventTime transitionTime_;
[ASN1Element(Name = "eventEnrollmentName", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public ObjectName EventEnrollmentName
{
get
{
return eventEnrollmentName_;
}
set
{
eventEnrollmentName_ = value;
}
}
[ASN1Element(Name = "eventConditionName", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ObjectName EventConditionName
{
get
{
return eventConditionName_;
}
set
{
eventConditionName_ = value;
}
}
[ASN1Element(Name = "severity", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public Severity Severity
{
get
{
return severity_;
}
set
{
severity_ = value;
}
}
[ASN1Element(Name = "currentState", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)]
public EC_State CurrentState
{
get
{
return currentState_;
}
set
{
currentState_ = value;
currentState_present = true;
}
}
[ASN1Element(Name = "transitionTime", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public EventTime TransitionTime
{
get
{
return transitionTime_;
}
set
{
transitionTime_ = value;
}
}
[ASN1Boolean(Name = "")]
[ASN1Element(Name = "notificationLost", IsOptional = false, HasTag = true, Tag = 6, HasDefaultValue = true)]
public bool NotificationLost
{
get
{
return notificationLost_;
}
set
{
notificationLost_ = value;
}
}
[ASN1Element(Name = "alarmAcknowledgmentRule", IsOptional = true, HasTag = true, Tag = 7, HasDefaultValue = false)]
public AlarmAckRule AlarmAcknowledgmentRule
{
get
{
return alarmAcknowledgmentRule_;
}
set
{
alarmAcknowledgmentRule_ = value;
alarmAcknowledgmentRule_present = true;
}
}
[ASN1Element(Name = "actionResult", IsOptional = true, HasTag = true, Tag = 8, HasDefaultValue = false)]
public ActionResultSequenceType ActionResult
{
get
{
return actionResult_;
}
set
{
actionResult_ = value;
actionResult_present = true;
}
}
public void initWithDefaults()
{
bool param_NotificationLost =
false;
NotificationLost = param_NotificationLost;
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isCurrentStatePresent()
{
return currentState_present;
}
public bool isAlarmAcknowledgmentRulePresent()
{
return alarmAcknowledgmentRule_present;
}
public bool isActionResultPresent()
{
return actionResult_present;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "actionResult", IsSet = false)]
public class ActionResultSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(ActionResultSequenceType));
private ObjectName eventActionName_;
private SuccessOrFailureChoiceType successOrFailure_;
[ASN1Element(Name = "eventActionName", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public ObjectName EventActionName
{
get
{
return eventActionName_;
}
set
{
eventActionName_ = value;
}
}
[ASN1Element(Name = "successOrFailure", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public SuccessOrFailureChoiceType SuccessOrFailure
{
get
{
return successOrFailure_;
}
set
{
successOrFailure_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
[ASN1PreparedElement]
[ASN1Choice(Name = "successOrFailure")]
public class SuccessOrFailureChoiceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(SuccessOrFailureChoiceType));
private FailureSequenceType failure_;
private bool failure_selected;
private SuccessSequenceType success_;
private bool success_selected;
[ASN1Element(Name = "success", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public SuccessSequenceType Success
{
get
{
return success_;
}
set
{
selectSuccess(value);
}
}
[ASN1Element(Name = "failure", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public FailureSequenceType Failure
{
get
{
return failure_;
}
set
{
selectFailure(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isSuccessSelected()
{
return success_selected;
}
public void selectSuccess(SuccessSequenceType val)
{
success_ = val;
success_selected = true;
failure_selected = false;
}
public bool isFailureSelected()
{
return failure_selected;
}
public void selectFailure(FailureSequenceType val)
{
failure_ = val;
failure_selected = true;
success_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "failure", IsSet = false)]
public class FailureSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(FailureSequenceType));
private Unsigned32 modifierPosition_;
private bool modifierPosition_present;
private ServiceError serviceError_;
[ASN1Element(Name = "modifierPosition", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Unsigned32 ModifierPosition
{
get
{
return modifierPosition_;
}
set
{
modifierPosition_ = value;
modifierPosition_present = true;
}
}
[ASN1Element(Name = "serviceError", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public ServiceError ServiceError
{
get
{
return serviceError_;
}
set
{
serviceError_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isModifierPositionPresent()
{
return modifierPosition_present;
}
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "success", IsSet = false)]
public class SuccessSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(SuccessSequenceType));
private ConfirmedServiceResponse confirmedServiceResponse_;
private Response_Detail cs_Response_Detail_;
private bool cs_Response_Detail_present;
[ASN1Element(Name = "confirmedServiceResponse", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public ConfirmedServiceResponse ConfirmedServiceResponse
{
get
{
return confirmedServiceResponse_;
}
set
{
confirmedServiceResponse_ = value;
}
}
[ASN1Element(Name = "cs-Response-Detail", IsOptional = true, HasTag = true, Tag = 79, HasDefaultValue = false)]
public Response_Detail Cs_Response_Detail
{
get
{
return cs_Response_Detail_;
}
set
{
cs_Response_Detail_ = value;
cs_Response_Detail_present = true;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isCs_Response_DetailPresent()
{
return cs_Response_Detail_present;
}
}
}
}
}
}
| |
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc.">
// Copyright (C) Google 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.
// </copyright>
#if UNITY_ANDROID
namespace GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Google Play Game Services Setup dialog for Android.
/// </summary>
public class GPGSAndroidSetupUI : EditorWindow
{
/// <summary>
/// The configuration data from the play games console "resource data"
/// </summary>
private string mConfigData = string.Empty;
/// <summary>
/// The name of the class to generate containing the resource constants.
/// </summary>
private string mClassName = "GPGSIds";
/// <summary>
/// The scroll position
/// </summary>
private Vector2 scroll;
/// <summary>
/// The directory for the constants class.
/// </summary>
private string mConstantDirectory = "Assets";
/// <summary>
/// The web client identifier.
/// </summary>
private string mWebClientId = string.Empty;
/// <summary>
/// Menus the item for GPGS android setup.
/// </summary>
[MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)]
public static void MenuItemFileGPGSAndroidSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title);
window.minSize = new Vector2(500, 400);
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="clientId">The web client id.</param>
/// <param name="classDirectory">the directory to write the constants file to.</param>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">Indicates this app requires G+</param>
public static bool PerformSetup(
string clientId,
string classDirectory,
string className,
string resourceXmlData,
string nearbySvcId)
{
if (string.IsNullOrEmpty(resourceXmlData) &&
!string.IsNullOrEmpty(nearbySvcId))
{
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId);
}
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory);
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData);
// check the bundle id and set it if needed.
CheckBundleId();
Google.VersionHandler.VerboseLoggingEnabled = true;
Google.VersionHandler.UpdateVersionedAssets(forceUpdate: true);
Google.VersionHandler.Enabled = true;
AssetDatabase.Refresh();
GPGSDependencies.RegisterDependencies();
Google.VersionHandler.InvokeStaticMethod(
Google.VersionHandler.FindClass(
"Google.JarResolver",
"GooglePlayServices.PlayServicesResolver"),
"MenuResolve", null);
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId);
}
return false;
}
/// <summary>
/// Provide static access to setup for facilitating automated builds.
/// </summary>
/// <param name="webClientId">The oauth2 client id for the game. This is only
/// needed if the ID Token or access token are needed.</param>
/// <param name="appId">App identifier.</param>
/// <param name="nearbySvcId">Optional nearby connection serviceId</param>
/// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param>
/// <returns>true if successful</returns>
public static bool PerformSetup(string webClientId, string appId, string nearbySvcId)
{
if (!string.IsNullOrEmpty(webClientId))
{
if (!GPGSUtil.LooksLikeValidClientId(webClientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
string serverAppId = webClientId.Split('-')[0];
if (!serverAppId.Equals(appId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch);
return false;
}
}
// check for valid app id
if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdError);
return false;
}
if (nearbySvcId != null)
{
if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true))
{
return false;
}
}
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Save();
GPGSUtil.UpdateGameInfo();
// check that Android SDK is there
if (!GPGSUtil.HasAndroidSdk())
{
Debug.LogError("Android SDK not found.");
EditorUtility.DisplayDialog(
GPGSStrings.AndroidSetup.SdkNotFound,
GPGSStrings.AndroidSetup.SdkNotFoundBlurb,
GPGSStrings.Ok);
return false;
}
// Generate AndroidManifest.xml
GPGSUtil.GenerateAndroidManifest();
// refresh assets, and we're done
AssetDatabase.Refresh();
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
return true;
}
/// <summary>
/// Called when this object is enabled by Unity editor.
/// </summary>
public void OnEnable()
{
GPGSProjectSettings settings = GPGSProjectSettings.Instance;
mConstantDirectory = settings.Get(GPGSUtil.CLASSDIRECTORYKEY, mConstantDirectory);
mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY, mClassName);
mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY);
mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY);
}
/// <summary>
/// Called when the GUI should be rendered.
/// </summary>
public void OnGUI()
{
GUI.skin.label.wordWrap = true;
GUILayout.BeginVertical();
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(0f, 0f, 1f);
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.AndroidSetup.Blurb);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mConstantDirectory = EditorGUILayout.TextField(
"Directory to save constants",
mConstantDirectory,
GUILayout.Width(480));
mClassName = EditorGUILayout.TextField(
"Constants class name",
mClassName,
GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Android Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(
mConfigData,
GUILayout.Width(475),
GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb);
mWebClientId = EditorGUILayout.TextField(
GPGSStrings.Setup.ClientId,
mWebClientId,
GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100)))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
return;
}
}
catch (Exception e)
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button("Cancel", GUILayout.Width(100)))
{
Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Starts the setup process.
/// </summary>
public void DoSetup()
{
if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null))
{
CheckBundleId();
EditorUtility.DisplayDialog(
GPGSStrings.Success,
GPGSStrings.AndroidSetup.SetupComplete,
GPGSStrings.Ok);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
Close();
}
else
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid or missing XML resource data. Make sure the data is" +
" valid and contains the app_id element");
}
}
/// <summary>
/// Checks the bundle identifier.
/// </summary>
/// <remarks>
/// Check the package id. If one is set the gpgs properties,
/// and the player settings are the default or empty, set it.
/// if the player settings is not the default, then prompt before
/// overwriting.
/// </remarks>
public static void CheckBundleId()
{
string packageName = GPGSProjectSettings.Instance.Get(
GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty);
string currentId;
#if UNITY_5_6_OR_NEWER
currentId = PlayerSettings.GetApplicationIdentifier(
BuildTargetGroup.Android);
#else
currentId = PlayerSettings.bundleIdentifier;
#endif
if (!string.IsNullOrEmpty(packageName))
{
if (string.IsNullOrEmpty(currentId) ||
currentId == "com.Company.ProductName")
{
#if UNITY_5_6_OR_NEWER
PlayerSettings.SetApplicationIdentifier(
BuildTargetGroup.Android, packageName);
#else
PlayerSettings.bundleIdentifier = packageName;
#endif
}
else if (currentId != packageName)
{
if (EditorUtility.DisplayDialog(
"Set Bundle Identifier?",
"The server configuration is using " +
packageName + ", but the player settings is set to " +
currentId + ".\nSet the Bundle Identifier to " +
packageName + "?",
"OK",
"Cancel"))
{
#if UNITY_5_6_OR_NEWER
PlayerSettings.SetApplicationIdentifier(
BuildTargetGroup.Android, packageName);
#else
PlayerSettings.bundleIdentifier = packageName;
#endif
}
}
}
else
{
Debug.Log("NULL package!!");
}
}
/// <summary>
/// Parses the resources xml and set the properties. Also generates the
/// constants file.
/// </summary>
/// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="res">Res. the data to parse.</param>
private static bool ParseResources(string classDirectory, string className, string res)
{
XmlTextReader reader = new XmlTextReader(new StringReader(res));
bool inResource = false;
string lastProp = null;
Hashtable resourceKeys = new Hashtable();
string appId = null;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "string")
{
lastProp = reader.GetAttribute("name");
}
else if (inResource && !string.IsNullOrEmpty(lastProp))
{
if (reader.HasValue)
{
if (lastProp == "app_id")
{
appId = reader.Value;
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
}
else if (lastProp == "package_name")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value);
}
else
{
resourceKeys[lastProp] = reader.Value;
}
lastProp = null;
}
}
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
return appId != null;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 TestCUInt32()
{
var test = new BooleanBinaryOpTest__TestCUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestCUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt32> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestCUInt32 testClass)
{
var result = Sse41.TestC(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCUInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestCUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public BooleanBinaryOpTest__TestCUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.TestC(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.TestC(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.TestC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(pClsVar1)),
Sse2.LoadVector128((UInt32*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse41.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.TestC(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestCUInt32();
var result = Sse41.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestCUInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.TestC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.TestC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.TestC(
Sse2.LoadVector128((UInt32*)(&test._fld1)),
Sse2.LoadVector128((UInt32*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt32> op1, Vector128<UInt32> op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((~left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.TestC)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// These interfaces serve as an extension to the BCL's SymbolStore interfaces.
namespace Luma.SimpleEntity.Tools.Pdb.SymStore
{
// Interface does not need to be marked with the serializable attribute
using System;
using System.Diagnostics.SymbolStore;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
[
ComImport,
Guid("B4CE6286-2A6B-3712-A3B7-1EE1DAD467B5"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedReader
{
void GetDocument([MarshalAs(UnmanagedType.LPWStr)] String url,
Guid language,
Guid languageVendor,
Guid documentType,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocument retVal);
void GetDocuments(int cDocs,
out int pcDocs,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedDocument[] pDocs);
// These methods will often return error HRs in common cases.
// Using PreserveSig and manually handling error cases provides a big performance win.
// Far fewer exceptions will be thrown and caught.
// Exceptions should be reserved for truely "exceptional" cases.
[PreserveSig]
int GetUserEntryPoint(out SymbolToken EntryPoint);
[PreserveSig]
int GetMethod(SymbolToken methodToken,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedMethod retVal);
[PreserveSig]
int GetMethodByVersion(SymbolToken methodToken,
int version,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedMethod retVal);
void GetVariables(SymbolToken parent,
int cVars,
out int pcVars,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] ISymUnmanagedVariable[] vars);
void GetGlobalVariables(int cVars,
out int pcVars,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedVariable[] vars);
void GetMethodFromDocumentPosition(ISymUnmanagedDocument document,
int line,
int column,
[MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedMethod retVal);
void GetSymAttribute(SymbolToken parent,
[MarshalAs(UnmanagedType.LPWStr)] String name,
int sizeBuffer,
out int lengthBuffer,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)] byte[] buffer);
void GetNamespaces(int cNameSpaces,
out int pcNameSpaces,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedNamespace[] namespaces);
void Initialize(IntPtr importer,
[MarshalAs(UnmanagedType.LPWStr)] String filename,
[MarshalAs(UnmanagedType.LPWStr)] String searchPath,
IStream stream);
void UpdateSymbolStore([MarshalAs(UnmanagedType.LPWStr)] String filename,
IStream stream);
void ReplaceSymbolStore([MarshalAs(UnmanagedType.LPWStr)] String filename,
IStream stream);
void GetSymbolStoreFileName(int cchName,
out int pcchName,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder szName);
void GetMethodsFromDocumentPosition(ISymUnmanagedDocument document,
int line,
int column,
int cMethod,
out int pcMethod,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=3)] ISymUnmanagedMethod[] pRetVal);
void GetDocumentVersion(ISymUnmanagedDocument pDoc,
out int version,
out Boolean pbCurrent);
void GetMethodVersion(ISymUnmanagedMethod pMethod,
out int version);
};
[
ComImport,
Guid("E502D2DD-8671-4338-8F2A-FC08229628C4"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedEncUpdate
{
void UpdateSymbolStore2(IStream stream,
[MarshalAs(UnmanagedType.LPArray)] SymbolLineDelta[] iSymbolLineDeltas,
int cDeltaLines);
void GetLocalVariableCount(SymbolToken mdMethodToken,
out int pcLocals);
void GetLocalVariables(SymbolToken mdMethodToken,
int cLocals,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] ISymUnmanagedVariable[] rgLocals,
out int pceltFetched);
}
[
ComImport,
Guid("20D9645D-03CD-4e34-9C11-9848A5B084F1"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedReaderSymbolSearchInfo
{
void GetSymbolSearchInfoCount(out int pcSearchInfo);
void GetSymbolSearchInfo(int cSearchInfo,
out int pcSearchInfo,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ISymUnmanagedSymbolSearchInfo[] searchInfo);
}
[
ComImport,
Guid("969708D2-05E5-4861-A3B0-96E473CDF63F"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(false)
]
internal interface ISymUnmanagedDispose
{
void Destroy();
}
internal class SymReader : ISymbolReader, ISymbolReader2, ISymbolReaderSymbolSearchInfo, ISymbolEncUpdate, IDisposable
{
private ISymUnmanagedReader m_reader; // Unmanaged Reader pointer
internal SymReader(ISymUnmanagedReader reader)
{
// We should not wrap null instances
if (reader == null)
throw new ArgumentNullException("reader");
m_reader = reader;
}
public void Dispose()
{
GC.SuppressFinalize(this);
// If the underlying symbol reader supports an explicit dispose interface to release it's resources,
// then call it.
ISymUnmanagedDispose disposer = m_reader as ISymUnmanagedDispose;
if (disposer != null)
{
disposer.Destroy();
}
m_reader = null;
}
public ISymbolDocument GetDocument(String url,
Guid language,
Guid languageVendor,
Guid documentType)
{
ISymUnmanagedDocument document = null;
m_reader.GetDocument(url, language, languageVendor, documentType, out document);
if (document == null)
{
return null;
}
return new SymbolDocument(document);
}
public ISymbolDocument[] GetDocuments()
{
int cDocs = 0;
m_reader.GetDocuments(0, out cDocs, null);
ISymUnmanagedDocument[] unmanagedDocuments = new ISymUnmanagedDocument[cDocs];
m_reader.GetDocuments(cDocs, out cDocs, unmanagedDocuments);
ISymbolDocument[] documents = new SymbolDocument[cDocs];
uint i;
for (i = 0; i < cDocs; i++)
{
documents[i] = new SymbolDocument(unmanagedDocuments[i]);
}
return documents;
}
public SymbolToken UserEntryPoint
{
get
{
SymbolToken entryPoint;
int hr = m_reader.GetUserEntryPoint(out entryPoint);
if (hr == (int)HResult.E_FAIL)
{
// Not all assemblies have entry points
// dlls for example...
return new SymbolToken(0);
}
else
{
Marshal.ThrowExceptionForHR(hr);
}
return entryPoint;
}
}
public ISymbolMethod GetMethod(SymbolToken method)
{
ISymUnmanagedMethod unmanagedMethod = null;
int hr = m_reader.GetMethod(method, out unmanagedMethod);
if (hr == (int)HResult.E_FAIL)
{
// This means that the method has no symbol info because it's probably empty
// This can happen for virtual methods with no IL
return null;
}
else
{
Marshal.ThrowExceptionForHR(hr);
}
return new SymMethod(unmanagedMethod);
}
public ISymbolMethod GetMethod(SymbolToken method, int version)
{
ISymUnmanagedMethod unmanagedMethod = null;
int hr = m_reader.GetMethodByVersion(method, version, out unmanagedMethod);
if (hr == (int)HResult.E_FAIL)
{
// This means that the method has no symbol info because it's probably empty
// This can happen for virtual methods with no IL
return null;
}
else
{
Marshal.ThrowExceptionForHR(hr);
}
return new SymMethod(unmanagedMethod);
}
public ISymbolVariable[] GetVariables(SymbolToken parent)
{
int cVars = 0;
uint i;
m_reader.GetVariables(parent, 0, out cVars, null);
ISymUnmanagedVariable[] unmanagedVariables = new ISymUnmanagedVariable[cVars];
m_reader.GetVariables(parent, cVars, out cVars, unmanagedVariables);
SymVariable[] variables = new SymVariable[cVars];
for (i = 0; i < cVars; i++)
{
variables[i] = new SymVariable(unmanagedVariables[i]);
}
return variables;
}
public ISymbolVariable[] GetGlobalVariables()
{
int cVars = 0;
uint i;
m_reader.GetGlobalVariables(0, out cVars, null);
ISymUnmanagedVariable[] unmanagedVariables = new ISymUnmanagedVariable[cVars];
m_reader.GetGlobalVariables(cVars, out cVars, unmanagedVariables);
SymVariable[] variables = new SymVariable[cVars];
for (i = 0; i < cVars; i++)
{
variables[i] = new SymVariable(unmanagedVariables[i]);
}
return variables;
}
public ISymbolMethod GetMethodFromDocumentPosition(ISymbolDocument document,
int line,
int column)
{
ISymUnmanagedMethod unmanagedMethod = null;
m_reader.GetMethodFromDocumentPosition(((SymbolDocument)document).InternalDocument, line, column, out unmanagedMethod);
return new SymMethod(unmanagedMethod);
}
public byte[] GetSymAttribute(SymbolToken parent, String name)
{
byte[] Data;
int cData = 0;
m_reader.GetSymAttribute(parent, name, 0, out cData, null);
if (cData == 0)
{
// no such attribute (can't distinguish from empty attribute value)
return null;
}
Data = new byte[cData];
m_reader.GetSymAttribute(parent, name, cData, out cData, Data);
return Data;
}
public ISymbolNamespace[] GetNamespaces()
{
int count = 0;
uint i;
m_reader.GetNamespaces(0, out count, null);
ISymUnmanagedNamespace[] unmanagedNamespaces = new ISymUnmanagedNamespace[count];
m_reader.GetNamespaces(count, out count, unmanagedNamespaces);
ISymbolNamespace[] namespaces = new SymNamespace[count];
for (i = 0; i < count; i++)
{
namespaces[i] = new SymNamespace(unmanagedNamespaces[i]);
}
return namespaces;
}
public void Initialize(Object importer, String filename,
String searchPath, IStream stream)
{
IntPtr uImporter = IntPtr.Zero;
try {
uImporter = Marshal.GetIUnknownForObject(importer);
m_reader.Initialize(uImporter, filename, searchPath, stream);
} finally {
if (uImporter != IntPtr.Zero)
Marshal.Release(uImporter);
}
}
public void UpdateSymbolStore(String fileName, IStream stream)
{
m_reader.UpdateSymbolStore(fileName, stream);
}
public void ReplaceSymbolStore(String fileName, IStream stream)
{
m_reader.ReplaceSymbolStore(fileName, stream);
}
public String GetSymbolStoreFileName()
{
StringBuilder fileName;
int count = 0;
// there's a known issue in Diasymreader where we can't query the size of the pdb filename.
// So we'll just estimate large as a workaround.
// <strip>@todo - See VSWhidbey bug 321941.
//m_reader.GetSymbolStoreFileName(0, out count, null);
// </strip>
count = 300;
fileName = new StringBuilder(count);
m_reader.GetSymbolStoreFileName(count, out count, fileName);
return fileName.ToString();
}
public ISymbolMethod[] GetMethodsFromDocumentPosition(
ISymbolDocument document, int line, int column)
{
ISymUnmanagedMethod[] unmanagedMethods;
ISymbolMethod[] methods;
int count = 0;
uint i;
m_reader.GetMethodsFromDocumentPosition(((SymbolDocument)document).InternalDocument, line, column, 0, out count, null);
unmanagedMethods = new ISymUnmanagedMethod[count];
m_reader.GetMethodsFromDocumentPosition(((SymbolDocument)document).InternalDocument, line, column, count, out count, unmanagedMethods);
methods = new ISymbolMethod[count];
for (i = 0; i < count; i++)
{
methods[i] = new SymMethod(unmanagedMethods[i]);
}
return methods;
}
public int GetDocumentVersion(ISymbolDocument document,
out Boolean isCurrent)
{
int version = 0;
m_reader.GetDocumentVersion(((SymbolDocument)document).InternalDocument, out version, out isCurrent);
return version;
}
public int GetMethodVersion(ISymbolMethod method)
{
int version = 0;
m_reader.GetMethodVersion(((SymMethod)method).InternalMethod, out version);
return version;
}
public void UpdateSymbolStore(IStream stream,
SymbolLineDelta[] iSymbolLineDeltas)
{
((ISymUnmanagedEncUpdate)m_reader).UpdateSymbolStore2(stream, iSymbolLineDeltas, iSymbolLineDeltas.Length);
}
public int GetLocalVariableCount(SymbolToken mdMethodToken)
{
int count = 0;
((ISymUnmanagedEncUpdate)m_reader).GetLocalVariableCount(mdMethodToken, out count);
return count;
}
public ISymbolVariable[] GetLocalVariables(SymbolToken mdMethodToken)
{
int count = 0;
((ISymUnmanagedEncUpdate)m_reader).GetLocalVariables(mdMethodToken, 0, null, out count);
ISymUnmanagedVariable[] unmanagedVariables = new ISymUnmanagedVariable[count];
((ISymUnmanagedEncUpdate)m_reader).GetLocalVariables(mdMethodToken, count, unmanagedVariables, out count);
ISymbolVariable[] variables = new ISymbolVariable[count];
uint i;
for (i = 0; i < count; i++)
{
variables[i] = new SymVariable(unmanagedVariables[i]);
}
return variables;
}
public int GetSymbolSearchInfoCount()
{
int count = 0;
((ISymUnmanagedReaderSymbolSearchInfo)m_reader).GetSymbolSearchInfoCount(out count);
return count;
}
public ISymbolSearchInfo[] GetSymbolSearchInfo()
{
int count = 0;
((ISymUnmanagedReaderSymbolSearchInfo)m_reader).GetSymbolSearchInfo(0, out count, null);
ISymUnmanagedSymbolSearchInfo[] unmanagedSearchInfo = new ISymUnmanagedSymbolSearchInfo[count];
((ISymUnmanagedReaderSymbolSearchInfo)m_reader).GetSymbolSearchInfo(count, out count, unmanagedSearchInfo);
ISymbolSearchInfo[] searchInfo = new ISymbolSearchInfo[count];
uint i;
for (i = 0; i < count; i++)
{
searchInfo[i] = new SymSymbolSearchInfo(unmanagedSearchInfo[i]);
}
return searchInfo;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Net.Http.Headers
{
// The purpose of this type is to extract the handling of general headers in one place rather than duplicating
// functionality in both HttpRequestHeaders and HttpResponseHeaders.
internal sealed class HttpGeneralHeaders
{
private HttpHeaderValueCollection<string> _connection;
private HttpHeaderValueCollection<string> _trailer;
private HttpHeaderValueCollection<TransferCodingHeaderValue> _transferEncoding;
private HttpHeaderValueCollection<ProductHeaderValue> _upgrade;
private HttpHeaderValueCollection<ViaHeaderValue> _via;
private HttpHeaderValueCollection<WarningHeaderValue> _warning;
private HttpHeaderValueCollection<NameValueHeaderValue> _pragma;
private HttpHeaders _parent;
private bool _transferEncodingChunkedSet;
private bool _connectionCloseSet;
public CacheControlHeaderValue CacheControl
{
get { return (CacheControlHeaderValue)_parent.GetParsedValues(HttpKnownHeaderNames.CacheControl); }
set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.CacheControl, value); }
}
public HttpHeaderValueCollection<string> Connection
{
get { return ConnectionCore; }
}
public bool? ConnectionClose
{
get
{
if (ConnectionCore.IsSpecialValueSet)
{
return true;
}
if (_connectionCloseSet)
{
return false;
}
return null;
}
set
{
if (value == true)
{
_connectionCloseSet = true;
ConnectionCore.SetSpecialValue();
}
else
{
_connectionCloseSet = value != null;
ConnectionCore.RemoveSpecialValue();
}
}
}
public DateTimeOffset? Date
{
get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.Date, _parent); }
set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.Date, value); }
}
public HttpHeaderValueCollection<NameValueHeaderValue> Pragma
{
get
{
if (_pragma == null)
{
_pragma = new HttpHeaderValueCollection<NameValueHeaderValue>(HttpKnownHeaderNames.Pragma, _parent);
}
return _pragma;
}
}
public HttpHeaderValueCollection<string> Trailer
{
get
{
if (_trailer == null)
{
_trailer = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Trailer,
_parent, HeaderUtilities.TokenValidator);
}
return _trailer;
}
}
public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding
{
get { return TransferEncodingCore; }
}
public bool? TransferEncodingChunked
{
get
{
if (TransferEncodingCore.IsSpecialValueSet)
{
return true;
}
if (_transferEncodingChunkedSet)
{
return false;
}
return null;
}
set
{
if (value == true)
{
_transferEncodingChunkedSet = true;
TransferEncodingCore.SetSpecialValue();
}
else
{
_transferEncodingChunkedSet = value != null;
TransferEncodingCore.RemoveSpecialValue();
}
}
}
public HttpHeaderValueCollection<ProductHeaderValue> Upgrade
{
get
{
if (_upgrade == null)
{
_upgrade = new HttpHeaderValueCollection<ProductHeaderValue>(HttpKnownHeaderNames.Upgrade, _parent);
}
return _upgrade;
}
}
public HttpHeaderValueCollection<ViaHeaderValue> Via
{
get
{
if (_via == null)
{
_via = new HttpHeaderValueCollection<ViaHeaderValue>(HttpKnownHeaderNames.Via, _parent);
}
return _via;
}
}
public HttpHeaderValueCollection<WarningHeaderValue> Warning
{
get
{
if (_warning == null)
{
_warning = new HttpHeaderValueCollection<WarningHeaderValue>(HttpKnownHeaderNames.Warning, _parent);
}
return _warning;
}
}
private HttpHeaderValueCollection<string> ConnectionCore
{
get
{
if (_connection == null)
{
_connection = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Connection,
_parent, HeaderUtilities.ConnectionClose, HeaderUtilities.TokenValidator);
}
return _connection;
}
}
private HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncodingCore
{
get
{
if (_transferEncoding == null)
{
_transferEncoding = new HttpHeaderValueCollection<TransferCodingHeaderValue>(
HttpKnownHeaderNames.TransferEncoding, _parent, HeaderUtilities.TransferEncodingChunked);
}
return _transferEncoding;
}
}
internal HttpGeneralHeaders(HttpHeaders parent)
{
Contract.Requires(parent != null);
_parent = parent;
}
internal static void AddParsers(Dictionary<string, HttpHeaderParser> parserStore)
{
Contract.Requires(parserStore != null);
parserStore.Add(HttpKnownHeaderNames.CacheControl, CacheControlHeaderParser.Parser);
parserStore.Add(HttpKnownHeaderNames.Connection, GenericHeaderParser.TokenListParser);
parserStore.Add(HttpKnownHeaderNames.Date, DateHeaderParser.Parser);
parserStore.Add(HttpKnownHeaderNames.Pragma, GenericHeaderParser.MultipleValueNameValueParser);
parserStore.Add(HttpKnownHeaderNames.Trailer, GenericHeaderParser.TokenListParser);
parserStore.Add(HttpKnownHeaderNames.TransferEncoding, TransferCodingHeaderParser.MultipleValueParser);
parserStore.Add(HttpKnownHeaderNames.Upgrade, GenericHeaderParser.MultipleValueProductParser);
parserStore.Add(HttpKnownHeaderNames.Via, GenericHeaderParser.MultipleValueViaParser);
parserStore.Add(HttpKnownHeaderNames.Warning, GenericHeaderParser.MultipleValueWarningParser);
}
internal static void AddKnownHeaders(HashSet<string> headerSet)
{
Contract.Requires(headerSet != null);
headerSet.Add(HttpKnownHeaderNames.CacheControl);
headerSet.Add(HttpKnownHeaderNames.Connection);
headerSet.Add(HttpKnownHeaderNames.Date);
headerSet.Add(HttpKnownHeaderNames.Pragma);
headerSet.Add(HttpKnownHeaderNames.Trailer);
headerSet.Add(HttpKnownHeaderNames.TransferEncoding);
headerSet.Add(HttpKnownHeaderNames.Upgrade);
headerSet.Add(HttpKnownHeaderNames.Via);
headerSet.Add(HttpKnownHeaderNames.Warning);
}
internal void AddSpecialsFrom(HttpGeneralHeaders sourceHeaders)
{
// Copy special values, but do not overwrite
bool? chunked = TransferEncodingChunked;
if (!chunked.HasValue)
{
TransferEncodingChunked = sourceHeaders.TransferEncodingChunked;
}
bool? close = ConnectionClose;
if (!close.HasValue)
{
ConnectionClose = sourceHeaders.ConnectionClose;
}
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: logicmoo@gmail.com
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
using org.jpl7;
#if USE_IKVM
using IKVM.Internal;
using ikvm.runtime;
using java.net;
//using org.jpl7;
#endif
#if USE_IKVM
using Hashtable = java.util.Hashtable;
using ClassLoader = java.lang.ClassLoader;
using Class = java.lang.Class;
using sun.reflect.misc;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using SbsSW.SwiPlCs;
using SbsSW.SwiPlCs.Callback;
using PlTerm = SbsSW.SwiPlCs.PlTerm;
namespace Swicli.Library
{
public partial class PrologCLR
{
static public void load_swiplcs()
{
}
private static readonly object PrologIsSetupLock = new object();
private static bool PrologIsSetup;
public static void SetupProlog()
{
lock (PrologIsSetupLock)
{
if (PrologIsSetup) return;
Embedded.ConsoleWriteLine(typeof(PrologCLR).Name + ".AssemblyResolve starting");
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
PrologIsSetup = true;
SafelyRun(SetupProlog0);
SafelyRun(SetupProlog2);
RegisterPLCSForeigns();
}
}
public static void SetupProlog0()
{
Embedded.Debug("SetupProlog");
// SafelyRun(SetupIKVM);
if (!IsUseableSwiProlog(SwiHomeDir))
{
try
{
//SwiHomeDir = System.Windows.Forms.Application.StartupPath;
SwiHomeDir = Path.GetDirectoryName(Environment.CurrentDirectory);
// CommandLine.Trim(' ', '"', '\''));
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = null;
}
}
catch (Exception)
{
}
}
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = Environment.GetEnvironmentVariable("SWI_HOME_DIR");
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = null;
}
}
string pf = GetProgramFilesDir();
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = pf + "/pl";
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = pf + "/swipl";
}
}
AltSwiHomeDir = AltSwiHomeDir ?? ".";
bool copyPlatFormVersions = false;
if (!IsUseableSwiProlog(SwiHomeDir))
{
SwiHomeDir = AltSwiHomeDir;
copyPlatFormVersions = true;
if (true)
{
//for now never copy!
copyPlatFormVersions = false;
}
}
SwiHomeDir = SwiHomeDir ?? AltSwiHomeDir;
if (IsUseableSwiProlog(SwiHomeDir))
{
Environment.SetEnvironmentVariable("SWI_HOME_DIR", SwiHomeDir);
}
if (!ConfirmRCFile(SwiHomeDir)) ConsoleTrace("RC file missing from " + SwiHomeDir);
string platformSuffix = Embedded.Is64BitRuntime() ? "-x64" : "-x86";
if (copyPlatFormVersions)
{
string destination = Path.Combine(SwiHomeDir, "bin");
CopyFiles(destination + platformSuffix, destination, true, "*.*", true);
destination = Path.Combine(SwiHomeDir, "lib");
CopyFiles(destination + platformSuffix, destination, true, "*.*", true);
}
if (IsUseableSwiProlog(SwiHomeDir))
{
Environment.SetEnvironmentVariable("SWI_HOME_DIR", SwiHomeDir);
}
SafelyRun(SetupProlog1);
}
private static string GetProgramFilesDir()
{
if (Embedded.Is64BitComputer())
{
if (!Embedded.Is64BitRuntime())
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
private static string GetMyPathExtras()
{
if (libpath != null) return libpath;
string swiHomeBin = Path.Combine(SwiHomeDir, "bin");
libpath += swiHomeBin;
if (swiHomeBin != IKVMHome && !String.IsNullOrEmpty(IKVMHome))
{
libpath += Path.PathSeparator;
libpath += IKVMHome;
}
libpath += Path.PathSeparator;
libpath += ".";
return libpath;
}
/// <summary>
/// This after the SwiPrologDir and IKVMHome is set up will update the environment
/// </summary>
public static void SetupProlog1()
{
string myPathExt = GetMyPathExtras();
String path = Environment.GetEnvironmentVariable("PATH");
if (path != null)
{
if (!path.ToLower().StartsWith(myPathExt.ToLower()))
{
path = myPathExt + path;
Environment.SetEnvironmentVariable("PATH", path);
}
}
string LD_LIBRARY_PATH = Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");
if (String.IsNullOrEmpty(LD_LIBRARY_PATH))
{
LD_LIBRARY_PATH = libpath;
Environment.SetEnvironmentVariable("LD_LIBRARY_PATH", LD_LIBRARY_PATH);
}
else if (!LD_LIBRARY_PATH.ToLower().Contains(myPathExt.ToLower()))
{
LD_LIBRARY_PATH = myPathExt + LD_LIBRARY_PATH;
Environment.SetEnvironmentVariable("LD_LIBRARY_PATH", LD_LIBRARY_PATH);
}
// SafelyRun(SetupProlog1);
// SafelyRun(SetupProlog2);
}
/*
#if USE_IKVM
public static void SetupProlog1()
{
PrologCLR.ConsoleTrace("geting lib path");
CLASSPATH = java.lang.System.getProperty("java.class.path");
ConsoleTrace("GOT lib path");
string CLASSPATH0 = Environment.GetEnvironmentVariable("CLASSPATH");
if (String.IsNullOrEmpty(CLASSPATH))
{
CLASSPATH = CLASSPATH0;
}
string jplcp = clasPathOf(new org.jpl7.JPL());
if (!JplDisabled)
CLASSPATH = IKVMHome + "/SWIJPL.dll" + ";" + IKVMHome + "/SWIJPL.jar;" + CLASSPATH0;
ConsoleWriteLine("CLASSPATH=" + CLASSPATH);
if (CLASSPATH != null)
{
Environment.SetEnvironmentVariable("CLASSPATH", CLASSPATH);
java.lang.System.setProperty("java.class.path", CLASSPATH);
}
java.lang.System.setProperty("java.library.path", libpath);
}
#endif*/
static string libpath = null;
public static void SetupProlog2()
{
try
{
#if USE_IKVM
/*
if (!JplDisabled)
{
JPL.setNativeLibraryDir(SwiHomeDir + "/bin");
try
{
JPL.loadNativeLibrary();
}
catch (Exception e)
{
WriteException(e);
JplDisabled = true;
}
if (!JplDisabled)
{
SafelyRun(() => org.jpl7.fli.Prolog.initialise());
}
}
SafelyRun(TestClassLoader);
*/
#endif
//if (Embedded.IsPLWin) return;
try
{
if (!PlEngine.IsInitialized)
{
String[] param = { "-q" }; // suppressing informational and banner messages
PlEngine.Initialize(param);
}
if (Embedded.IsPLWin) return;
if (!PlEngine.IsStreamFunctionReadModified) PlEngine.SetStreamReader(Sread);
if (PlEngine.IsStreamFunctionWriteModified)
{
PlQuery.PlCall("nl.");
}
}
catch (Exception e)
{
Embedded.WriteException(e);
Embedded.PlCsDisabled = true;
}
// PlAssert("org.jpl7:jvm_ready");
// PlAssert("module_transparent(jvm_ready)");
}
catch (Exception exception)
{
Embedded.WriteException(exception);
return;
}
}
private static bool IsUseableSwiProlog(string swiHomeDir)
{
if (String.IsNullOrEmpty(swiHomeDir)) return false;
if (!Directory.Exists(swiHomeDir)) return false;
string swibin = Path.Combine(swiHomeDir, "bin");
String oldFile = Path.Combine(swibin, "libpl.dll");
if (File.Exists(oldFile))
{
ConsoleTrace("SWI too old: " + oldFile);
return false;
}
if (!ConfirmRCFile(swiHomeDir)) return false;
if (File.Exists(Path.Combine(swibin, "libswipl.dll"))) return true;
if (File.Exists(Path.Combine(swibin, "swipl.dll"))) return true;
return true;
}
private static bool ConfirmRCFile(string swiHomeDir)
{
if (!Embedded.Is64BitRuntime())
{
return File.Exists(Path.Combine(swiHomeDir, "boot32.prc")) ||
File.Exists(Path.Combine(swiHomeDir, "boot.prc"));
}
return File.Exists(Path.Combine(swiHomeDir, "boot64.prc"));
}
//FileInfo & DirectoryInfo are in System.IO
//This is something you should be able to tweak to your specific needs.
static void CopyFiles(string source,
string destination,
bool overwrite,
string searchPattern, bool recurse)
{
if (Directory.Exists(source))
CopyFiles(new DirectoryInfo(source), new DirectoryInfo(destination), overwrite, searchPattern, recurse);
}
static void CopyFiles(DirectoryInfo source,
DirectoryInfo destination,
bool overwrite,
string searchPattern, bool recurse)
{
FileInfo[] files = source.GetFiles(searchPattern);
if (!destination.Exists)
{
destination.Create();
}
foreach (FileInfo file in files)
{
string destName = Path.Combine(destination.FullName, file.Name);
try
{
file.CopyTo(destName, overwrite);
}
catch (Exception e0)
{
if (!overwrite)
{
Embedded.ConsoleWriteLine("file: " + file + " copy to " + destName + " " + e0);
}
else
{
try
{
if (File.Exists(destName))
{
if (File.Exists(destName + ".dead")) File.Delete(destName + ".dead");
File.Move(destName, destName + ".dead");
file.CopyTo(destName, false);
}
}
catch (Exception e)
{
Embedded.ConsoleWriteLine("file: " + file + " copy to " + destName + " " + e);
}
}
}
}
if (recurse)
{
foreach (var info in source.GetDirectories())
{
string destName = Path.Combine(destination.FullName, info.Name);
try
{
if (!Directory.Exists(destName)) Directory.CreateDirectory(destName);
CopyFiles(info, new DirectoryInfo(destName), overwrite, searchPattern, recurse);
}
catch (Exception e)
{
Embedded.ConsoleWriteLine("file: " + info + " copy to " + destName + " " + e);
}
}
}
}
//[MTAThread]
public static void Main(string[] args0)
{
while (false)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Maximized;
startInfo.FileName = @"c:\pf\swipl\bin\swipl-win.exe";
startInfo.Arguments = "winapi_dll.pl";
startInfo.WorkingDirectory = @"C:\Users\Administrator\AppData\Roaming\SWI-Prolog\pack\swicli\cffi-tests";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
PingThreadFactories();
bool demo = false;
SetupProlog();
libpl.PL_initialise(args0.Length, args0);
//Main12(args0);
libpl.PL_toplevel();
}
//[MTAThread]
public static void Main_Was(string[] args0)
{
PingThreadFactories();
bool demo = false;
SetupProlog();
if (demo)
{
DoQuery("asserta(fff(1))");
DoQuery("asserta(fff(9))");
DoQuery("nl");
DoQuery("flush");
PlAssert("father(martin, inka)");
if (!Embedded.PlCsDisabled)
{
PlQuery.PlCall("assert(father(uwe, gloria))");
PlQuery.PlCall("assert(father(uwe, melanie))");
PlQuery.PlCall("assert(father(uwe, ayala))");
using (PlQuery q = new PlQuery("father(P, C), atomic_list_concat([P,' is_father_of ',C], L)"))
{
foreach (PlTermV v in q.Solutions)
ConsoleTrace(ToCSString(v));
foreach (PlQueryVariables v in q.SolutionVariables)
ConsoleTrace(v["L"].ToString());
ConsoleTrace("all child's from uwe:");
q.Variables["P"].Unify("uwe");
foreach (PlQueryVariables v in q.SolutionVariables)
ConsoleTrace(v["C"].ToString());
}
//PlQuery.PlCall("ensure_loaded(library(thread_util))");
//Warning: [Thread 2] Thread running "thread_run_interactor" died on exception: thread_util:attach_console/0: Undefined procedure: thread_util:win_open_console/5
//PlQuery.PlCall("interactor");
//Delegate Foo0 = foo0;
RegisterPLCSForeigns();
}
PlAssert("tc2:-foo2(X,Y),writeq(f(X,Y)),nl,X=5");
PlAssert("tc3:-foo3(X,Y,Z),Z,writeln(f(X,Y,Z)),X=5");
}
#if USE_IKVM
// ClassFile.ThrowFormatErrors = false;
libpl.NoToString = true;
//SafelyRun((() => PlCall("jpl0")));
//SafelyRun((() => DoQuery(new Query(new org.jpl7.Atom("jpl0")))));
libpl.NoToString = false;
// ClassFile.ThrowFormatErrors = true;
#endif
if (args0.Length > 0)
{
int i = 0;
foreach (var s in args0)
{
if (s == "-f")
{
string s1 = args0[i + 1];
args0[i + 1] = "['" + s1 + "']";
continue;
}
PlCall(s);
i++;
}
}
if (!Embedded.JplDisabled)
{
#if USE_IKVM
var run = new org.jpl7.Atom("prolog");
while (!Embedded.IsHalted) SafelyRun(() => DoQuery(new org.jpl7.Query(run)));
#endif
}
else
{
if (!Embedded.PlCsDisabled)
// loops on exception
while (!SafelyRun(() => libpl.PL_toplevel())) ;
}
ConsoleTrace("press enter to exit");
Console.ReadLine();
SafelyRun(() => PlEngine.PlCleanup());
ConsoleTrace("finshed!");
}
private static bool SafelyRun(Action invoker)
{
try
{
invoker();
return true;
}
catch (Exception e)
{
Embedded.WriteException(e);
return false;
}
}
public static void RegisterPLCSForeigns()
{
CreatorThread = Thread.CurrentThread;
RegisterMainThread();
ShortNameType = new Dictionary<string, Type>();
ShortNameType["string"] = typeof(String);
ShortNameType["object"] = typeof(Object);
ShortNameType["sbyte"] = typeof(sbyte);
// libpl.PL_agc_hook(new AtomGCHook(Tracker_FreeAtom));
//ShortNameType = new PrologBackedDictionary<string, Type>(null, "shortTypeName");
//PlEngine.RegisterForeign(null, "cliFindClass", 2, new DelegateParameter2(PrologCli.cliFindClass), PlForeignSwitches.None);
PlEngine.RegisterForeign(Embedded.ExportModule, "cli_load_assembly", 1, new DelegateParameter1(cliLoadAssembly), PlForeignSwitches.None);
if (Embedded.VerboseStartup) Embedded.ConsoleWriteLine("RegisterPLCSForeigns");
InternMethod(null, "cwl", typeof(Console).GetMethod("WriteLine", ONE_STRING));
Type t = typeof(PrologCLR);
InternMethod(Embedded.ExportModule, "cli_load_assembly_methods", t.GetMethod("cliLoadAssemblyMethods"));
InternMethod(t.GetMethod("cliAddAssemblySearchPath"), "cli_");
InternMethod(t.GetMethod("cliRemoveAssemblySearchPath"), "cli_");
AddForeignMethods(t, false, "cli_");
RegisterJPLForeigns();
if (Embedded.VerboseStartup) Embedded.ConsoleWriteLine("done RegisterPLCSForeigns");
}
private static void RegisterJPLForeigns()
{
// backup old org.jpl7.pl and copy over it
if (!Embedded.JplDisabled)
SafelyRun(() =>
{
if (File.Exists(IKVMHome + "/jpl_for_ikvm.phps"))
{
if (!File.Exists(SwiHomeDir + "/library/org.jpl7.pl.old"))
{
File.Copy(SwiHomeDir + "/library/org.jpl7.pl",
SwiHomeDir + "/library/org.jpl7.pl.old",
true);
}
File.Copy(IKVMHome + "/jpl_for_ikvm.phps", SwiHomeDir + "/library/org.jpl7.pl", true);
}
});
PlEngine.RegisterForeign("swicli", "link_swiplcs", 1, new DelegateParameter1(link_swiplcs),
PlForeignSwitches.None);
//JplSafeNativeMethods.install();
Embedded.JplSafeNativeMethodsCalled = true;
//DoQuery(new Query("ensure_loaded(library(org.jpl7))."));
/*
jpl_jlist_demo :-
jpl_new( 'javax.swing.JFrame', ['modules'], F),
jpl_new( 'javax.swing.DefaultListModel', [], DLM),
jpl_new( 'javax.swing.JList', [DLM], L),
jpl_call( F, getContentPane, [], CP),
jpl_call( CP, add, [L], _),
( current_module( M),
jpl_call( DLM, addElement, [M], _),
fail
; true
),
jpl_call( F, pack, [], _),
jpl_call( F, getHeight, [], H),
jpl_call( F, setSize, [150,H], _),
jpl_call( F, setVisible, [@(true)], _).
% this directive runs the above demo
:- jpl_jlist_demo.
*/
return; //we dont need to really do this
PlCall("use_module(library(org.jpl7)).");
PlAssert("jpl0 :- jpl_new( 'java.lang.String', ['hi'], DLM),writeln(DLM)");
PlAssert("jpl1 :- jpl_new( 'javax.swing.DefaultListModel', [], DLM),writeln(DLM)");
}
private static bool link_swiplcs(PlTerm pathName)
{
try
{
return true;
if (Embedded.JplSafeNativeMethodsCalled)
{
bool enabled = !Embedded.JplSafeNativeMethodsDisabled;
SafelyRun(
() => ConsoleTrace("JplSafeNativeMethods called again from " + pathName + " result=" + enabled));
return enabled;
}
Embedded.JplSafeNativeMethodsCalled = true;
SafelyRun(() => ConsoleTrace("JplSafeNativeMethods call first time from " + pathName));
JplSafeNativeMethods.install();
//var v = new PlTerm("_1");
//JplSafeNativeMethods.jpl_c_lib_version_1_plc(v.TermRef);
return true;
}
catch (Exception e)
{
Embedded.JplSafeNativeMethodsDisabled = true;
Embedded.WriteException(e);
return false;
}
}
private static void FooMethod(String print)
{
//DoQuery(new Query("asserta(org.jpl7:jvm_ready)."));
//DoQuery(new Query("asserta(org.jpl7:jpl_c_lib_version(3-3-3-3))."));
//DoQuery(new Query("module(org.jpl7)."));
//JplSafeNativeMethods.install();
//DoQuery("ensure_loaded(library(org.jpl7)).");
//DoQuery("module(user).");
//DoQuery(new Query("load_foreign_library(foreign(org.jpl7))."));
// DoQuery(new Query(new org.jpl7.Compound("member", new Term[] { new org.jpl7.Integer(1), new org.jpl7.Variable("H") })));
//DoQuery(new Query(new org.jpl7.Atom("interactor")));
//DoQuery(new Query(new org.jpl7.Compound("writeq", new Term[] { new org.jpl7.Integer(1) })));
ConsoleTrace(print);
}
static internal long Sread(IntPtr handle, IntPtr buffer, long buffersize)
{
int i = Console.Read();
if (i == -1) return 0;
string s = "" + (char)i;
byte[] array = Encoding.Unicode.GetBytes(s);
Marshal.Copy(array, 0, buffer, array.Length);
return array.Length;
}
private static string _ikvmHome = ".";
public static string IKVMHome
{
get { return _ikvmHome; }
set { _ikvmHome = RemoveTrailingPathSeps(value); }
}
private static string _swiHomeDir;// = Path.Combine(".", "swiprolog");
public static string SwiHomeDir
{
get
{
if (_swiHomeDir == null)
{
_swiHomeDir = Environment.GetEnvironmentVariable("SWI_HOME_DIR");
}
return _swiHomeDir;
}
set
{
_swiHomeDir = RemoveTrailingPathSeps(value); ;
}
}
private static string RemoveTrailingPathSeps(string value)
{
if (value != null)
{
value = value.TrimEnd("\\/".ToCharArray()).Replace("\\", "/");
}
return value;
}
public static string AltSwiHomeDir = ".";//C:/development/opensim4opencog";// Path.Combine(".", "swiprolog");
private static Int64 TopOHandle = 6660000;
private static readonly Dictionary<string, object> SavedDelegates = new Dictionary<string, object>();
public static Thread CreatorThread;
public void InitFromUser()
{
ConsultIfExists("prolog/cogbot.pl");
}
}
}
| |
// BrickBreakerEditorControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Chapter24;
namespace BrickBreakerLevelEditor
{
public partial class EditorControl : UserControl
{
// default constructor
public EditorControl()
{
InitializeComponent();
// init the main HitsToClear menu icon with the icon
// of the default HitsToClear selection
mnuNumHits.Image = toolStripMenuItem4.Image;
}
// the level data that we're currently editing
protected LevelData m_LevelData = new LevelData();
public LevelData LevelData
{
get { return m_LevelData; }
set
{
m_LevelData = value;
// the level changed, redraw our edit window
this.Invalidate();
}
}
// the HitsToClear value to be used with new bricks
protected int m_NumHitsToClear = 1;
public int NumHitsToClear
{
get { return m_NumHitsToClear; }
set { m_NumHitsToClear = value; }
}
// enable and disable the grid snap feature
protected bool m_DrawGrid = true;
public bool DrawGrid
{
get { return m_DrawGrid; }
set { m_DrawGrid = value; this.Invalidate(); }
}
// used when no level is actively being edited
protected Font m_font = new Font(FontFamily.GenericSansSerif, 12.0f);
protected const string
MSG_NO_LEVEL = "[No data. Select a level to edit.]";
// bounds of the game screen, and the playable area
protected Rectangle m_ScreenRect = new Rectangle(0, 0, 640, 480);
protected Rectangle m_GameRect = new Rectangle(40, 40, 400, 400);
// update our editor window
private void BrickBreakerEditorControl_Paint(
object sender, PaintEventArgs e)
{
// local temp variable to save some typing
Graphics g = e.Graphics;
// if there is no level selected, draw a generic message
if (LevelData == null)
{
SizeF dimensions = g.MeasureString(MSG_NO_LEVEL, m_font);
PointF loc = new PointF(
this.Width / 2.0f - dimensions.Width / 2.0f,
this.Height / 2.0f - dimensions.Height / 2.0f);
g.DrawString(
MSG_NO_LEVEL,
m_font,
SystemBrushes.ControlText,
loc);
}
// looks like we have a level to edit, render its current state
else
{
DrawLevelBorder(g);
DrawLevelGrid(g);
DrawLevelData(g, LevelData);
DrawGhostBrick(g, LevelData);
}
}
// fill in the screen and playable areas
protected void DrawLevelBorder(Graphics g)
{
g.FillRectangle(SystemBrushes.ControlDark, m_ScreenRect);
g.FillRectangle(Brushes.White, m_GameRect);
}
// draw the grid, if enabled
protected void DrawLevelGrid(Graphics g)
{
// is the grid enabled?
if (DrawGrid)
{
// calc change in y from grid cell to grid cell, draw lines
int dy = LevelData.BrickHeight / 2;
for (int y = m_GameRect.Top; y <= m_GameRect.Bottom; y += dy)
{
g.DrawLine(
Pens.Black,
m_GameRect.Left,
y,
m_GameRect.Right,
y);
}
// calc change in x from grid cell to grid cell, draw lines
int dx = LevelData.BrickWidth / 2;
for (int x = m_GameRect.Left; x <= m_GameRect.Right; x += dx)
{
g.DrawLine(
Pens.Black,
x,
m_GameRect.Top,
x,
m_GameRect.Bottom);
}
}
}
// create brushes for each of our brick colors
protected SolidBrush[] m_BrickBrushes =
{
new SolidBrush(Color.FromArgb(255,128,128)), // 1 hit
new SolidBrush(Color.FromArgb(128,255,128)), // 2 hits
new SolidBrush(Color.FromArgb(128,128,255)), // 3 hits
new SolidBrush(Color.FromArgb(255,128,255)), // 4 hits
new SolidBrush(Color.FromArgb(255,255,128)), // 5 hits
new SolidBrush(Color.FromArgb(255,194,129)), // 6 hits
new SolidBrush(Color.FromArgb(192,192,192)), // 7 hits
new SolidBrush(Color.FromArgb(255,192,192)), // 8 hits
new SolidBrush(Color.FromArgb(192,255,255)), // 9 hits
};
// draw the bricks
protected void DrawLevelData(Graphics g, LevelData level)
{
foreach (Brick b in level.Bricks)
{
g.FillRectangle( // fill brick
m_BrickBrushes[b.HitsToClear - 1],
m_GameRect.Left + b.X,
m_GameRect.Top + b.Y,
level.BrickWidth,
level.BrickHeight);
g.DrawRectangle( // outline brick
Pens.Black,
m_GameRect.Left + b.X,
m_GameRect.Top + b.Y,
level.BrickWidth,
level.BrickHeight);
}
}
// position of new brick, based on grid settings
protected int m_NewBrickX = -1;
protected int m_NewBrickY = -1;
// calc position of new brick, based on grid settings
// called whenever the mouse moves, while over our editor control
protected void CalcNewBrickXY(Point location)
{
// make sure mouse is within the playable area and
// that it's not over an existing brick
if (m_GameRect.Contains(location) && m_ClickedBrick == null)
{
// determine raw top, left for brick
m_NewBrickX = location.X - m_GameRect.Left;
m_NewBrickY = location.Y - m_GameRect.Top;
// snap to grid?
if (DrawGrid)
{
// snap to nearest grid cell's top, left
m_NewBrickX =
(m_NewBrickX / LevelData.HalfWidth) *
LevelData.HalfWidth;
m_NewBrickY =
(m_NewBrickY / LevelData.HalfHeight) *
LevelData.HalfHeight;
}
// mske sure that the new brick won't extend
// outside of the playable area
m_NewBrickX =
Math.Min(
m_NewBrickX,
m_GameRect.Width - LevelData.BrickWidth);
m_NewBrickY =
Math.Min(
m_NewBrickY,
m_GameRect.Height - LevelData.BrickHeight);
// since the intended location may have changed (due to
// grid snap or enforcement of playable bounds), make
// sure that the new brick isn't about to sit on top of
// an existing brick
bool collide =
LevelData.FindBrick(m_NewBrickX, m_NewBrickY) != null;
collide |=
LevelData.FindBrick(
m_NewBrickX + LevelData.BrickWidth - 1,
m_NewBrickY) != null;
collide |=
LevelData.FindBrick(
m_NewBrickX,
m_NewBrickY + LevelData.BrickHeight - 1) != null;
collide |=
LevelData.FindBrick(
m_NewBrickX + LevelData.BrickWidth - 1,
m_NewBrickY + LevelData.BrickHeight - 1) != null;
// did we collide with another brick?
if (collide)
{
// disallow placement of new brick
m_NewBrickX = -1;
m_NewBrickY = -1;
}
// redraw the editor so that we can see the ghosted brick
this.Invalidate();
}
// mouse is not within the playable area
else
{
// avoid repainting when the mouse moves outside of the
// playable area or moves within an existing brick;
// we have to redraw when it first moves into one of these
// forbidden positions to get rid of the ghosted brick
if (m_NewBrickX != -1 || m_NewBrickY != -1)
{
m_NewBrickX = -1;
m_NewBrickY = -1;
this.Invalidate();
}
}
}
// need to repaint when the mouse moves so that we
// can draw the ghosted brick
private void BrickBreakerEditorControl_MouseMove(
object sender, MouseEventArgs e)
{
// if we're actually editing a level
if (LevelData != null)
{
// see if mouse is over an existing brick
// brick data is zero-based, so we subtract the top, left
// of the playable area to translate to a 0,0 origin
m_ClickedBrick =
LevelData.FindBrick(
e.X - m_GameRect.Left,
e.Y - m_GameRect.Top);
// apply grid settings and bounds checking
CalcNewBrickXY(e.Location);
}
}
// reference to selected brick for context menu (right-click popup)
// and by logic to deny placement over existing bricks
protected Brick m_ClickedBrick = null;
// process mouse clicks
private void BrickBreakerEditorControl_MouseUp(
object sender, MouseEventArgs e)
{
// if we're actually editing a level
if (LevelData != null)
{
// right-clicked an existing brick, show popup menu
if (m_ClickedBrick != null && e.Button == MouseButtons.Right)
{
// get HitsToClear for the selected brick
string hits = m_ClickedBrick.HitsToClear.ToString();
// find the corresponding menu item and set the
// top-level HitsToClear menu's icon to the selected
// child menu item's icon
foreach (
ToolStripMenuItem item in mnuNumHits.DropDownItems)
{
if (item.Tag.ToString() == hits)
{
mnuNumHits.Image = item.Image;
break;
}
}
// we're ready, show the popup menu
this.contextMenuStrip1.Show(MousePosition);
}
// left-clicked empty space; try to add a new brick; redraw
if (m_ClickedBrick == null && e.Button == MouseButtons.Left)
{
LevelData.AddBrick(
m_NewBrickX,
m_NewBrickY,
NumHitsToClear);
this.Invalidate();
}
}
}
// create brush for our ghosted brick
protected Brush m_GhostBrush =
new HatchBrush(
HatchStyle.Percent30,
SystemColors.Window,
SystemColors.ControlText);
// draw "ghosted" brick where the new brick would be located
protected void DrawGhostBrick(Graphics g, LevelData level)
{
if (m_NewBrickX >= 0 && m_NewBrickY >= 0)
{
g.FillRectangle( // fill brick
m_GhostBrush,
m_GameRect.Left + m_NewBrickX,
m_GameRect.Top + m_NewBrickY,
level.BrickWidth,
level.BrickHeight);
g.DrawRectangle( // outline brick
Pens.Black,
m_GameRect.Left + m_NewBrickX,
m_GameRect.Top + m_NewBrickY,
level.BrickWidth,
level.BrickHeight);
}
}
// user requested that we remove the selected brick
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
LevelData.DeleteBrick(m_ClickedBrick);
this.Invalidate();
}
// user changed the HitsToClear value for the selected brick
private void toolStripMenuItem_Click(object sender, EventArgs e)
{
// has a brick been selected?
if (m_ClickedBrick != null)
{
// update brick's HitsToClear with the menu item's value
ToolStripMenuItem item = (ToolStripMenuItem)sender;
m_ClickedBrick.HitsToClear = int.Parse(item.Tag.ToString());
this.Invalidate();
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.GridView.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public partial class GridView : CompositeDataBoundControl, IPostBackContainer, System.Web.UI.IPostBackEventHandler, ICallbackContainer, System.Web.UI.ICallbackEventHandler, IPersistedSelector
#if NETFRAMEWORK_4_0
, IDataBoundControl
, IDataBoundListControl
, System.Web.UI.IDataKeysControl
, IFieldControl
#endif
{
#region Methods and constructors
protected virtual new AutoGeneratedField CreateAutoGeneratedColumn (AutoGeneratedFieldProperties fieldProperties)
{
Contract.Requires (fieldProperties != null);
return default(AutoGeneratedField);
}
protected override int CreateChildControls (System.Collections.IEnumerable dataSource, bool dataBinding)
{
return default(int);
}
protected virtual new Table CreateChildTable ()
{
return default(Table);
}
protected virtual new System.Collections.ICollection CreateColumns (PagedDataSource dataSource, bool useDataSource)
{
return default(System.Collections.ICollection);
}
protected override Style CreateControlStyle ()
{
return default(Style);
}
protected override System.Web.UI.DataSourceSelectArguments CreateDataSourceSelectArguments ()
{
return default(System.Web.UI.DataSourceSelectArguments);
}
protected virtual new GridViewRow CreateRow (int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
{
return default(GridViewRow);
}
public sealed override void DataBind ()
{
}
public virtual new void DeleteRow (int rowIndex)
{
}
protected virtual new void ExtractRowValues (System.Collections.Specialized.IOrderedDictionary fieldValues, GridViewRow row, bool includeReadOnlyFields, bool includePrimaryKey)
{
Contract.Requires (row != null);
}
protected virtual new string GetCallbackResult ()
{
return default(string);
}
protected virtual new string GetCallbackScript (IButtonControl buttonControl, string argument)
{
Contract.Requires (buttonControl != null);
return default(string);
}
public GridView ()
{
}
protected virtual new void InitializePager (GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
{
Contract.Requires (row != null);
}
protected virtual new void InitializeRow (GridViewRow row, DataControlField[] fields)
{
Contract.Requires (row != null);
Contract.Requires (fields != null);
}
public virtual new bool IsBindableType (Type type)
{
return default(bool);
}
protected internal override void LoadControlState (Object savedState)
{
}
protected override void LoadViewState (Object savedState)
{
}
protected override bool OnBubbleEvent (Object source, EventArgs e)
{
return default(bool);
}
protected override void OnDataPropertyChanged ()
{
}
protected override void OnDataSourceViewChanged (Object sender, EventArgs e)
{
}
protected internal override void OnInit (EventArgs e)
{
}
protected virtual new void OnPageIndexChanged (EventArgs e)
{
}
protected virtual new void OnPageIndexChanging (GridViewPageEventArgs e)
{
Contract.Requires (e != null);
}
protected override void OnPagePreLoad (Object sender, EventArgs e)
{
}
protected internal override void OnPreRender (EventArgs e)
{
}
protected virtual new void OnRowCancelingEdit (GridViewCancelEditEventArgs e)
{
Contract.Requires (e != null);
}
#if false
protected virtual new void OnRowCommand (GridViewCommandEventArgs e)
{
}
#endif
protected virtual new void OnRowCreated (GridViewRowEventArgs e)
{
Contract.Requires(e != null);
}
protected virtual new void OnRowDataBound (GridViewRowEventArgs e)
{
}
protected virtual new void OnRowDeleted (GridViewDeletedEventArgs e)
{
}
protected virtual new void OnRowDeleting (GridViewDeleteEventArgs e)
{
Contract.Requires (e != null);
}
protected virtual new void OnRowEditing (GridViewEditEventArgs e)
{
Contract.Requires (e != null);
}
protected virtual new void OnRowUpdated (GridViewUpdatedEventArgs e)
{
}
protected virtual new void OnRowUpdating (GridViewUpdateEventArgs e)
{
Contract.Requires (e != null);
}
protected virtual new void OnSelectedIndexChanged (EventArgs e)
{
}
#if false
protected virtual new void OnSelectedIndexChanging (GridViewSelectEventArgs e)
{
}
#endif
protected virtual new void OnSorted (EventArgs e)
{
}
protected virtual new void OnSorting (GridViewSortEventArgs e)
{
Contract.Requires (e != null);
}
protected internal override void PerformDataBinding (System.Collections.IEnumerable data)
{
}
protected internal virtual new void PrepareControlHierarchy ()
{
}
protected virtual new void RaiseCallbackEvent (string eventArgument)
{
Contract.Requires (eventArgument != null);
}
protected virtual new void RaisePostBackEvent (string eventArgument)
{
Contract.Requires (eventArgument != null);
}
protected internal override void Render (System.Web.UI.HtmlTextWriter writer)
{
}
protected internal override Object SaveControlState ()
{
return default(Object);
}
protected override Object SaveViewState ()
{
return default(Object);
}
#if NETFRAMEWORK_4_0
public void SelectRow (int rowIndex)
{
}
public void SetEditRow (int rowIndex)
{
}
public void SetPageIndex (int rowIndex)
{
}
#endif
public virtual new void Sort (string sortExpression, SortDirection sortDirection)
{
}
string System.Web.UI.ICallbackEventHandler.GetCallbackResult ()
{
return default(string);
}
void System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent (string eventArgument)
{
}
void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
{
}
string System.Web.UI.WebControls.ICallbackContainer.GetCallbackScript (IButtonControl buttonControl, string argument)
{
return default(string);
}
System.Web.UI.PostBackOptions System.Web.UI.WebControls.IPostBackContainer.GetPostBackOptions (IButtonControl buttonControl)
{
return default(System.Web.UI.PostBackOptions);
}
protected override void TrackViewState ()
{
}
public virtual new void UpdateRow (int rowIndex, bool causesValidation)
{
}
#endregion
#region Properties and indexers
public virtual new bool AllowPaging
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool AllowSorting
{
get
{
return default(bool);
}
set
{
}
}
public TableItemStyle AlternatingRowStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new bool AutoGenerateColumns
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool AutoGenerateDeleteButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool AutoGenerateEditButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool AutoGenerateSelectButton
{
get
{
return default(bool);
}
set
{
}
}
public virtual new string BackImageUrl
{
get
{
return default(string);
}
set
{
Contract.Requires (this.ControlStyle != null);
}
}
public virtual new GridViewRow BottomPagerRow
{
get
{
return default(GridViewRow);
}
}
public virtual new string Caption
{
get
{
return default(string);
}
set
{
}
}
public virtual new TableCaptionAlign CaptionAlign
{
get
{
return default(TableCaptionAlign);
}
set
{
}
}
public virtual new int CellPadding
{
get
{
return default(int);
}
set
{
Contract.Requires (this.ControlStyle != null);
}
}
public virtual new int CellSpacing
{
get
{
return default(int);
}
set
{
Contract.Requires (this.ControlStyle != null);
}
}
#if NETFRAMEWORK_4_0
public virtual new string[] ClientIDRowSuffix
{
get
{
return default(string[]);
}
set
{
}
}
public DataKeyArray ClientIDRowSuffixDataKeys
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.DataKeyArray>() != null);
return default(DataKeyArray);
}
}
#endif
public virtual new DataControlFieldCollection Columns
{
get
{
Contract.Ensures(Contract.Result<DataControlFieldCollection>() != null);
return default(DataControlFieldCollection);
}
}
public System.Web.UI.IAutoFieldGenerator ColumnsGenerator
{
get
{
return default(System.Web.UI.IAutoFieldGenerator);
}
set
{
}
}
public virtual new string[] DataKeyNames
{
get
{
return default(string[]);
}
set
{
}
}
public virtual new DataKeyArray DataKeys
{
get
{
return default(DataKeyArray);
}
}
public virtual new int EditIndex
{
get
{
return default(int);
}
set
{
}
}
public TableItemStyle EditRowStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public TableItemStyle EmptyDataRowStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new System.Web.UI.ITemplate EmptyDataTemplate
{
get
{
return default(System.Web.UI.ITemplate);
}
set
{
}
}
public virtual new string EmptyDataText
{
get
{
return default(string);
}
set
{
}
}
public virtual new bool EnableModelValidation
{
get
{
return default(bool);
}
set
{
}
}
#if NETFRAMEWORK_4_0
public virtual new bool EnablePersistedSelection
{
get
{
return default(bool);
}
set
{
}
}
#endif
public virtual new bool EnableSortingAndPagingCallbacks
{
get
{
return default(bool);
}
set
{
}
}
public virtual new GridViewRow FooterRow
{
get
{
return default(GridViewRow);
}
}
public TableItemStyle FooterStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new GridLines GridLines
{
get
{
return default(GridLines);
}
set
{
Contract.Requires (this.ControlStyle != null);
}
}
public virtual new GridViewRow HeaderRow
{
get
{
return default(GridViewRow);
}
}
public TableItemStyle HeaderStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new HorizontalAlign HorizontalAlign
{
get
{
return default(HorizontalAlign);
}
set
{
Contract.Requires (this.ControlStyle != null);
}
}
public virtual new int PageCount
{
get
{
return default(int);
}
}
public virtual new int PageIndex
{
get
{
return default(int);
}
set
{
}
}
public virtual new PagerSettings PagerSettings
{
get
{
return default(PagerSettings);
}
}
public TableItemStyle PagerStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new System.Web.UI.ITemplate PagerTemplate
{
get
{
return default(System.Web.UI.ITemplate);
}
set
{
}
}
public virtual new int PageSize
{
get
{
return default(int);
}
set
{
}
}
public virtual new string RowHeaderColumn
{
get
{
return default(string);
}
set
{
}
}
public virtual new GridViewRowCollection Rows
{
get
{
Contract.Ensures(Contract.Result<GridViewRowCollection>() != null);
return default(GridViewRowCollection);
}
}
public TableItemStyle RowStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public virtual new DataKey SelectedDataKey
{
get
{
return default(DataKey);
}
}
public virtual new int SelectedIndex
{
get
{
return default(int);
}
set
{
}
}
public virtual new DataKey SelectedPersistedDataKey
{
get
{
return default(DataKey);
}
set
{
}
}
public virtual new GridViewRow SelectedRow
{
get
{
Contract.Requires (this.Rows != null);
return default(GridViewRow);
}
}
public TableItemStyle SelectedRowStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public Object SelectedValue
{
get
{
return default(Object);
}
}
public virtual new bool ShowFooter
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool ShowHeader
{
get
{
return default(bool);
}
set
{
}
}
#if NETFRAMEWORK_4_0
public virtual new bool ShowHeaderWhenEmpty
{
get
{
return default(bool);
}
set
{
}
}
#endif
public virtual new SortDirection SortDirection
{
get
{
return default(SortDirection);
}
}
#if NETFRAMEWORK_4_0
public TableItemStyle SortedAscendingCellStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public TableItemStyle SortedAscendingHeaderStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public TableItemStyle SortedDescendingCellStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
public TableItemStyle SortedDescendingHeaderStyle
{
get
{
Contract.Ensures (Contract.Result<System.Web.UI.WebControls.TableItemStyle>() != null);
return default(TableItemStyle);
}
}
#endif
public virtual new string SortExpression
{
get
{
return default(string);
}
}
#if NETFRAMEWORK_4_0
DataKeyArray System.Web.UI.IDataKeysControl.ClientIDRowSuffixDataKeys
{
get
{
return default(DataKeyArray);
}
}
string[] System.Web.UI.WebControls.IDataBoundControl.DataKeyNames
{
get
{
return default(string[]);
}
set
{
}
}
string System.Web.UI.WebControls.IDataBoundControl.DataMember
{
get
{
return default(string);
}
set
{
}
}
Object System.Web.UI.WebControls.IDataBoundControl.DataSource
{
get
{
return default(Object);
}
set
{
}
}
string System.Web.UI.WebControls.IDataBoundControl.DataSourceID
{
get
{
return default(string);
}
set
{
}
}
System.Web.UI.IDataSource System.Web.UI.WebControls.IDataBoundControl.DataSourceObject
{
get
{
return default(System.Web.UI.IDataSource);
}
}
string[] System.Web.UI.WebControls.IDataBoundListControl.ClientIDRowSuffix
{
get
{
return default(string[]);
}
set
{
}
}
DataKeyArray System.Web.UI.WebControls.IDataBoundListControl.DataKeys
{
get
{
return default(DataKeyArray);
}
}
bool System.Web.UI.WebControls.IDataBoundListControl.EnablePersistedSelection
{
get
{
return default(bool);
}
set
{
}
}
DataKey System.Web.UI.WebControls.IDataBoundListControl.SelectedDataKey
{
get
{
return default(DataKey);
}
}
int System.Web.UI.WebControls.IDataBoundListControl.SelectedIndex
{
get
{
return default(int);
}
set
{
}
}
System.Web.UI.IAutoFieldGenerator System.Web.UI.WebControls.IFieldControl.FieldsGenerator
{
get
{
return default(System.Web.UI.IAutoFieldGenerator);
}
set
{
}
}
#endif
DataKey System.Web.UI.WebControls.IPersistedSelector.DataKey
{
get
{
return default(DataKey);
}
set
{
}
}
protected override System.Web.UI.HtmlTextWriterTag TagKey
{
get
{
return default(System.Web.UI.HtmlTextWriterTag);
}
}
public virtual new GridViewRow TopPagerRow
{
get
{
return default(GridViewRow);
}
}
public virtual new bool UseAccessibleHeader
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean
// operations like union and intersection to combine 3D solids. This library
// implements CSG operations on meshes elegantly and concisely using BSP trees,
// and is meant to serve as an easily understandable implementation of the
// algorithm. All edge cases involving overlapping coplanar polygons in both
// solids are correctly handled.
//
// Example usage:
//
// var cube = CSG.cube();
// var sphere = CSG.sphere({ radius: 1.3 });
// var polygons = cube.subtract(sphere).toPolygons();
//
// ## Implementation Details
//
// All CSG operations are implemented in terms of two functions, `clipTo()` and
// `invert()`, which remove parts of a BSP tree inside another BSP tree and swap
// solid and empty space, respectively. To find the union of `a` and `b`, we
// want to remove everything in `a` inside `b` and everything in `b` inside `a`,
// then combine polygons from `a` and `b` into one solid:
//
// a.clipTo(b);
// b.clipTo(a);
// a.build(b.allPolygons());
//
// The only tricky part is handling overlapping coplanar polygons in both trees.
// The code above keeps both copies, but we need to keep them in one tree and
// remove them in the other tree. To remove them from `b` we can clip the
// inverse of `b` against `a`. The code for union now looks like this:
//
// a.clipTo(b);
// b.clipTo(a);
// b.invert();
// b.clipTo(a);
// b.invert();
// a.build(b.allPolygons());
//
// Subtraction and intersection naturally follow from set operations. If
// union is `A | B`, subtraction is `A - B = ~(~A | B)` and intersection is
// `A & B = ~(~A | ~B)` where `~` is the complement operator.
//
// ## License
//
// Original ActionScript version copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license.
// Ported to C# / Unity by Andrew Perry, 2013.
namespace ConstructiveSolidGeometry
{
/// <summary>
/// Holds a binary space partition tree representing a 3D solid. Two solids can
/// be combined using the `union()`, `subtract()`, and `intersect()` methods.
/// </summary>
public class CSG
{
public List<Polygon> polygons;
private Bounds bounds = new Bounds();
/// <summary>
/// Constuctor
/// </summary>
public CSG()
{
this.polygons = new List<Polygon>();
}
/// <summary>
/// Clone
/// </summary>
/// <returns></returns>
public CSG clone()
{
CSG csg = new CSG();
foreach (Polygon p in this.polygons)
{
csg.polygons.Add(p.clone());
}
return csg;
}
public CSG inverse()
{
CSG csg = this.clone();
foreach (Polygon p in csg.polygons)
{
p.flip();
}
return csg;
}
public List<Polygon> toPolygons()
{
return this.polygons;
}
public Mesh toMesh()
{
List<Polygon> trisFromPolygons = new List<Polygon>();
// triangulate polygons
for (int i = this.polygons.Count - 1; i >= 0; i--)
{
if (this.polygons[i].vertices.Length > 3)
{
//Debug.Log("!!! Poly to Tri (order): " + this.polygons[i].vertices.Length);
for (int vi = 1; vi < this.polygons[i].vertices.Length - 1; vi++)
{
IVertex[] tri = new IVertex[] {
this.polygons[i].vertices[0],
this.polygons[i].vertices[vi],
this.polygons[i].vertices[vi+1]
};
trisFromPolygons.Add(new Polygon(tri));
}
// the original polygon is replaced by a set of triangles
this.polygons.RemoveAt(i);
}
}
this.polygons.AddRange(trisFromPolygons);
// TODO: Simplify mesh - the boolean CSG algorithm leaves lots of coplanar
// polygons that share an edge that could be simplified.
// At this point, we have a soup of triangles without regard for shared vertices.
// We index these to combine any vertices with identical positions & normals
// (and maybe later UVs & vertex colors)
List<Vertex> vertices = new List<Vertex>();
int[] tris = new int[this.polygons.Count * 3];
for (int pi = 0; pi < this.polygons.Count; pi++)
{
Polygon tri = this.polygons[pi];
if (tri.vertices.Length > 3) Debug.LogError("Polygon should be a triangle, but isn't !!");
for (int vi = 0; vi < 3; vi++)
{
Vertex vertex = tri.vertices[vi] as Vertex;
bool equivalentVertexAlreadyInList = false;
for (int i = 0; i < vertices.Count; i++)
{
if (vertices[i].pos.ApproximatelyEqual(vertex.pos) &&
vertices[i].normal.ApproximatelyEqual(vertex.normal))
{
equivalentVertexAlreadyInList = true;
vertex.index = vertices[i].index;
}
}
if (!equivalentVertexAlreadyInList)
{
vertices.Add(vertex);
vertex.index = vertices.Count - 1;
}
tris[(pi * 3) + vi] = vertex.index;
}
//Debug.Log(string.Format("Added tri {0},{1},{2}: {3},{4},{5}", pi, pi+1, pi+2, tris[pi], tris[pi+1], tris[pi+2]));
}
Vector3[] verts = new Vector3[this.polygons.Count * 3];
Vector3[] normals = new Vector3[this.polygons.Count * 3];
Mesh m = new Mesh();
for (int i = 0; i < vertices.Count; i++)
{
verts[i] = vertices[i].pos;
normals[i] = vertices[i].normal;
}
m.vertices = verts;
m.normals = normals;
m.triangles = tris;
//m.RecalculateBounds();
//m.RecalculateNormals();
//m.Optimize();
//Debug.Log("toMesh verts, normals, tris: " + m.vertices.Length + ", " +m.normals.Length+", "+m.triangles.Length);
return m;
}
public static CSG fromMesh(Mesh m, Transform tf)
{
List<Polygon> triangles = new List<Polygon>();
int[] tris = m.triangles;
Debug.Log("tris " + tris.Length);
for (int t = 0; t < tris.Length; t += 3)
{
Vertex[] vs = new Vertex[3];
vs[0] = TranslateVertex(m, tf, tris[t]);
vs[1] = TranslateVertex(m, tf, tris[t + 1]);
vs[2] = TranslateVertex(m, tf, tris[t + 2]);
//Debug.Log("Tri index: " + (t+i).ToString() + ", Vertex: " + vs[i].pos);
triangles.Add(new Polygon(vs));
}
Debug.Log("Poly " + triangles.Count);
return CSG.fromPolygons(triangles);
}
private static Vertex TranslateVertex(Mesh m, Transform tf, int tri)
{
Vector3 pos = tf.TransformPoint(m.vertices[tri]);
Vector3 norm = tf.TransformDirection(m.normals[tri]);
return new Vertex(pos, norm);
}
/// <summary>
/// Return a new CSG solid representing space in either this solid or in the
/// solid `csg`. Neither this solid nor the solid `csg` are modified.
/// </summary>
/// <remarks>
/// A.union(B)
///
/// +-------+ +-------+
/// | | | |
/// | A | | |
/// | +--+----+ = | +----+
/// +----+--+ | +----+ |
/// | B | | |
/// | | | |
/// +-------+ +-------+
/// </summary>
/// <param name="csg"></param>
/// <returns></returns>
public CSG union(CSG csg)
{
Node a = new Node(this.polygons);
Node b = new Node(csg.polygons);
a.clipTo(b);
b.clipTo(a);
//b.invert();
//b.clipTo(a);
//b.invert();
a.build(b.allPolygons());
return CSG.fromPolygons(a.allPolygons());
}
/// <summary>
/// Return a new CSG solid representing space in this solid but not in the
/// solid `csg`. Neither this solid nor the solid `csg` are modified.
/// </summary>
/// <remarks>
/// A.subtract(B)
/// +-------+ +-------+
/// | | | |
/// | A | | |
/// | +--+----+ = | +--+
/// +----+--+ | +----+
/// | B |
/// | |
/// +-------+
/// </remarks>
/// <param name="csg"></param>
/// <returns></returns>
public CSG subtract(CSG csg)
{
Node a = new Node(this.polygons);
Node b = new Node(csg.polygons);
//Debug.Log(this.clone().polygons.Count + " -- " + csg.clone().polygons.Count);
//Debug.Log("CSG.subtract: Node a = " + a.polygons.Count + " polys, Node b = " + b.polygons.Count + " polys.");
a.invert();
a.clipTo(b);
b.clipTo(a);
b.invert();
b.clipTo(a);
b.invert();
a.build(b.allPolygons());
a.invert();
return CSG.fromPolygons(a.allPolygons());
}
/// <summary>
/// Return a new CSG solid representing space both this solid and in the
/// solid `csg`. Neither this solid nor the solid `csg` are modified.
/// </summary>
/// <remarks>
/// A.intersect(B)
///
/// +-------+
/// | |
/// | A |
/// | +--+----+ = +--+
/// +----+--+ | +--+
/// | B |
/// | |
/// +-------+
/// </remarks>
/// <param name="csg"></param>
/// <returns>CSG of the intersection</returns>
public CSG intersect(CSG csg)
{
Node a = new Node(this.polygons);
Node b = new Node(csg.polygons);
a.invert();
b.invert();
a.clipTo(b);
b.clipTo(a);
a.build(b.allPolygons());
return CSG.fromPolygons(a.allPolygons()).inverse();
}
/// <summary>
/// Cube function, Untested but compiles
/// </summary>
/// <param name="center">world space center of the cube</param>
/// <param name="radius">size of the cube created at center</param>
/// <returns></returns>
public static CSG cube(Vector3? center, Vector3? radius)
{
Vector3 c = center.GetValueOrDefault(Vector3.zero);
Vector3 r = radius.GetValueOrDefault(Vector3.one);
//TODO: Test if this works
Polygon[] polygons = new Polygon[6];
int[][][] data = new int[][][] {
new int[][]{new int[]{0, 4, 6, 2}, new int[]{-1, 0, 0}},
new int[][]{new int[]{1, 3, 7, 5}, new int[]{1, 0, 0}},
new int[][]{new int[]{0, 1, 5, 4}, new int[]{0, -1, 0}},
new int[][]{new int[]{2, 6, 7, 3}, new int[]{0, 1, 0}},
new int[][]{new int[]{0, 2, 3, 1}, new int[]{0, 0, -1}},
new int[][]{new int[]{4, 5, 7, 6}, new int[]{0, 0, 1}}
};
for (int x = 0; x < 6; x++)
{
int[][] v = data[x];
Vector3 normal = new Vector3((float)v[1][0], (float)v[1][1], (float)v[1][2]);
IVertex[] verts = new IVertex[4];
for (int i = 0; i < 4; i++)
{
verts[i] = new Vertex(
new Vector3(
c.x + (r.x * (2 * (((v[0][i] & 1) > 0) ? 1 : 0) - 1)),
c.y + (r.y * (2 * (((v[0][i] & 2) > 0) ? 1 : 0) - 1)),
c.z + (r.z * (2 * (((v[0][i] & 4) > 0) ? 1 : 0) - 1))),
normal
);
}
polygons[x] = new Polygon(verts);
}
return CSG.fromPolygons(polygons);
}
private static void makeSphereVertex(ref List<IVertex> vxs, Vector3 center, float r, float theta, float phi)
{
theta *= Mathf.PI * 2;
phi *= Mathf.PI;
Vector3 dir = new Vector3(Mathf.Cos(theta) * Mathf.Sin(phi),
Mathf.Cos(phi),
Mathf.Sin(theta) * Mathf.Sin(phi)
);
Vector3 sdir = dir;
sdir *= r;
vxs.Add(new Vertex(center + sdir, dir));
}
public static CSG sphere(Vector3 center, float radius = 1, float slices = 16f, float stacks = 8f)
{
float r = radius;
List<Polygon> polygons = new List<Polygon>();
List<IVertex> vertices;
for (int i = 0; i < slices; i++)
{
for (int j = 0; j < stacks; j++)
{
vertices = new List<IVertex>();
makeSphereVertex(ref vertices, center, r, i / slices, j / stacks);
if (j > 0) makeSphereVertex(ref vertices, center, r, (i + 1) / slices, j / stacks);
if (j < stacks - 1) makeSphereVertex(ref vertices, center, r, (i + 1) / slices, (j + 1) / stacks);
makeSphereVertex(ref vertices, center, r, i / slices, (j + 1) / stacks);
polygons.Add(new Polygon(vertices));
}
}
return CSG.fromPolygons(polygons);
}
/// <summary>
/// Construct a CSG solid from a list of `Polygon` instances.
/// The polygons are cloned
/// </summary>
/// <param name="polygons"></param>
/// <returns></returns>
public static CSG fromPolygons(List<Polygon> polygons)
{
//TODO: Optimize polygons to share vertices
CSG csg = new CSG();
foreach (Polygon p in polygons)
{
csg.polygons.Add(p.clone());
}
return csg;
}
/// <summary>
/// Create CSG from array, does not clone the polygons
/// </summary>
/// <param name="polygon"></param>
/// <returns></returns>
private static CSG fromPolygons(Polygon[] polygons)
{
//TODO: Optimize polygons to share vertices
CSG csg = new CSG();
csg.polygons.AddRange(polygons);
return csg;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Hosting;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Transactions;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int? _retryCount;
[NonSerialized]
private int? _maxRetries;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int? RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
public int? MaxRetries
{
get { return _maxRetries; }
set { _maxRetries = value; }
}
/// <summary>
/// NOTE: The contents of bodyBytes should never be modified
/// </summary>
private List<ArraySegment<byte>> bodyBytes;
private List<ArraySegment<byte>> headerBytes;
private object bodyObject;
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
static Message()
{
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
}
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public bool IsReturnedFromRemoteCluster
{
get { return Headers.IsReturnedFromRemoteCluster; }
set { Headers.IsReturnedFromRemoteCluster = value; }
}
public bool IsTransactionRequired
{
get { return Headers.IsTransactionRequired; }
set { Headers.IsTransactionRequired = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ResendCount
{
get { return Headers.ResendCount; }
set { Headers.ResendCount = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return Headers.TargetObserverId; }
set
{
Headers.TargetObserverId = value;
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public CorrelationId CallChainId
{
get { return Headers.CallChainId; }
set { Headers.CallChainId = value; }
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public bool IsUsingInterfaceVersions
{
get { return Headers.IsUsingIfaceVersion; }
set
{
Headers.IsUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public TimeSpan? TimeToLive
{
get { return Headers.TimeToLive; }
set { Headers.TimeToLive = value; }
}
public bool IsExpired
{
get
{
if (!TimeToLive.HasValue)
return false;
return TimeToLive <= TimeSpan.Zero;
}
}
public bool IsExpirableMessage(bool dropExpiredMessages)
{
if (!dropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget;
}
public ITransactionInfo TransactionInfo
{
get { return Headers.TransactionInfo; }
set { Headers.TransactionInfo = value; }
}
public string DebugContext
{
get { return GetNotNullString(Headers.DebugContext); }
set { Headers.DebugContext = value; }
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
// Resends are used by the sender, usualy due to en error to send or due to a transient rejection.
public bool MayResend(int maxResendCount)
{
return ResendCount < maxResendCount;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetNotNullString(Headers.NewGrainType); }
set { Headers.NewGrainType = value; }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetNotNullString(Headers.GenericGrainType); }
set { Headers.GenericGrainType = value; }
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
public object GetDeserializedBody(SerializationManager serializationManager)
{
if (this.bodyObject != null) return this.bodyObject;
try
{
this.bodyObject = DeserializeBody(serializationManager, this.bodyBytes);
}
finally
{
if (this.bodyBytes != null)
{
BufferPool.GlobalPool.Release(bodyBytes);
this.bodyBytes = null;
}
}
return this.bodyObject;
}
public object BodyObject
{
set
{
bodyObject = value;
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
private static object DeserializeBody(SerializationManager serializationManager, List<ArraySegment<byte>> bytes)
{
if (bytes == null)
{
return null;
}
var stream = new BinaryTokenStreamReader(bytes);
return serializationManager.Deserialize(stream);
}
public Message()
{
bodyObject = null;
bodyBytes = null;
headerBytes = null;
}
/// <summary>
/// Clears the current body and sets the serialized body contents to the provided value.
/// </summary>
/// <param name="body">The serialized body contents.</param>
public void SetBodyBytes(List<ArraySegment<byte>> body)
{
// Dispose of the current body.
this.BodyObject = null;
this.bodyBytes = body;
}
/// <summary>
/// Deserializes the provided value into this instance's <see cref="BodyObject"/>.
/// </summary>
/// <param name="serializationManager">The serialization manager.</param>
/// <param name="body">The serialized body contents.</param>
public void DeserializeBodyObject(SerializationManager serializationManager, List<ArraySegment<byte>> body)
{
this.BodyObject = DeserializeBody(serializationManager, body);
}
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
public List<ArraySegment<byte>> Serialize(SerializationManager serializationManager, out int headerLengthOut, out int bodyLengthOut)
{
var context = new SerializationContext(serializationManager)
{
StreamWriter = new BinaryTokenStreamWriter()
};
SerializationManager.SerializeMessageHeaders(Headers, context);
if (bodyBytes == null)
{
var bodyStream = new BinaryTokenStreamWriter();
serializationManager.Serialize(bodyObject, bodyStream);
// We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
// being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
// serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
// pretty high (an array allocation plus a bunch of copying).
bodyBytes = bodyStream.ToBytes();
}
if (headerBytes != null)
{
BufferPool.GlobalPool.Release(headerBytes);
}
headerBytes = context.StreamWriter.ToBytes();
int headerLength = context.StreamWriter.CurrentOffset;
int bodyLength = BufferLength(bodyBytes);
var bytes = new List<ArraySegment<byte>>();
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
bytes.AddRange(headerBytes);
bytes.AddRange(bodyBytes);
headerLengthOut = headerLength;
bodyLengthOut = bodyLength;
return bytes;
}
public void ReleaseBodyAndHeaderBuffers()
{
ReleaseHeadersOnly();
ReleaseBodyOnly();
}
public void ReleaseHeadersOnly()
{
if (headerBytes == null) return;
BufferPool.GlobalPool.Release(headerBytes);
headerBytes = null;
}
public void ReleaseBodyOnly()
{
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESEND_COUNT, sb, (m) => m.ResendCount);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId);
AppendIfExists(HeadersContainer.Headers.CALL_CHAIN_ID, sb, (m) => m.CallChainId);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9
DebugContext); //10
}
internal void SetTargetPlacement(PlacementResult value)
{
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (TargetGrain != null)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation != null)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
public static Message CreatePromptExceptionResponse(Message request, Exception exception)
{
return new Message
{
Category = request.Category,
Direction = Message.Directions.Response,
Result = Message.ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase)
{
MessagingStatisticsGroup.OnMessageExpired(phase);
ReleaseBodyAndHeaderBuffers();
}
private static int BufferLength(List<ArraySegment<byte>> buffer)
{
var result = 0;
for (var i = 0; i < buffer.Count; i++)
{
result += buffer[i].Count;
}
return result;
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4,
DIRECTION = 1 << 5,
TIME_TO_LIVE = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14,
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 <<16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25,
IS_USING_INTERFACE_VERSION = 1 << 26,
// transactions
TRANSACTION_INFO = 1 << 27,
IS_TRANSACTION_REQUIRED = 1 << 28,
CALL_CHAIN_ID = 1 << 29,
// Do not add over int.MaxValue of these.
}
private Categories _category;
private Directions? _direction;
private bool _isReadOnly;
private bool _isAlwaysInterleave;
private bool _isUnordered;
private bool _isReturnedFromRemoteCluster;
private bool _isTransactionRequired;
private CorrelationId _id;
private int _resendCount;
private int _forwardCount;
private SiloAddress _targetSilo;
private GrainId _targetGrain;
private ActivationId _targetActivation;
private GuidId _targetObserverId;
private SiloAddress _sendingSilo;
private GrainId _sendingGrain;
private ActivationId _sendingActivation;
private bool _isNewPlacement;
private bool _isUsingIfaceVersion;
private ResponseTypes _result;
private ITransactionInfo _transactionInfo;
private TimeSpan? _timeToLive;
private string _debugContext;
private List<ActivationAddress> _cacheInvalidationHeader;
private string _newGrainType;
private string _genericGrainType;
private RejectionTypes _rejectionType;
private string _rejectionInfo;
private Dictionary<string, object> _requestContextData;
private CorrelationId _callChainId;
private readonly DateTime _localCreationTime;
public HeadersContainer()
{
_localCreationTime = DateTime.UtcNow;
}
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public bool IsReturnedFromRemoteCluster
{
get { return _isReturnedFromRemoteCluster; }
set
{
_isReturnedFromRemoteCluster = value;
}
}
public bool IsTransactionRequired
{
get { return _isTransactionRequired; }
set
{
_isTransactionRequired = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ResendCount
{
get { return _resendCount; }
set
{
_resendCount = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public GuidId TargetObserverId
{
get { return _targetObserverId; }
set
{
_targetObserverId = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public bool IsUsingIfaceVersion
{
get { return _isUsingIfaceVersion; }
set
{
_isUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public ITransactionInfo TransactionInfo
{
get { return _transactionInfo; }
set
{
_transactionInfo = value;
}
}
public TimeSpan? TimeToLive
{
get
{
return _timeToLive - (DateTime.UtcNow - _localCreationTime);
}
set
{
_timeToLive = value;
}
}
public string DebugContext
{
get { return _debugContext; }
set
{
_debugContext = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return _newGrainType; }
set
{
_newGrainType = value;
}
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return _genericGrainType; }
set
{
_genericGrainType = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
public CorrelationId CallChainId
{
get { return _callChainId; }
set
{
_callChainId = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if(Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if(IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if (_resendCount != default(int))
headers = headers | Headers.RESEND_COUNT;
if(_forwardCount != default (int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER;
headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _isReturnedFromRemoteCluster == default(bool) ? headers & ~Headers.IS_RETURNED_FROM_REMOTE_CLUSTER : headers | Headers.IS_RETURNED_FROM_REMOTE_CLUSTER;
headers = _isUsingIfaceVersion == default(bool) ? headers & ~Headers.IS_USING_INTERFACE_VERSION : headers | Headers.IS_USING_INTERFACE_VERSION;
headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE;
headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE;
headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
headers = _callChainId == null ? headers & ~Headers.CALL_CHAIN_ID : headers | Headers.CALL_CHAIN_ID;
headers = IsTransactionRequired ? headers | Headers.IS_TRANSACTION_REQUIRED : headers & ~Headers.IS_TRANSACTION_REQUIRED;
headers = _transactionInfo == null ? headers & ~Headers.TRANSACTION_INFO : headers | Headers.TRANSACTION_INFO;
return headers;
}
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
return original;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
HeadersContainer input = (HeadersContainer)untypedInput;
var headers = input.GetHeadersMask();
var writer = context.StreamWriter;
writer.Write((int)headers);
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var count = input.CacheInvalidationHeader.Count;
writer.Write(input.CacheInvalidationHeader.Count);
for (int i = 0; i < count; i++)
{
WriteObj(context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]);
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
{
writer.Write((byte)input.Category);
}
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
writer.Write(input.DebugContext);
if ((headers & Headers.DIRECTION) != Headers.NONE)
writer.Write((byte)input.Direction.Value);
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
writer.Write(input.TimeToLive.Value);
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
writer.Write(input.ForwardCount);
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.GenericGrainType);
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
writer.Write(input.Id);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
writer.Write(input.IsAlwaysInterleave);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
writer.Write(input.IsNewPlacement);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
writer.Write(input.IsReturnedFromRemoteCluster);
// Nothing to do with Headers.IS_USING_INTERFACE_VERSION since the value in
// the header is sufficient
if ((headers & Headers.READ_ONLY) != Headers.NONE)
writer.Write(input.IsReadOnly);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
writer.Write(input.IsUnordered);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.NewGrainType);
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
writer.Write(input.RejectionInfo);
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
writer.Write((byte)input.RejectionType);
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var requestData = input.RequestContextData;
var count = requestData.Count;
writer.Write(count);
foreach (var d in requestData)
{
writer.Write(d.Key);
SerializationManager.SerializeInner(d.Value, context, typeof(object));
}
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
writer.Write(input.ResendCount);
if ((headers & Headers.RESULT) != Headers.NONE)
writer.Write((byte)input.Result);
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
{
writer.Write(input.SendingActivation);
}
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
{
writer.Write(input.SendingGrain);
}
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
{
writer.Write(input.SendingSilo);
}
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
{
writer.Write(input.TargetActivation);
}
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
{
writer.Write(input.TargetGrain);
}
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
{
WriteObj(context, typeof(GuidId), input.TargetObserverId);
}
if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE)
{
writer.Write(input.CallChainId);
}
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
{
writer.Write(input.TargetSilo);
}
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
SerializationManager.SerializeInner(input.TransactionInfo, context, typeof(ITransactionInfo));
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
var result = new HeadersContainer();
var reader = context.StreamReader;
context.RecordObject(result);
var headers = (Headers)reader.ReadInt();
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var n = reader.ReadInt();
if (n > 0)
{
var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n);
for (int i = 0; i < n; i++)
{
list.Add((ActivationAddress)ReadObj(typeof(ActivationAddress), context));
}
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
result.Category = (Categories)reader.ReadByte();
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
result.DebugContext = reader.ReadString();
if ((headers & Headers.DIRECTION) != Headers.NONE)
result.Direction = (Message.Directions)reader.ReadByte();
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
result.TimeToLive = reader.ReadTimeSpan();
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
result.ForwardCount = reader.ReadInt();
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
result.GenericGrainType = reader.ReadString();
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
result.Id = (Orleans.Runtime.CorrelationId)ReadObj(typeof(Orleans.Runtime.CorrelationId), context);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
result.IsAlwaysInterleave = ReadBool(reader);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
result.IsNewPlacement = ReadBool(reader);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
result.IsReturnedFromRemoteCluster = ReadBool(reader);
if ((headers & Headers.IS_USING_INTERFACE_VERSION) != Headers.NONE)
result.IsUsingIfaceVersion = true;
if ((headers & Headers.READ_ONLY) != Headers.NONE)
result.IsReadOnly = ReadBool(reader);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
result.IsUnordered = ReadBool(reader);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
result.NewGrainType = reader.ReadString();
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
result.RejectionInfo = reader.ReadString();
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
result.RejectionType = (RejectionTypes)reader.ReadByte();
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var c = reader.ReadInt();
var requestData = new Dictionary<string, object>(c);
for (int i = 0; i < c; i++)
{
requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context);
}
result.RequestContextData = requestData;
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
result.ResendCount = reader.ReadInt();
if ((headers & Headers.RESULT) != Headers.NONE)
result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte();
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
result.SendingActivation = reader.ReadActivationId();
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
result.SendingGrain = reader.ReadGrainId();
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
result.SendingSilo = reader.ReadSiloAddress();
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
result.TargetActivation = reader.ReadActivationId();
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
result.TargetGrain = reader.ReadGrainId();
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
result.TargetObserverId = (Orleans.Runtime.GuidId)ReadObj(typeof(Orleans.Runtime.GuidId), context);
if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE)
result.CallChainId = reader.ReadCorrelationId();
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
result.TargetSilo = reader.ReadSiloAddress();
result.IsTransactionRequired = (headers & Headers.IS_TRANSACTION_REQUIRED) != Headers.NONE;
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
result.TransactionInfo = SerializationManager.DeserializeInner<ITransactionInfo>(context);
return result;
}
private static bool ReadBool(IBinaryTokenStreamReader stream)
{
return stream.ReadByte() == (byte) SerializationTokenType.True;
}
private static void WriteObj(ISerializationContext context, Type type, object input)
{
var ser = context.GetSerializationManager().GetSerializer(type);
ser.Invoke(input, context, type);
}
private static object ReadObj(Type t, IDeserializationContext context)
{
var des = context.GetSerializationManager().GetDeserializer(t);
return des.Invoke(t, context);
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ClientDependency.Core;
using System.Linq;
using ClientDependency.Core.Controls;
using Umbraco.Core.Configuration;
namespace umbraco.uicontrols
{
[ClientDependency(ClientDependencyType.Javascript, "CodeArea/javascript.js", "UmbracoClient")]
[ClientDependency(ClientDependencyType.Javascript, "CodeArea/UmbracoEditor.js", "UmbracoClient")]
[ClientDependency(ClientDependencyType.Css, "CodeArea/styles.css", "UmbracoClient")]
[ClientDependency(ClientDependencyType.Javascript, "Application/jQuery/jquery-fieldselection.js", "UmbracoClient")]
public class CodeArea : WebControl
{
public CodeArea()
{
//set the default to Css
CodeBase = EditorType.Css;
}
protected TextBox CodeTextBox;
public bool AutoResize { get; set; }
public bool AutoSuggest { get; set; }
public string EditorMimeType { get; set; }
public ScrollingMenu Menu = new ScrollingMenu();
public int OffSetX { get; set; }
public int OffSetY { get; set; }
public string Text
{
get
{
EnsureChildControls();
return CodeTextBox.Text;
}
set
{
EnsureChildControls();
CodeTextBox.Text = value;
}
}
public bool CodeMirrorEnabled
{
get
{
return UmbracoConfig.For.UmbracoSettings().Content.ScriptEditorDisable == false;
}
}
public EditorType CodeBase { get; set; }
public string ClientSaveMethod { get; set; }
public enum EditorType { JavaScript, Css, Python, XML, HTML, Razor, HtmlMixed }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
if (CodeMirrorEnabled)
{
ClientDependencyLoader.Instance.RegisterDependency(0, "lib/CodeMirror/lib/codemirror.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/mode/" + CodeBase.ToString().ToLower() + "/" + CodeBase.ToString().ToLower() + ".js", "UmbracoRoot", ClientDependencyType.Javascript);
if (CodeBase == EditorType.HtmlMixed)
{
ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/xml/xml.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/javascript/javascript.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/css/css.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/mode/htmlmixed/htmlmixed.js", "UmbracoRoot", ClientDependencyType.Javascript);
}
ClientDependencyLoader.Instance.RegisterDependency(1, "lib/CodeMirror/addon/edit/matchbrackets.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/search/search.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/search/searchcursor.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/dialog/dialog.js", "UmbracoRoot", ClientDependencyType.Javascript);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/addon/dialog/dialog.css", "UmbracoRoot", ClientDependencyType.Css);
ClientDependencyLoader.Instance.RegisterDependency(2, "lib/CodeMirror/lib/codemirror.css", "UmbracoRoot", ClientDependencyType.Css);
//ClientDependencyLoader.Instance.RegisterDependency(3, "CodeMirror/css/umbracoCustom.css", "UmbracoClient", ClientDependencyType.Css);
ClientDependencyLoader.Instance.RegisterDependency(4, "CodeArea/styles.css", "UmbracoClient", ClientDependencyType.Css);
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
CodeTextBox = new TextBox();
CodeTextBox.ID = "CodeTextBox";
if (CodeMirrorEnabled == false)
{
CodeTextBox.Attributes.Add("class", "codepress");
CodeTextBox.Attributes.Add("wrap", "off");
}
CodeTextBox.TextMode = TextBoxMode.MultiLine;
this.Controls.Add(Menu);
this.Controls.Add(CodeTextBox);
}
/// <summary>
/// Client ID is different if the code editor is turned on/off
/// </summary>
public override string ClientID
{
get
{
if (CodeMirrorEnabled == false)
return CodeTextBox.ClientID;
else
return base.ClientID;
}
}
protected override void Render(HtmlTextWriter writer)
{
EnsureChildControls();
var jsEventCode = new StringBuilder();
if (CodeMirrorEnabled == false)
{
CodeTextBox.RenderControl(writer);
jsEventCode.Append(RenderBasicEditor());
}
else
{
writer.WriteBeginTag("div");
writer.WriteAttribute("id", this.ClientID);
writer.WriteAttribute("class", "umb-editor umb-codeeditor " + this.CssClass);
this.ControlStyle.AddAttributesToRender(writer);
writer.Write(HtmlTextWriter.TagRightChar);
Menu.RenderControl(writer);
writer.WriteBeginTag("div");
writer.WriteAttribute("class", "code-container");
this.ControlStyle.AddAttributesToRender(writer);
writer.Write(HtmlTextWriter.TagRightChar);
CodeTextBox.RenderControl(writer);
writer.WriteEndTag("div");
writer.WriteEndTag("div");
jsEventCode.Append(RenderCodeEditor());
}
jsEventCode.Append(@"
//TODO: for now this is a global var, need to refactor all this so that is using proper js standards
//with correct objects, and proper accessors to these objects.
var UmbEditor;
$(document).ready(function () {
//create the editor
UmbEditor = new Umbraco.Controls.CodeEditor.UmbracoEditor(" + (CodeMirrorEnabled == false).ToString().ToLower() + @", '" + ClientID + @"');");
if (this.AutoResize)
{
if (CodeMirrorEnabled)
{
//reduce the width if using code mirror because of the line numbers
OffSetX += 20;
OffSetY += 50;
}
//add the resize code
jsEventCode.Append(@"
var m_textEditor = jQuery('#" + ClientID + @"');
//with codemirror adding divs for line numbers, we need to target a different element
m_textEditor = m_textEditor.find('iframe').length > 0 ? m_textEditor.children('div').get(0) : m_textEditor.get(0);
jQuery(window).resize(function(){ resizeTextArea(m_textEditor, " + OffSetX + "," + OffSetY + @"); });
jQuery(document).ready(function(){ resizeTextArea(m_textEditor, " + OffSetX + "," + OffSetY + @"); });");
}
jsEventCode.Append(@"
});");
writer.WriteLine(@"<script type=""text/javascript"">{0}</script>", jsEventCode);
}
protected string RenderBasicEditor()
{
string jsEventCode = @"
var m_textEditor = document.getElementById('" + this.ClientID + @"');
tab.watch('" + this.ClientID + @"');
";
return jsEventCode;
}
protected string RenderCodeEditor()
{
var extraKeys = "";
var editorMimetype = "";
if (string.IsNullOrEmpty(EditorMimeType) == false)
editorMimetype = @",
mode: """ + EditorMimeType + "\"";
var jsEventCode = @"
var textarea = document.getElementById('" + CodeTextBox.ClientID + @"');
var codeEditor = CodeMirror.fromTextArea(textarea, {
tabMode: ""shift"",
matchBrackets: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: ""keep"",
lineWrapping: false" +
editorMimetype + @",
lineNumbers: true" +
extraKeys + @"
});
";
return jsEventCode;
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class FlagTests
{
public static FlagController Fixture()
{
FlagController controller = new FlagController(new FlagRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.Flag flag = Fixture().Get(0);
Assert.NotNull(flag);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.Flag flag = Fixture().GetFirst();
Assert.NotNull(flag);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.Flag flag = Fixture().GetPrevious(0);
Assert.NotNull(flag);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.Flag flag = Fixture().GetNext(0);
Assert.NotNull(flag);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.Flag flag = Fixture().GetLast();
Assert.NotNull(flag);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.Flag> flags = Fixture().Get(new long[] { });
Assert.NotNull(flags);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
//
// TextEntryBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Xwt.Backends;
using System;
#if MONOMAC
using nint = System.Int32;
using nfloat = System.Single;
using MonoMac.Foundation;
using MonoMac.AppKit;
#else
using Foundation;
using AppKit;
#endif
namespace Xwt.Mac
{
public class TextEntryBackend: ViewBackend<NSView,ITextEntryEventSink>, ITextEntryBackend
{
int cacheSelectionStart, cacheSelectionLength;
bool checkMouseSelection;
public TextEntryBackend ()
{
}
internal TextEntryBackend (MacComboBox field)
{
ViewObject = field;
}
public override void Initialize ()
{
base.Initialize ();
if (ViewObject is MacComboBox) {
((MacComboBox)ViewObject).SetEntryEventSink (EventSink);
} else {
var view = new CustomTextField (EventSink, ApplicationContext);
ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view);
MultiLine = false;
}
Frontend.MouseEntered += delegate {
checkMouseSelection = true;
};
Frontend.MouseExited += delegate {
checkMouseSelection = false;
HandleSelectionChanged ();
};
Frontend.MouseMoved += delegate {
if (checkMouseSelection)
HandleSelectionChanged ();
};
}
protected override void OnSizeToFit ()
{
Container.SizeToFit ();
}
CustomAlignedContainer Container {
get { return base.Widget as CustomAlignedContainer; }
}
public new NSTextField Widget {
get { return (ViewObject is MacComboBox) ? (NSTextField)ViewObject : (NSTextField) Container.Child; }
}
protected override Size GetNaturalSize ()
{
var s = base.GetNaturalSize ();
return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height);
}
#region ITextEntryBackend implementation
public string Text {
get {
return Widget.StringValue;
}
set {
Widget.StringValue = value ?? string.Empty;
}
}
public Alignment TextAlignment {
get {
return Widget.Alignment.ToAlignment ();
}
set {
Widget.Alignment = value.ToNSTextAlignment ();
}
}
public bool ReadOnly {
get {
return !Widget.Editable;
}
set {
Widget.Editable = !value;
}
}
public bool ShowFrame {
get {
return Widget.Bordered;
}
set {
Widget.Bordered = value;
}
}
public string PlaceholderText {
get {
return ((NSTextFieldCell) Widget.Cell).PlaceholderString;
}
set {
((NSTextFieldCell) Widget.Cell).PlaceholderString = value;
}
}
public bool MultiLine {
get {
if (Widget is MacComboBox)
return false;
return Widget.Cell.UsesSingleLineMode;
}
set {
if (Widget is MacComboBox)
return;
if (value) {
Widget.Cell.UsesSingleLineMode = false;
Widget.Cell.Scrollable = false;
Widget.Cell.Wraps = true;
} else {
Widget.Cell.UsesSingleLineMode = true;
Widget.Cell.Scrollable = true;
Widget.Cell.Wraps = false;
}
Container.ExpandVertically = value;
}
}
public int CursorPosition {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionStart {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Location;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (value, SelectionLength);
HandleSelectionChanged ();
}
}
public int SelectionLength {
get {
if (Widget.CurrentEditor == null)
return 0;
return (int)Widget.CurrentEditor.SelectedRange.Length;
}
set {
Widget.CurrentEditor.SelectedRange = new NSRange (SelectionStart, value);
HandleSelectionChanged ();
}
}
public string SelectedText {
get {
if (Widget.CurrentEditor == null)
return String.Empty;
int start = SelectionStart;
int end = start + SelectionLength;
if (start == end) return String.Empty;
try {
return Text.Substring (start, end - start);
} catch {
return String.Empty;
}
}
set {
int cacheSelStart = SelectionStart;
int pos = cacheSelStart;
if (SelectionLength > 0) {
Text = Text.Remove (pos, SelectionLength).Insert (pos, value);
}
SelectionStart = pos;
SelectionLength = value.Length;
HandleSelectionChanged ();
}
}
void HandleSelectionChanged ()
{
if (cacheSelectionStart != SelectionStart ||
cacheSelectionLength != SelectionLength) {
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
}
public override void SetFocus ()
{
Widget.BecomeFirstResponder ();
}
#endregion
}
class CustomTextField: NSTextField, IViewObject
{
ITextEntryEventSink eventSink;
ApplicationContext context;
public CustomTextField (ITextEntryEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
}
public NSView View {
get {
return this;
}
}
public ViewBackend Backend { get; set; }
public override void DidChange (NSNotification notification)
{
base.DidChange (notification);
context.InvokeUserCode (delegate {
eventSink.OnChanged ();
eventSink.OnSelectionChanged ();
});
}
int cachedCursorPosition;
public override void KeyUp (NSEvent theEvent)
{
base.KeyUp (theEvent);
if (cachedCursorPosition != CurrentEditor.SelectedRange.Location)
context.InvokeUserCode (delegate {
eventSink.OnSelectionChanged ();
});
cachedCursorPosition = (int)CurrentEditor.SelectedRange.Location;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2014 Paul Louth
//
// 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 Monad.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Monad
{
/// <summary>
/// The Try monad delegate
/// </summary>
public delegate TryResult<T> Try<T>();
/// <summary>
/// Holds the state of the error monad during the bind function
/// If IsFaulted == true then the bind function will be cancelled.
/// </summary>
/// <typeparam name="T"></typeparam>
public struct TryResult<T>
{
public readonly T Value;
public readonly Exception Exception;
/// <summary>
/// Ctor
/// </summary>
public TryResult(T value)
{
Value = value;
Exception = null;
}
/// <summary>
/// Ctor
/// </summary>
public TryResult(Exception e)
{
if (e == null) throw new ArgumentNullException("e");
Exception = e;
Value = default(T);
}
public static implicit operator TryResult<T>(T value)
{
return new TryResult<T>(value);
}
/// <summary>
/// True if faulted
/// </summary>
public bool IsFaulted
{
get
{
return Exception != null;
}
}
/// <summary>
/// ToString override
/// </summary>
/// <returns></returns>
public override string ToString()
{
return IsFaulted
? Exception.ToString()
: Value != null
? Value.ToString()
: "[null]";
}
}
/// <summary>
/// Extension methods for the error monad
/// </summary>
public static class TryExt
{
public static TryResult<T> Try<T>(this Try<T> self)
{
try
{
return self();
}
catch (Exception e)
{
return new TryResult<T>(e);
}
}
/// <summary>
/// Return a valid value regardless of the faulted state
/// </summary>
public static T GetValueOrDefault<T>(this Try<T> self)
{
var res = self.Try();
if (res.IsFaulted)
return default(T);
else
return res.Value;
}
/// <summary>
/// Return the Value of the monad. Note this will throw an InvalidOperationException if
/// the monad is in a faulted state.
/// </summary>
public static T Value<T>(this Try<T> self)
{
var res = self.Try();
if (res.IsFaulted)
throw new InvalidOperationException("The try monad has no value. It holds an exception of type: " + res.GetType().Name + ".");
else
return res.Value;
}
/// <summary>
/// Select
/// </summary>
public static Try<U> Select<T, U>(this Try<T> self, Func<T, U> select)
{
if (select == null) throw new ArgumentNullException("select");
return new Try<U>(() =>
{
TryResult<T> resT;
try
{
resT = self();
if (resT.IsFaulted)
return new TryResult<U>(resT.Exception);
}
catch (Exception e)
{
return new TryResult<U>(e);
}
U resU;
try
{
resU = select(resT.Value);
}
catch (Exception e)
{
return new TryResult<U>(e);
}
return new TryResult<U>(resU);
});
}
/// <summary>
/// SelectMany
/// </summary>
public static Try<V> SelectMany<T, U, V>(
this Try<T> self,
Func<T, Try<U>> select,
Func<T, U, V> bind
)
{
if (select == null) throw new ArgumentNullException("select");
if (bind == null) throw new ArgumentNullException("bind");
return new Try<V>(
() =>
{
TryResult<T> resT;
try
{
resT = self();
if (resT.IsFaulted)
return new TryResult<V>(resT.Exception);
}
catch (Exception e)
{
return new TryResult<V>(e);
}
TryResult<U> resU;
try
{
resU = select(resT.Value)();
if (resU.IsFaulted)
return new TryResult<V>(resU.Exception);
}
catch (Exception e)
{
return new TryResult<V>(e);
}
V resV;
try
{
resV = bind(resT.Value, resU.Value);
}
catch (Exception e)
{
return new TryResult<V>(e);
}
return new TryResult<V>(resV);
}
);
}
/// <summary>
/// Allows fluent chaining of Try monads
/// </summary>
public static Try<U> Then<T, U>(this Try<T> self, Func<T, U> getValue)
{
if (getValue == null) throw new ArgumentNullException("getValue");
var resT = self.Try();
return resT.IsFaulted
? new Try<U>(() => new TryResult<U>(resT.Exception))
: new Try<U>(() =>
{
try
{
U resU = getValue(resT.Value);
return new TryResult<U>(resU);
}
catch (Exception e)
{
return new TryResult<U>(e);
}
});
}
/// <summary>
/// Converts the Try to an enumerable of T
/// </summary>
/// <returns>
/// Success: A list with one T in
/// Error: An empty list
/// </returns>
public static IEnumerable<T> AsEnumerable<T>(this Try<T> self)
{
var res = self.Try();
if (res.IsFaulted)
yield break;
else
yield return res.Value;
}
/// <summary>
/// Converts the Try to an infinite enumerable of T
/// </summary>
/// <returns>
/// Success: An infinite list of T
/// Error: An empty list
/// </returns>
public static IEnumerable<T> AsEnumerableInfinite<T>(this Try<T> self)
{
var res = self.Try();
if (res.IsFaulted)
yield break;
else
while (true) yield return res.Value;
}
/// <summary>
/// Mappend
/// </summary>
public static Try<T> Mappend<T>(this Try<T> lhs, Try<T> rhs)
{
if (rhs == null) throw new ArgumentNullException("rhs");
return () =>
{
var lhsValue = lhs();
if (lhsValue.IsFaulted) return lhsValue;
var rhsValue = rhs();
if (rhsValue.IsFaulted) return rhsValue;
bool IsAppendable = typeof(IAppendable<T>).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
if (IsAppendable)
{
var lhsAppendValue = lhsValue.Value as IAppendable<T>;
return lhsAppendValue.Append(rhsValue.Value);
}
else
{
string TypeOfT = typeof(T).ToString();
// TODO: Consider replacing this with a static Reflection.Emit which does this job efficiently.
switch (TypeOfT)
{
case "System.Int64":
return (T)Convert.ChangeType((Convert.ToInt64(lhsValue.Value) + Convert.ToInt64(rhsValue.Value)), typeof(T));
case "System.UInt64":
return (T)Convert.ChangeType((Convert.ToUInt64(lhsValue.Value) + Convert.ToUInt64(rhsValue.Value)), typeof(T));
case "System.Int32":
return (T)Convert.ChangeType((Convert.ToInt32(lhsValue.Value) + Convert.ToInt32(rhsValue.Value)), typeof(T));
case "System.UInt32":
return (T)Convert.ChangeType((Convert.ToUInt32(lhsValue.Value) + Convert.ToUInt32(rhsValue.Value)), typeof(T));
case "System.Int16":
return (T)Convert.ChangeType((Convert.ToInt16(lhsValue.Value) + Convert.ToInt16(rhsValue.Value)), typeof(T));
case "System.UInt16":
return (T)Convert.ChangeType((Convert.ToUInt16(lhsValue.Value) + Convert.ToUInt16(rhsValue.Value)), typeof(T));
case "System.Decimal":
return (T)Convert.ChangeType((Convert.ToDecimal(lhsValue.Value) + Convert.ToDecimal(rhsValue.Value)), typeof(T));
case "System.Double":
return (T)Convert.ChangeType((Convert.ToDouble(lhsValue.Value) + Convert.ToDouble(rhsValue.Value)), typeof(T));
case "System.Single":
return (T)Convert.ChangeType((Convert.ToSingle(lhsValue.Value) + Convert.ToSingle(rhsValue.Value)), typeof(T));
case "System.Char":
return (T)Convert.ChangeType((Convert.ToChar(lhsValue.Value) + Convert.ToChar(rhsValue.Value)), typeof(T));
case "System.Byte":
return (T)Convert.ChangeType((Convert.ToByte(lhsValue.Value) + Convert.ToByte(rhsValue.Value)), typeof(T));
case "System.String":
return (T)Convert.ChangeType((Convert.ToString(lhsValue.Value) + Convert.ToString(rhsValue.Value)), typeof(T));
default:
throw new InvalidOperationException("Type " + typeof(T).Name + " is not appendable. Consider implementing the IAppendable interface.");
}
}
};
}
/// <summary>
/// Mconcat
/// </summary>
public static Try<T> Mconcat<T>(this IEnumerable<Try<T>> ms)
{
return () =>
{
var value = ms.Head();
foreach (var m in ms.Tail())
{
value = value.Mappend(m);
}
return value();
};
}
/// <summary>
/// Pattern matching
/// </summary>
public static Func<R> Match<T, R>(this Try<T> self, Func<T, R> Success, Func<Exception, R> Fail)
{
if (Success == null) throw new ArgumentNullException("Success");
if (Fail == null) throw new ArgumentNullException("Fail");
return () =>
{
var res = self.Try();
return res.IsFaulted
? Fail(res.Exception)
: Success(res.Value);
};
}
/// <summary>
/// Pattern matching
/// </summary>
public static Func<R> Match<T, R>(this Try<T> self, Func<T, R> Success)
{
if (Success == null) throw new ArgumentNullException("Success");
return () =>
{
var res = self.Try();
return res.IsFaulted
? default(R)
: Success(res.Value);
};
}
/// <summary>
/// Pattern matching
/// </summary>
public static Func<Unit> Match<T>(this Try<T> self, Action<T> Success, Action<Exception> Fail)
{
if (Success == null) throw new ArgumentNullException("Success");
if (Fail == null) throw new ArgumentNullException("Fail");
return () =>
{
var res = self.Try();
if (res.IsFaulted)
Fail(res.Exception);
else
Success(res.Value);
return Unit.Default;
};
}
/// <summary>
/// Pattern matching
/// </summary>
public static Func<Unit> Match<T>(this Try<T> self, Action<T> Success)
{
if (Success == null) throw new ArgumentNullException("Success");
return () =>
{
var res = self.Try();
if (!res.IsFaulted)
Success(res.Value);
return Unit.Default;
};
}
/// <summary>
/// Fetch and memoize the result
/// </summary>
public static Func<TryResult<T>> TryMemo<T>(this Try<T> self)
{
TryResult<T> res;
try
{
res = self();
}
catch (Exception e)
{
res = new TryResult<T>(e);
}
return () => res;
}
}
public class Try
{
/// <summary>
/// Mempty
/// </summary>
public static Try<T> Mempty<T>()
{
return () => default(T);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Management.Automation;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Drawing;
using System.Media;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Specialized;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the different type supported by the clipboard.
/// </summary>
public enum ClipboardFormat
{
/// Text format as default.
Text = 0,
/// File format.
FileDropList = 1,
/// Image format.
Image = 2,
/// Audio format.
Audio = 3,
};
/// <summary>
/// Defines the implementation of the 'Get-Clipboard' cmdlet.
/// This cmdlet get the content from system clipboard.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Clipboard", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=526219")]
[Alias("gcb")]
[OutputType(typeof(string), typeof(FileInfo), typeof(Image), typeof(Stream))]
public class GetClipboardCommand : PSCmdlet
{
/// <summary>
/// Property that sets clipboard type. This will return the required format from clipboard.
/// </summary>
[Parameter]
public ClipboardFormat Format { get; set; }
/// <summary>
/// Property that sets format type when the return type is text.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public TextDataFormat TextFormatType
{
get { return _textFormat; }
set
{
_isTextFormatTypeSet = true;
_textFormat = value;
}
}
private TextDataFormat _textFormat = TextDataFormat.UnicodeText;
private bool _isTextFormatTypeSet = false;
/// <summary>
/// Property that sets raw parameter. This will allow clipboard return text or file list as one string.
/// </summary>
[Parameter]
public SwitchParameter Raw
{
get { return _raw; }
set
{
_isRawSet = true;
_raw = value;
}
}
private bool _raw;
private bool _isRawSet = false;
/// <summary>
/// This method implements the ProcessRecord method for Get-Clipboard command.
/// </summary>
protected override void BeginProcessing()
{
// TextFormatType should only combine with Text.
if (Format != ClipboardFormat.Text && _isTextFormatTypeSet)
{
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, ClipboardResources.InvalidTypeCombine)),
"FailedToGetClipboard", ErrorCategory.InvalidOperation, "Clipboard"));
}
// Raw should only combine with Text or FileDropList.
if (Format != ClipboardFormat.Text && Format != ClipboardFormat.FileDropList && _isRawSet)
{
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, ClipboardResources.InvalidRawCombine)),
"FailedToGetClipboard", ErrorCategory.InvalidOperation, "Clipboard"));
}
if (Format == ClipboardFormat.Text)
{
this.WriteObject(GetClipboardContentAsText(_textFormat), true);
}
else if (Format == ClipboardFormat.Image)
{
this.WriteObject(Clipboard.GetImage());
}
else if (Format == ClipboardFormat.FileDropList)
{
if (_raw)
{
this.WriteObject(Clipboard.GetFileDropList(), true);
}
else
{
this.WriteObject(GetClipboardContentAsFileList());
}
}
else if (Format == ClipboardFormat.Audio)
{
this.WriteObject(Clipboard.GetAudioStream());
}
}
/// <summary>
/// Returns the clipboard content as text format.
/// </summary>
/// <param name="textFormat"></param>
/// <returns></returns>
private List<string> GetClipboardContentAsText(TextDataFormat textFormat)
{
if (!Clipboard.ContainsText(textFormat))
{
return null;
}
List<string> result = new List<string>();
// TextFormat default value is Text, by default it is same as Clipboard.GetText()
string textContent = Clipboard.GetText(textFormat);
if (_raw)
{
result.Add(textContent);
}
else
{
string[] splitSymbol = { Environment.NewLine };
result.AddRange(textContent.Split(splitSymbol, StringSplitOptions.None));
}
return result;
}
/// <summary>
/// Returns the clipboard content as file info.
/// </summary>
/// <returns></returns>
private List<PSObject> GetClipboardContentAsFileList()
{
if (!Clipboard.ContainsFileDropList())
{
return null;
}
List<PSObject> result = new List<PSObject>();
foreach (string filePath in Clipboard.GetFileDropList())
{
FileInfo file = new FileInfo(filePath);
result.Add(WrapOutputInPSObject(file, filePath));
}
return result;
}
/// <summary>
/// Wraps the item in a PSObject and attaches some notes to the
/// object that deal with path information.
/// </summary>
/// <param name="item"></param>
/// <param name="path"></param>
/// <returns></returns>
private PSObject WrapOutputInPSObject(
FileInfo item,
string path)
{
PSObject result = new PSObject(item);
// Now get the parent path and child name
if (path != null)
{
// Get the parent path
string parentPath = Directory.GetParent(path).FullName;
result.AddOrSetProperty("PSParentPath", parentPath);
// Get the child name
string childName = item.Name;
result.AddOrSetProperty("PSChildName", childName);
}
return result;
}
}
}
| |
using System;
using System.ComponentModel.DataAnnotations;
namespace Affixx.Core.Database.Generated
{
// ReSharper disable InconsistentNaming
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable ConditionIsAlwaysTrueOrFalse
public abstract class TableEntity
{
internal abstract void EntitySetId(long id);
internal abstract string EntityInsertSql { get; }
internal abstract string EntityUpdateSql { get; }
public abstract long Id { get; set; }
}
public partial class Comment : TableEntity
{
public long DocumentId { get; set; }
public string Text { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Comments([CreatedAt], [CreatedBy], [DeletedAt], [DocumentId], [Text]) VALUES (@CreatedAt, @CreatedBy, @DeletedAt, @DocumentId, @Text)";} }
internal override string EntityUpdateSql { get { return "UPDATE Comments SET [CreatedAt] = @CreatedAt, [CreatedBy] = @CreatedBy, [DeletedAt] = @DeletedAt, [DocumentId] = @DocumentId, [Text] = @Text WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as Comment;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (DocumentId != entity.DocumentId) {
return false;
}
if (Text != entity.Text) {
return false;
}
if (CreatedBy != entity.CreatedBy) {
return false;
}
if (CreatedAt != entity.CreatedAt) {
return false;
}
if (DeletedAt != entity.DeletedAt) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ DocumentId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Text != null ? Text.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ CreatedBy.GetHashCode();
hashCode = (hashCode*randomPrime) ^ CreatedAt.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (DeletedAt != null ? DeletedAt.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class DocumentCategory : TableEntity
{
public string Name { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO DocumentCategories([Name]) VALUES (@Name)";} }
internal override string EntityUpdateSql { get { return "UPDATE DocumentCategories SET [Name] = @Name WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as DocumentCategory;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (Name != entity.Name) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Name != null ? Name.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class DocumentClaim : TableEntity
{
public long UserId { get; set; }
public int AvailableFree { get; set; }
public int RemainingQuota { get; set; }
public string Reason { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO DocumentClaims([AvailableFree], [Reason], [RemainingQuota], [UserId]) VALUES (@AvailableFree, @Reason, @RemainingQuota, @UserId)";} }
internal override string EntityUpdateSql { get { return "UPDATE DocumentClaims SET [AvailableFree] = @AvailableFree, [Reason] = @Reason, [RemainingQuota] = @RemainingQuota, [UserId] = @UserId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as DocumentClaim;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (UserId != entity.UserId) {
return false;
}
if (AvailableFree != entity.AvailableFree) {
return false;
}
if (RemainingQuota != entity.RemainingQuota) {
return false;
}
if (Reason != entity.Reason) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UserId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ AvailableFree.GetHashCode();
hashCode = (hashCode*randomPrime) ^ RemainingQuota.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Reason != null ? Reason.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class DocumentRating : TableEntity
{
public long DocumentId { get; set; }
public int Rating { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO DocumentRatings([CreatedAt], [CreatedBy], [DocumentId], [Rating]) VALUES (@CreatedAt, @CreatedBy, @DocumentId, @Rating)";} }
internal override string EntityUpdateSql { get { return "UPDATE DocumentRatings SET [CreatedAt] = @CreatedAt, [CreatedBy] = @CreatedBy, [DocumentId] = @DocumentId, [Rating] = @Rating WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as DocumentRating;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (DocumentId != entity.DocumentId) {
return false;
}
if (Rating != entity.Rating) {
return false;
}
if (CreatedBy != entity.CreatedBy) {
return false;
}
if (CreatedAt != entity.CreatedAt) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ DocumentId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ Rating.GetHashCode();
hashCode = (hashCode*randomPrime) ^ CreatedBy.GetHashCode();
hashCode = (hashCode*randomPrime) ^ CreatedAt.GetHashCode();
return hashCode;
}
}
}
public partial class DocumentView : TableEntity
{
public long DocumentId { get; set; }
public long UserId { get; set; }
public DateTime ViewedAt { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO DocumentViews([DocumentId], [UserId], [ViewedAt]) VALUES (@DocumentId, @UserId, @ViewedAt)";} }
internal override string EntityUpdateSql { get { return "UPDATE DocumentViews SET [DocumentId] = @DocumentId, [UserId] = @UserId, [ViewedAt] = @ViewedAt WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as DocumentView;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (DocumentId != entity.DocumentId) {
return false;
}
if (UserId != entity.UserId) {
return false;
}
if (ViewedAt != entity.ViewedAt) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ DocumentId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UserId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ ViewedAt.GetHashCode();
return hashCode;
}
}
}
public partial class Document : TableEntity
{
public string FullDocumentFileName { get; set; }
public string FreeSnippetFileName { get; set; }
public string OriginalFileName { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Degree { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public string Year { get; set; }
public long UniversityId { get; set; }
public long UploadedBy { get; set; }
public DateTime UploadedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public bool IsFree { get; set; }
public bool? IsApproved { get; set; }
public string Hash { get; set; }
public string MinHashSignature { get; set; }
public long CategoryId { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Documents([CategoryId], [CourseCode], [CourseName], [Degree], [DeletedAt], [Description], [FreeSnippetFileName], [FullDocumentFileName], [Hash], [IsApproved], [IsFree], [MinHashSignature], [OriginalFileName], [Title], [UniversityId], [UploadedAt], [UploadedBy], [Year]) VALUES (@CategoryId, @CourseCode, @CourseName, @Degree, @DeletedAt, @Description, @FreeSnippetFileName, @FullDocumentFileName, @Hash, @IsApproved, @IsFree, @MinHashSignature, @OriginalFileName, @Title, @UniversityId, @UploadedAt, @UploadedBy, @Year)";} }
internal override string EntityUpdateSql { get { return "UPDATE Documents SET [CategoryId] = @CategoryId, [CourseCode] = @CourseCode, [CourseName] = @CourseName, [Degree] = @Degree, [DeletedAt] = @DeletedAt, [Description] = @Description, [FreeSnippetFileName] = @FreeSnippetFileName, [FullDocumentFileName] = @FullDocumentFileName, [Hash] = @Hash, [IsApproved] = @IsApproved, [IsFree] = @IsFree, [MinHashSignature] = @MinHashSignature, [OriginalFileName] = @OriginalFileName, [Title] = @Title, [UniversityId] = @UniversityId, [UploadedAt] = @UploadedAt, [UploadedBy] = @UploadedBy, [Year] = @Year WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as Document;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (FullDocumentFileName != entity.FullDocumentFileName) {
return false;
}
if (FreeSnippetFileName != entity.FreeSnippetFileName) {
return false;
}
if (OriginalFileName != entity.OriginalFileName) {
return false;
}
if (Title != entity.Title) {
return false;
}
if (Description != entity.Description) {
return false;
}
if (Degree != entity.Degree) {
return false;
}
if (CourseName != entity.CourseName) {
return false;
}
if (CourseCode != entity.CourseCode) {
return false;
}
if (Year != entity.Year) {
return false;
}
if (UniversityId != entity.UniversityId) {
return false;
}
if (UploadedBy != entity.UploadedBy) {
return false;
}
if (UploadedAt != entity.UploadedAt) {
return false;
}
if (DeletedAt != entity.DeletedAt) {
return false;
}
if (IsFree != entity.IsFree) {
return false;
}
if (IsApproved != entity.IsApproved) {
return false;
}
if (Hash != entity.Hash) {
return false;
}
if (MinHashSignature != entity.MinHashSignature) {
return false;
}
if (CategoryId != entity.CategoryId) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (FullDocumentFileName != null ? FullDocumentFileName.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (FreeSnippetFileName != null ? FreeSnippetFileName.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (OriginalFileName != null ? OriginalFileName.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Title != null ? Title.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Description != null ? Description.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Degree != null ? Degree.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (CourseName != null ? CourseName.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (CourseCode != null ? CourseCode.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Year != null ? Year.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ UniversityId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UploadedBy.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UploadedAt.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (DeletedAt != null ? DeletedAt.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ IsFree.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (IsApproved != null ? IsApproved.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Hash != null ? Hash.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (MinHashSignature != null ? MinHashSignature.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ CategoryId.GetHashCode();
return hashCode;
}
}
}
public partial class Follower : TableEntity
{
public long UserId { get; set; }
public long FollowerId { get; set; }
public DateTime FollowedAt { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Followers([FollowedAt], [FollowerId], [UserId]) VALUES (@FollowedAt, @FollowerId, @UserId)";} }
internal override string EntityUpdateSql { get { return "UPDATE Followers SET [FollowedAt] = @FollowedAt, [FollowerId] = @FollowerId, [UserId] = @UserId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as Follower;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (UserId != entity.UserId) {
return false;
}
if (FollowerId != entity.FollowerId) {
return false;
}
if (FollowedAt != entity.FollowedAt) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UserId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ FollowerId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ FollowedAt.GetHashCode();
return hashCode;
}
}
}
public partial class Purchase : TableEntity
{
public long DocumentId { get; set; }
public long BuyerId { get; set; }
public DateTime PurchasedAt { get; set; }
public string TransactionId { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Purchases([BuyerId], [DocumentId], [PurchasedAt], [TransactionId]) VALUES (@BuyerId, @DocumentId, @PurchasedAt, @TransactionId)";} }
internal override string EntityUpdateSql { get { return "UPDATE Purchases SET [BuyerId] = @BuyerId, [DocumentId] = @DocumentId, [PurchasedAt] = @PurchasedAt, [TransactionId] = @TransactionId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as Purchase;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (DocumentId != entity.DocumentId) {
return false;
}
if (BuyerId != entity.BuyerId) {
return false;
}
if (PurchasedAt != entity.PurchasedAt) {
return false;
}
if (TransactionId != entity.TransactionId) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ DocumentId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ BuyerId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ PurchasedAt.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (TransactionId != null ? TransactionId.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class Referral : TableEntity
{
public long UserId { get; set; }
public string InvitedEmail { get; set; }
public long? InvitedUserId { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Referrals([InvitedEmail], [InvitedUserId], [UserId]) VALUES (@InvitedEmail, @InvitedUserId, @UserId)";} }
internal override string EntityUpdateSql { get { return "UPDATE Referrals SET [InvitedEmail] = @InvitedEmail, [InvitedUserId] = @InvitedUserId, [UserId] = @UserId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as Referral;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (UserId != entity.UserId) {
return false;
}
if (InvitedEmail != entity.InvitedEmail) {
return false;
}
if (InvitedUserId != entity.InvitedUserId) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UserId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (InvitedEmail != null ? InvitedEmail.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (InvitedUserId != null ? InvitedUserId.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class University : TableEntity
{
public string Name { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Universities([Name]) VALUES (@Name)";} }
internal override string EntityUpdateSql { get { return "UPDATE Universities SET [Name] = @Name WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as University;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (Name != entity.Name) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Name != null ? Name.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class UniversityCourse : TableEntity
{
public long UniversityId { get; set; }
public string Group { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public long CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO UniversityCourses([Code], [CreatedAt], [CreatedBy], [DeletedAt], [Group], [Name], [UniversityId]) VALUES (@Code, @CreatedAt, @CreatedBy, @DeletedAt, @Group, @Name, @UniversityId)";} }
internal override string EntityUpdateSql { get { return "UPDATE UniversityCourses SET [Code] = @Code, [CreatedAt] = @CreatedAt, [CreatedBy] = @CreatedBy, [DeletedAt] = @DeletedAt, [Group] = @Group, [Name] = @Name, [UniversityId] = @UniversityId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as UniversityCourse;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (UniversityId != entity.UniversityId) {
return false;
}
if (Group != entity.Group) {
return false;
}
if (Name != entity.Name) {
return false;
}
if (Code != entity.Code) {
return false;
}
if (CreatedBy != entity.CreatedBy) {
return false;
}
if (CreatedAt != entity.CreatedAt) {
return false;
}
if (DeletedAt != entity.DeletedAt) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ UniversityId.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Group != null ? Group.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Code != null ? Code.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ CreatedBy.GetHashCode();
hashCode = (hashCode*randomPrime) ^ CreatedAt.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (DeletedAt != null ? DeletedAt.GetHashCode() : 0);
return hashCode;
}
}
}
public partial class UserLogin : TableEntity
{
public string LoginProvider { get; set; }
public string ProviderKey { get; set; }
public long UserId { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO UserLogins([LoginProvider], [ProviderKey], [UserId]) VALUES (@LoginProvider, @ProviderKey, @UserId)";} }
internal override string EntityUpdateSql { get { return "UPDATE UserLogins SET [LoginProvider] = @LoginProvider, [ProviderKey] = @ProviderKey, [UserId] = @UserId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as UserLogin;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (LoginProvider != entity.LoginProvider) {
return false;
}
if (ProviderKey != entity.ProviderKey) {
return false;
}
if (UserId != entity.UserId) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (LoginProvider != null ? LoginProvider.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (ProviderKey != null ? ProviderKey.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ UserId.GetHashCode();
return hashCode;
}
}
}
public partial class User : TableEntity
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? EmailConfirmedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public string InviteCode { get; set; }
public long? UniversityId { get; set; }
public string Role { get; set; }
public string AcademicField { get; set; }
public string AcademicResume { get; set; }
public override long Id { get; set; }
internal override void EntitySetId(long id) { Id = id; }
internal override string EntityInsertSql { get { return "INSERT INTO Users([AcademicField], [AcademicResume], [CreatedAt], [DeletedAt], [Email], [EmailConfirmedAt], [InviteCode], [Name], [Password], [Role], [UniversityId]) VALUES (@AcademicField, @AcademicResume, @CreatedAt, @DeletedAt, @Email, @EmailConfirmedAt, @InviteCode, @Name, @Password, @Role, @UniversityId)";} }
internal override string EntityUpdateSql { get { return "UPDATE Users SET [AcademicField] = @AcademicField, [AcademicResume] = @AcademicResume, [CreatedAt] = @CreatedAt, [DeletedAt] = @DeletedAt, [Email] = @Email, [EmailConfirmedAt] = @EmailConfirmedAt, [InviteCode] = @InviteCode, [Name] = @Name, [Password] = @Password, [Role] = @Role, [UniversityId] = @UniversityId WHERE [Id] = @Id"; } }
public override bool Equals(object other)
{
if (ReferenceEquals(this, other)) {
return true;
}
var entity = other as User;
if (entity == null) {
return false;
}
if (Id != entity.Id) {
return false;
}
if (Name != entity.Name) {
return false;
}
if (Email != entity.Email) {
return false;
}
if (Password != entity.Password) {
return false;
}
if (CreatedAt != entity.CreatedAt) {
return false;
}
if (EmailConfirmedAt != entity.EmailConfirmedAt) {
return false;
}
if (DeletedAt != entity.DeletedAt) {
return false;
}
if (InviteCode != entity.InviteCode) {
return false;
}
if (UniversityId != entity.UniversityId) {
return false;
}
if (Role != entity.Role) {
return false;
}
if (AcademicField != entity.AcademicField) {
return false;
}
if (AcademicResume != entity.AcademicResume) {
return false;
}
return true;
}
public override int GetHashCode()
{
unchecked {
const int randomPrime = 397;
int hashCode = Id.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (Name != null ? Name.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Email != null ? Email.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Password != null ? Password.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ CreatedAt.GetHashCode();
hashCode = (hashCode*randomPrime) ^ (EmailConfirmedAt != null ? EmailConfirmedAt.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (DeletedAt != null ? DeletedAt.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (InviteCode != null ? InviteCode.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (UniversityId != null ? UniversityId.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (Role != null ? Role.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (AcademicField != null ? AcademicField.GetHashCode() : 0);
hashCode = (hashCode*randomPrime) ^ (AcademicResume != null ? AcademicResume.GetHashCode() : 0);
return hashCode;
}
}
}
// ReSharper restore ConditionIsAlwaysTrueOrFalse
// ReSharper restore PartialTypeWithSinglePart
// ReSharper restore InconsistentNaming
}
| |
// -------------------------------------------------------------------------------------------
// <copyright file="Validators.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// -------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.PriceMatrix
{
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using Sitecore.Data.Items;
using Sitecore.Data.Validators;
/// <summary>
/// The Price matrix validator.
/// </summary>
[Serializable]
public class PriceMatrixValidator : StandardValidator
{
/// <summary>
/// The message
/// </summary>
private string message = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="PriceMatrixValidator"/> class.
/// </summary>
public PriceMatrixValidator()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PriceMatrixValidator"/> class.
/// </summary>
/// <param name="info">The Serialization info.</param>
/// <param name="context">The context.</param>
protected PriceMatrixValidator(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.message = (string)info.GetValue("PriceMatrixValidator.message", typeof(string));
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>
/// The validator name.
/// </value>
public override string Name
{
get
{
return "Required";
}
}
/// <summary>
/// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo" />
/// with the data needed to serialize the target object.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> to populate with data.</param>
/// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext" />) for this serialization.</param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("PriceMatrixValidator.message", this.message, typeof(string));
}
/// <summary>
/// When overridden in a derived class, this method contains the code
/// to determine whether the value in the input control is valid.
/// </summary>
/// <returns>
/// The result of the evaluation.
/// </returns>
protected override ValidatorResult Evaluate()
{
var priceMatrixItem = PriceMatrix.Load(this.ControlValidationValue);
var item = Sitecore.Context.Database.SelectSingleItem("/*/system/Modules/*[@@templatekey='configuration']").Children["PriceMatrix"];
if (priceMatrixItem != null)
{
this.IterateRecursiveToLoad(priceMatrixItem.MainCategory, item);
}
if (string.IsNullOrEmpty(this.message))
{
return ValidatorResult.Valid;
}
this.Text = string.Format("Field \"{0}\" has some invalid fields.\n", this.GetFieldDisplayName()) +
this.message;
return this.GetFailedResult(ValidatorResult.CriticalError);
}
/// <summary>
/// Iterates the recursive to load.
/// </summary>
/// <param name="priceMatrixItem">The price matrix item.</param>
/// <param name="item">The item.</param>
protected virtual void IterateRecursiveToLoad(IPriceMatrixItem priceMatrixItem, Item item)
{
var key = item.Template.Key;
if (key.Equals("pricematrix settings"))
{
var children = item.Children;
foreach (Item child in children)
{
IPriceMatrixItem categoryChild = null;
var matrixItem = priceMatrixItem as Category;
if (matrixItem != null)
{
var category = matrixItem;
categoryChild = category.GetElement(child.Name);
}
this.IterateRecursiveToLoad(categoryChild, child);
}
}
else if (key.Equals("pricematrix site"))
{
foreach (Item child in item.Children)
{
IPriceMatrixItem categoryChild = null;
var matrixItem = priceMatrixItem as Category;
if (matrixItem != null)
{
var category = matrixItem;
categoryChild = category.GetElement(child.Name);
}
this.IterateRecursiveToLoad(categoryChild, child);
}
}
else if (key.Equals("pricematrix price"))
{
var matrixItem = priceMatrixItem as CategoryItem;
var categoryItem = matrixItem;
if (categoryItem == null)
{
return;
}
var value = categoryItem.Amount ?? string.Empty;
var expression = this.Parameters["Pattern"];
var regex = new Regex(expression);
if (string.IsNullOrEmpty(value))
{
return;
}
if (!regex.IsMatch(value))
{
this.message += string.Format("Price field \"{0}\" has wrong format: \"{1}\".\n", new object[] { this.GetAncestorPath(item), value });
}
}
}
/// <summary>
/// Gets the ancestor path.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>the ancestor path.</returns>
protected virtual string GetAncestorPath(Item item)
{
var path = string.Empty;
while (item != null && !item.Template.Key.Equals("pricematrix settings"))
{
var title = item["title"];
title = string.IsNullOrEmpty(title) ? item.Name : title.Replace(":", string.Empty);
if (string.IsNullOrEmpty(path))
{
path = title;
}
else
{
path = title + "/" + path;
}
item = item.Parent;
}
return path;
}
/// <summary>
/// Gets the max validator result.
/// </summary>
/// <returns>
/// The max validator result.
/// </returns>
/// <remarks>
/// This is used when saving and the validator uses a thread. If the Max Validator Result
/// is Error or below, the validator does not have to be evaluated before saving.
/// If the Max Validator Result is CriticalError or FatalError, the validator must have
/// been evaluated before saving.
/// </remarks>
protected override ValidatorResult GetMaxValidatorResult()
{
return this.GetFailedResult(ValidatorResult.CriticalError);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridColumnCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Runtime.Remoting;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Collections;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.Globalization;
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection"]/*' />
/// <devdoc>
/// <para>Represents a collection of System.Windows.Forms.DataGridColumnStyle objects in the <see cref='System.Windows.Forms.DataGrid'/>
/// control.</para>
/// </devdoc>
[
Editor("System.Windows.Forms.Design.DataGridColumnCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
ListBindable(false)
]
public class GridColumnStylesCollection : BaseCollection, IList {
CollectionChangeEventHandler onCollectionChanged;
ArrayList items = new ArrayList();
DataGridTableStyle owner = null;
private bool isDefault = false;
// we have to implement IList for the Collection editor to work
//
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.Add"]/*' />
/// <internalonly/>
int IList.Add(object value) {
return this.Add((DataGridColumnStyle) value);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.Clear"]/*' />
/// <internalonly/>
void IList.Clear() {
this.Clear();
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.Contains"]/*' />
/// <internalonly/>
bool IList.Contains(object value) {
return items.Contains(value);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.IndexOf"]/*' />
/// <internalonly/>
int IList.IndexOf(object value) {
return items.IndexOf(value);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.Insert"]/*' />
/// <internalonly/>
void IList.Insert(int index, object value) {
throw new NotSupportedException();
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.Remove"]/*' />
/// <internalonly/>
void IList.Remove(object value) {
this.Remove((DataGridColumnStyle)value);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.RemoveAt"]/*' />
/// <internalonly/>
void IList.RemoveAt(int index) {
this.RemoveAt(index);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.IsFixedSize"]/*' />
/// <internalonly/>
bool IList.IsFixedSize {
get {return false;}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.IsReadOnly"]/*' />
/// <internalonly/>
bool IList.IsReadOnly {
get {return false;}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IList.this"]/*' />
/// <internalonly/>
object IList.this[int index] {
get { return items[index]; }
set { throw new NotSupportedException(); }
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.ICollection.CopyTo"]/*' />
/// <internalonly/>
void ICollection.CopyTo(Array array, int index) {
this.items.CopyTo(array, index);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.ICollection.Count"]/*' />
/// <internalonly/>
int ICollection.Count {
get {return this.items.Count;}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.ICollection.IsSynchronized"]/*' />
/// <internalonly/>
bool ICollection.IsSynchronized {
get {return false;}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.ICollection.SyncRoot"]/*' />
/// <internalonly/>
object ICollection.SyncRoot {
get {return this;}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IEnumerable.GetEnumerator"]/*' />
/// <internalonly/>
IEnumerator IEnumerable.GetEnumerator() {
return items.GetEnumerator();
}
internal GridColumnStylesCollection(DataGridTableStyle table) {
owner = table;
}
internal GridColumnStylesCollection(DataGridTableStyle table, bool isDefault) : this(table) {
this.isDefault = isDefault;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.List"]/*' />
/// <devdoc>
/// <para>Gets the list of items in the collection.</para>
/// </devdoc>
protected override ArrayList List {
get {
return items;
}
}
/* implemented in BaseCollection
/// <summary>
/// <para>
/// Gets the number of System.Windows.Forms.DataGridColumnStyle objects in the collection.
/// </para>
/// </summary>
/// <value>
/// <para>
/// The number of System.Windows.Forms.DataGridColumnStyle objects in the System.Windows.Forms.GridColumnsStyleCollection .
/// </para>
/// </value>
/// <example>
/// <para>
/// The following example uses the <see cref='System.Windows.Forms.GridColumnsCollection.Count'/>
/// property to determine how many System.Windows.Forms.DataGridColumnStyle objects are in a System.Windows.Forms.GridColumnsStyleCollection, and uses that number to iterate through the
/// collection.
/// </para>
/// <code lang='VB'>
/// Private Sub PrintGridColumns()
/// Dim colsCount As Integer
/// colsCount = DataGrid1.GridColumns.Count
/// Dim i As Integer
/// For i = 0 to colsCount - 1
/// Debug.Print DataGrid1.GridColumns(i).GetType.ToString
/// Next i
/// End Sub
/// </code>
/// </example>
/// <seealso cref='System.Windows.Forms.GridColumnsCollection.Add'/>
/// <seealso cref='System.Windows.Forms.GridColumnsCollection.Remove'/>
public override int Count {
get {
return items.Count;
}
}
*/
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.this"]/*' />
/// <devdoc>
/// <para>Gets the System.Windows.Forms.DataGridColumnStyle at a specified index.</para>
/// </devdoc>
public DataGridColumnStyle this[int index] {
get {
return (DataGridColumnStyle)items[index];
}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.this1"]/*' />
/// <devdoc>
/// <para>Gets the System.Windows.Forms.DataGridColumnStyle
/// with the specified name.</para>
/// </devdoc>
public DataGridColumnStyle this[string columnName] {
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
get {
int itemCount = items.Count;
for (int i = 0; i < itemCount; ++i) {
DataGridColumnStyle column = (DataGridColumnStyle)items[i];
// NOTE: case-insensitive
if (String.Equals(column.MappingName, columnName, StringComparison.OrdinalIgnoreCase))
return column;
}
return null;
}
}
internal DataGridColumnStyle MapColumnStyleToPropertyName(string mappingName) {
int itemCount = items.Count;
for (int i = 0; i < itemCount; ++i) {
DataGridColumnStyle column = (DataGridColumnStyle)items[i];
// NOTE: case-insensitive
if (String.Equals(column.MappingName, mappingName, StringComparison.OrdinalIgnoreCase))
return column;
}
return null;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.this2"]/*' />
/// <devdoc>
/// <para>Gets the System.Windows.Forms.DataGridColumnStyle associated with the
/// specified <see cref='System.Data.DataColumn'/>.</para>
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")]
public DataGridColumnStyle this[PropertyDescriptor propertyDesciptor] {
[
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly") // already shipped
]
get {
int itemCount = items.Count;
for (int i = 0; i < itemCount; ++i) {
DataGridColumnStyle column = (DataGridColumnStyle)items[i];
if (propertyDesciptor.Equals(column.PropertyDescriptor))
return column;
}
return null;
}
}
internal DataGridTableStyle DataGridTableStyle {
get {
return this.owner;
}
}
/// <devdoc>
/// <para>Adds a System.Windows.Forms.DataGridColumnStyle to the System.Windows.Forms.GridColumnStylesCollection</para>
/// </devdoc>
internal void CheckForMappingNameDuplicates(DataGridColumnStyle column) {
if (String.IsNullOrEmpty(column.MappingName))
return;
for (int i = 0; i < items.Count; i++)
if ( ((DataGridColumnStyle)items[i]).MappingName.Equals(column.MappingName) && column != items[i])
throw new ArgumentException(SR.GetString(SR.DataGridColumnStyleDuplicateMappingName), "column");
}
private void ColumnStyleMappingNameChanged(object sender, EventArgs pcea) {
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null));
}
private void ColumnStylePropDescChanged(object sender, EventArgs pcea) {
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, (DataGridColumnStyle) sender));
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Add"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual int Add(DataGridColumnStyle column) {
if (this.isDefault) {
throw new ArgumentException(SR.GetString(SR.DataGridDefaultColumnCollectionChanged));
}
CheckForMappingNameDuplicates(column);
column.SetDataGridTableInColumn(owner, true);
column.MappingNameChanged += new EventHandler(ColumnStyleMappingNameChanged);
column.PropertyDescriptorChanged += new EventHandler(ColumnStylePropDescChanged);
// columns which are not the default should have a default
// width of DataGrid.PreferredColumnWidth
if (this.DataGridTableStyle != null && column.Width == -1)
column.width = this.DataGridTableStyle.PreferredColumnWidth;
#if false
column.AddOnPropertyChanged(owner.OnColumnChanged);
#endif
int index = items.Add(column);
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, column));
return index;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.AddRange"]/*' />
public void AddRange(DataGridColumnStyle[] columns) {
if (columns == null) {
throw new ArgumentNullException("columns");
}
for (int i = 0; i < columns.Length; i++) {
Add(columns[i]);
}
}
// the dataGrid will need to add default columns to a default
// table when there is no match for the listName in the tableStyle
internal void AddDefaultColumn(DataGridColumnStyle column) {
#if DEBUG
Debug.Assert(this.isDefault, "we should be calling this function only for default tables");
Debug.Assert(column.IsDefault, "we should be a default column");
#endif // DEBUG
column.SetDataGridTableInColumn(owner, true);
this.items.Add(column);
}
internal void ResetDefaultColumnCollection() {
Debug.Assert(this.isDefault, "we should be calling this function only for default tables");
// unparent the edit controls
for (int i = 0; i < Count; i++) {
this[i].ReleaseHostedControl();
}
// get rid of the old list and get a new empty list
items.Clear();
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.CollectionChanged"]/*' />
/// <devdoc>
/// <para>Occurs when a change is made to the System.Windows.Forms.GridColumnStylesCollection.</para>
/// </devdoc>
public event CollectionChangeEventHandler CollectionChanged {
add {
onCollectionChanged += value;
}
remove {
onCollectionChanged -= value;
}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Clear"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Clear() {
for (int i = 0; i < Count; i ++) {
this[i].ReleaseHostedControl();
}
items.Clear();
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null));
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Contains"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether the System.Windows.Forms.GridColumnStylesCollection contains a System.Windows.Forms.DataGridColumnStyle associated with the
/// specified <see cref='System.Data.DataColumn'/>.
/// </para>
/// </devdoc>
public bool Contains(PropertyDescriptor propertyDescriptor) {
return this[propertyDescriptor] != null;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Contains1"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the specified System.Windows.Forms.DataGridColumnStyle.
/// </para>
/// </devdoc>
public bool Contains(DataGridColumnStyle column) {
int index = items.IndexOf(column);
return index != -1;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Contains2"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether the System.Windows.Forms.GridColumnsStyleCollection contains the System.Windows.Forms.DataGridColumnStyle with the specified name.
/// </para>
/// </devdoc>
public bool Contains(string name) {
IEnumerator e = items.GetEnumerator();
while (e.MoveNext()) {
DataGridColumnStyle column = (DataGridColumnStyle)e.Current;
// NOTE: case-insensitive
if (String.Compare(column.MappingName, name, true, CultureInfo.InvariantCulture) == 0)
return true;
}
return false;
}
/* implemented at BaseCollection
/// <overload>
/// <para>
/// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection.
/// </para>
/// </overload>
/// <summary>
/// <para>
/// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection.
/// </para>
/// </summary>
/// <returns>
/// <para>
/// An <see cref='System.Collections.IEnumerator'/>
/// that can be used to iterate through the collection.
/// </para>
/// </returns>
/// <example>
/// <para>
/// The following example gets an <see cref='System.Collections.IEnumerator'/> that iterates through the System.Windows.Forms.GridColumnsStyleCollection. and prints the
/// <see cref='System.Windows.Forms.GridColumnsCollection.Caption'/> of each <see cref='System.Data.DataColumn'/>
/// associated with the object.
/// </para>
/// <code lang='VB'>
/// Private Sub EnumerateThroughGridColumns()
/// Dim ie As System.Collections.IEnumerator
/// Dim dgCol As DataGridColumn
/// Set ie = DataGrid1.GridColumns.GetEnumerator
/// Do While ie.GetNext = True
/// Set dgCol = ie.GetObject
/// Debug.Print dgCol.DataColumn.Caption
/// Loop
/// End Sub
/// </code>
/// </example>
/// <seealso cref='System.Data.DataColumn'/>
/// <seealso cref='System.Collections.IEnumerator'/>
/// <seealso cref='System.Windows.Forms.IEnumerator.GetNext'/>
/// <seealso cref='System.Windows.Forms.IEnumerator.GetObject'/>
public override IEnumerator GetEnumerator() {
return items.GetEnumerator();
}
/// <summary>
/// <para>
/// Gets an enumerator for the System.Windows.Forms.GridColumnsStyleCollection
/// .
/// </para>
/// </summary>
/// <param name='allowRemove'>
/// <para>A value that indicates if the enumerator can remove elements. <see langword='true'/>, if removals are allowed; otherwise, <see langword='false'/>. The default is <see langword='false'/>.</para>
/// </param>
/// <returns>
/// <para>
/// An <see cref='System.Collections.IEnumerator'/> that can be used to iterate through the
/// collection.
/// </para>
/// </returns>
/// <exception cref='NotSupportedException'>
/// An attempt was made to remove the System.Windows.Forms.DataGridColumnStyle through the <see cref='System.Collections.Enumerator'/> object's <see cref='System.Windows.Forms.Enumerator.Remove'/> method. Use the System.Windows.Forms.GridColumnsStyleCollection object's <see cref='System.Windows.Forms.GridColumnsCollection.Remove'/> method instead.
/// </exception>
/// <remarks>
/// <para>
/// Because this implementation doesn't support the removal
/// of System.Windows.Forms.DataGridColumnStyle objects through the <see cref='System.Collections.Enumerator'/>
/// class's <see cref='System.Windows.Forms.Enumerator.Remove'/> method, you must use the <see cref='System.Windows.Forms.DataGridCollection'/> class's <see cref='System.Windows.Forms.GridColumnsCollection.Remove'/>
/// method instead.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// The following example gets an <see cref='System.Collections.IEnumerator'/> for that iterates through the System.Windows.Forms.GridColumnsStyleCollection. If a column in the collection is of type <see cref='System.Windows.Forms.DataGridBoolColumn'/>, it is deleted.
/// </para>
/// <code lang='VB'>
/// Private Sub RemoveBoolColumns()
/// Dim ie As System.Collections.IEnumerator
/// Dim dgCol As DataGridColumn
/// Set ie = DataGrid1.GridColumns.GetEnumerator(true)
/// Do While ie.GetNext
/// Set dgCol = ie.GetObject
///
/// If dgCol.ToString = "DataGridBoolColumn" Then
/// DataGrid1.GridColumns.Remove dgCol
/// End If
/// Loop
/// End If
/// </code>
/// </example>
/// <seealso cref='System.Collections.IEnumerator'/>
/// <seealso cref='System.Windows.Forms.IEnumerator.GetNext'/>
/// <seealso cref='System.Windows.Forms.IEnumerator.GetObject'/>
/// <seealso cref='System.Windows.Forms.GridColumnsCollection.Remove'/>
public override IEnumerator GetEnumerator(bool allowRemove) {
if (!allowRemove)
return GetEnumerator();
else
throw new NotSupportedException(SR.GetString(SR.DataGridColumnCollectionGetEnumerator));
}
*/
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.IndexOf"]/*' />
/// <devdoc>
/// <para>Gets the index of a specified System.Windows.Forms.DataGridColumnStyle.</para>
/// </devdoc>
public int IndexOf(DataGridColumnStyle element) {
int itemCount = items.Count;
for (int i = 0; i < itemCount; ++i) {
DataGridColumnStyle column = (DataGridColumnStyle)items[i];
if (element == column)
return i;
}
return -1;
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.OnCollectionChanged"]/*' />
/// <devdoc>
/// <para>Raises the System.Windows.Forms.GridColumnsCollection.CollectionChanged event.</para>
/// </devdoc>
protected void OnCollectionChanged(CollectionChangeEventArgs e) {
if (onCollectionChanged != null)
onCollectionChanged(this, e);
DataGrid grid = owner.DataGrid;
if (grid != null) {
grid.checkHierarchy = true;
}
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.Remove"]/*' />
/// <devdoc>
/// <para>Removes the specified System.Windows.Forms.DataGridColumnStyle from the System.Windows.Forms.GridColumnsStyleCollection.</para>
/// </devdoc>
public void Remove(DataGridColumnStyle column) {
if (this.isDefault) {
throw new ArgumentException(SR.GetString(SR.DataGridDefaultColumnCollectionChanged));
}
int columnIndex = -1;
int itemsCount = items.Count;
for (int i = 0; i < itemsCount; ++i)
if (items[i] == column) {
columnIndex = i;
break;
}
if (columnIndex == -1)
throw new InvalidOperationException(SR.GetString(SR.DataGridColumnCollectionMissing));
else
RemoveAt(columnIndex);
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.RemoveAt"]/*' />
/// <devdoc>
/// <para>Removes the System.Windows.Forms.DataGridColumnStyle with the specified index from the System.Windows.Forms.GridColumnsStyleCollection.</para>
/// </devdoc>
public void RemoveAt(int index) {
if (this.isDefault) {
throw new ArgumentException(SR.GetString(SR.DataGridDefaultColumnCollectionChanged));
}
DataGridColumnStyle toRemove = (DataGridColumnStyle)items[index];
toRemove.SetDataGridTableInColumn(null, true);
toRemove.MappingNameChanged -= new EventHandler(ColumnStyleMappingNameChanged);
toRemove.PropertyDescriptorChanged -= new EventHandler(ColumnStylePropDescChanged);
#if false
toRemove.RemoveOnPropertyChange(owner.OnColumnChanged);
#endif
items.RemoveAt(index);
OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, toRemove));
}
/// <include file='doc\DataGridColumnCollection.uex' path='docs/doc[@for="GridColumnStylesCollection.ResetPropertyDescriptors"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void ResetPropertyDescriptors() {
for (int i = 0; i < this.Count; i++) {
this[i].PropertyDescriptor = null;
}
}
}
}
| |
//
// SourceActions.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.Playlist.Gui;
using Banshee.Playlists.Formats;
using Banshee.SmartPlaylist;
namespace Banshee.Gui
{
public class SourceActions : BansheeActionGroup
{
public IHasSourceView SourceView {
get;
set;
}
public event Action<Source> Updated;
public Source ActionSource {
get { return ((SourceView == null) ? null : SourceView.HighlightedSource) ?? ActiveSource; }
}
public override PrimarySource ActivePrimarySource {
get { return (SourceView.HighlightedSource as PrimarySource) ?? base.ActivePrimarySource; }
}
public SourceActions () : base ("Source")
{
Add (new ActionEntry [] {
new ActionEntry ("NewPlaylistAction", null,
Catalog.GetString ("_New Playlist"), "<control>N",
Catalog.GetString ("Create a new empty playlist"), OnNewPlaylist),
new ActionEntry ("NewSmartPlaylistAction", null,
Catalog.GetString ("New _Smart Playlist..."), "",
Catalog.GetString ("Create a new smart playlist"), OnNewSmartPlaylist),
/*new ActionEntry ("NewSmartPlaylistFromSearchAction", null,
Catalog.GetString ("New _Smart Playlist _From Search"), null,
Catalog.GetString ("Create a new smart playlist from the current search"), OnNewSmartPlaylistFromSearch),*/
new ActionEntry ("SourceContextMenuAction", null,
String.Empty, null, null, OnSourceContextMenu),
new ActionEntry ("ImportSourceAction", null,
Catalog.GetString ("Import to Library"), null,
Catalog.GetString ("Import source to library"), OnImportSource),
new ActionEntry ("RenameSourceAction", null,
Catalog.GetString ("Rename"), "F2", Catalog.GetString ("Rename"), OnRenameSource),
new ActionEntry ("ExportPlaylistAction", null,
Catalog.GetString ("Export Playlist..."), null,
Catalog.GetString ("Export a playlist"), OnExportPlaylist),
new ActionEntry ("UnmapSourceAction", null,
Catalog.GetString ("Unmap"), "<shift>Delete", null, OnUnmapSource),
new ActionEntry ("SourcePropertiesAction", null,
Catalog.GetString ("Source Properties"), null, null, OnSourceProperties),
new ActionEntry ("SortChildrenAction", Stock.SortDescending,
Catalog.GetString ("Sort Children by"), null, null,
OnSortChildrenMenu),
new ActionEntry ("OpenSourceSwitcher", null,
Catalog.GetString ("Switch Source"), "G",
Catalog.GetString ("Switch to a source by typing its name"),
null),
new ActionEntry ("SourcePreferencesAction", null, Catalog.GetString ("Preferences"), null,
Catalog.GetString ("Edit preferences related to this source"), OnSourcePreferences),
});
this["NewSmartPlaylistAction"].ShortLabel = Catalog.GetString ("New _Smart Playlist");
this["NewPlaylistAction"].IconName = Stock.New;
this["UnmapSourceAction"].IconName = Stock.Delete;
this["SourcePropertiesAction"].IconName = Stock.Properties;
this["SortChildrenAction"].HideIfEmpty = false;
this["SourcePreferencesAction"].IconName = Stock.Preferences;
AddImportant (
new ActionEntry ("RefreshSmartPlaylistAction", Stock.Refresh,
Catalog.GetString ("Refresh"), null,
Catalog.GetString ("Refresh this randomly sorted smart playlist"), OnRefreshSmartPlaylist)
);
//ServiceManager.SourceManager.SourceUpdated += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceViewChanged += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceAdded += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceRemoved += OnPlayerEngineStateChanged;
ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
Actions.GlobalActions["EditMenuAction"].Activated += HandleEditMenuActivated;
}
#region State Event Handlers
private void HandleActiveSourceChanged (SourceEventArgs args)
{
ThreadAssist.ProxyToMain (() => {
UpdateActions ();
if (last_source != null) {
last_source.Updated -= HandleActiveSourceUpdated;
}
if (ActiveSource != null) {
ActiveSource.Updated += HandleActiveSourceUpdated;
}
});
}
private void HandleEditMenuActivated (object sender, EventArgs args)
{
UpdateActions ();
}
private void HandleActiveSourceUpdated (object o, EventArgs args)
{
ThreadAssist.ProxyToMain (() => {
UpdateActions (true);
});
}
#endregion
#region Action Event Handlers
private void OnNewPlaylist (object o, EventArgs args)
{
PlaylistSource playlist = new PlaylistSource (Catalog.GetString ("New Playlist"), ActivePrimarySource);
playlist.Save ();
playlist.PrimarySource.AddChildSource (playlist);
playlist.NotifyUser ();
SourceView.BeginRenameSource (playlist);
}
private void OnNewSmartPlaylist (object o, EventArgs args)
{
Editor ed = new Editor (ActivePrimarySource);
ed.RunDialog ();
}
/*private void OnNewSmartPlaylistFromSearch (object o, EventArgs args)
{
Source active_source = ServiceManager.SourceManager.ActiveSource;
QueryNode node = UserQueryParser.Parse (active_source.FilterQuery, BansheeQuery.FieldSet);
if (node == null) {
return;
}
// If the active source is a playlist or smart playlist, add that as a condition to the query
QueryListNode list_node = null;
if (active_source is PlaylistSource) {
list_node = new QueryListNode (Keyword.And);
list_node.AddChild (QueryTermNode.ParseUserQuery (BansheeQuery.FieldSet, String.Format ("playlistid:{0}", (active_source as PlaylistSource).DbId)));
list_node.AddChild (node);
} else if (active_source is SmartPlaylistSource) {
list_node = new QueryListNode (Keyword.And);
list_node.AddChild (QueryTermNode.ParseUserQuery (BansheeQuery.FieldSet, String.Format ("smartplaylistid:{0}", (active_source as SmartPlaylistSource).DbId)));
list_node.AddChild (node);
}
SmartPlaylistSource playlist = new SmartPlaylistSource (active_source.FilterQuery);
playlist.ConditionTree = list_node ?? node;
playlist.Save ();
ServiceManager.SourceManager.Library.AddChildSource (playlist);
playlist.NotifyUpdated ();
// TODO should begin editing the name after making it, but this changed
// the ActiveSource to the new playlist and we don't want that.
//SourceView.BeginRenameSource (playlist);
}*/
private void OnSourceContextMenu (object o, EventArgs args)
{
UpdateActions ();
string path = ActionSource.Properties.Get<string> ("GtkActionPath") ?? "/SourceContextMenu";
Gtk.Menu menu = Actions.UIManager.GetWidget (path) as Menu;
if (menu == null || menu.Children.Length == 0) {
SourceView.ResetHighlight ();
UpdateActions ();
return;
}
int visible_children = 0;
foreach (Widget child in menu) {
if (child.Visible) {
visible_children++;
}
}
if (visible_children == 0) {
SourceView.ResetHighlight ();
UpdateActions ();
return;
}
menu.Show ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.SelectionDone += delegate {
SourceView.ResetHighlight ();
UpdateActions ();
};
}
private void OnImportSource (object o, EventArgs args)
{
((IImportSource)ActionSource).Import ();
}
private void OnRenameSource (object o, EventArgs args)
{
SourceView.BeginRenameSource (ActionSource);
}
private void OnExportPlaylist (object o, EventArgs args)
{
AbstractPlaylistSource source = ActionSource as AbstractPlaylistSource;
if (source == null) {
return;
}
source.Activate ();
PlaylistExportDialog chooser = new PlaylistExportDialog (source.Name, PrimaryWindow);
string uri = null;
PlaylistFormatDescription format = null;
int response = chooser.Run ();
if (response == (int) ResponseType.Ok) {
uri = chooser.Uri;
// Get the format that the user selected.
format = chooser.GetExportFormat ();
}
chooser.Destroy ();
if (uri == null) {
// User cancelled export.
return;
}
try {
IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type);
SafeUri suri = new SafeUri (uri);
if (suri.IsLocalPath) {
playlist.BaseUri = new Uri (System.IO.Path.GetDirectoryName (suri.LocalPath));
}
playlist.Save (Banshee.IO.File.OpenWrite (new SafeUri (uri), true), source);
} catch (Exception e) {
Console.WriteLine (e);
Log.Error (Catalog.GetString ("Could not export playlist"), e.Message, true);
}
}
private void OnUnmapSource (object o, EventArgs args)
{
IUnmapableSource source = ActionSource as IUnmapableSource;
if (source != null && source.CanUnmap && (!source.ConfirmBeforeUnmap || ConfirmUnmap (source)))
source.Unmap ();
}
private void OnRefreshSmartPlaylist (object o, EventArgs args)
{
SmartPlaylistSource playlist = ActionSource as SmartPlaylistSource;
if (playlist != null && playlist.CanRefresh) {
playlist.RefreshAndReload ();
}
}
private void OnSourceProperties (object o, EventArgs args)
{
if (ActionSource.Properties.Contains ("SourceProperties.GuiHandler")) {
ActionSource.Properties.Get<Source.OpenPropertiesDelegate> ("SourceProperties.GuiHandler") ();
return;
}
SmartPlaylistSource source = ActionSource as SmartPlaylistSource;
if (source != null) {
Editor ed = new Editor (source);
ed.RunDialog ();
}
}
private void OnSortChildrenMenu (object o, EventArgs args)
{
foreach (Widget proxy_widget in this["SortChildrenAction"].Proxies) {
MenuItem menu = proxy_widget as MenuItem;
if (menu == null) {
continue;
}
Menu submenu = BuildSortMenu (ActionSource);
menu.Submenu = submenu;
submenu.ShowAll ();
}
}
private void OnSourcePreferences (object o, EventArgs args)
{
try {
Banshee.Preferences.Gui.PreferenceDialog dialog = new Banshee.Preferences.Gui.PreferenceDialog ();
dialog.ShowSourcePageId (ActionSource.PreferencesPageId);
dialog.Run ();
dialog.Destroy ();
} catch (ApplicationException) {
}
}
#endregion
#region Utility Methods
private Source last_source = null;
private void UpdateActions ()
{
UpdateActions (false);
}
private void UpdateActions (bool force)
{
Source source = ActionSource;
if ((force || source != last_source) && source != null) {
IUnmapableSource unmapable = (source as IUnmapableSource);
IImportSource import_source = (source as IImportSource);
SmartPlaylistSource smart_playlist = (source as SmartPlaylistSource);
PrimarySource primary_source = (source as PrimarySource) ?? (source.Parent as PrimarySource);
UpdateAction ("UnmapSourceAction", unmapable != null, unmapable != null && unmapable.CanUnmap, source);
UpdateAction ("RenameSourceAction", source.CanRename, true, null);
UpdateAction ("ImportSourceAction", import_source != null, import_source != null && import_source.CanImport, source);
UpdateAction ("ExportPlaylistAction", source is AbstractPlaylistSource, true, source);
UpdateAction ("SourcePropertiesAction", source.HasProperties, true, source);
UpdateAction ("SourcePreferencesAction", source.PreferencesPageId != null, true, source);
UpdateAction ("RefreshSmartPlaylistAction", smart_playlist != null && smart_playlist.CanRefresh, true, source);
this["OpenSourceSwitcher"].Visible = false;
bool playlists_writable = primary_source != null && primary_source.SupportsPlaylists && !primary_source.PlaylistsReadOnly;
UpdateAction ("NewPlaylistAction", playlists_writable, true, source);
UpdateAction ("NewSmartPlaylistAction", playlists_writable, true, source);
/*UpdateAction ("NewSmartPlaylistFromSearchAction", (source is LibrarySource || source.Parent is LibrarySource),
!String.IsNullOrEmpty (source.FilterQuery), source);*/
IFilterableSource filterable_source = source as IFilterableSource;
bool has_browser = filterable_source != null && filterable_source.AvailableFilters.Count > 0;
ActionGroup browser_actions = Actions.FindActionGroup ("BrowserView");
if (browser_actions != null) {
UpdateAction (browser_actions["BrowserTopAction"], has_browser);
UpdateAction (browser_actions["BrowserLeftAction"], has_browser);
UpdateAction (browser_actions["BrowserVisibleAction"], has_browser);
}
ActionGroup browser_config_actions = Actions.FindActionGroup ("BrowserConfiguration");
if (browser_config_actions != null) {
// TODO: Be more specific than has_browser. Those actions have no effect
// on some sources that have a browser, like podcasts or radio.
UpdateAction (browser_config_actions["BrowserContentMenuAction"], has_browser);
}
last_source = source;
}
if (source != null) {
UpdateAction ("SortChildrenAction", source.ChildSortTypes.Length > 0 && source.Children.Count > 1, true, source);
}
Action<Source> handler = Updated;
if (handler != null) {
handler (source);
}
}
private static bool ConfirmUnmap (IUnmapableSource source)
{
string key = "no_confirm_unmap_" + source.GetType ().Name.ToLower ();
bool do_not_ask = ConfigurationClient.Instance.Get<bool> ("sources", key, false);
if (do_not_ask) {
return true;
}
Hyena.Widgets.HigMessageDialog dialog = new Hyena.Widgets.HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
Gtk.DialogFlags.Modal,
Gtk.MessageType.Question,
Gtk.ButtonsType.Cancel,
String.Format (Catalog.GetString ("Are you sure you want to delete this {0}?"),
source.GenericName.ToLower ()),
source.Name);
dialog.AddButton (Gtk.Stock.Delete, Gtk.ResponseType.Ok, false);
Gtk.Alignment alignment = new Gtk.Alignment (0.0f, 0.0f, 0.0f, 0.0f);
alignment.TopPadding = 10;
Gtk.CheckButton confirm_button = new Gtk.CheckButton (String.Format (Catalog.GetString (
"Do not ask me this again"), source.GenericName.ToLower ()));
confirm_button.Toggled += delegate {
do_not_ask = confirm_button.Active;
};
alignment.Add (confirm_button);
alignment.ShowAll ();
dialog.LabelVBox.PackStart (alignment, false, false, 0);
try {
if (dialog.Run () == (int)Gtk.ResponseType.Ok) {
ConfigurationClient.Instance.Set<bool> ("sources", key, do_not_ask);
return true;
}
return false;
} finally {
dialog.Destroy ();
}
}
private Menu BuildSortMenu (Source source)
{
Menu menu = new Menu ();
RadioMenuItem [] group = null;
foreach (SourceSortType sort_type in source.ChildSortTypes) {
RadioMenuItem item = new RadioMenuItem (group, sort_type.Label);
group = item.Group;
item.Active = (sort_type == source.ActiveChildSort);
item.Toggled += BuildSortChangedHandler (source, sort_type);
menu.Append (item);
}
menu.Append (new SeparatorMenuItem ());
CheckMenuItem sort_types_item = new CheckMenuItem (Catalog.GetString ("Separate by Type"));
sort_types_item.Active = source.SeparateChildrenByType;
sort_types_item.Toggled += OnSeparateTypesChanged;
menu.Append (sort_types_item);
return menu;
}
private void OnSeparateTypesChanged (object o, EventArgs args)
{
CheckMenuItem item = o as CheckMenuItem;
if (item != null) {
ActionSource.SeparateChildrenByType = item.Active;
}
}
private static EventHandler BuildSortChangedHandler (Source source, SourceSortType sort_type)
{
return delegate (object sender, EventArgs args) {
RadioMenuItem item = sender as RadioMenuItem;
if (item != null && item.Active) {
source.SortChildSources (sort_type);
}
};
}
#endregion
}
}
| |
//
// StatisticsPage.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
namespace Banshee.Gui.TrackEditor
{
internal class FixedTreeView : TreeView
{
public FixedTreeView (ListStore model) : base (model)
{
}
protected override bool OnKeyPressEvent (Gdk.EventKey evnt)
{
if ((evnt.State & Gdk.ModifierType.ControlMask) != 0 &&
(evnt.Key == Gdk.Key.Page_Up || evnt.Key == Gdk.Key.Page_Down)) {
return false;
}
return base.OnKeyPressEvent (evnt);
}
}
public class StatisticsPage : ScrolledWindow, ITrackEditorPage
{
private CellRendererText name_renderer;
private CellRendererText value_renderer;
private ListStore model;
private TreeView view;
public StatisticsPage ()
{
ShadowType = ShadowType.In;
VscrollbarPolicy = PolicyType.Automatic;
HscrollbarPolicy = PolicyType.Never;
BorderWidth = 2;
view = new FixedTreeView (model);
view.HeadersVisible = false;
view.RowSeparatorFunc = new TreeViewRowSeparatorFunc (RowSeparatorFunc);
view.HasTooltip = true;
view.QueryTooltip += HandleQueryTooltip;
name_renderer = new CellRendererText ();
name_renderer.Alignment = Pango.Alignment.Right;
name_renderer.Weight = (int)Pango.Weight.Bold;
name_renderer.Xalign = 1.0f;
name_renderer.Scale = Pango.Scale.Small;
value_renderer = new CellRendererText ();
value_renderer.Ellipsize = Pango.EllipsizeMode.End;
value_renderer.Editable = true;
value_renderer.Scale = Pango.Scale.Small;
value_renderer.EditingStarted += delegate(object o, EditingStartedArgs args) {
var entry = args.Editable as Entry;
if (entry != null) {
entry.IsEditable = false;
}
};
view.AppendColumn (Catalog.GetString ("Name"), name_renderer, "text", 0);
view.AppendColumn (Catalog.GetString ("Value"), value_renderer, "text", 1);
Add (view);
ShowAll ();
}
public CellRendererText NameRenderer { get { return name_renderer; } }
public CellRendererText ValueRenderer { get { return value_renderer; } }
private bool RowSeparatorFunc (TreeModel model, TreeIter iter)
{
return (bool)model.GetValue (iter, 2);
}
private void HandleQueryTooltip(object o, QueryTooltipArgs args)
{
TreePath path;
TreeIter iter;
if (view.GetPathAtPos (args.X, args.Y, out path) && view.Model.GetIter (out iter, path)) {
string text = (string)view.Model.GetValue (iter, 1);
if (!String.IsNullOrEmpty (text)) {
using (var layout = new Pango.Layout (view.PangoContext)) {
layout.FontDescription = value_renderer.FontDesc;
layout.SetText (text);
layout.Attributes = new Pango.AttrList ();
layout.Attributes.Insert (new Pango.AttrScale (value_renderer.Scale));
int width, height;
layout.GetPixelSize (out width, out height);
var column = view.GetColumn (1);
var column_width = column.Width - 2 * value_renderer.Xpad -
(int)view.StyleGetProperty ("horizontal-separator") -
2 * (int)view.StyleGetProperty ("focus-line-width");
if (width > column_width) {
args.Tooltip.Text = text;
view.SetTooltipCell (args.Tooltip, path, column, value_renderer);
args.RetVal = true;
}
}
}
}
// Work around ref counting SIGSEGV, see http://bugzilla.gnome.org/show_bug.cgi?id=478519#c9
if (args.Tooltip != null) {
args.Tooltip.Dispose ();
}
}
protected override void OnStyleSet (Style previous_style)
{
base.OnStyleSet (previous_style);
name_renderer.CellBackgroundGdk = Style.Background (StateType.Normal);
}
public void Initialize (TrackEditorDialog dialog)
{
}
public void LoadTrack (EditorTrackInfo track)
{
model = null;
CreateModel ();
TagLib.File file = track.GetTaglibFile ();
if (track.Uri.IsLocalPath) {
string path = track.Uri.AbsolutePath;
AddItem (Catalog.GetString ("File Name:"), System.IO.Path.GetFileName (path));
AddItem (Catalog.GetString ("Directory:"), System.IO.Path.GetDirectoryName (path));
AddItem (Catalog.GetString ("Full Path:"), path);
try {
AddFileSizeItem (Banshee.IO.File.GetSize (track.Uri));
} catch {
}
} else {
AddItem (Catalog.GetString ("URI:"), track.Uri.AbsoluteUri);
AddFileSizeItem (track.FileSize);
}
AddSeparator ();
if (file != null) {
System.Text.StringBuilder builder = new System.Text.StringBuilder ();
Banshee.Sources.DurationStatusFormatters.ConfusingPreciseFormatter (builder, file.Properties.Duration);
AddItem (Catalog.GetString ("Duration:"), String.Format ("{0} ({1}ms)",
builder, file.Properties.Duration.TotalMilliseconds));
AddItem (Catalog.GetString ("Audio Bitrate:"), String.Format ("{0} KB/sec",
file.Properties.AudioBitrate));
AddItem (Catalog.GetString ("Audio Sample Rate:"), String.Format ("{0} Hz",
file.Properties.AudioSampleRate));
AddItem (Catalog.GetString ("Audio Channels:"), file.Properties.AudioChannels);
if (file.Properties.BitsPerSample > 0) {
AddItem (Catalog.GetString ("Bits Per Sample:"), String.Format ("{0} bits",
file.Properties.BitsPerSample));
}
if ((file.Properties.MediaTypes & TagLib.MediaTypes.Video) != 0) {
AddItem (Catalog.GetString ("Video Dimensions:"), String.Format ("{0}x{1}",
file.Properties.VideoWidth, file.Properties.VideoHeight));
}
foreach (TagLib.ICodec codec in file.Properties.Codecs) {
if (codec != null) {
/* Translators: {0} is the description of the codec */
AddItem (String.Format (Catalog.GetString ("{0} Codec:"),
codec.MediaTypes.ToString ()), codec.Description);
}
}
AddItem (Catalog.GetString ("Container Formats:"), file.TagTypes.ToString ());
AddSeparator ();
file.Dispose ();
}
AddItem (Catalog.GetString ("Imported On:"), track.DateAdded > DateTime.MinValue
? track.DateAdded.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Last Played:"), track.LastPlayed > DateTime.MinValue
? track.LastPlayed.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Last Skipped:"), track.LastSkipped > DateTime.MinValue
? track.LastSkipped.ToString () : Catalog.GetString ("Unknown"));
AddItem (Catalog.GetString ("Play Count:"), track.PlayCount);
AddItem (Catalog.GetString ("Skip Count:"), track.SkipCount);
AddItem (Catalog.GetString ("Score:"), track.Score);
}
private void AddFileSizeItem (long bytes)
{
Hyena.Query.FileSizeQueryValue value = new Hyena.Query.FileSizeQueryValue (bytes);
AddItem (Catalog.GetString ("File Size:"), String.Format ("{0} ({1} {2})",
value.ToUserQuery (), bytes, Catalog.GetString ("bytes")));
}
private void CreateModel ()
{
if (model == null) {
model = new ListStore (typeof (string), typeof (string), typeof (bool));
view.Model = model;
}
}
public void AddItem (string name, object value)
{
CreateModel ();
if (name != null && value != null) {
model.AppendValues (name, value.ToString (), false);
}
}
public void AddSeparator ()
{
CreateModel ();
model.AppendValues (String.Empty, String.Empty, true);
}
public int Order {
get { return 40; }
}
public string Title {
get { return Catalog.GetString ("Properties"); }
}
public PageType PageType {
get { return PageType.View; }
}
public Gtk.Widget TabWidget {
get { return null; }
}
public Gtk.Widget Widget {
get { return this; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// These helper methods are known to a NUTC intrinsic used to implement the Comparer<T> class. We don't use them directly
// from the framework and they have nothing to do with Reflection.
//
// These methods need to be housed in a framework assembly that's part of SharedLibrary. System.Private.Reflection.Execution is part of
// the SharedLibrary so it got picked to be the host.
//
// The general issue here is that Comparer<T>.get_Default is not written in a manner which fully supports IEquatable
// and Nullable types. Due to point in time restrictions it is not possible to change that code. So, the compiler will instead
// replace the IL code within get_Default to call one of GetUnknownComparer, GetKnownGenericComparer,
// GetKnownNullableComparer, GetKnownEnumComparer or GetKnownObjectComparer based on what sort of
// type is being compared.
using System;
using System.Collections;
using System.Collections.Generic;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
namespace Internal.IntrinsicSupport
{
internal static class ComparerHelpers
{
private static bool ImplementsIComparable(RuntimeTypeHandle t)
{
int interfaceCount = RuntimeAugments.GetInterfaceCount(t);
for (int i = 0; i < interfaceCount; i++)
{
RuntimeTypeHandle interfaceType = RuntimeAugments.GetInterface(t, i);
if (!RuntimeAugments.IsGenericType(interfaceType))
continue;
RuntimeTypeHandle genericDefinition;
RuntimeTypeHandle[] genericTypeArgs;
bool success = TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeComponents(interfaceType,
out genericDefinition,
out genericTypeArgs);
if (success)
{
if (genericDefinition.Equals(typeof(IComparable<>).TypeHandle))
{
if (genericTypeArgs.Length != 1)
continue;
if (RuntimeAugments.IsValueType(t))
{
if (genericTypeArgs[0].Equals(t))
{
return true;
}
}
else if (RuntimeAugments.IsAssignableFrom(genericTypeArgs[0], t))
{
return true;
}
}
}
}
return false;
}
private static object GetComparer(RuntimeTypeHandle t)
{
RuntimeTypeHandle comparerType;
RuntimeTypeHandle openComparerType = default(RuntimeTypeHandle);
RuntimeTypeHandle comparerTypeArgument = default(RuntimeTypeHandle);
if (RuntimeAugments.IsNullable(t))
{
RuntimeTypeHandle nullableType = RuntimeAugments.GetNullableType(t);
if (ImplementsIComparable(nullableType))
{
openComparerType = typeof(NullableComparer<>).TypeHandle;
comparerTypeArgument = nullableType;
}
}
if (openComparerType.Equals(default(RuntimeTypeHandle)))
{
if (ImplementsIComparable(t))
{
openComparerType = typeof(GenericComparer<>).TypeHandle;
comparerTypeArgument = t;
}
else
{
openComparerType = typeof(ObjectComparer<>).TypeHandle;
comparerTypeArgument = t;
}
}
bool success = TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(openComparerType, new RuntimeTypeHandle[] { comparerTypeArgument }, out comparerType);
if (!success)
{
Environment.FailFast("Unable to create comparer");
}
return RuntimeAugments.NewObject(comparerType);
}
private static Comparer<T> GetUnknownComparer<T>()
{
return (Comparer<T>)GetComparer(typeof(T).TypeHandle);
}
private static Comparer<T> GetKnownGenericComparer<T>() where T : IComparable<T>
{
return new GenericComparer<T>();
}
private static Comparer<Nullable<U>> GetKnownNullableComparer<U>() where U : struct, IComparable<U>
{
return new NullableComparer<U>();
}
private static Comparer<T> GetKnownObjectComparer<T>()
{
return new ObjectComparer<T>();
}
// This routine emulates System.Collection.Comparer.Default.Compare(), which lives in the System.Collections.NonGenerics contract.
// To avoid adding a reference to that contract just for this hack, we'll replicate the implementation here.
private static int CompareObjects(object x, object y)
{
if (x == y)
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
{
// System.Collection.Comparer.Default.Compare() compares strings using the CurrentCulture.
string sx = x as string;
string sy = y as string;
if (sx != null && sy != null)
return string.Compare(sx, sy, StringComparison.CurrentCulture);
}
IComparable ix = x as IComparable;
if (ix != null)
return ix.CompareTo(y);
IComparable iy = y as IComparable;
if (iy != null)
return -iy.CompareTo(x);
throw new ArgumentException(SR.Argument_ImplementIComparable);
}
//-----------------------------------------------------------------------
// Implementations of EqualityComparer<T> for the various possible scenarios
//-----------------------------------------------------------------------
private sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
public sealed override int Compare(T x, T y)
{
if (x != null)
{
if (y != null)
return x.CompareTo(y);
return 1;
}
if (y != null)
return -1;
return 0;
}
}
private sealed class NullableComparer<T> : Comparer<Nullable<T>> where T : struct, IComparable<T>
{
public sealed override int Compare(Nullable<T> x, Nullable<T> y)
{
if (x.HasValue)
{
if (y.HasValue)
return x.Value.CompareTo(y.Value);
return 1;
}
if (y.HasValue)
return -1;
return 0;
}
}
private sealed class ObjectComparer<T> : Comparer<T>
{
public sealed override int Compare(T x, T y)
{
return ComparerHelpers.CompareObjects(x, y);
}
}
}
}
| |
// Copyright 2008-2009 Louis DeJardin - http://whereslou.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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Spark.Compiler.ChunkVisitors
{
public abstract class AbstractChunkVisitor : IChunkVisitor
{
private readonly Stack<RenderPartialChunk> _renderPartialStack = new Stack<RenderPartialChunk>();
public RenderPartialChunk OuterPartial
{
get { return _renderPartialStack.Any() ? _renderPartialStack.Peek() : null; }
}
public void Accept(IList<Chunk> chunks)
{
if (chunks == null) throw new ArgumentNullException("chunks");
foreach (var chunk in chunks)
Accept(chunk);
}
public void Accept(Chunk chunk)
{
if (chunk == null) throw new ArgumentNullException("chunk");
if (chunk is SendLiteralChunk)
{
Visit((SendLiteralChunk)chunk);
}
else if (chunk is LocalVariableChunk)
{
Visit((LocalVariableChunk)chunk);
}
else if (chunk is SendExpressionChunk)
{
Visit((SendExpressionChunk)chunk);
}
else if (chunk is ForEachChunk)
{
Visit((ForEachChunk)chunk);
}
else if (chunk is ScopeChunk)
{
Visit((ScopeChunk)chunk);
}
else if (chunk is GlobalVariableChunk)
{
Visit((GlobalVariableChunk)chunk);
}
else if (chunk is AssignVariableChunk)
{
Visit((AssignVariableChunk)chunk);
}
else if (chunk is ContentChunk)
{
Visit((ContentChunk)chunk);
}
else if (chunk is ContentSetChunk)
{
Visit((ContentSetChunk)chunk);
}
else if (chunk is UseContentChunk)
{
Visit((UseContentChunk)chunk);
}
else if (chunk is RenderPartialChunk)
{
Visit((RenderPartialChunk)chunk);
}
else if (chunk is RenderSectionChunk)
{
Visit((RenderSectionChunk)chunk);
}
else if (chunk is ViewDataChunk)
{
Visit((ViewDataChunk)chunk);
}
else if (chunk is ViewDataModelChunk)
{
Visit((ViewDataModelChunk)chunk);
}
else if (chunk is UseNamespaceChunk)
{
Visit((UseNamespaceChunk)chunk);
}
else if (chunk is ConditionalChunk)
{
Visit((ConditionalChunk)chunk);
}
else if (chunk is ExtensionChunk)
{
Visit((ExtensionChunk)chunk);
}
else if (chunk is CodeStatementChunk)
{
Visit((CodeStatementChunk)chunk);
}
else if (chunk is MacroChunk)
{
Visit((MacroChunk)chunk);
}
else if (chunk is UseAssemblyChunk)
{
Visit((UseAssemblyChunk)chunk);
}
else if (chunk is UseImportChunk)
{
Visit((UseImportChunk)chunk);
}
else if (chunk is DefaultVariableChunk)
{
Visit((DefaultVariableChunk)chunk);
}
else if (chunk is UseMasterChunk)
{
Visit((UseMasterChunk)chunk);
}
else if (chunk is PageBaseTypeChunk)
{
Visit((PageBaseTypeChunk)chunk);
}
else if (chunk is CacheChunk)
{
Visit((CacheChunk)chunk);
}
else if (chunk is MarkdownChunk)
{
Visit((MarkdownChunk)chunk);
}
else
{
throw new CompilerException(string.Format("Unknown chunk type {0}", chunk.GetType().Name));
}
}
protected abstract void Visit(UseMasterChunk chunk);
protected abstract void Visit(DefaultVariableChunk chunk);
protected abstract void Visit(UseImportChunk chunk);
protected abstract void Visit(ContentSetChunk chunk);
protected abstract void Visit(RenderSectionChunk chunk);
protected abstract void Visit(UseAssemblyChunk chunk);
protected abstract void Visit(MacroChunk chunk);
protected abstract void Visit(CodeStatementChunk chunk);
protected abstract void Visit(ExtensionChunk chunk);
protected abstract void Visit(ConditionalChunk chunk);
protected abstract void Visit(ViewDataModelChunk chunk);
protected abstract void Visit(ViewDataChunk chunk);
protected abstract void Visit(RenderPartialChunk chunk);
protected abstract void Visit(AssignVariableChunk chunk);
protected abstract void Visit(UseContentChunk chunk);
protected abstract void Visit(GlobalVariableChunk chunk);
protected abstract void Visit(ScopeChunk chunk);
protected abstract void Visit(ForEachChunk chunk);
protected abstract void Visit(SendLiteralChunk chunk);
protected abstract void Visit(LocalVariableChunk chunk);
protected abstract void Visit(SendExpressionChunk chunk);
protected abstract void Visit(ContentChunk chunk);
protected abstract void Visit(UseNamespaceChunk chunk);
protected abstract void Visit(PageBaseTypeChunk chunk);
protected abstract void Visit(CacheChunk chunk);
protected abstract void Visit(MarkdownChunk chunk);
protected void EnterRenderPartial(RenderPartialChunk chunk)
{
// throw an exception if a partial is entered recursively
if (_renderPartialStack.Any(recursed => recursed.FileContext == chunk.FileContext))
{
var sb = new StringBuilder();
foreach (var recursed in _renderPartialStack.Concat(new[] { chunk }))
{
sb
.Append(recursed.Position.SourceContext.FileName)
.Append("(")
.Append(recursed.Position.Line)
.Append(",")
.Append(recursed.Position.Line)
.Append("): rendering partial '")
.Append(recursed.Name)
.AppendLine("'");
}
throw new CompilerException(string.Format("Recursive rendering of partial files not possible.\r\n{0}", sb));
}
_renderPartialStack.Push(chunk);
}
protected RenderPartialChunk ExitRenderPartial()
{
if (_renderPartialStack.Any() == false)
{
throw new CompilerException("Internal compiler error. Partial stack unexpectedly empty.");
}
return _renderPartialStack.Pop();
}
protected void ExitRenderPartial(RenderPartialChunk expectedTopChunk)
{
var topChunk = ExitRenderPartial();
if (expectedTopChunk != topChunk)
{
throw new CompilerException(string.Format(
"Internal compiler error. Expected to be leaving partial {0} but was {1}",
expectedTopChunk.FileContext.ViewSourcePath,
topChunk.FileContext.ViewSourcePath));
}
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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 Autofac;
using Autofac.Builder;
using log4net;
using MindTouch.Dream.AmazonS3;
using MindTouch.Dream.Test;
using MindTouch.Extensions.Time;
using MindTouch.Tasking;
using MindTouch.Xml;
using Moq;
using NUnit.Framework;
namespace MindTouch.Dream.Storage.Test {
using Helper = AmazonS3TestHelpers;
[TestFixture]
public class AmazonS3PrivateStorageTests {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private DreamHostInfo _hostInfo;
private Mock<IAmazonS3Client> _s3ClientMock;
private MockServiceInfo _mockService;
private string _storageRoot;
private string _rootPath;
[TestFixtureSetUp]
public void Init() {
var config = new XDoc("config")
.Start("storage")
.Attr("type", "s3")
.Elem("root", "rootpath")
.Elem("bucket", "bucket")
.Elem("privatekey", "private")
.Elem("publickey", "public")
.End();
var builder = new ContainerBuilder();
builder.Register((c, p) => {
var s3Config = p.TypedAs<AmazonS3ClientConfig>();
_rootPath = s3Config.RootPath;
Assert.AreEqual("http://s3.amazonaws.com", s3Config.S3BaseUri.ToString());
Assert.AreEqual("bucket", s3Config.Bucket);
Assert.AreEqual("private", s3Config.PrivateKey);
Assert.AreEqual("public", s3Config.PublicKey);
Assert.IsNull(_s3ClientMock, "storage already resolved");
_s3ClientMock = new Mock<IAmazonS3Client>();
return _s3ClientMock.Object;
}).As<IAmazonS3Client>().ServiceScoped();
_hostInfo = DreamTestHelper.CreateRandomPortHost(config, builder.Build());
}
[SetUp]
public void Setup() {
_s3ClientMock = null;
_mockService = MockService.CreateMockServiceWithPrivateStorage(_hostInfo);
_storageRoot = _mockService.Service.Storage.Uri.LastSegment;
}
[Test]
public void Can_init() {
Assert.IsNotNull(_s3ClientMock);
Assert.AreEqual("rootpath/" + _storageRoot, _rootPath);
}
[Test]
public void Can_put_file_without_expiration_at_path() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar", It.Is<AmazonS3FileHandle>(y => Helper.ValidateFileHandle(y, data, null)))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_put_file_without_expiration_at_root() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo", It.Is<AmazonS3FileHandle>(y => Helper.ValidateFileHandle(y, data, null)))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo").Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_put_file_with_expiration() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar", It.Is<AmazonS3FileHandle>(y => Helper.ValidateFileHandle(y, data, 10.Seconds())))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").With("ttl", 10).Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Put_at_directory_path_fails() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.PutFile("foo/bar/", It.IsAny<AmazonS3FileHandle>())).Throws(new Exception("bad puppy")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Put(DreamMessage.Ok(MimeType.TEXT, data), new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_read_file() {
var data = StringUtil.CreateAlphaNumericKey(10);
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", false)).Returns(Helper.CreateFileInfo(data)).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Get(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(data, response.ToText());
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_head_file() {
var info = new AmazonS3DataInfo(new AmazonS3FileHandle() {
Expiration = null,
TimeToLive = null,
MimeType = MimeType.TEXT,
Modified = DateTime.UtcNow,
Size = 10,
});
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", true)).Returns(info).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Head(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(10, response.ContentLength);
_s3ClientMock.VerifyAll();
}
[Test]
public void Reading_nonexisting_file_returns_Not_Found() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar", false)).Returns((AmazonS3DataInfo)null).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Get(new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
Assert.AreEqual(DreamStatus.NotFound, response.Status);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_list_directory() {
var doc = new XDoc("files").Elem("x", StringUtil.CreateAlphaNumericKey(10));
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", false)).Returns(new AmazonS3DataInfo(doc)).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Get(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
Assert.AreEqual(doc.ToCompactString(), response.ToDocument().ToCompactString());
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_head_directory() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", true)).Returns(new AmazonS3DataInfo(new XDoc("x"))).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Head(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Listing_nonexisting_directory_returns_Not_Found() {
_s3ClientMock.Setup(x => x.GetDataInfo("foo/bar/", false)).Returns((AmazonS3DataInfo)null).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Get(new Result<DreamMessage>())
);
Assert.IsFalse(response.IsSuccessful);
Assert.AreEqual(DreamStatus.NotFound, response.Status);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_delete_file() {
_s3ClientMock.Setup(x => x.Delete("foo/bar")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").Delete(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
[Test]
public void Can_delete_directory() {
_s3ClientMock.Setup(x => x.Delete("foo/bar/")).AtMostOnce().Verifiable();
var response = _mockService.CallStorage(storage =>
storage.At("foo", "bar").WithTrailingSlash().Delete(new Result<DreamMessage>())
);
Assert.IsTrue(response.IsSuccessful);
_s3ClientMock.VerifyAll();
}
}
}
| |
//
// SourceActions.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Query;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Configuration;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.Playlist.Gui;
using Banshee.Playlists.Formats;
using Banshee.SmartPlaylist;
using Banshee.Query;
using Banshee.Gui.Dialogs;
namespace Banshee.Gui
{
public class SourceActions : BansheeActionGroup
{
private IHasSourceView source_view;
public IHasSourceView SourceView {
get { return source_view; }
set { source_view = value; }
}
public event Action<Source> Updated;
public Source ActionSource {
get { return ((SourceView == null) ? null : SourceView.HighlightedSource) ?? ActiveSource; }
}
public override PrimarySource ActivePrimarySource {
get { return (SourceView.HighlightedSource as PrimarySource) ?? base.ActivePrimarySource; }
}
public SourceActions () : base ("Source")
{
Add (new ActionEntry [] {
new ActionEntry ("NewPlaylistAction", null,
Catalog.GetString ("_New Playlist"), "<control>N",
Catalog.GetString ("Create a new empty playlist"), OnNewPlaylist),
new ActionEntry ("NewSmartPlaylistAction", null,
Catalog.GetString ("New _Smart Playlist..."), "",
Catalog.GetString ("Create a new smart playlist"), OnNewSmartPlaylist),
/*new ActionEntry ("NewSmartPlaylistFromSearchAction", null,
Catalog.GetString ("New _Smart Playlist _From Search"), null,
Catalog.GetString ("Create a new smart playlist from the current search"), OnNewSmartPlaylistFromSearch),*/
new ActionEntry ("SourceContextMenuAction", null,
String.Empty, null, null, OnSourceContextMenu),
new ActionEntry ("ImportSourceAction", null,
Catalog.GetString ("Import to Library"), null,
Catalog.GetString ("Import source to library"), OnImportSource),
new ActionEntry ("RenameSourceAction", null,
Catalog.GetString ("Rename"), "F2", Catalog.GetString ("Rename"), OnRenameSource),
new ActionEntry ("ExportPlaylistAction", null,
Catalog.GetString ("Export Playlist..."), null,
Catalog.GetString ("Export a playlist"), OnExportPlaylist),
new ActionEntry ("UnmapSourceAction", null,
Catalog.GetString ("Unmap"), "<shift>Delete", null, OnUnmapSource),
new ActionEntry ("SourcePropertiesAction", null,
Catalog.GetString ("Source Properties"), null, null, OnSourceProperties),
new ActionEntry ("SortChildrenAction", Stock.SortDescending,
Catalog.GetString ("Sort Children by"), null, null,
OnSortChildrenMenu),
new ActionEntry ("OpenSourceSwitcher", null,
Catalog.GetString ("Switch Source"), "G",
Catalog.GetString ("Switch to a source by typing its name"),
null),
new ActionEntry ("SourcePreferencesAction", null, Catalog.GetString ("Preferences"), null,
Catalog.GetString ("Edit preferences related to this source"), OnSourcePreferences),
});
this["NewSmartPlaylistAction"].ShortLabel = Catalog.GetString ("New _Smart Playlist");
this["NewPlaylistAction"].IconName = Stock.New;
this["UnmapSourceAction"].IconName = Stock.Delete;
this["SourcePropertiesAction"].IconName = Stock.Properties;
this["SortChildrenAction"].HideIfEmpty = false;
this["SourcePreferencesAction"].IconName = Stock.Preferences;
AddImportant (
new ActionEntry ("RefreshSmartPlaylistAction", Stock.Refresh,
Catalog.GetString ("Refresh"), null,
Catalog.GetString ("Refresh this randomly sorted smart playlist"), OnRefreshSmartPlaylist)
);
//ServiceManager.SourceManager.SourceUpdated += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceViewChanged += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceAdded += OnPlayerEngineStateChanged;
//ServiceManager.SourceManager.SourceRemoved += OnPlayerEngineStateChanged;
ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
Actions.GlobalActions["EditMenuAction"].Activated += HandleEditMenuActivated;
}
#region State Event Handlers
private void HandleActiveSourceChanged (SourceEventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
UpdateActions ();
if (last_source != null) {
last_source.Updated -= HandleActiveSourceUpdated;
}
if (ActiveSource != null) {
ActiveSource.Updated += HandleActiveSourceUpdated;
}
});
}
private void HandleEditMenuActivated (object sender, EventArgs args)
{
UpdateActions ();
}
private void HandleActiveSourceUpdated (object o, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
UpdateActions (true);
});
}
#endregion
#region Action Event Handlers
private void OnNewPlaylist (object o, EventArgs args)
{
PlaylistSource playlist = new PlaylistSource (Catalog.GetString ("New Playlist"), ActivePrimarySource);
playlist.Save ();
playlist.PrimarySource.AddChildSource (playlist);
playlist.NotifyUser ();
SourceView.BeginRenameSource (playlist);
}
private void OnNewSmartPlaylist (object o, EventArgs args)
{
Editor ed = new Editor (ActivePrimarySource);
ed.RunDialog ();
}
/*private void OnNewSmartPlaylistFromSearch (object o, EventArgs args)
{
Source active_source = ServiceManager.SourceManager.ActiveSource;
QueryNode node = UserQueryParser.Parse (active_source.FilterQuery, BansheeQuery.FieldSet);
if (node == null) {
return;
}
// If the active source is a playlist or smart playlist, add that as a condition to the query
QueryListNode list_node = null;
if (active_source is PlaylistSource) {
list_node = new QueryListNode (Keyword.And);
list_node.AddChild (QueryTermNode.ParseUserQuery (BansheeQuery.FieldSet, String.Format ("playlistid:{0}", (active_source as PlaylistSource).DbId)));
list_node.AddChild (node);
} else if (active_source is SmartPlaylistSource) {
list_node = new QueryListNode (Keyword.And);
list_node.AddChild (QueryTermNode.ParseUserQuery (BansheeQuery.FieldSet, String.Format ("smartplaylistid:{0}", (active_source as SmartPlaylistSource).DbId)));
list_node.AddChild (node);
}
SmartPlaylistSource playlist = new SmartPlaylistSource (active_source.FilterQuery);
playlist.ConditionTree = list_node ?? node;
playlist.Save ();
ServiceManager.SourceManager.Library.AddChildSource (playlist);
playlist.NotifyUpdated ();
// TODO should begin editing the name after making it, but this changed
// the ActiveSource to the new playlist and we don't want that.
//SourceView.BeginRenameSource (playlist);
}*/
private void OnSourceContextMenu (object o, EventArgs args)
{
UpdateActions ();
string path = ActionSource.Properties.Get<string> ("GtkActionPath") ?? "/SourceContextMenu";
Gtk.Menu menu = Actions.UIManager.GetWidget (path) as Menu;
if (menu == null || menu.Children.Length == 0) {
SourceView.ResetHighlight ();
UpdateActions ();
return;
}
int visible_children = 0;
foreach (Widget child in menu)
if (child.Visible)
visible_children++;
if (visible_children == 0) {
SourceView.ResetHighlight ();
UpdateActions ();
return;
}
menu.Show ();
menu.Popup (null, null, null, 0, Gtk.Global.CurrentEventTime);
menu.SelectionDone += delegate {
SourceView.ResetHighlight ();
UpdateActions ();
};
}
private void OnImportSource (object o, EventArgs args)
{
(ActionSource as IImportSource).Import ();
}
private void OnRenameSource (object o, EventArgs args)
{
SourceView.BeginRenameSource (ActionSource);
}
private void OnExportPlaylist (object o, EventArgs args)
{
AbstractPlaylistSource source = ActionSource as AbstractPlaylistSource;
if (source == null) {
return;
}
source.Activate ();
PlaylistExportDialog chooser = new PlaylistExportDialog (source.Name, PrimaryWindow);
string uri = null;
PlaylistFormatDescription format = null;
int response = chooser.Run ();
if (response == (int) ResponseType.Ok) {
uri = chooser.Uri;
// Get the format that the user selected.
format = chooser.GetExportFormat ();
}
chooser.Destroy ();
if (uri == null) {
// User cancelled export.
return;
}
try {
IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type);
SafeUri suri = new SafeUri (uri);
if (suri.IsLocalPath) {
playlist.BaseUri = new Uri (System.IO.Path.GetDirectoryName (suri.LocalPath));
}
playlist.Save (Banshee.IO.File.OpenWrite (new SafeUri (uri), true), source);
} catch (Exception e) {
Console.WriteLine (e);
Log.Error (Catalog.GetString ("Could not export playlist"), e.Message, true);
}
}
private void OnUnmapSource (object o, EventArgs args)
{
IUnmapableSource source = ActionSource as IUnmapableSource;
if (source != null && source.CanUnmap && (!source.ConfirmBeforeUnmap || ConfirmUnmap (source)))
source.Unmap ();
}
private void OnRefreshSmartPlaylist (object o, EventArgs args)
{
SmartPlaylistSource playlist = ActionSource as SmartPlaylistSource;
if (playlist != null && playlist.CanRefresh) {
playlist.RefreshAndReload ();
}
}
private void OnSourceProperties (object o, EventArgs args)
{
if (ActionSource.Properties.Contains ("SourceProperties.GuiHandler")) {
ActionSource.Properties.Get<Source.OpenPropertiesDelegate> ("SourceProperties.GuiHandler") ();
return;
}
SmartPlaylistSource source = ActionSource as SmartPlaylistSource;
if (source != null) {
Editor ed = new Editor (source);
ed.RunDialog ();
}
}
private void OnSortChildrenMenu (object o, EventArgs args)
{
foreach (Widget proxy_widget in this["SortChildrenAction"].Proxies) {
MenuItem menu = proxy_widget as MenuItem;
if (menu == null)
continue;
Menu submenu = BuildSortMenu (ActionSource);
menu.Submenu = submenu;
submenu.ShowAll ();
}
}
private void OnSourcePreferences (object o, EventArgs args)
{
try {
Banshee.Preferences.Gui.PreferenceDialog dialog = new Banshee.Preferences.Gui.PreferenceDialog ();
dialog.ShowSourcePageId (ActionSource.PreferencesPageId);
dialog.Run ();
dialog.Destroy ();
} catch (ApplicationException) {
}
}
#endregion
#region Utility Methods
private Source last_source = null;
private void UpdateActions ()
{
UpdateActions (false);
}
private void UpdateActions (bool force)
{
Source source = ActionSource;
if ((force || source != last_source) && source != null) {
IUnmapableSource unmapable = (source as IUnmapableSource);
IImportSource import_source = (source as IImportSource);
SmartPlaylistSource smart_playlist = (source as SmartPlaylistSource);
PrimarySource primary_source = (source as PrimarySource) ?? (source.Parent as PrimarySource);
UpdateAction ("UnmapSourceAction", unmapable != null, unmapable != null && unmapable.CanUnmap, source);
UpdateAction ("RenameSourceAction", source.CanRename, true, null);
UpdateAction ("ImportSourceAction", import_source != null, import_source != null && import_source.CanImport, source);
UpdateAction ("ExportPlaylistAction", source is AbstractPlaylistSource, true, source);
UpdateAction ("SourcePropertiesAction", source.HasProperties, true, source);
UpdateAction ("SourcePreferencesAction", source.PreferencesPageId != null, true, source);
UpdateAction ("RefreshSmartPlaylistAction", smart_playlist != null && smart_playlist.CanRefresh, true, source);
this["OpenSourceSwitcher"].Visible = false;
bool playlists_writable = primary_source != null && primary_source.SupportsPlaylists && !primary_source.PlaylistsReadOnly;
UpdateAction ("NewPlaylistAction", playlists_writable, true, source);
UpdateAction ("NewSmartPlaylistAction", playlists_writable, true, source);
/*UpdateAction ("NewSmartPlaylistFromSearchAction", (source is LibrarySource || source.Parent is LibrarySource),
!String.IsNullOrEmpty (source.FilterQuery), source);*/
IFilterableSource filterable_source = source as IFilterableSource;
bool has_browser = filterable_source != null && filterable_source.AvailableFilters.Count > 0;
ActionGroup browser_actions = Actions.FindActionGroup ("BrowserView");
if (browser_actions != null) {
UpdateAction (browser_actions["BrowserTopAction"], has_browser);
UpdateAction (browser_actions["BrowserLeftAction"], has_browser);
UpdateAction (browser_actions["BrowserVisibleAction"], has_browser);
}
ActionGroup browser_config_actions = Actions.FindActionGroup ("BrowserConfiguration");
if (browser_config_actions != null) {
// TODO: Be more specific than has_browser. Those actions have no effect
// on some sources that have a browser, like podcasts or radio.
UpdateAction (browser_config_actions["BrowserContentMenuAction"], has_browser);
}
last_source = source;
}
if (source != null) {
UpdateAction ("SortChildrenAction", source.ChildSortTypes.Length > 0 && source.Children.Count > 1, true, source);
}
Action<Source> handler = Updated;
if (handler != null) {
handler (source);
}
}
private static bool ConfirmUnmap (IUnmapableSource source)
{
string key = "no_confirm_unmap_" + source.GetType ().Name.ToLower ();
bool do_not_ask = ConfigurationClient.Get<bool> ("sources", key, false);
if (do_not_ask) {
return true;
}
Hyena.Widgets.HigMessageDialog dialog = new Hyena.Widgets.HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
Gtk.DialogFlags.Modal,
Gtk.MessageType.Question,
Gtk.ButtonsType.Cancel,
String.Format (Catalog.GetString ("Are you sure you want to delete this {0}?"),
source.GenericName.ToLower ()),
source.Name);
dialog.AddButton (Gtk.Stock.Delete, Gtk.ResponseType.Ok, false);
Gtk.Alignment alignment = new Gtk.Alignment (0.0f, 0.0f, 0.0f, 0.0f);
alignment.TopPadding = 10;
Gtk.CheckButton confirm_button = new Gtk.CheckButton (String.Format (Catalog.GetString (
"Do not ask me this again"), source.GenericName.ToLower ()));
confirm_button.Toggled += delegate {
do_not_ask = confirm_button.Active;
};
alignment.Add (confirm_button);
alignment.ShowAll ();
dialog.LabelVBox.PackStart (alignment, false, false, 0);
try {
if (dialog.Run () == (int)Gtk.ResponseType.Ok) {
ConfigurationClient.Set<bool> ("sources", key, do_not_ask);
return true;
}
return false;
} finally {
dialog.Destroy ();
}
}
private Menu BuildSortMenu (Source source)
{
Menu menu = new Menu ();
GLib.SList group = null;
foreach (SourceSortType sort_type in source.ChildSortTypes) {
RadioMenuItem item = new RadioMenuItem (group, sort_type.Label);
group = item.Group;
item.Active = (sort_type == source.ActiveChildSort);
item.Toggled += BuildSortChangedHandler (source, sort_type);
menu.Append (item);
}
menu.Append (new SeparatorMenuItem ());
CheckMenuItem sort_types_item = new CheckMenuItem (Catalog.GetString ("Separate by Type"));
sort_types_item.Active = source.SeparateChildrenByType;
sort_types_item.Toggled += OnSeparateTypesChanged;
menu.Append (sort_types_item);
return menu;
}
private void OnSeparateTypesChanged (object o, EventArgs args)
{
CheckMenuItem item = o as CheckMenuItem;
if (item != null) {
ActionSource.SeparateChildrenByType = item.Active;
}
}
private static EventHandler BuildSortChangedHandler (Source source, SourceSortType sort_type)
{
return delegate (object sender, EventArgs args) {
RadioMenuItem item = sender as RadioMenuItem;
if (item != null && item.Active) {
source.SortChildSources (sort_type);
}
};
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Linq;
using Common;
using Common.Controls;
using Common.Dialogs;
using DTA;
using Standardization;
using Fairweather.Service;
using TT = Versioning.TransType;
using System.Diagnostics;
namespace Screens
{
// autogenerated: D:\Scripts\struct_creator2.pl
[Serializable]
[DebuggerStepThrough]
public struct TE_Truncated_Entry
{
public TE_Truncated_Entry(int column,
int row,
int maximum_length,
string original,
string truncated)
: this() {
this.Column = column;
this.Row = row;
this.Maximum_Length = maximum_length;
this.Original = original;
this.Truncated = truncated;
}
public int Column {
get;
set;
}
public int Row {
get;
set;
}
public int Maximum_Length {
get;
set;
}
public string Original {
get;
set;
}
public string Truncated {
get;
set;
}
/* Boilerplate */
public override string ToString() {
string ret = "";
const string _null = "[null]";
#pragma warning disable 472
ret += "Column = " + this.Column == null ? _null : this.Column.ToString();
ret += ", ";
ret += "Row = " + this.Row == null ? _null : this.Row.ToString();
ret += ", ";
ret += "Maximum_Length = " + this.Maximum_Length == null ? _null : this.Maximum_Length.ToString();
ret += ", ";
ret += "Original = " + this.Original == null ? _null : this.Original.ToString();
ret += ", ";
ret += "Truncated = " + this.Truncated == null ? _null : this.Truncated.ToString();
#pragma warning restore
ret = "{TE_Truncated_Entry: " + ret + "}";
return ret;
}
public bool Equals(TE_Truncated_Entry obj2) {
#pragma warning disable 472
if (this.Column == null) {
if (obj2.Column != null)
return false;
}
else if (!this.Column.Equals(obj2.Column)) {
return false;
}
if (this.Row == null) {
if (obj2.Row != null)
return false;
}
else if (!this.Row.Equals(obj2.Row)) {
return false;
}
if (this.Maximum_Length == null) {
if (obj2.Maximum_Length != null)
return false;
}
else if (!this.Maximum_Length.Equals(obj2.Maximum_Length)) {
return false;
}
if (this.Original == null) {
if (obj2.Original != null)
return false;
}
else if (!this.Original.Equals(obj2.Original)) {
return false;
}
if (this.Truncated == null) {
if (obj2.Truncated != null)
return false;
}
else if (!this.Truncated.Equals(obj2.Truncated)) {
return false;
}
#pragma warning restore
return true;
}
public override bool Equals(object obj2) {
if (obj2 == null)
return false;
if (!(obj2 is TE_Truncated_Entry))
return false;
var ret = this.Equals((TE_Truncated_Entry)obj2);
return ret;
}
public static bool operator ==(TE_Truncated_Entry left, TE_Truncated_Entry right) {
var ret = left.Equals(right);
return ret;
}
public static bool operator !=(TE_Truncated_Entry left, TE_Truncated_Entry right) {
var ret = !left.Equals(right);
return ret;
}
public override int GetHashCode() {
#pragma warning disable 472
unchecked {
int ret = 23;
int temp;
if (this.Column != null) {
ret *= 31;
temp = this.Column.GetHashCode();
ret += temp;
}
if (this.Row != null) {
ret *= 31;
temp = this.Row.GetHashCode();
ret += temp;
}
if (this.Maximum_Length != null) {
ret *= 31;
temp = this.Maximum_Length.GetHashCode();
ret += temp;
}
if (this.Original != null) {
ret *= 31;
temp = this.Original.GetHashCode();
ret += temp;
}
if (this.Truncated != null) {
ret *= 31;
temp = this.Truncated.GetHashCode();
ret += temp;
}
return ret;
} // unchecked block
#pragma warning restore
} // method
}
}
| |
// <copyright file="IPlayGamesClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google 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.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using UnityEngine;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Defines an abstract interface for a Play Games Client.
/// </summary>
/// <remarks>Concrete implementations
/// might be, for example, the client for Android or for iOS. One fundamental concept
/// that implementors of this class must adhere to is stable authentication state.
/// This means that once Authenticate() returns true through its callback, the user is
/// considered to be forever after authenticated while the app is running. The implementation
/// must make sure that this is the case -- for example, it must try to silently
/// re-authenticate the user if authentication is lost or wait for the authentication
/// process to get fixed if it is temporarily in a bad state (such as when the
/// Activity in Android has just been brought to the foreground and the connection to
/// the Games services hasn't yet been established). To the user of this
/// interface, once the user is authenticated, they're forever authenticated.
/// Unless, of course, there is an unusual permanent failure such as the underlying
/// service dying, in which it's acceptable that API method calls will fail.
///
/// <para>All methods can be called from the game thread. The user of this interface
/// DOES NOT NEED to call them from the UI thread of the game. Transferring to the UI
/// thread when necessary is a responsibility of the implementors of this interface.</para>
///
/// <para>CALLBACKS: all callbacks must be invoked in Unity's main thread.
/// Implementors of this interface must guarantee that (suggestion: use
/// <see cref="GooglePlayGames.OurUtils.RunOnGameThread(System.Action action)"/>).</para>
/// </remarks>
public interface IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks>If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
void Authenticate(System.Action<bool, string> callback, bool silent);
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns><c>true</c> if the user is authenticated; otherwise, <c>false</c>.</returns>
bool IsAuthenticated();
/// <summary>
/// Signs the user out.
/// </summary>
void SignOut();
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user's ID, <code>null</code> if the user is not logged in.</returns>
string GetUserId();
/// <summary>
/// Load friends of the authenticated user.
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
void LoadFriends(Action<bool> callback);
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user's human-readable name. <code>null</code> if they are not logged
/// in</returns>
string GetUserDisplayName();
/// <summary>
/// Returns an id token, which can be verified server side, if they are logged in.
/// </summary>
string GetIdToken();
/// <summary>
/// The server auth code for this client.
/// </summary>
/// <remarks>
/// Note: This function is currently only implemented for Android.
/// </remarks>
string GetServerAuthCode();
/// <summary>
/// Gets the user's email.
/// </summary>
/// <remarks>The email address returned is selected by the user from the accounts present
/// on the device. There is no guarantee this uniquely identifies the player.
/// For unique identification use the id property of the local player.
/// The user can also choose to not select any email address, meaning it is not
/// available.
/// </remarks>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
string GetUserEmail();
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The URL to load the avatar image. <code>null</code> if they are not logged
/// in</returns>
string GetUserImageUrl();
/// <summary>Gets the player stats.</summary>
/// <param name="callback">Callback for response.</param>
void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback);
/// <summary>
/// Loads the users specified. This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </summary>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback.</param>
void LoadUsers(string[] userIds, Action<IUserProfile[]> callback);
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement corresponding to the identifer. <code>null</code> if no such
/// achievement is found or if authentication has not occurred.</returns>
/// <param name="achievementId">The identifier of the achievement.</param>
Achievement GetAchievement(string achievementId);
/// <summary>
/// Loads the achievements for the current signed in user and invokes
/// the callback.
/// </summary>
void LoadAchievements(Action<Achievement[]> callback);
/// <summary>
/// Unlocks the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already unlocked, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to unlock.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void UnlockAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Reveals the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already in a revealed state, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to reveal.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void RevealAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Increments the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the
/// callback will be invoked on the game thread with <code>true</code>. If the operation fails,
/// the callback will be invoked with <code>false</code>. This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="achievementId">The ID of the achievement to increment.</param>
/// <param name="steps">The number of steps to increment by.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void IncrementAchievement(string achievementId, int steps,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Ach identifier.</param>
/// <param name="steps">Steps.</param>
/// <param name="callback">Callback.</param>
void SetStepsAtLeast(string achId, int steps, Action<bool> callback);
/// <summary>
/// Shows the appropriate platform-specific achievements UI.
/// <param name="callback">The callback to invoke when complete. If null,
/// no callback is called. </param>
/// </summary>
void ShowAchievementsUI(Action<UIStatus> callback);
/// <summary>
/// Shows the leaderboard UI for a specific leaderboard.
/// </summary>
/// <remarks>If the passed ID is <code>null</code>, all leaderboards are displayed.
/// </remarks>
/// <param name="leaderboardId">The leaderboard to display. <code>null</code> to display
/// all.</param>
/// <param name="span">Timespan to display for the leaderboard</param>
/// <param name="callback">If non-null, the callback to invoke when the
/// leaderboard is dismissed.
/// </param>
void ShowLeaderboardUI(string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback);
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">max number of scores to return. non-positive indicates
// no rows should be returned. This causes only the summary info to
/// be loaded. This can be limited
// by the SDK.</param>
/// <param name="collection">leaderboard collection: public or social</param>
/// <param name="timeSpan">leaderboard timespan</param>
/// <param name="callback">callback with the scores, and a page token.
/// The token can be used to load next/prev pages.</param>
void LoadScores(string leaderboardId, LeaderboardStart start,
int rowCount, LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token for tracking the score loading.</param>
/// <param name="rowCount">max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback.</param>
void LoadMoreScores(ScorePageToken token, int rowCount,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
int LeaderboardMaxResults();
/// <summary>
/// Submits the passed score to the passed leaderboard.
/// </summary>
/// <remarks>This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void SubmitScore(string leaderboardId, long score,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Submits the score for the currently signed-in player.
/// </summary>
/// <param name="score">Score.</param>
/// <param name="board">leaderboard id.</param>
/// <param name="metadata">metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
void SubmitScore(string leaderboardId, long score, string metadata,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"/>
/// <returns>The rtmp client.</returns>
IRealTimeMultiplayerClient GetRtmpClient();
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
ITurnBasedMultiplayerClient GetTbmpClient();
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
SavedGame.ISavedGameClient GetSavedGameClient();
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
Events.IEventsClient GetEventsClient();
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
[Obsolete("Quests are being removed in 2018.")]
Quests.IQuestsClient GetQuestsClient();
/// <summary>
/// Gets the video client.
/// </summary>
/// <returns>The video client.</returns>
Video.IVideoClient GetVideoClient();
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate);
IUserProfile[] GetFriends();
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
IntPtr GetApiClient();
/// <summary>
/// Sets the gravity for popups (Android only).
/// </summary>
/// <remarks>This can only be called after authentication. It affects
/// popups for achievements and other game services elements.</remarks>
/// <param name="gravity">Gravity for the popup.</param>
void SetGravityForPopups(Gravity gravity);
}
/// <summary>
/// Delegate that handles an incoming invitation (for both RTMP and TBMP).
/// </summary>
/// <param name="invitation">The invitation received.</param>
/// <param name="shouldAutoAccept">If this is true, then the game should immediately
/// accept the invitation and go to the game screen without prompting the user. If
/// false, you should prompt the user before accepting the invitation. As an example,
/// when a user taps on the "Accept" button on a notification in Android, it is
/// clear that they want to accept that invitation right away, so the plugin calls this
/// delegate with shouldAutoAccept = true. However, if we receive an incoming invitation
/// that the player hasn't specifically indicated they wish to accept (for example,
/// we received one in the background from the server), this delegate will be called
/// with shouldAutoAccept=false to indicate that you should confirm with the user
/// to see if they wish to accept or decline the invitation.</param>
public delegate void InvitationReceivedDelegate(Invitation invitation, bool shouldAutoAccept);
}
#endif
| |
namespace android.view.accessibility
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class AccessibilityEvent : java.lang.Object, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AccessibilityEvent()
{
InitJNI();
}
internal AccessibilityEvent(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _toString9841;
public sealed override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._toString9841)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._toString9841)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getClassName9842;
public global::java.lang.CharSequence getClassName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getClassName9842)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getClassName9842)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getPackageName9843;
public global::java.lang.CharSequence getPackageName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getPackageName9843)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getPackageName9843)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getText9844;
public global::java.util.List getText()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getText9844)) as java.util.List;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getText9844)) as java.util.List;
}
internal static global::MonoJavaBridge.MethodId _isChecked9845;
public bool isChecked()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._isChecked9845);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._isChecked9845);
}
internal static global::MonoJavaBridge.MethodId _setChecked9846;
public void setChecked(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setChecked9846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setChecked9846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isEnabled9847;
public bool isEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._isEnabled9847);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._isEnabled9847);
}
internal static global::MonoJavaBridge.MethodId _setEnabled9848;
public void setEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setEnabled9848, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setEnabled9848, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isPassword9849;
public bool isPassword()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._isPassword9849);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._isPassword9849);
}
internal static global::MonoJavaBridge.MethodId _setPassword9850;
public void setPassword(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setPassword9850, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setPassword9850, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setFullScreen9851;
public void setFullScreen(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setFullScreen9851, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setFullScreen9851, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isFullScreen9852;
public bool isFullScreen()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._isFullScreen9852);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._isFullScreen9852);
}
internal static global::MonoJavaBridge.MethodId _getEventType9853;
public int getEventType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getEventType9853);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getEventType9853);
}
internal static global::MonoJavaBridge.MethodId _setEventType9854;
public void setEventType(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setEventType9854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setEventType9854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getItemCount9855;
public int getItemCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getItemCount9855);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getItemCount9855);
}
internal static global::MonoJavaBridge.MethodId _setItemCount9856;
public void setItemCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setItemCount9856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setItemCount9856, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCurrentItemIndex9857;
public int getCurrentItemIndex()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getCurrentItemIndex9857);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getCurrentItemIndex9857);
}
internal static global::MonoJavaBridge.MethodId _setCurrentItemIndex9858;
public void setCurrentItemIndex(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setCurrentItemIndex9858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setCurrentItemIndex9858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFromIndex9859;
public int getFromIndex()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getFromIndex9859);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getFromIndex9859);
}
internal static global::MonoJavaBridge.MethodId _setFromIndex9860;
public void setFromIndex(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setFromIndex9860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setFromIndex9860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getAddedCount9861;
public int getAddedCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getAddedCount9861);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getAddedCount9861);
}
internal static global::MonoJavaBridge.MethodId _setAddedCount9862;
public void setAddedCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setAddedCount9862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setAddedCount9862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getRemovedCount9863;
public int getRemovedCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getRemovedCount9863);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getRemovedCount9863);
}
internal static global::MonoJavaBridge.MethodId _setRemovedCount9864;
public void setRemovedCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setRemovedCount9864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setRemovedCount9864, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getEventTime9865;
public long getEventTime()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getEventTime9865);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getEventTime9865);
}
internal static global::MonoJavaBridge.MethodId _setEventTime9866;
public void setEventTime(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setEventTime9866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setEventTime9866, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setClassName9867;
public void setClassName(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setClassName9867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setClassName9867, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setClassName(string arg0)
{
setClassName((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _setPackageName9868;
public void setPackageName(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setPackageName9868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setPackageName9868, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setPackageName(string arg0)
{
setPackageName((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getBeforeText9869;
public global::java.lang.CharSequence getBeforeText()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getBeforeText9869)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getBeforeText9869)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _setBeforeText9870;
public void setBeforeText(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setBeforeText9870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setBeforeText9870, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setBeforeText(string arg0)
{
setBeforeText((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getContentDescription9871;
public global::java.lang.CharSequence getContentDescription()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getContentDescription9871)) as java.lang.CharSequence;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getContentDescription9871)) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _setContentDescription9872;
public void setContentDescription(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setContentDescription9872, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setContentDescription9872, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setContentDescription(string arg0)
{
setContentDescription((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _getParcelableData9873;
public global::android.os.Parcelable getParcelableData()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._getParcelableData9873)) as android.os.Parcelable;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._getParcelableData9873)) as android.os.Parcelable;
}
internal static global::MonoJavaBridge.MethodId _setParcelableData9874;
public void setParcelableData(android.os.Parcelable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._setParcelableData9874, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._setParcelableData9874, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _obtain9875;
public static global::android.view.accessibility.AccessibilityEvent obtain()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._obtain9875)) as android.view.accessibility.AccessibilityEvent;
}
internal static global::MonoJavaBridge.MethodId _obtain9876;
public static global::android.view.accessibility.AccessibilityEvent obtain(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._obtain9876, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.accessibility.AccessibilityEvent;
}
internal static global::MonoJavaBridge.MethodId _recycle9877;
public void recycle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._recycle9877);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._recycle9877);
}
internal static global::MonoJavaBridge.MethodId _initFromParcel9878;
public void initFromParcel(android.os.Parcel arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._initFromParcel9878, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._initFromParcel9878, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _writeToParcel9879;
public void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._writeToParcel9879, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._writeToParcel9879, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _describeContents9880;
public int describeContents()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent._describeContents9880);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.accessibility.AccessibilityEvent.staticClass, global::android.view.accessibility.AccessibilityEvent._describeContents9880);
}
public static int INVALID_POSITION
{
get
{
return -1;
}
}
public static int MAX_TEXT_LENGTH
{
get
{
return 500;
}
}
public static int TYPE_VIEW_CLICKED
{
get
{
return 1;
}
}
public static int TYPE_VIEW_LONG_CLICKED
{
get
{
return 2;
}
}
public static int TYPE_VIEW_SELECTED
{
get
{
return 4;
}
}
public static int TYPE_VIEW_FOCUSED
{
get
{
return 8;
}
}
public static int TYPE_VIEW_TEXT_CHANGED
{
get
{
return 16;
}
}
public static int TYPE_WINDOW_STATE_CHANGED
{
get
{
return 32;
}
}
public static int TYPE_NOTIFICATION_STATE_CHANGED
{
get
{
return 64;
}
}
public static int TYPES_ALL_MASK
{
get
{
return -1;
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR9881;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.accessibility.AccessibilityEvent.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/accessibility/AccessibilityEvent"));
global::android.view.accessibility.AccessibilityEvent._toString9841 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "toString", "()Ljava/lang/String;");
global::android.view.accessibility.AccessibilityEvent._getClassName9842 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getClassName", "()Ljava/lang/CharSequence;");
global::android.view.accessibility.AccessibilityEvent._getPackageName9843 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getPackageName", "()Ljava/lang/CharSequence;");
global::android.view.accessibility.AccessibilityEvent._getText9844 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getText", "()Ljava/util/List;");
global::android.view.accessibility.AccessibilityEvent._isChecked9845 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "isChecked", "()Z");
global::android.view.accessibility.AccessibilityEvent._setChecked9846 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setChecked", "(Z)V");
global::android.view.accessibility.AccessibilityEvent._isEnabled9847 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "isEnabled", "()Z");
global::android.view.accessibility.AccessibilityEvent._setEnabled9848 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setEnabled", "(Z)V");
global::android.view.accessibility.AccessibilityEvent._isPassword9849 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "isPassword", "()Z");
global::android.view.accessibility.AccessibilityEvent._setPassword9850 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setPassword", "(Z)V");
global::android.view.accessibility.AccessibilityEvent._setFullScreen9851 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setFullScreen", "(Z)V");
global::android.view.accessibility.AccessibilityEvent._isFullScreen9852 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "isFullScreen", "()Z");
global::android.view.accessibility.AccessibilityEvent._getEventType9853 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getEventType", "()I");
global::android.view.accessibility.AccessibilityEvent._setEventType9854 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setEventType", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getItemCount9855 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getItemCount", "()I");
global::android.view.accessibility.AccessibilityEvent._setItemCount9856 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setItemCount", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getCurrentItemIndex9857 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getCurrentItemIndex", "()I");
global::android.view.accessibility.AccessibilityEvent._setCurrentItemIndex9858 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setCurrentItemIndex", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getFromIndex9859 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getFromIndex", "()I");
global::android.view.accessibility.AccessibilityEvent._setFromIndex9860 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setFromIndex", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getAddedCount9861 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getAddedCount", "()I");
global::android.view.accessibility.AccessibilityEvent._setAddedCount9862 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setAddedCount", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getRemovedCount9863 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getRemovedCount", "()I");
global::android.view.accessibility.AccessibilityEvent._setRemovedCount9864 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setRemovedCount", "(I)V");
global::android.view.accessibility.AccessibilityEvent._getEventTime9865 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getEventTime", "()J");
global::android.view.accessibility.AccessibilityEvent._setEventTime9866 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setEventTime", "(J)V");
global::android.view.accessibility.AccessibilityEvent._setClassName9867 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setClassName", "(Ljava/lang/CharSequence;)V");
global::android.view.accessibility.AccessibilityEvent._setPackageName9868 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setPackageName", "(Ljava/lang/CharSequence;)V");
global::android.view.accessibility.AccessibilityEvent._getBeforeText9869 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getBeforeText", "()Ljava/lang/CharSequence;");
global::android.view.accessibility.AccessibilityEvent._setBeforeText9870 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setBeforeText", "(Ljava/lang/CharSequence;)V");
global::android.view.accessibility.AccessibilityEvent._getContentDescription9871 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getContentDescription", "()Ljava/lang/CharSequence;");
global::android.view.accessibility.AccessibilityEvent._setContentDescription9872 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setContentDescription", "(Ljava/lang/CharSequence;)V");
global::android.view.accessibility.AccessibilityEvent._getParcelableData9873 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "getParcelableData", "()Landroid/os/Parcelable;");
global::android.view.accessibility.AccessibilityEvent._setParcelableData9874 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "setParcelableData", "(Landroid/os/Parcelable;)V");
global::android.view.accessibility.AccessibilityEvent._obtain9875 = @__env.GetStaticMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "obtain", "()Landroid/view/accessibility/AccessibilityEvent;");
global::android.view.accessibility.AccessibilityEvent._obtain9876 = @__env.GetStaticMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "obtain", "(I)Landroid/view/accessibility/AccessibilityEvent;");
global::android.view.accessibility.AccessibilityEvent._recycle9877 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "recycle", "()V");
global::android.view.accessibility.AccessibilityEvent._initFromParcel9878 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "initFromParcel", "(Landroid/os/Parcel;)V");
global::android.view.accessibility.AccessibilityEvent._writeToParcel9879 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V");
global::android.view.accessibility.AccessibilityEvent._describeContents9880 = @__env.GetMethodIDNoThrow(global::android.view.accessibility.AccessibilityEvent.staticClass, "describeContents", "()I");
}
}
}
| |
/*
* Copyright (c) 2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace OpenMetaverse.Rendering
{
public class LindenMesh
{
const string MESH_HEADER = "Linden Binary Mesh 1.0";
const string MORPH_FOOTER = "End Morphs";
#region Mesh Structs
public struct Face
{
public short[] Indices;
}
public struct Vertex
{
public Vector3 Coord;
public Vector3 Normal;
public Vector3 BiNormal;
public Vector2 TexCoord;
public Vector2 DetailTexCoord;
public float Weight;
public override string ToString()
{
return String.Format("Coord: {0} Norm: {1} BiNorm: {2} TexCoord: {3} DetailTexCoord: {4}", Coord, Normal, BiNormal, TexCoord, DetailTexCoord, Weight);
}
}
public struct MorphVertex
{
public uint VertexIndex;
public Vector3 Coord;
public Vector3 Normal;
public Vector3 BiNormal;
public Vector2 TexCoord;
public override string ToString()
{
return String.Format("Index: {0} Coord: {1} Norm: {2} BiNorm: {3} TexCoord: {4}", VertexIndex, Coord, Normal, BiNormal, TexCoord);
}
}
public struct Morph
{
public string Name;
public int NumVertices;
public MorphVertex[] Vertices;
public override string ToString()
{
return Name;
}
}
public struct VertexRemap
{
public int RemapSource;
public int RemapDestination;
public override string ToString()
{
return String.Format("{0} -> {1}", RemapSource, RemapDestination);
}
}
#endregion Mesh Structs
/// <summary>
/// Level of Detail mesh
/// </summary>
public class LODMesh
{
public float MinPixelWidth;
protected string _header;
protected bool _hasWeights;
protected bool _hasDetailTexCoords;
protected Vector3 _position;
protected Vector3 _rotationAngles;
protected byte _rotationOrder;
protected Vector3 _scale;
protected ushort _numFaces;
protected Face[] _faces;
public virtual void LoadMesh(string filename)
{
byte[] buffer = File.ReadAllBytes(filename);
BitPack input = new BitPack(buffer, 0);
_header = TrimAt0(input.UnpackString(24));
if (!String.Equals(_header, MESH_HEADER))
throw new FileLoadException("Unrecognized mesh format");
// Populate base mesh variables
_hasWeights = (input.UnpackByte() != 0);
_hasDetailTexCoords = (input.UnpackByte() != 0);
_position = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationAngles = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationOrder = input.UnpackByte();
_scale = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_numFaces = (ushort)input.UnpackUShort();
_faces = new Face[_numFaces];
for (int i = 0; i < _numFaces; i++)
_faces[i].Indices = new short[] { input.UnpackShort(), input.UnpackShort(), input.UnpackShort() };
}
}
public float MinPixelWidth;
public string Name { get { return _name; } }
public string Header { get { return _header; } }
public bool HasWeights { get { return _hasWeights; } }
public bool HasDetailTexCoords { get { return _hasDetailTexCoords; } }
public Vector3 Position { get { return _position; } }
public Vector3 RotationAngles { get { return _rotationAngles; } }
//public byte RotationOrder
public Vector3 Scale { get { return _scale; } }
public ushort NumVertices { get { return _numVertices; } }
public Vertex[] Vertices { get { return _vertices; } }
public ushort NumFaces { get { return _numFaces; } }
public Face[] Faces { get { return _faces; } }
public ushort NumSkinJoints { get { return _numSkinJoints; } }
public string[] SkinJoints { get { return _skinJoints; } }
public Morph[] Morphs { get { return _morphs; } }
public int NumRemaps { get { return _numRemaps; } }
public VertexRemap[] VertexRemaps { get { return _vertexRemaps; } }
public SortedList<int, LODMesh> LODMeshes { get { return _lodMeshes; } }
protected string _name;
protected string _header;
protected bool _hasWeights;
protected bool _hasDetailTexCoords;
protected Vector3 _position;
protected Vector3 _rotationAngles;
protected byte _rotationOrder;
protected Vector3 _scale;
protected ushort _numVertices;
protected Vertex[] _vertices;
protected ushort _numFaces;
protected Face[] _faces;
protected ushort _numSkinJoints;
protected string[] _skinJoints;
protected Morph[] _morphs;
protected int _numRemaps;
protected VertexRemap[] _vertexRemaps;
protected SortedList<int, LODMesh> _lodMeshes;
public LindenMesh(string name)
{
_name = name;
_lodMeshes = new SortedList<int, LODMesh>();
}
public virtual void LoadMesh(string filename)
{
byte[] buffer = File.ReadAllBytes(filename);
BitPack input = new BitPack(buffer, 0);
_header = TrimAt0(input.UnpackString(24));
if (!String.Equals(_header, MESH_HEADER))
throw new FileLoadException("Unrecognized mesh format");
// Populate base mesh variables
_hasWeights = (input.UnpackByte() != 0);
_hasDetailTexCoords = (input.UnpackByte() != 0);
_position = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationAngles = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_rotationOrder = input.UnpackByte();
_scale = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
_numVertices = (ushort)input.UnpackUShort();
// Populate the vertex array
_vertices = new Vertex[_numVertices];
for (int i = 0; i < _numVertices; i++)
_vertices[i].Coord = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].Normal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].BiNormal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
for (int i = 0; i < _numVertices; i++)
_vertices[i].TexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
if (_hasDetailTexCoords)
{
for (int i = 0; i < _numVertices; i++)
_vertices[i].DetailTexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
}
if (_hasWeights)
{
for (int i = 0; i < _numVertices; i++)
_vertices[i].Weight = input.UnpackFloat();
}
_numFaces = input.UnpackUShort();
_faces = new Face[_numFaces];
for (int i = 0; i < _numFaces; i++)
_faces[i].Indices = new short[] { input.UnpackShort(), input.UnpackShort(), input.UnpackShort() };
if (_hasWeights)
{
_numSkinJoints = input.UnpackUShort();
_skinJoints = new string[_numSkinJoints];
for (int i = 0; i < _numSkinJoints; i++)
{
_skinJoints[i] = TrimAt0(input.UnpackString(64));
}
}
else
{
_numSkinJoints = 0;
_skinJoints = new string[0];
}
// Grab morphs
List<Morph> morphs = new List<Morph>();
string morphName = TrimAt0(input.UnpackString(64));
while (morphName != MORPH_FOOTER)
{
if (input.BytePos + 48 >= input.Data.Length) throw new FileLoadException("Encountered end of file while parsing morphs");
Morph morph = new Morph();
morph.Name = morphName;
morph.NumVertices = input.UnpackInt();
morph.Vertices = new MorphVertex[morph.NumVertices];
for (int i = 0; i < morph.NumVertices; i++)
{
morph.Vertices[i].VertexIndex = input.UnpackUInt();
morph.Vertices[i].Coord = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
morph.Vertices[i].Normal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
morph.Vertices[i].BiNormal = new Vector3(input.UnpackFloat(), input.UnpackFloat(), input.UnpackFloat());
morph.Vertices[i].TexCoord = new Vector2(input.UnpackFloat(), input.UnpackFloat());
}
morphs.Add(morph);
// Grab the next name
morphName = TrimAt0(input.UnpackString(64));
}
_morphs = morphs.ToArray();
// Check if there are remaps or if we're at the end of the file
if (input.BytePos < input.Data.Length - 1)
{
_numRemaps = input.UnpackInt();
_vertexRemaps = new VertexRemap[_numRemaps];
for (int i = 0; i < _numRemaps; i++)
{
_vertexRemaps[i].RemapSource = input.UnpackInt();
_vertexRemaps[i].RemapDestination = input.UnpackInt();
}
}
else
{
_numRemaps = 0;
_vertexRemaps = new VertexRemap[0];
}
}
public virtual void LoadLODMesh(int level, string filename)
{
LODMesh lod = new LODMesh();
lod.LoadMesh(filename);
_lodMeshes[level] = lod;
}
public static string TrimAt0(string s)
{
int pos = s.IndexOf("\0");
if (pos >= 0)
{
return s.Substring(0, pos);
}
else
{
return s;
}
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Concrete class that writes the 4.0 frq/prx postings format.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="Lucene40PostingsFormat"/>
#pragma warning disable 612, 618
public sealed class Lucene40PostingsWriter : PostingsWriterBase
{
internal readonly IndexOutput freqOut;
internal readonly IndexOutput proxOut;
internal readonly Lucene40SkipListWriter skipListWriter;
/// <summary>
/// Expert: The fraction of TermDocs entries stored in skip tables,
/// used to accelerate <see cref="Search.DocIdSetIterator.Advance(int)"/>. Larger values result in
/// smaller indexes, greater acceleration, but fewer accelerable cases, while
/// smaller values result in bigger indexes, less acceleration and more
/// accelerable cases. More detailed experiments would be useful here.
/// </summary>
internal const int DEFAULT_SKIP_INTERVAL = 16;
internal readonly int skipInterval;
/// <summary>
/// Expert: minimum docFreq to write any skip data at all
/// </summary>
internal readonly int skipMinimum;
/// <summary>
/// Expert: The maximum number of skip levels. Smaller values result in
/// slightly smaller indexes, but slower skipping in big posting lists.
/// </summary>
internal readonly int maxSkipLevels = 10;
internal readonly int totalNumDocs;
internal IndexOptions indexOptions;
internal bool storePayloads;
internal bool storeOffsets;
// Starts a new term
internal long freqStart;
internal long proxStart;
internal FieldInfo fieldInfo;
internal int lastPayloadLength;
internal int lastOffsetLength;
internal int lastPosition;
internal int lastOffset;
internal static readonly StandardTermState emptyState = new StandardTermState();
internal StandardTermState lastState;
// private String segment;
/// <summary>
/// Creates a <see cref="Lucene40PostingsWriter"/>, with the
/// <see cref="DEFAULT_SKIP_INTERVAL"/>.
/// </summary>
public Lucene40PostingsWriter(SegmentWriteState state)
: this(state, DEFAULT_SKIP_INTERVAL)
{
}
/// <summary>
/// Creates a <see cref="Lucene40PostingsWriter"/>, with the
/// specified <paramref name="skipInterval"/>.
/// </summary>
public Lucene40PostingsWriter(SegmentWriteState state, int skipInterval)
: base()
{
this.skipInterval = skipInterval;
this.skipMinimum = skipInterval; // set to the same for now
// this.segment = state.segmentName;
string fileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, Lucene40PostingsFormat.FREQ_EXTENSION);
freqOut = state.Directory.CreateOutput(fileName, state.Context);
bool success = false;
IndexOutput proxOut = null;
try
{
CodecUtil.WriteHeader(freqOut, Lucene40PostingsReader.FRQ_CODEC, Lucene40PostingsReader.VERSION_CURRENT);
// TODO: this is a best effort, if one of these fields has no postings
// then we make an empty prx file, same as if we are wrapped in
// per-field postingsformat. maybe... we shouldn't
// bother w/ this opto? just create empty prx file...?
if (state.FieldInfos.HasProx)
{
// At least one field does not omit TF, so create the
// prox file
fileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, Lucene40PostingsFormat.PROX_EXTENSION);
proxOut = state.Directory.CreateOutput(fileName, state.Context);
CodecUtil.WriteHeader(proxOut, Lucene40PostingsReader.PRX_CODEC, Lucene40PostingsReader.VERSION_CURRENT);
}
else
{
// Every field omits TF so we will write no prox file
proxOut = null;
}
this.proxOut = proxOut;
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(freqOut, proxOut);
}
}
totalNumDocs = state.SegmentInfo.DocCount;
skipListWriter = new Lucene40SkipListWriter(skipInterval, maxSkipLevels, totalNumDocs, freqOut, proxOut);
}
public override void Init(IndexOutput termsOut)
{
CodecUtil.WriteHeader(termsOut, Lucene40PostingsReader.TERMS_CODEC, Lucene40PostingsReader.VERSION_CURRENT);
termsOut.WriteInt32(skipInterval); // write skipInterval
termsOut.WriteInt32(maxSkipLevels); // write maxSkipLevels
termsOut.WriteInt32(skipMinimum); // write skipMinimum
}
public override BlockTermState NewTermState()
{
return new StandardTermState();
}
public override void StartTerm()
{
freqStart = freqOut.GetFilePointer();
//if (DEBUG) System.out.println("SPW: startTerm freqOut.fp=" + freqStart);
if (proxOut != null)
{
proxStart = proxOut.GetFilePointer();
}
// force first payload to write its length
lastPayloadLength = -1;
// force first offset to write its length
lastOffsetLength = -1;
skipListWriter.ResetSkip();
}
// Currently, this instance is re-used across fields, so
// our parent calls setField whenever the field changes
public override int SetField(FieldInfo fieldInfo)
{
//System.out.println("SPW: setField");
/*
if (BlockTreeTermsWriter.DEBUG && fieldInfo.Name.Equals("id", StringComparison.Ordinal)) {
DEBUG = true;
} else {
DEBUG = false;
}
*/
this.fieldInfo = fieldInfo;
indexOptions = fieldInfo.IndexOptions;
storeOffsets = indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
storePayloads = fieldInfo.HasPayloads;
lastState = emptyState;
//System.out.println(" set init blockFreqStart=" + freqStart);
//System.out.println(" set init blockProxStart=" + proxStart);
return 0;
}
internal int lastDocID;
internal int df;
public override void StartDoc(int docID, int termDocFreq)
{
// if (DEBUG) System.out.println("SPW: startDoc seg=" + segment + " docID=" + docID + " tf=" + termDocFreq + " freqOut.fp=" + freqOut.getFilePointer());
int delta = docID - lastDocID;
if (docID < 0 || (df > 0 && delta <= 0))
{
throw new CorruptIndexException("docs out of order (" + docID + " <= " + lastDocID + " ) (freqOut: " + freqOut + ")");
}
if ((++df % skipInterval) == 0)
{
skipListWriter.SetSkipData(lastDocID, storePayloads, lastPayloadLength, storeOffsets, lastOffsetLength);
skipListWriter.BufferSkip(df);
}
if (Debugging.AssertsEnabled) Debugging.Assert(docID < totalNumDocs, () => "docID=" + docID + " totalNumDocs=" + totalNumDocs);
lastDocID = docID;
if (indexOptions == IndexOptions.DOCS_ONLY)
{
freqOut.WriteVInt32(delta);
}
else if (1 == termDocFreq)
{
freqOut.WriteVInt32((delta << 1) | 1);
}
else
{
freqOut.WriteVInt32(delta << 1);
freqOut.WriteVInt32(termDocFreq);
}
lastPosition = 0;
lastOffset = 0;
}
/// <summary>
/// Add a new <paramref name="position"/> & <paramref name="payload"/>. </summary>
public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset)
{
//if (DEBUG) System.out.println("SPW: addPos pos=" + position + " payload=" + (payload == null ? "null" : (payload.Length + " bytes")) + " proxFP=" + proxOut.getFilePointer());
if (Debugging.AssertsEnabled) Debugging.Assert(indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0, () => "invalid indexOptions: " + indexOptions);
if (Debugging.AssertsEnabled) Debugging.Assert(proxOut != null);
int delta = position - lastPosition;
if (Debugging.AssertsEnabled) Debugging.Assert(delta >= 0, () => "position=" + position + " lastPosition=" + lastPosition); // not quite right (if pos=0 is repeated twice we don't catch it)
lastPosition = position;
int payloadLength = 0;
if (storePayloads)
{
payloadLength = payload == null ? 0 : payload.Length;
if (payloadLength != lastPayloadLength)
{
lastPayloadLength = payloadLength;
proxOut.WriteVInt32((delta << 1) | 1);
proxOut.WriteVInt32(payloadLength);
}
else
{
proxOut.WriteVInt32(delta << 1);
}
}
else
{
proxOut.WriteVInt32(delta);
}
if (storeOffsets)
{
// don't use startOffset - lastEndOffset, because this creates lots of negative vints for synonyms,
// and the numbers aren't that much smaller anyways.
int offsetDelta = startOffset - lastOffset;
int offsetLength = endOffset - startOffset;
if (Debugging.AssertsEnabled) Debugging.Assert(offsetDelta >= 0 && offsetLength >= 0, () => "startOffset=" + startOffset + ",lastOffset=" + lastOffset + ",endOffset=" + endOffset);
if (offsetLength != lastOffsetLength)
{
proxOut.WriteVInt32(offsetDelta << 1 | 1);
proxOut.WriteVInt32(offsetLength);
}
else
{
proxOut.WriteVInt32(offsetDelta << 1);
}
lastOffset = startOffset;
lastOffsetLength = offsetLength;
}
if (payloadLength > 0)
{
proxOut.WriteBytes(payload.Bytes, payload.Offset, payloadLength);
}
}
public override void FinishDoc()
{
}
internal class StandardTermState : BlockTermState
{
public long FreqStart { get; set; }
public long ProxStart { get; set; }
public long SkipOffset { get; set; }
}
/// <summary>
/// Called when we are done adding docs to this term. </summary>
public override void FinishTerm(BlockTermState state)
{
StandardTermState state_ = (StandardTermState)state;
// if (DEBUG) System.out.println("SPW: finishTerm seg=" + segment + " freqStart=" + freqStart);
if (Debugging.AssertsEnabled) Debugging.Assert(state_.DocFreq > 0);
// TODO: wasteful we are counting this (counting # docs
// for this term) in two places?
if (Debugging.AssertsEnabled) Debugging.Assert(state_.DocFreq == df);
state_.FreqStart = freqStart;
state_.ProxStart = proxStart;
if (df >= skipMinimum)
{
state_.SkipOffset = skipListWriter.WriteSkip(freqOut) - freqStart;
}
else
{
state_.SkipOffset = -1;
}
lastDocID = 0;
df = 0;
}
public override void EncodeTerm(long[] empty, DataOutput @out, FieldInfo fieldInfo, BlockTermState state, bool absolute)
{
StandardTermState state_ = (StandardTermState)state;
if (absolute)
{
lastState = emptyState;
}
@out.WriteVInt64(state_.FreqStart - lastState.FreqStart);
if (state_.SkipOffset != -1)
{
if (Debugging.AssertsEnabled) Debugging.Assert(state_.SkipOffset > 0);
@out.WriteVInt64(state_.SkipOffset);
}
if (indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0)
{
@out.WriteVInt64(state_.ProxStart - lastState.ProxStart);
}
lastState = state_;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
freqOut.Dispose();
}
finally
{
if (proxOut != null)
{
proxOut.Dispose();
}
}
}
}
}
#pragma warning restore 612, 618
}
| |
/*
* Copyright 2002 Fluent Consulting, Inc. All rights reserved.
* PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Xml;
using Inform.Common;
namespace Inform {
/// <summary>
/// Provides a set of commands to access a relational database as both objects and relational data.
/// </summary>
public abstract class DataStore : ICloneable {
//Properties
private string name;
private DataStoreSettings settings;
private bool inTransaction;
private IDbTransaction transaction;
private ConnectionManager connectionManager;
private DataStorageManager storageManager;
private Hashtable commands;
#region Properties
/// <summary>
/// Gets or sets the <see cref="DataStore"/> name.
/// </summary>
public string Name {
get { return name; }
set { name = value; }
}
/// <summary>
/// The <see cref="DataStoreSettings"/> for the <see cref="DataStore"/>.
/// </summary>
public DataStoreSettings Settings {
get { return settings; }
}
/// <summary>
/// Whether a transaction has been started;
/// </summary>
public bool InTransaction {
get { return inTransaction; }
set { inTransaction = value; }
}
/// <summary>
/// Gets the current IDbTransaction if the <see cref="DataStore"/> is currently in a transaction, otherwise returns <see langword="null"/>.
/// </summary>
protected internal IDbTransaction CurrentTransaction {
get { return transaction; }
}
/// <exclude />
/// <summary>
/// Gets the <see cref="ConnectionManager"/> for database connections.
/// </summary>
public ConnectionManager Connection {
get {
if (connectionManager == null){
connectionManager = CreateConnectionManager();
}
return connectionManager;
}
}
/// <summary>
/// The DataStorageManager.
/// </summary>
internal DataStorageManager DataStorageManager {
get {
if (storageManager == null){
storageManager = CreateStorageManager();
}
return storageManager;
}
}
/// <summary>
/// The Predefined Commands.
/// </summary>
//TODO: Need typed collection?
internal IDictionary Commands {
get { return commands; }
}
#endregion
#region Abstract Methods
protected internal abstract ConnectionManager CreateConnectionManager();
protected internal abstract DataStorageManager CreateStorageManager();
/// <summary>
/// Creates an <see cref="IDataAccessCommand"/> with the text command to execute.
/// </summary>
/// <param name="cmdText">The text command to execute.</param>
/// <returns>An <see cref="IDataAccessCommand"/> object.</returns>
public abstract IDataAccessCommand CreateDataAccessCommand(string cmdText);
/// <summary>
/// Creates an <see cref="IDataAccessCommand"/> with the text command to execute and specifies how the text command is interpreted.
/// </summary>
/// <param name="cmdText">The text command to execute.</param>
/// <param name="commandType">Specifies how a command string is interpreted.</param>
/// <returns>An <see cref="IDataAccessCommand"/> object.</returns>
public abstract IDataAccessCommand CreateDataAccessCommand(string cmdText, System.Data.CommandType commandType);
/// <summary>
/// Creates an <see cref="IObjectAccessCommand"/> with the type to return and filter to apply.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <returns>An <see cref="IObjectAccessCommand"/> object.</returns>
public abstract IObjectAccessCommand CreateObjectAccessCommand(Type type, string filter);
/// <summary>
/// Creates an <see cref="IObjectAccessCommand"/> with the type to return, a filter to apply, and whether to return subclasses.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <param name="polymorphic">Whether to return subclasses.</param>
/// <returns>An <see cref="IObjectAccessCommand"/> object.</returns>
public abstract IObjectAccessCommand CreateObjectAccessCommand(Type type, string filter, bool polymorphic);
/// <summary>
/// Creates an <see cref="IObjectAccessCommand"/> with the type to return, the command text, whether to return subclasses, and specifies how the text command is interpreted.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="cmdText">The text command to execute.</param>
/// <param name="polymorphic">Whether to return subclasses.</param>
/// <param name="commandType">Specifies how a command string is interpreted.</param>
/// <returns>An <see cref="IObjectAccessCommand"/> object.</returns>
public abstract IObjectAccessCommand CreateObjectAccessCommand(Type type, string cmdText, bool polymorphic, System.Data.CommandType commandType);
/// <summary>
/// Creates an <see cref="IFindObjectCommand"/> with the type to return and filter to apply.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <returns>An <see cref="IFindObjectCommand"/> object.</returns>
public abstract IFindObjectCommand CreateFindObjectCommand(Type type, string filter);
/// <summary>
/// Creates an <see cref="IFindObjectCommand"/> with the type to return, the command text, and specifies how the text command is interpreted.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="cmdText">The text command to execute.</param>
/// <param name="commandType">Specifies how a command string is interpreted.</param>
/// <returns>An <see cref="IFindObjectCommand"/> object.</returns>
public abstract IFindObjectCommand CreateFindObjectCommand(Type type, string cmdText, System.Data.CommandType commandType);
/// <summary>
/// Creates an <see cref="IFindObjectCommand"/> with the type to return, the filter to apply, and whether to return subclasses.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <param name="polymorphic">Whether to return subclasses.</param>
/// <returns>An <see cref="IFindObjectCommand"/> object.</returns>
public abstract IFindObjectCommand CreateFindObjectCommand(Type type, string filter, bool polymorphic);
/// <summary>
/// Creates an <see cref="IFindCollectionCommand"/> with the type to return and filter to apply.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <returns>An <see cref="IFindCollectionCommand"/> object.</returns>
public abstract IFindCollectionCommand CreateFindCollectionCommand(Type type, string filter );
/// <summary>
/// Creates an <see cref="IFindCollectionCommand"/> with the type to return, the comand text, and specifies how the text command is interpreted.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="cmdText">The text command to execute.</param>
/// <param name="commandType">Specifies how a command string is interpreted.</param>
/// <returns>An <see cref="IFindCollectionCommand"/> object.</returns>
public abstract IFindCollectionCommand CreateFindCollectionCommand(Type type, string cmdText, System.Data.CommandType commandType);
/// <summary>
/// Creates an <see cref="IFindCollectionCommand"/> with the type to return, the filter to apply, and whether to return subclasses.
/// </summary>
/// <param name="type">The type to return.</param>
/// <param name="filter">The filter to apply.</param>
/// <param name="polymorphic">Whether to return subclasses.</param>
/// <returns>An <see cref="IFindCollectionCommand"/> object.</returns>
public abstract IFindCollectionCommand CreateFindCollectionCommand(Type type, string filter, bool polymorphic);
/// <summary>
/// Inserts an object into the data source.
/// </summary>
/// <param name="o">The object to insert.</param>
/// <param name="typeMapping">The TypeMapping that defines the mapping to the data source.</param>
abstract internal void Insert(object o, TypeMapping typeMapping);
/// <summary>
/// Updates an object in the data source.
/// </summary>
/// <param name="o">The object to update.</param>
/// <param name="typeMapping">The TypeMapping that defines the mapping to the data source.</param>
abstract internal void Update(object o, TypeMapping typeMapping);
/// <summary>
/// Deletes an object from the data source by primary key..
/// </summary>
/// <param name="type">The <see cref="Type"/> of the object to be deleted.</param>
/// <param name="primaryKey">The value of the objects primary key.</param>
/// <remarks>Using a <see cref="Type"/> that does not have a primary key defined in its <see cref="TypeMapping"/> will cause an exception.</remarks>
abstract public void Delete(Type type, object primaryKey);
/// <summary>
/// Finds an object from the data source by primary key.
/// </summary>
/// <param name="type">The <see cref="Type"/> of the object to return.</param>
/// <param name="primaryKey">The value of the objects primary key.</param>
/// <returns>The object or <see langword="null"/> if not found. </returns>
/// <remarks> If the DataStore's <see cref="Settings"/> FindObjectReturnsNull is <see langword="true"/> and the object is noe found, an <see cref="ObjectNotFoundException"/> will be thrown.
/// Using a <see cref="Type"/> that does not have a primary key defined in its <see cref="TypeMapping"/> will cause an exception.
/// </remarks>
public object FindByPrimaryKey(Type type, object primaryKey){
TypeMapping typeMapping = null;
typeMapping = DataStorageManager.GetTypeMapping(type, true);
if(typeMapping.PrimaryKey == null) {
throw new DataStoreException("TypeMapping does not have defined PrimaryKey for " + type.FullName);
}
bool polymorphic = type.BaseType != null;
IFindObjectCommand findCommand = this.CreateFindObjectCommand(type, this.DataStorageManager.GenerateFindByPrimaryKeySql(typeMapping), polymorphic);
IMemberMapping mapping = typeMapping.PrimaryKey;
findCommand.CreateInputParameter("@" + mapping.ColumnName, primaryKey);
return findCommand.Execute();
}
#endregion
#region Methods
/// <summary>
/// A DataStore normally is created through factory methods provided by <see cref="DataStoreSevices"/>.
/// </summary>
protected DataStore() {
settings = new DataStoreSettings();
commands = new Hashtable();
}
/// <summary>
/// Creates storage in the datasource for the registered typemappings if it does not currently exist.
/// </summary>
protected internal void EnsureStorage(){
foreach(TypeMapping typeMapping in this.DataStorageManager.TypeMappings){
if(!this.ExistsStorage(typeMapping.MappedType)){
this.CreateStorage(typeMapping);
}
}
}
/// <summary>
/// Creates the necessary tables and, if defined, stored procedures in the datasource for the type.
/// </summary>
public void CreateStorage(Type type){
CreateStorage(type, Settings.AutoGenerate);
}
/// <summary>
/// Creates the necessary tables and, if defined in the TypeMapping, stored procedures in the datasource for the type.
/// </summary>
/// <param name="autoGenerate">
/// Whether to auto generate type mappings by using attributes.
/// </param>
public void CreateStorage(Type type, bool autoGenerate){
TypeMapping typeMapping = DataStorageManager.GetTypeMapping(type, true);
this.DataStorageManager.CreateStorage(typeMapping);
}
/// <summary>
/// Creates the necessary tables and, if defined in the TypeMapping, stored procedures in the datasource for the type using a specific TypeMapping.
/// </summary>
public void CreateStorage(TypeMapping typeMapping){
//TODO: Review - add if not already added
if(DataStorageManager.GetTypeMapping(typeMapping.MappedType) == null){
DataStorageManager.AddTypeMapping(typeMapping);
}
this.DataStorageManager.CreateStorage(typeMapping);
}
/// <summary>
/// Checks if the necessary tables and, if defined in the TypeMapping, stored procedures exists in the datasource for a type.
/// </summary>
public bool ExistsStorage(Type type){
if(type == null){
throw new ArgumentNullException("type");
}
TypeMapping typeMapping = DataStorageManager.GetTypeMapping(type, true);
return this.DataStorageManager.ExistsStorage(typeMapping);
}
/// <summary>
/// Deletes the tables and, if defined in the TypeMapping, stored procedures from the data source for this type.
/// </summary>
public void DeleteStorage(Type type){
if(type == null){
throw new ArgumentNullException("type");
}
TypeMapping typeMapping = DataStorageManager.GetTypeMapping(type, true);
this.DataStorageManager.DeleteStorage(typeMapping);
}
/// <summary>
/// Inserts an object into the data source.
/// </summary>
/// <param name="o">The object to insert.</param>
public void Insert(object o){
TypeMapping typeMapping = null;
if((typeMapping = DataStorageManager.GetTypeMapping(o.GetType())) == null){
throw new DataStoreException("DataStore does not contain storage for " + o.GetType().FullName);
}
Insert(o,typeMapping);
SetContext(o);
}
/// <summary>
/// Updates an object int the data source.
/// </summary>
/// <param name="o">The object to update.</param>
/// <remarks>Using a <see cref="Type"/> that does not have a primary key defined in its <see cref="TypeMapping"/> will cause an exception.</remarks>
public void Update(object o){
TypeMapping typeMapping = null;
if((typeMapping = DataStorageManager.GetTypeMapping(o.GetType())) == null){
throw new DataStoreException("DataStore does not contain storage for " + o.GetType().FullName);
} else if(typeMapping.PrimaryKey == null) {
throw new DataStoreException("TypeMapping does not have defined PrimaryKey for " + o.GetType().FullName);
}
Update(o,typeMapping);
}
/// <summary>
/// Inserts an object into the data source if the primary key is not set, otherwise updates the object.
/// </summary>
/// <param name="o">The object to insert or update.</param>
/// <remarks>Using a <see cref="Type"/> that does not have a primary key defined in its <see cref="TypeMapping"/> will cause an exception.</remarks>
public void InsertOrUpdate(object o){
TypeMapping typeMapping = null;
if((typeMapping = DataStorageManager.GetTypeMapping(o.GetType())) == null){
throw new DataStoreException("DataStore does not contain storage for " + o.GetType().FullName);
} else if(typeMapping.PrimaryKey == null) {
throw new DataStoreException("TypeMapping does not have defined PrimaryKey for " + o.GetType().FullName);
}
IMemberMapping memberMapping = typeMapping.PrimaryKey;
if(!memberMapping.HasIdentity(o)){
Insert(o, typeMapping);
} else {
Update(o, typeMapping);
}
}
/// <summary>
/// Deletes an object from the data source.
/// </summary>
/// <param name="o">The object to insert or update.</param>
/// <remarks>Using a <see cref="Type"/> that does not have a primary key defined in its <see cref="TypeMapping"/> will cause an exception.</remarks>
public void Delete(object o) {
TypeMapping typeMapping = DataStorageManager.GetTypeMapping(o.GetType(), true);
if(typeMapping.PrimaryKey == null) {
throw new ApplicationException("TypeMapping does not have defined PrimaryKey for " + o.GetType().FullName);
}
IMemberMapping memberMapping = typeMapping.PrimaryKey;
Delete(o.GetType(), memberMapping.GetValue(o));
}
internal string GetFullName(Type type){
return type.FullName + "," + type.Assembly.GetName().Name;
}
/// <summary>
/// Sets the context on each <see cref="CacheMapping"/> defined for an object.
/// </summary>
/// <param name="o">The object to set the context.</param>
/// <remarks>
/// Setting the context is only required when using cach mappings and the object was not inserted or retrieved from a DataStore command.
/// </remarks>
public void SetContext(object o){
TypeMapping typeMapping = DataStorageManager.GetTypeMapping(o.GetType(), true);
SetContext(o,typeMapping);
}
private void SetContext(object o, TypeMapping typeMapping){
foreach( CacheMapping mapping in typeMapping.CacheMappings){
mapping.SetContext(o);
}
if(typeMapping.BaseType != null){
TypeMapping baseTypeMapping = DataStorageManager.GetTypeMapping(typeMapping.BaseType, true);
SetContext(o,baseTypeMapping);
}
}
/// <summary>
/// Begins a database transaction.
/// </summary>
public void BeginTransaction(){
if(inTransaction){
throw new DataStoreException("Transaction has already been started");
}
IDbConnection connection = this.Connection.CreateConnection();
connection.Open();
transaction = connection.BeginTransaction();
inTransaction = true;
}
/// <summary>
/// Commits the database transaction.
/// </summary>
public void CommitTransaction(){
if(!inTransaction){
throw new DataStoreException("No transaction has been started");
}
transaction.Commit();
inTransaction = false;
}
/// <summary>
/// Rolls back a transaction from a pending state.
/// </summary>
public void RollbackTransaction(){
if(!inTransaction){
throw new DataStoreException("No transaction has been started");
}
transaction.Rollback();
inTransaction = false;
}
/// <summary>
/// Returns a pre-defined IDataAccessCommand.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An <see cref="IDataAccessCommand"/> object.</returns>
public IDataAccessCommand GetDataAccessCommand(string name){
object command = Commands[name];
if(command != null){
return (IDataAccessCommand)((IDataAccessCommand)command).Clone();
} else {
return null;
}
}
/// <summary>
/// Returns a pre-defined IObjectAccessCommand.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An <see cref="IObjectAccessCommand"/> object.</returns>
public IObjectAccessCommand GetObjectAccessCommand(string name){
object command = Commands[name];
if(command != null){
return (IObjectAccessCommand)((IObjectAccessCommand)command).Clone();
} else {
return null;
}
}
/// <summary>
/// Returns a pre-defined IFindObjectCommand.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An <see cref="IFindObjectCommand"/> object.</returns>
public IFindObjectCommand GetFindObjectCommand(string name){
object command = Commands[name];
if(command != null){
return (IFindObjectCommand)((IFindObjectCommand)command).Clone();
} else {
return null;
}
}
/// <summary>
/// Returns a pre-defined IFindCollectionCommand.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>An <see cref="IFindCollectionCommand"/> object.</returns>
public IFindCollectionCommand GetFindCollectionCommand(string name){
object command = Commands[name];
if(command != null){
return (IFindCollectionCommand)((IFindCollectionCommand)command).Clone();
} else {
return null;
}
}
#endregion
#region Implementation of ICloneable
/// <summary>
/// As each instance of DataStore is not thread, this creates a copy of this DataStore object that can be safely used.
/// </summary>
/// <returns></returns>
public object Clone() {
return this.MemberwiseClone();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace LogCentric.Web.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
using AutoMapper.Configuration.Internal;
namespace AutoMapper.Configuration
{
using static Expression;
using static ExpressionFactory;
public class MappingExpression : MappingExpression<object, object>, IMappingExpression
{
public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types)
{
}
public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap();
public IMappingExpression Substitute(Func<object, object> substituteFunc)
=> (IMappingExpression) base.Substitute(substituteFunc);
public new IMappingExpression ConstructUsingServiceLocator()
=> (IMappingExpression)base.ConstructUsingServiceLocator();
public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts));
void IMappingExpression.ConvertUsing<TTypeConverter>()
=> ConvertUsing(typeof(TTypeConverter));
public void ConvertUsing(Type typeConverterType)
=> TypeMapActions.Add(tm => tm.TypeConverterType = typeConverterType);
public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions)
=> base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o));
public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c));
public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
=> (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions);
public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType)
=> (IMappingExpression)base.Include(otherSourceType, otherDestinationType);
public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter();
public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
=> (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase)
=> (IMappingExpression)base.IncludeBase(sourceBase, destinationBase);
public new IMappingExpression BeforeMap(Action<object, object> beforeFunction)
=> (IMappingExpression)base.BeforeMap(beforeFunction);
public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.BeforeMap<TMappingAction>();
public new IMappingExpression AfterMap(Action<object, object> afterFunction)
=> (IMappingExpression)base.AfterMap(afterFunction);
public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>
=> (IMappingExpression)base.AfterMap<TMappingAction>();
public new IMappingExpression ConstructUsing(Func<object, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public new IMappingExpression ConstructUsing(Func<object, ResolutionContext, object> ctor)
=> (IMappingExpression)base.ConstructUsing(ctor);
public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor)
{
TypeMapActions.Add(tm => tm.ConstructExpression = ctor);
return this;
}
public new IMappingExpression ValidateMemberList(MemberList memberList)
=> (IMappingExpression) base.ValidateMemberList(memberList);
public new IMappingExpression MaxDepth(int depth)
=> (IMappingExpression)base.MaxDepth(depth);
public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions)
=> (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions);
public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences();
protected override IPropertyMapConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType)
=> new MemberConfigurationExpression(member, sourceType);
protected override MappingExpression<object, object> CreateReverseMapExpression()
=> new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source);
internal class MemberConfigurationExpression : MemberConfigurationExpression<object, object, object>, IMemberConfigurationExpression
{
public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType)
: base(destinationMember, sourceType)
{
}
public void ResolveUsing(Type valueResolverType)
{
var config = new ValueResolverConfiguration(valueResolverType, valueResolverType.GetGenericInterface(typeof(IValueResolver<,,>)));
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing(Type valueResolverType, string memberName)
{
var config = new ValueResolverConfiguration(valueResolverType, valueResolverType.GetGenericInterface(typeof(IMemberValueResolver<,,,>)))
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TSource, TDestination, TSourceMember, TDestMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember> resolver, string memberName)
{
var config = new ValueResolverConfiguration(resolver, typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TDestMember>))
{
SourceMemberName = memberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
}
}
public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration
{
private readonly List<IPropertyMapConfiguration> _memberConfigurations = new List<IPropertyMapConfiguration>();
private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>();
private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>();
private readonly List<ValueTransformerConfiguration> _valueTransformers = new List<ValueTransformerConfiguration>();
private MappingExpression<TDestination, TSource> _reverseMap;
private Action<IMemberConfigurationExpression<TSource, TDestination, object>> _allMemberOptions;
private Func<MemberInfo, bool> _memberFilter;
public MappingExpression(MemberList memberList)
: this(memberList, typeof(TSource), typeof(TDestination))
{
}
public MappingExpression(MemberList memberList, Type sourceType, Type destinationType)
: this(memberList, new TypePair(sourceType, destinationType))
{
}
public MappingExpression(MemberList memberList, TypePair types)
{
Types = types;
IsOpenGeneric = types.SourceType.IsGenericTypeDefinition() || types.DestinationType.IsGenericTypeDefinition();
TypeMapActions.Add(tm => tm.ConfiguredMemberList = memberList);
}
public TypePair Types { get; }
public Type SourceType => Types.SourceType;
public Type DestinationType => Types.DestinationType;
public bool IsOpenGeneric { get; }
public ITypeMapConfiguration ReverseTypeMap => _reverseMap;
public IList<ValueTransformerConfiguration> ValueTransformers => _valueTransformers;
protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>();
public IMappingExpression<TSource, TDestination> PreserveReferences()
{
TypeMapActions.Add(tm => tm.PreserveReferences = true);
return this;
}
protected virtual IPropertyMapConfiguration CreateMemberConfigurationExpression<TMember>(MemberInfo member, Type sourceType)
=> new MemberConfigurationExpression<TSource, TDestination, TMember>(member, sourceType);
protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression()
=> new MappingExpression<TDestination, TSource>(MemberList.None, DestinationType, SourceType);
public IMappingExpression<TSource, TDestination> ForPath<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IPathConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
if(!destinationMember.IsMemberPath())
{
throw new ArgumentOutOfRangeException(nameof(destinationMember), "Only member accesses are allowed.");
}
var expression = new PathConfigurationExpression<TSource, TDestination, TMember>(destinationMember);
var firstMember = expression.MemberPath.First;
var firstMemberConfig = GetDestinationMemberConfiguration(firstMember);
if(firstMemberConfig == null)
{
IgnoreDestinationMember(firstMember, ignorePaths: false);
}
_memberConfigurations.Add(expression);
memberOptions(expression);
return this;
}
public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember,
Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(destinationMember);
return ForDestinationMember(memberInfo, memberOptions);
}
public IMappingExpression<TSource, TDestination> ForMember(string name,
Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
var member = DestinationType.GetFieldOrProperty(name);
return ForDestinationMember(member, memberOptions);
}
public void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = m => GetDestinationMemberConfiguration(m) == null;
}
public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, TDestination, object>> memberOptions)
{
_allMemberOptions = memberOptions;
_memberFilter = _ => true;
}
public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter()
{
foreach(var property in DestinationType.PropertiesWithAnInaccessibleSetter())
{
IgnoreDestinationMember(property);
}
return this;
}
private void IgnoreDestinationMember(MemberInfo property, bool ignorePaths = true) =>
ForDestinationMember<object>(property, options => options.Ignore(ignorePaths));
public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter()
{
foreach(var property in SourceType.PropertiesWithAnInaccessibleSetter())
{
ForSourceMember(property.Name, options => options.Ignore());
}
return this;
}
public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>()
where TOtherSource : TSource
where TOtherDestination : TDestination
=> IncludeCore(typeof(TOtherSource), typeof(TOtherDestination));
public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType)
{
CheckIsDerived(otherSourceType, SourceType);
CheckIsDerived(otherDestinationType, DestinationType);
return IncludeCore(otherSourceType, otherDestinationType);
}
IMappingExpression<TSource, TDestination> IncludeCore(Type otherSourceType, Type otherDestinationType)
{
TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType));
return this;
}
public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>()
=> IncludeBase(typeof(TSourceBase), typeof(TDestinationBase));
public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase)
{
CheckIsDerived(SourceType, sourceBase);
CheckIsDerived(DestinationType, destinationBase);
TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase));
return this;
}
public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression)
{
TypeMapActions.Add(tm => tm.CustomProjection = projectionExpression);
}
public IMappingExpression<TSource, TDestination> MaxDepth(int depth)
{
TypeMapActions.Add(tm => tm.MaxDepth = depth);
return this;
}
public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator()
{
TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true);
return this;
}
public IMappingExpression<TDestination, TSource> ReverseMap()
{
_reverseMap = CreateReverseMapExpression();
_reverseMap._memberConfigurations.AddRange(_memberConfigurations.Select(m => m.Reverse()).Where(m=>m!=null));
return _reverseMap;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = ReflectionHelper.FindProperty(sourceMember);
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions)
{
var memberInfo = SourceType.GetFieldOrProperty(sourceMemberName);
var srcConfig = new SourceMappingExpression(memberInfo);
memberOptions(srcConfig);
_sourceMemberConfigurations.Add(srcConfig);
return this;
}
public IMappingExpression<TSource, TDestination> Substitute<TSubstitute>(Func<TSource, TSubstitute> substituteFunc)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TSubstitute>> expr = (src, dest, ctxt) => substituteFunc(src);
tm.Substitution = expr;
});
return this;
}
public void ConvertUsing(Func<TSource, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src, dest);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(Func<TSource, TDestination, ResolutionContext, TDestination> mappingFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, TDestination>> expr =
(src, dest, ctxt) => mappingFunction(src, dest, ctxt);
tm.CustomMapper = expr;
});
}
public void ConvertUsing(ITypeConverter<TSource, TDestination> converter)
{
ConvertUsing(converter.Convert);
}
public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>
{
TypeMapActions.Add(tm => tm.TypeConverterType = typeof (TTypeConverter));
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => beforeFunction(src, dest, ctxt);
tm.AddBeforeMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
void BeforeFunction(TSource src, TDestination dest, ResolutionContext ctxt)
=> ((TMappingAction) ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);
return BeforeMap(BeforeFunction);
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction)
{
TypeMapActions.Add(tm =>
{
Expression<Action<TSource, TDestination, ResolutionContext>> expr =
(src, dest, ctxt) => afterFunction(src, dest, ctxt);
tm.AddAfterMapAction(expr);
});
return this;
}
public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>
{
void AfterFunction(TSource src, TDestination dest, ResolutionContext ctxt)
=> ((TMappingAction) ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest);
return AfterMap(AfterFunction);
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, ResolutionContext, TDestination> ctor)
{
TypeMapActions.Add(tm =>
{
Expression<Func<TSource, ResolutionContext, TDestination>> expr = (src, ctxt) => ctor(src, ctxt);
tm.DestinationCtor = expr;
});
return this;
}
public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor)
{
TypeMapActions.Add(tm =>
{
tm.ConstructExpression = ctor;
var ctxtParam = Parameter(typeof (ResolutionContext), "ctxt");
var srcParam = Parameter(typeof (TSource), "src");
var body = ctor.ReplaceParameters(srcParam);
tm.DestinationCtor = Lambda(body, srcParam, ctxtParam);
});
return this;
}
private IMappingExpression<TSource, TDestination> ForDestinationMember<TMember>(MemberInfo destinationProperty, Action<MemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
{
var expression = (MemberConfigurationExpression<TSource, TDestination, TMember>) CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType);
_memberConfigurations.Add(expression);
memberOptions(expression);
return this;
}
public void As<T>() where T : TDestination => As(typeof(T));
public void As(Type typeOverride)
{
CheckIsDerived(typeOverride, DestinationType);
TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride);
}
private void CheckIsDerived(Type derivedType, Type baseType)
{
if(!baseType.IsAssignableFrom(derivedType) && !derivedType.IsGenericTypeDefinition() && !baseType.IsGenericTypeDefinition())
{
throw new ArgumentOutOfRangeException(nameof(derivedType), $"{derivedType} is not derived from {baseType}.");
}
}
public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions)
{
var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName);
paramOptions(ctorParamExpression);
_ctorParamConfigurations.Add(ctorParamExpression);
return this;
}
public IMappingExpression<TSource, TDestination> DisableCtorValidation()
{
TypeMapActions.Add(tm =>
{
tm.DisableConstructorValidation = true;
});
return this;
}
public IMappingExpression<TSource, TDestination> AddTransform<TValue>(Expression<Func<TValue, TValue>> transformer)
{
var config = new ValueTransformerConfiguration(typeof(TValue), transformer);
_valueTransformers.Add(config);
return this;
}
public IMappingExpression<TSource, TDestination> ValidateMemberList(MemberList memberList)
{
TypeMapActions.Add(tm =>
{
tm.ConfiguredMemberList = memberList;
});
return this;
}
private IPropertyMapConfiguration GetDestinationMemberConfiguration(MemberInfo destinationMember) =>
_memberConfigurations.FirstOrDefault(m => m.DestinationMember == destinationMember);
public void Configure(TypeMap typeMap)
{
foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors)
{
var attrs = destProperty.GetCustomAttributes(true);
if (attrs.Any(x => x is IgnoreMapAttribute))
{
IgnoreDestinationMember(destProperty);
var sourceProperty = typeMap.SourceType.GetInheritedMember(destProperty.Name);
if (sourceProperty != null)
{
_reverseMap?.IgnoreDestinationMember(sourceProperty);
}
}
if (typeMap.Profile.GlobalIgnores.Contains(destProperty.Name) && GetDestinationMemberConfiguration(destProperty) == null)
{
IgnoreDestinationMember(destProperty);
}
}
if (_allMemberOptions != null)
{
foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Where(_memberFilter))
{
ForDestinationMember(accessor, _allMemberOptions);
}
}
foreach (var action in TypeMapActions)
{
action(typeMap);
}
foreach (var memberConfig in _memberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var memberConfig in _sourceMemberConfigurations)
{
memberConfig.Configure(typeMap);
}
foreach (var paramConfig in _ctorParamConfigurations)
{
paramConfig.Configure(typeMap);
}
foreach (var valueTransformer in _valueTransformers)
{
typeMap.AddValueTransformation(valueTransformer);
}
if (_reverseMap != null)
{
ReverseSourceMembers(typeMap);
foreach(var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.Ignored))
{
_reverseMap.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore());
}
foreach(var includedDerivedType in typeMap.IncludedDerivedTypes)
{
_reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType);
}
foreach(var includedBaseType in typeMap.IncludedBaseTypes)
{
_reverseMap.IncludeBase(includedBaseType.DestinationType, includedBaseType.SourceType);
}
}
}
private void ReverseSourceMembers(TypeMap typeMap)
{
foreach(var propertyMap in typeMap.GetPropertyMaps().Where(p => p.SourceMembers.Count > 1 && !p.SourceMembers.Any(s=>s is MethodInfo)))
{
_reverseMap.TypeMapActions.Add(reverseTypeMap =>
{
var memberPath = new MemberPath(propertyMap.SourceMembers);
var newDestination = Parameter(reverseTypeMap.DestinationType, "destination");
var path = propertyMap.SourceMembers.MemberAccesses(newDestination);
var forPathLambda = Lambda(path, newDestination);
var pathMap = reverseTypeMap.FindOrCreatePathMapFor(forPathLambda, memberPath, reverseTypeMap);
pathMap.SourceExpression = MemberAccessLambda(propertyMap.DestinationProperty);
});
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Agent.PluginHost
{
public static class Program
{
private static CancellationTokenSource tokenSource = new CancellationTokenSource();
private static string executingAssemblyLocation = string.Empty;
public static int Main(string[] args)
{
if (PlatformUtil.UseLegacyHttpHandler)
{
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
}
Console.CancelKeyPress += Console_CancelKeyPress;
// Set encoding to UTF8, process invoker will use UTF8 write to STDIN
Console.InputEncoding = Encoding.UTF8;
Console.OutputEncoding = Encoding.UTF8;
try
{
ArgUtil.NotNull(args, nameof(args));
ArgUtil.Equal(2, args.Length, nameof(args.Length));
string pluginType = args[0];
if (string.Equals("task", pluginType, StringComparison.OrdinalIgnoreCase))
{
string assemblyQualifiedName = args[1];
ArgUtil.NotNullOrEmpty(assemblyQualifiedName, nameof(assemblyQualifiedName));
string serializedContext = Console.ReadLine();
ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));
AgentTaskPluginExecutionContext executionContext = StringUtil.ConvertFromJson<AgentTaskPluginExecutionContext>(serializedContext);
ArgUtil.NotNull(executionContext, nameof(executionContext));
VariableValue culture;
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
if (executionContext.Variables.TryGetValue("system.culture", out culture) &&
!string.IsNullOrEmpty(culture?.Value))
{
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(culture.Value);
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture.Value);
}
AssemblyLoadContext.Default.Resolving += ResolveAssembly;
try
{
Type type = Type.GetType(assemblyQualifiedName, throwOnError: true);
var taskPlugin = Activator.CreateInstance(type) as IAgentTaskPlugin;
ArgUtil.NotNull(taskPlugin, nameof(taskPlugin));
taskPlugin.RunAsync(executionContext, tokenSource.Token).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// any exception throw from plugin will fail the task.
executionContext.Error(ex.Message);
executionContext.Debug(ex.StackTrace);
}
finally
{
AssemblyLoadContext.Default.Resolving -= ResolveAssembly;
}
return 0;
}
else if (string.Equals("command", pluginType, StringComparison.OrdinalIgnoreCase))
{
string assemblyQualifiedName = args[1];
ArgUtil.NotNullOrEmpty(assemblyQualifiedName, nameof(assemblyQualifiedName));
string serializedContext = Console.ReadLine();
ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));
AgentCommandPluginExecutionContext executionContext = StringUtil.ConvertFromJson<AgentCommandPluginExecutionContext>(serializedContext);
ArgUtil.NotNull(executionContext, nameof(executionContext));
AssemblyLoadContext.Default.Resolving += ResolveAssembly;
try
{
Type type = Type.GetType(assemblyQualifiedName, throwOnError: true);
var commandPlugin = Activator.CreateInstance(type) as IAgentCommandPlugin;
ArgUtil.NotNull(commandPlugin, nameof(commandPlugin));
commandPlugin.ProcessCommandAsync(executionContext, tokenSource.Token).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// any exception throw from plugin will fail the command.
executionContext.Error(ex.ToString());
}
finally
{
AssemblyLoadContext.Default.Resolving -= ResolveAssembly;
}
return 0;
}
else if (string.Equals("log", pluginType, StringComparison.OrdinalIgnoreCase))
{
// read commandline arg to get the instance id
var instanceId = args[1];
ArgUtil.NotNullOrEmpty(instanceId, nameof(instanceId));
// read STDIN, the first line will be the HostContext for the log plugin host
string serializedContext = Console.ReadLine();
ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));
AgentLogPluginHostContext hostContext = StringUtil.ConvertFromJson<AgentLogPluginHostContext>(serializedContext);
ArgUtil.NotNull(hostContext, nameof(hostContext));
// create plugin object base on plugin assembly names from the HostContext
List<IAgentLogPlugin> logPlugins = new List<IAgentLogPlugin>();
AssemblyLoadContext.Default.Resolving += ResolveAssembly;
try
{
foreach (var pluginAssembly in hostContext.PluginAssemblies)
{
try
{
Type type = Type.GetType(pluginAssembly, throwOnError: true);
var logPlugin = Activator.CreateInstance(type) as IAgentLogPlugin;
ArgUtil.NotNull(logPlugin, nameof(logPlugin));
logPlugins.Add(logPlugin);
}
catch (Exception ex)
{
// any exception throw from plugin will get trace and ignore, error from plugins will not fail the job.
Console.WriteLine($"Unable to load plugin '{pluginAssembly}': {ex}");
}
}
}
finally
{
AssemblyLoadContext.Default.Resolving -= ResolveAssembly;
}
// start the log plugin host
var logPluginHost = new AgentLogPluginHost(hostContext, logPlugins);
Task hostTask = logPluginHost.Run();
while (true)
{
var consoleInput = Console.ReadLine();
if (string.Equals(consoleInput, $"##vso[logplugin.finish]{instanceId}", StringComparison.OrdinalIgnoreCase))
{
// singal all plugins, the job has finished.
// plugin need to start their finalize process.
logPluginHost.Finish();
break;
}
else
{
// the format is TimelineRecordId(GUID):Output(String)
logPluginHost.EnqueueOutput(consoleInput);
}
}
// wait for the host to finish.
hostTask.GetAwaiter().GetResult();
return 0;
}
else
{
throw new ArgumentOutOfRangeException(pluginType);
}
}
catch (Exception ex)
{
// infrastructure failure.
Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
Console.CancelKeyPress -= Console_CancelKeyPress;
}
}
private static Assembly ResolveAssembly(AssemblyLoadContext context, AssemblyName assembly)
{
string assemblyFilename = assembly.Name + ".dll";
if (string.IsNullOrEmpty(executingAssemblyLocation))
{
executingAssemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
return context.LoadFromAssemblyPath(Path.Combine(executingAssemblyLocation, assemblyFilename));
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
tokenSource.Cancel();
}
}
}
| |
// ***********************************************************************
// 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 NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
public partial class Assert
{
#region Assert.That
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void That(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
static public void That(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#endregion
#region Lambda returning Boolean
#if !NET_2_0
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void That(Func<bool> condition, string message, params object[] args)
{
Assert.That(condition.Invoke(), Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
static public void That(Func<bool> condition)
{
Assert.That(condition.Invoke(), Is.True, null, null);
}
#endif
#endregion
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
static public void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void That<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
throw new AssertionException(writer.ToString());
}
}
#endregion
#region TestDelegate
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
static public void That(TestDelegate code, IResolveConstraint constraint)
{
Assert.That(code, constraint, null, null);
}
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A ThrowsConstraint used in the test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void That(TestDelegate code, IResolveConstraint constraint, string message, params string[] args)
{
Assert.That((object)code, constraint, message, args);
}
#endregion
#endregion
#region Assert.That<TActual>
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
static public void That<TActual>(TActual actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void That<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
throw new AssertionException(writer.ToString());
}
}
#endregion
#region Assert.ByVal
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <param name="expression">A Constraint to be applied</param>
/// <param name="actual">The actual value to test</param>
static public void ByVal(object actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// Used as a synonym for That in rare cases where a private setter
/// causes a Visual Basic compilation error.
/// </summary>
/// <remarks>
/// This method is provided for use by VB developers needing to test
/// the value of properties with private setters.
/// </remarks>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void ByVal(object actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(actual, expression, message, args);
}
#endregion
}
}
| |
// 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 1.2.2.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Search.Fluent
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Search;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ServicesOperations.
/// </summary>
public static partial class ServicesOperationsExtensions
{
/// <summary>
/// Creates or updates a Search service in the given resource group. If the
/// Search service already exists, all properties will be updated with the
/// given values.
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription. You can
/// obtain this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='searchServiceName'>
/// The name of the Azure Search service to create or update. Search service
/// names must only contain lowercase letters, digits or dashes, cannot use
/// dash as the first two or last one characters, cannot contain consecutive
/// dashes, and must be between 2 and 60 characters in length. Search service
/// names must be globally unique since they are part of the service URI
/// (https://<name>.search.windows.net). You cannot change the service
/// name after the service is created.
/// </param>
/// <param name='service'>
/// The definition of the Search service to create or update.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SearchServiceInner> CreateOrUpdateAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchServiceInner service, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, searchServiceName, service, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the Search service with the given name in the given resource group.
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription. You can
/// obtain this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='searchServiceName'>
/// The name of the Azure Search service associated with the specified resource
/// group.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SearchServiceInner> GetAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Search service in the given resource group, along with its
/// associated resources.
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription. You can
/// obtain this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='searchServiceName'>
/// The name of the Azure Search service associated with the specified resource
/// group.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets a list of all Search services in the given resource group.
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription. You can
/// obtain this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<SearchServiceInner>> ListByResourceGroupAsync(this IServicesOperations operations, string resourceGroupName, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Checks whether or not the given Search service name is available for use.
/// Search service names must be globally unique since they are part of the
/// service URI (https://<name>.search.windows.net).
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='name'>
/// The Search service name to validate. Search service names must only contain
/// lowercase letters, digits or dashes, cannot use dash as the first two or
/// last one characters, cannot contain consecutive dashes, and must be between
/// 2 and 60 characters in length.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CheckNameAvailabilityOutputInner> CheckNameAvailabilityAsync(this IServicesOperations operations, string name, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a Search service in the given resource group. If the
/// Search service already exists, all properties will be updated with the
/// given values.
/// <see href="https://aka.ms/search-manage" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the current subscription. You can
/// obtain this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='searchServiceName'>
/// The name of the Azure Search service to create or update. Search service
/// names must only contain lowercase letters, digits or dashes, cannot use
/// dash as the first two or last one characters, cannot contain consecutive
/// dashes, and must be between 2 and 60 characters in length. Search service
/// names must be globally unique since they are part of the service URI
/// (https://<name>.search.windows.net). You cannot change the service
/// name after the service is created.
/// </param>
/// <param name='service'>
/// The definition of the Search service to create or update.
/// </param>
/// <param name='searchManagementRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SearchServiceInner> BeginCreateOrUpdateAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchServiceInner service, SearchManagementRequestOptionsInner searchManagementRequestOptions = default(SearchManagementRequestOptionsInner), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, searchServiceName, service, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using System.Collections.Immutable;
namespace Signum.Engine.Authorization;
public static class OperationAuthLogic
{
static AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed> cache = null!;
public static IManualAuth<(OperationSymbol operation, Type type), OperationAllowed> Manual { get { return cache; } }
public static bool IsStarted { get { return cache != null; } }
public static readonly Dictionary<OperationSymbol, MinimumTypeAllowed> MinimumTypeAllowed = new Dictionary<OperationSymbol, MinimumTypeAllowed>();
public static readonly Dictionary<OperationSymbol, OperationAllowed> MaxAutomaticUpgrade = new Dictionary<OperationSymbol, OperationAllowed>();
internal static readonly string operationReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
AuthLogic.AssertStarted(sb);
OperationLogic.AssertStarted(sb);
OperationLogic.AllowOperation += OperationLogic_AllowOperation;
sb.Include<RuleOperationEntity>()
.WithUniqueIndex(rt => new { rt.Resource.Operation, rt.Resource.Type, rt.Role });
cache = new AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed>(sb,
toKey: s => (operation: s.Operation, type: s.Type.ToType()),
toEntity: s => new OperationTypeEmbedded { Operation = s.operation, Type = s.type.ToTypeEntity() },
isEquals: (o1, o2) => o1.Operation.Is(o2.Operation) && o1.Type.Is(o2.Type),
merger: new OperationMerger(),
invalidateWithTypes: true,
coercer: OperationCoercer.Instance);
sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query =>
{
Database.Query<RuleOperationEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
return null;
};
AuthLogic.ExportToXml += exportAll => cache.ExportXml("Operations", "Operation", s => s.operation.Key + "/" + s.type?.ToTypeEntity().CleanName, b => b.ToString(),
exportAll ? AllOperationTypes() : null);
AuthLogic.ImportFromXml += (x, roles, replacements) =>
{
var allResources = x.Element("Operations")!.Elements("Role").SelectMany(r => r.Elements("Operation")).Select(p => p.Attribute("Resource")!.Value).ToHashSet();
replacements.AskForReplacements(
allResources.Select(a => a.TryBefore("/") ?? a).ToHashSet(),
SymbolLogic<OperationSymbol>.AllUniqueKeys(),
operationReplacementKey);
string typeReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
replacements.AskForReplacements(
allResources.Select(a => a.After("/")).ToHashSet(),
TypeLogic.NameToType.Keys.ToHashSet(),
TypeAuthCache.typeReplacementKey);
return cache.ImportXml(x, "Operations", "Operation", roles,
s => {
var operation = SymbolLogic<OperationSymbol>.TryToSymbol(replacements.Apply(operationReplacementKey, s.Before("/")));
var type = TypeLogic.TryGetType(replacements.Apply(TypeAuthCache.typeReplacementKey, s.After("/")));
if (operation == null || type == null || !OperationLogic.IsDefined(type, operation))
return null;
return new OperationTypeEmbedded { Operation = operation, Type = type.ToTypeEntity() };
}, EnumExtensions.ToEnum<OperationAllowed>);
};
sb.Schema.Table<OperationSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteOperationSqlSync);
sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteTypeSqlSync);
}
}
static SqlPreCommand AuthCache_PreDeleteOperationSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Operation, (OperationSymbol)arg);
}
static SqlPreCommand AuthCache_PreDeleteTypeSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Type, (TypeEntity)arg);
}
public static T SetMaxAutomaticUpgrade<T>(this T operation, OperationAllowed allowed) where T : IOperation
{
MaxAutomaticUpgrade.Add(operation.OperationSymbol, allowed);
return operation;
}
static bool OperationLogic_AllowOperation(OperationSymbol operationKey, Type entityType, bool inUserInterface)
{
return GetOperationAllowed(operationKey, entityType, inUserInterface);
}
public static OperationRulePack GetOperationRules(Lite<RoleEntity> role, TypeEntity typeEntity)
{
var entityType = typeEntity.ToType();
var resources = OperationLogic.GetAllOperationInfos(entityType).Select(a => new OperationTypeEmbedded { Operation = a.OperationSymbol, Type = typeEntity });
var result = new OperationRulePack { Role = role, Type = typeEntity, };
cache.GetRules(result, resources);
var coercer = OperationCoercer.Instance.GetCoerceValue(role);
result.Rules.ForEach(r =>
{
var operationType = (operation: r.Resource.Operation, type: r.Resource.Type.ToType());
r.CoercedValues = EnumExtensions.GetValues<OperationAllowed>().Where(a => !coercer(operationType, a).Equals(a)).ToArray();
});
return result;
}
public static void SetOperationRules(OperationRulePack rules)
{
cache.SetRules(rules, r => r.Type.Is(rules.Type));
}
public static bool GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType, bool inUserInterface)
{
OperationAllowed allowed = GetOperationAllowed(role, operation, entityType);
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static OperationAllowed GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType)
{
return cache.GetAllowed(role, (operation, entityType));
}
public static bool GetOperationAllowed(OperationSymbol operation, Type type, bool inUserInterface)
{
if (!AuthLogic.IsEnabled || ExecutionMode.InGlobal)
return true;
if (GetTemporallyAllowed(operation))
return true;
OperationAllowed allowed = cache.GetAllowed(RoleEntity.Current, (operation, type));
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static AuthThumbnail? GetAllowedThumbnail(Lite<RoleEntity> role, Type entityType)
{
return OperationLogic.GetAllOperationInfos(entityType).Select(oi => cache.GetAllowed(role, (oi.OperationSymbol, entityType))).Collapse();
}
public static Dictionary<(OperationSymbol operation, Type type), OperationAllowed> AllowedOperations()
{
return AllOperationTypes().ToDictionary(a => a, a => cache.GetAllowed(RoleEntity.Current, a));
}
static List<(OperationSymbol operation, Type type)> AllOperationTypes()
{
return (from type in Schema.Current.Tables.Keys
from o in OperationLogic.TypeOperations(type)
select (operation: o.OperationSymbol, type: type))
.ToList();
}
static readonly Variable<ImmutableStack<OperationSymbol>> tempAllowed = Statics.ThreadVariable<ImmutableStack<OperationSymbol>>("authTempOperationsAllowed");
public static IDisposable AllowTemporally(OperationSymbol operationKey)
{
tempAllowed.Value = (tempAllowed.Value ?? ImmutableStack<OperationSymbol>.Empty).Push(operationKey);
return new Disposable(() => tempAllowed.Value = tempAllowed.Value.Pop());
}
internal static bool GetTemporallyAllowed(OperationSymbol operationKey)
{
var ta = tempAllowed.Value;
if (ta == null || ta.IsEmpty)
return false;
return ta.Contains(operationKey);
}
public static T SetMinimumTypeAllowed<T>(this T operation, TypeAllowedBasic? overridenType, TypeAllowedBasic? returnType = null) where T : IOperation
{
MinimumTypeAllowed.Add(operation.OperationSymbol, new MinimumTypeAllowed { OverridenType = overridenType, ReturnType = returnType });
return operation;
}
public static OperationAllowed InferredOperationAllowed((OperationSymbol operation, Type type) operationType, Func<Type, TypeAllowedAndConditions> allowed)
{
Func<Type, TypeAllowedBasic, OperationAllowed> operationAllowed = (t, checkFor) =>
{
if (!TypeLogic.TypeToEntity.ContainsKey(t))
return OperationAllowed.Allow;
var ta = allowed(t);
return checkFor <= ta.MaxUI() ? OperationAllowed.Allow :
checkFor <= ta.MaxDB() ? OperationAllowed.DBOnly :
OperationAllowed.None;
};
var operation = OperationLogic.FindOperation(operationType.type ?? /*Temp*/ OperationLogic.FindTypes(operationType.operation).First(), operationType.operation);
var mta = OperationAuthLogic.MinimumTypeAllowed.TryGetC(operationType.operation);
switch (operation.OperationType)
{
case OperationType.Execute:
case OperationType.Delete:
return operationAllowed(operation.OverridenType, mta?.OverridenType ?? TypeAllowedBasic.Write);
case OperationType.Constructor:
return operationAllowed(operation.ReturnType!, mta?.ReturnType ?? TypeAllowedBasic.Write);
case OperationType.ConstructorFrom:
case OperationType.ConstructorFromMany:
{
var fromTypeAllowed = operationAllowed(operation.OverridenType, mta?.OverridenType ?? TypeAllowedBasic.Read);
var returnTypeAllowed = operationAllowed(operation.ReturnType!, mta?.ReturnType ?? TypeAllowedBasic.Write);
return returnTypeAllowed < fromTypeAllowed ? returnTypeAllowed : fromTypeAllowed;
}
default:
throw new UnexpectedValueException(operation.OperationType);
}
}
}
class OperationMerger : IMerger<(OperationSymbol operation, Type type), OperationAllowed>
{
public OperationAllowed Merge((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role, IEnumerable<KeyValuePair<Lite<RoleEntity>, OperationAllowed>> baseValues)
{
OperationAllowed best = AuthLogic.GetMergeStrategy(role) == MergeStrategy.Union ?
Max(baseValues.Select(a => a.Value)):
Min(baseValues.Select(a => a.Value));
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return best;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(operationType.Item1);
if (maxUp.HasValue && maxUp <= best)
return best;
if (baseValues.Where(a => a.Value.Equals(best)).All(a => GetDefault(operationType, a.Key).Equals(a.Value)))
{
var def = GetDefault(operationType, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
}
return best;
}
static OperationAllowed GetDefault((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role)
{
return OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.GetAllowed(role, t));
}
static OperationAllowed Max(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.None;
foreach (var item in baseValues)
{
if (item > result)
result = item;
if (result == OperationAllowed.Allow)
return result;
}
return result;
}
static OperationAllowed Min(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.Allow;
foreach (var item in baseValues)
{
if (item < result)
result = item;
if (result == OperationAllowed.None)
return result;
}
return result;
}
public Func<(OperationSymbol operation, Type type), OperationAllowed> MergeDefault(Lite<RoleEntity> role)
{
return key =>
{
if (AuthLogic.GetDefaultAllowed(role))
return OperationAllowed.Allow;
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return OperationAllowed.None;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(key.operation);
var def = GetDefault(key, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
};
}
}
public class MinimumTypeAllowed
{
public TypeAllowedBasic? OverridenType;
public TypeAllowedBasic? ReturnType;
}
class OperationCoercer : Coercer<OperationAllowed, (OperationSymbol symbol, Type type)>
{
public static readonly OperationCoercer Instance = new OperationCoercer();
private OperationCoercer()
{
}
public override Func<(OperationSymbol symbol, Type type), OperationAllowed, OperationAllowed> GetCoerceValue(Lite<RoleEntity> role)
{
return (operationType, allowed) =>
{
var required = OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
public override Func<Lite<RoleEntity>, OperationAllowed, OperationAllowed> GetCoerceValueManual((OperationSymbol symbol, Type type) operationType)
{
return (role, allowed) =>
{
var required = OperationAuthLogic.InferredOperationAllowed(operationType, t => TypeAuthLogic.Manual.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
namespace Vanara.PInvoke
{
/// <summary>
/// Formal replacement for the Windows NTStatus definition. In ntstatus.h, it is a defined UINT value. For .NET, this class strongly
/// types the value.
/// <para>The 32-bit value is organized as follows:</para>
/// <list type="table">
/// <item>
/// <term>Bit</term>
/// <description>0 - 1</description>
/// <description>2</description>
/// <description>3</description>
/// <description>4 - 15</description>
/// <description>16 - 31</description>
/// </item>
/// <item>
/// <term>Field</term>
/// <description>Sev</description>
/// <description>Customer</description>
/// <description>Reserved</description>
/// <description>Facility</description>
/// <description>Code</description>
/// </item>
/// </list>
/// </summary>
/// <seealso cref="System.IComparable"/>
/// <seealso cref="System.IComparable{NTStatus}"/>
/// <seealso cref="System.IEquatable{NTStatus}"/>
[StructLayout(LayoutKind.Sequential)]
[TypeConverter(typeof(NTStatusTypeConverter))]
[PInvokeData("winerr.h")]
public partial struct NTStatus : IComparable, IComparable<NTStatus>, IEquatable<NTStatus>, IEquatable<int>, IEquatable<uint>, IConvertible, IErrorProvider
{
internal readonly int _value;
private const int codeMask = 0xFFFF;
private const uint customerMask = 0x20000000;
private const int FACILITY_NT_BIT = 0x10000000;
private const uint facilityMask = 0x0FFF0000;
private const int facilityShift = 16;
private const uint severityMask = 0xC0000000;
private const int severityShift = 30;
/// <summary>Initializes a new instance of the <see cref="NTStatus"/> structure.</summary>
/// <param name="rawValue">The raw NTStatus value.</param>
public NTStatus(int rawValue) => _value = rawValue;
/// <summary>Initializes a new instance of the <see cref="NTStatus"/> structure.</summary>
/// <param name="rawValue">The raw NTStatus value.</param>
public NTStatus(uint rawValue) => _value = unchecked((int)rawValue);
/// <summary>Enumeration of facility codes</summary>
[PInvokeData("winerr.h")]
public enum FacilityCode : ushort
{
/// <summary>The default facility code.</summary>
FACILITY_NULL = 0,
/// <summary>The facility debugger</summary>
FACILITY_DEBUGGER = 0x1,
/// <summary>The facility RPC runtime</summary>
FACILITY_RPC_RUNTIME = 0x2,
/// <summary>The facility RPC stubs</summary>
FACILITY_RPC_STUBS = 0x3,
/// <summary>The facility io error code</summary>
FACILITY_IO_ERROR_CODE = 0x4,
/// <summary>The facility codclass error code</summary>
FACILITY_CODCLASS_ERROR_CODE = 0x6,
/// <summary>The facility ntwi N32</summary>
FACILITY_NTWIN32 = 0x7,
/// <summary>The facility ntcert</summary>
FACILITY_NTCERT = 0x8,
/// <summary>The facility ntsspi</summary>
FACILITY_NTSSPI = 0x9,
/// <summary>The facility terminal server</summary>
FACILITY_TERMINAL_SERVER = 0xA,
/// <summary>The faciltiy MUI error code</summary>
FACILTIY_MUI_ERROR_CODE = 0xB,
/// <summary>The facility usb error code</summary>
FACILITY_USB_ERROR_CODE = 0x10,
/// <summary>The facility hid error code</summary>
FACILITY_HID_ERROR_CODE = 0x11,
/// <summary>The facility firewire error code</summary>
FACILITY_FIREWIRE_ERROR_CODE = 0x12,
/// <summary>The facility cluster error code</summary>
FACILITY_CLUSTER_ERROR_CODE = 0x13,
/// <summary>The facility acpi error code</summary>
FACILITY_ACPI_ERROR_CODE = 0x14,
/// <summary>The facility SXS error code</summary>
FACILITY_SXS_ERROR_CODE = 0x15,
/// <summary>The facility transaction</summary>
FACILITY_TRANSACTION = 0x19,
/// <summary>The facility commonlog</summary>
FACILITY_COMMONLOG = 0x1A,
/// <summary>The facility video</summary>
FACILITY_VIDEO = 0x1B,
/// <summary>The facility filter manager</summary>
FACILITY_FILTER_MANAGER = 0x1C,
/// <summary>The facility monitor</summary>
FACILITY_MONITOR = 0x1D,
/// <summary>The facility graphics kernel</summary>
FACILITY_GRAPHICS_KERNEL = 0x1E,
/// <summary>The facility driver framework</summary>
FACILITY_DRIVER_FRAMEWORK = 0x20,
/// <summary>The facility fve error code</summary>
FACILITY_FVE_ERROR_CODE = 0x21,
/// <summary>The facility FWP error code</summary>
FACILITY_FWP_ERROR_CODE = 0x22,
/// <summary>The facility ndis error code</summary>
FACILITY_NDIS_ERROR_CODE = 0x23,
/// <summary>The facility TPM</summary>
FACILITY_TPM = 0x29,
/// <summary>The facility RTPM</summary>
FACILITY_RTPM = 0x2A,
/// <summary>The facility hypervisor</summary>
FACILITY_HYPERVISOR = 0x35,
/// <summary>The facility ipsec</summary>
FACILITY_IPSEC = 0x36,
/// <summary>The facility virtualization</summary>
FACILITY_VIRTUALIZATION = 0x37,
/// <summary>The facility volmgr</summary>
FACILITY_VOLMGR = 0x38,
/// <summary>The facility BCD error code</summary>
FACILITY_BCD_ERROR_CODE = 0x39,
/// <summary>The facility wi N32 k ntuser</summary>
FACILITY_WIN32K_NTUSER = 0x3E,
/// <summary>The facility wi N32 k ntgdi</summary>
FACILITY_WIN32K_NTGDI = 0x3F,
/// <summary>The facility resume key filter</summary>
FACILITY_RESUME_KEY_FILTER = 0x40,
/// <summary>The facility RDBSS</summary>
FACILITY_RDBSS = 0x41,
/// <summary>The facility BTH att</summary>
FACILITY_BTH_ATT = 0x42,
/// <summary>The facility secureboot</summary>
FACILITY_SECUREBOOT = 0x43,
/// <summary>The facility audio kernel</summary>
FACILITY_AUDIO_KERNEL = 0x44,
/// <summary>The facility VSM</summary>
FACILITY_VSM = 0x45,
/// <summary>The facility volsnap</summary>
FACILITY_VOLSNAP = 0x50,
/// <summary>The facility sdbus</summary>
FACILITY_SDBUS = 0x51,
/// <summary>The facility shared VHDX</summary>
FACILITY_SHARED_VHDX = 0x5C,
/// <summary>The facility SMB</summary>
FACILITY_SMB = 0x5D,
/// <summary>The facility interix</summary>
FACILITY_INTERIX = 0x99,
/// <summary>The facility spaces</summary>
FACILITY_SPACES = 0xE7,
/// <summary>The facility security core</summary>
FACILITY_SECURITY_CORE = 0xE8,
/// <summary>The facility system integrity</summary>
FACILITY_SYSTEM_INTEGRITY = 0xE9,
/// <summary>The facility licensing</summary>
FACILITY_LICENSING = 0xEA,
/// <summary>The facility platform manifest</summary>
FACILITY_PLATFORM_MANIFEST = 0xEB,
/// <summary>The facility maximum value</summary>
FACILITY_MAXIMUM_VALUE = 0xEC
}
/// <summary>A value indicating the severity of an <see cref="NTStatus"/> value (bits 30-31).</summary>
[PInvokeData("winerr.h")]
public enum SeverityLevel : byte
{
/// <summary>
/// Indicates a successful NTSTATUS value, such as STATUS_SUCCESS, or the value IO_ERR_RETRY_SUCCEEDED in error log packets.
/// </summary>
STATUS_SEVERITY_SUCCESS = 0x0,
/// <summary>Indicates an informational NTSTATUS value, such as STATUS_SERIAL_MORE_WRITES.</summary>
STATUS_SEVERITY_INFORMATIONAL = 0x1,
/// <summary>Indicates a warning NTSTATUS value, such as STATUS_DEVICE_PAPER_EMPTY.</summary>
STATUS_SEVERITY_WARNING = 0x2,
/// <summary>
/// Indicates an error NTSTATUS value, such as STATUS_INSUFFICIENT_RESOURCES for a FinalStatus value or
/// IO_ERR_CONFIGURATION_ERROR for an ErrorCode value in error log packets.
/// </summary>
STATUS_SEVERITY_ERROR = 0x3
}
/// <summary>Gets the code portion of the <see cref="NTStatus"/>.</summary>
/// <value>The code value (bits 0-15).</value>
public ushort Code => GetCode(_value);
/// <summary>Gets a value indicating whether this code is customer defined (true) or from Microsoft (false).</summary>
/// <value><c>true</c> if customer defined; otherwise, <c>false</c>.</value>
public bool CustomerDefined => IsCustomerDefined(_value);
/// <summary>Gets the facility portion of the <see cref="NTStatus"/>.</summary>
/// <value>The facility value (bits 16-26).</value>
public FacilityCode Facility => GetFacility(_value);
/// <summary>Gets a value indicating whether this <see cref="NTStatus"/> is a failure (Severity bit 31 equals 1).</summary>
/// <value><c>true</c> if failed; otherwise, <c>false</c>.</value>
public bool Failed => Severity == SeverityLevel.STATUS_SEVERITY_ERROR;
/// <summary>Gets the severity level of the <see cref="NTStatus"/>.</summary>
/// <value>The severity level.</value>
public SeverityLevel Severity => GetSeverity(_value);
/// <summary>Gets a value indicating whether this <see cref="NTStatus"/> is a success (Severity bit 31 equals 0).</summary>
/// <value><c>true</c> if succeeded; otherwise, <c>false</c>.</value>
public bool Succeeded => !Failed;
/// <summary>Performs an explicit conversion from <see cref="NTStatus"/> to <see cref="HRESULT"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The resulting <see cref="HRESULT"/> instance from the conversion.</returns>
public static explicit operator HRESULT(NTStatus value) => value.ToHRESULT();
/// <summary>Performs an explicit conversion from <see cref="NTStatus"/> to <see cref="System.Int32"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator int(NTStatus value) => value._value;
/// <summary>Performs an explicit conversion from <see cref="NTStatus"/> to <see cref="System.UInt32"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(NTStatus value) => unchecked((uint)value._value);
/// <summary>Gets the code value from a 32-bit value.</summary>
/// <param name="ntstatus">The 32-bit raw NTStatus value.</param>
/// <returns>The code value (bits 0-15).</returns>
public static ushort GetCode(int ntstatus) => (ushort)(ntstatus & codeMask);
/// <summary>Gets the facility value from a 32-bit value.</summary>
/// <param name="ntstatus">The 32-bit raw NTStatus value.</param>
/// <returns>The facility value (bits 16-26).</returns>
public static FacilityCode GetFacility(int ntstatus) => (FacilityCode)((ntstatus & facilityMask) >> facilityShift);
/// <summary>Gets the severity value from a 32-bit value.</summary>
/// <param name="ntstatus">The 32-bit raw NTStatus value.</param>
/// <returns>The severity value (bit 31).</returns>
public static SeverityLevel GetSeverity(int ntstatus) => (SeverityLevel)((ntstatus & severityMask) >> severityShift);
/// <summary>Performs an implicit conversion from <see cref="System.Int32"/> to <see cref="NTStatus"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator NTStatus(int value) => new NTStatus(value);
/// <summary>Performs an implicit conversion from <see cref="System.UInt32"/> to <see cref="NTStatus"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator NTStatus(uint value) => new NTStatus(value);
/// <summary>Performs an implicit conversion from <see cref="Win32Error"/> to <see cref="NTStatus"/>.</summary>
/// <param name="value">The value.</param>
/// <returns>The resulting <see cref="NTStatus"/> instance from the conversion.</returns>
public static implicit operator NTStatus(Win32Error value) => NTSTATUS_FROM_WIN32((uint)value);
/// <summary>Gets the customer defined bit from a 32-bit value.</summary>
/// <param name="ntstatus">The 32-bit raw NTStatus value.</param>
/// <returns><c>true</c> if the customer defined bit is set; otherwise, <c>false</c>.</returns>
public static bool IsCustomerDefined(int ntstatus) => (ntstatus & customerMask) > 0;
/// <summary>Creates a new <see cref="NTStatus"/> from provided values.</summary>
/// <param name="severity">The severity level.</param>
/// <param name="customerDefined">The bit is set for customer-defined values and clear for Microsoft-defined values.</param>
/// <param name="facility">The facility.</param>
/// <param name="code">The code.</param>
/// <returns>The resulting <see cref="NTStatus"/>.</returns>
public static NTStatus Make(SeverityLevel severity, bool customerDefined, FacilityCode facility, ushort code) => Make(severity, customerDefined, (ushort)facility, code);
/// <summary>Creates a new <see cref="NTStatus"/> from provided values.</summary>
/// <param name="severity">The severity level.</param>
/// <param name="customerDefined">The bit is set for customer-defined values and clear for Microsoft-defined values.</param>
/// <param name="facility">The facility.</param>
/// <param name="code">The code.</param>
/// <returns>The resulting <see cref="NTStatus"/>.</returns>
public static NTStatus Make(SeverityLevel severity, bool customerDefined, ushort facility, ushort code) =>
new NTStatus(unchecked((int)(((uint)severity << severityShift) | (customerDefined ? customerMask : 0U) | ((uint)facility << facilityShift) | code)));
/// <summary>Converts a Win32 error to an NTSTATUS.</summary>
/// <param name="x">The Win32 error codex.</param>
/// <returns>The equivalent NTSTATUS value.</returns>
public static NTStatus NTSTATUS_FROM_WIN32(uint x) => unchecked((int)x) <= 0 ? unchecked((int)x) : unchecked((int)(((x) & 0x0000FFFF) | ((uint)FacilityCode.FACILITY_NTWIN32 << 16) | 0xC0000000U));
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="NTStatus"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(NTStatus hrLeft, NTStatus hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="int"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(NTStatus hrLeft, int hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator !=.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="uint"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(NTStatus hrLeft, uint hrRight) => !(hrLeft == hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="NTStatus"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(NTStatus hrLeft, NTStatus hrRight) => hrLeft.Equals(hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="int"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(NTStatus hrLeft, int hrRight) => hrLeft.Equals(hrRight);
/// <summary>Implements the operator ==.</summary>
/// <param name="hrLeft">The first <see cref="NTStatus"/>.</param>
/// <param name="hrRight">The second <see cref="uint"/>.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(NTStatus hrLeft, uint hrRight) => hrLeft.Equals(hrRight);
/// <summary>Converts the specified NTSTATUS code to its equivalent system error code.</summary>
/// <param name="status">The NTSTATUS code to be converted.</param>
/// <returns>
/// The function returns the corresponding system error code. ERROR_MR_MID_NOT_FOUND is returned when the specified NTSTATUS code
/// does not have a corresponding system error code.
/// </returns>
[DllImport(Lib.NtDll, ExactSpelling = true)]
[PInvokeData("Winternl.h", MSDNShortId = "ms680600")]
public static extern uint RtlNtStatusToDosError(int status);
/// <summary>
/// If the supplied raw NTStatus value represents a failure, throw the associated <see cref="Exception"/> with the optionally
/// supplied message.
/// </summary>
/// <param name="ntstatus">The 32-bit raw NTStatus value.</param>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
public static void ThrowIfFailed(int ntstatus, string message = null) => new NTStatus(ntstatus).ThrowIfFailed(message);
/// <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(NTStatus other) => _value.CompareTo(other._value);
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current
/// instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less
/// than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the
/// sort order as <paramref name="obj"/> . Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
public int CompareTo(object obj)
{
var v = ValueFromObj(obj);
return v.HasValue
? _value.CompareTo(v.Value)
: throw new ArgumentException(@"Object cannot be converted to a UInt32 value for comparison.", nameof(obj));
}
/// <summary>Indicates whether the current object is equal to an <see cref="int"/>.</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(int other) => other == _value;
/// <summary>Indicates whether the current object is equal to an <see cref="uint"/>.</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(uint other) => unchecked((int)other) == _value;
/// <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 switch
{
null => false,
NTStatus n => Equals(n),
int i => Equals(i),
uint u => Equals(u),
_ => Equals(_value, ValueFromObj(obj)),
};
/// <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(NTStatus other) => other._value == _value;
/// <summary>Gets the .NET <see cref="Exception"/> associated with the NTStatus value and optionally adds the supplied message.</summary>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
/// <returns>The associated <see cref="Exception"/> or <c>null</c> if this NTStatus is not a failure.</returns>
[SecurityCritical]
[SecuritySafeCritical]
public Exception GetException(string message = null) => !Failed ? null : ToHRESULT().GetException(message);
/// <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() => _value;
/// <summary>
/// If this <see cref="NTStatus"/> represents a failure, throw the associated <see cref="Exception"/> with the optionally supplied message.
/// </summary>
/// <param name="message">The optional message to assign to the <see cref="Exception"/>.</param>
[SecurityCritical]
[SecuritySafeCritical]
public void ThrowIfFailed(string message = null)
{
var exception = GetException(message);
if (exception != null)
throw exception;
}
/// <summary>Converts this error to an <see cref="T:Vanara.PInvoke.HRESULT"/>.</summary>
/// <returns>An equivalent <see cref="T:Vanara.PInvoke.HRESULT"/>.</returns>
public HRESULT ToHRESULT()
{
Win32Error werr = RtlNtStatusToDosError(_value);
return werr != Win32Error.ERROR_MR_MID_NOT_FOUND ? (HRESULT)werr : HRESULT_FROM_NT(_value);
}
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString()
{
// Check for defined NTStatus value
StaticFieldValueHash.TryGetFieldName<NTStatus, int>(_value, out var err);
var msg = HRESULT.FormatMessage(unchecked((uint)_value));
return (err ?? string.Format(CultureInfo.InvariantCulture, "0x{0:X8}", _value)) + (msg == null ? "" : ": " + msg);
}
TypeCode IConvertible.GetTypeCode() => _value.GetTypeCode();
bool IConvertible.ToBoolean(IFormatProvider provider) => Succeeded;
byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)_value).ToByte(provider);
char IConvertible.ToChar(IFormatProvider provider) => throw new NotSupportedException();
DateTime IConvertible.ToDateTime(IFormatProvider provider) => throw new NotSupportedException();
decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)_value).ToDecimal(provider);
double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)_value).ToDouble(provider);
short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)_value).ToInt16(provider);
int IConvertible.ToInt32(IFormatProvider provider) => _value;
long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)_value).ToInt64(provider);
sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)_value).ToSByte(provider);
float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)_value).ToSingle(provider);
string IConvertible.ToString(IFormatProvider provider) => ToString();
object IConvertible.ToType(Type conversionType, IFormatProvider provider) =>
((IConvertible)_value).ToType(conversionType, provider);
ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)unchecked((uint)_value)).ToUInt16(provider);
uint IConvertible.ToUInt32(IFormatProvider provider) => unchecked((uint)_value);
ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)unchecked((uint)_value)).ToUInt64(provider);
[ExcludeFromCodeCoverage]
private static HRESULT HRESULT_FROM_NT(int ntStatus) => ntStatus | FACILITY_NT_BIT;
private static int? ValueFromObj(object obj)
{
switch (obj)
{
case null:
return null;
case int i:
return i;
case uint u:
return unchecked((int)u);
default:
var c = TypeDescriptor.GetConverter(obj);
return c.CanConvertTo(typeof(int)) ? (int?)c.ConvertTo(obj, typeof(int)) : null;
}
}
}
internal class NTStatusTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType.IsPrimitive && sourceType != typeof(char))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string) || destinationType.IsPrimitive && destinationType != typeof(char))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value != null && value.GetType().IsPrimitive)
{
if (value is bool b)
return b ? NTStatus.STATUS_SUCCESS : NTStatus.STATUS_UNSUCCESSFUL;
if (!(value is char))
return new NTStatus((int)Convert.ChangeType(value, TypeCode.Int32));
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
Type destinationType)
{
if (!(value is NTStatus)) throw new NotSupportedException();
if (destinationType.IsPrimitive && destinationType != typeof(char))
return Convert.ChangeType((NTStatus)value, destinationType);
if (destinationType == typeof(string))
return ((NTStatus)value).ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
| |
// 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.Threading;
using Alachisoft.NCache.Common.Pooling;
using Alachisoft.NCache.Caching.Pooling;
using Alachisoft.NCache.Common.Pooling.Lease;
using Alachisoft.NCache.Runtime.Serialization;
namespace Alachisoft.NCache.Caching
{
/// <summary>
/// make it serializable coz cache operations performed through remoting will fail
/// otherwise.
/// </summary>
[Serializable]
public class OperationContext : SimpleLease, ICompactSerializable, ICloneable
{
private static readonly string s_operationUniqueID;
private static readonly OperationID s_operationID;
private static readonly int _fieldCount = Enum.GetValues(typeof(OperationContextFieldName)).Length;
private static long s_operationCounter;
private object[] _fieldValueTable = new object[_fieldCount];
[NonSerialized]
private CancellationToken _cancelationToken;
[ThreadStatic]
private static bool s_isReplicationOperaton;
public static bool IsReplicationOperation
{
get { return s_isReplicationOperaton; }
set { s_isReplicationOperaton = value; }
}
static OperationContext()
{
s_operationUniqueID = Guid.NewGuid().ToString().Substring(0, 4);
s_operationID = new OperationID() { OpCounter = s_operationCounter, OperationId = s_operationUniqueID };
}
public OperationContext()
{
NeedUserPayload = true;
CloneCacheEntry = true;
UseObjectPool = true;
//CreateOperationId();
}
public OperationContext(OperationContextFieldName fieldName, object fieldValue) : this()
{
Add(fieldName, fieldValue);
}
/// <summary>
/// This flag indicates weather we need user payload when a CachEntry is deep cloned or not
/// WARNGING : This flag MUST be set only when there is a genuine need to user payload and
/// Set it for only Get Operation.
/// </summary>
public bool NeedUserPayload
{
get { return Contains(OperationContextFieldName.NeedUserPayload); }
set
{
if (value) Add(OperationContextFieldName.NeedUserPayload, true);
else RemoveValueByField(OperationContextFieldName.NeedUserPayload);
}
}
/// <summary>
/// This flag indicates weather deep cloning of CachEntry is required or not
/// WARNGING : This flag MUST be Set for only Get Operation.
/// </summary>
public bool CloneCacheEntry
{
get { return Contains(OperationContextFieldName.CloneCacheEntry); }
set
{
if (value) Add(OperationContextFieldName.CloneCacheEntry, true);
else RemoveValueByField(OperationContextFieldName.CloneCacheEntry);
}
}
/// <summary>
/// This flag indicates weather to use pool for returning objects like CachEntry etc.
/// If set False, objects are created through normal new operator
/// </summary>
public bool UseObjectPool
{
get { return Contains(OperationContextFieldName.UseObjectPool); }
set
{
if (value) Add(OperationContextFieldName.UseObjectPool, true);
else RemoveValueByField(OperationContextFieldName.UseObjectPool);
}
}
#region Creating OperationContext
public static OperationContext Create(PoolManager poolManager)
{
return poolManager.GetOperationContextPool()?.Rent(true);
}
public static OperationContext CreateAndMarkInUse(PoolManager poolManager, int moduleRefId)
{
var instance = Create(poolManager);
instance.MarkInUse(moduleRefId);
return instance;
}
public static OperationContext Create(PoolManager poolManager, OperationContextFieldName fieldName, object fieldValue)
{
var instance = Create(poolManager);
instance.Add(fieldName, fieldValue);
return instance;
}
public static OperationContext CreateAndMarkInUse(PoolManager poolManager, int moduleRefId, OperationContextFieldName fieldName, object fieldValue)
{
var instance = Create(poolManager, fieldName, fieldValue);
instance.MarkInUse(moduleRefId);
return instance;
}
#endregion
public OperationID OperatoinID
{
get => s_operationID;
}
public bool IsRemoveQueryOperation
{
get => (GetValueByField(OperationContextFieldName.RemoveQueryOperation) as bool?) ?? false;
}
public CancellationToken CancellationToken
{
set { _cancelationToken = value; }
get { return _cancelationToken; }
}
public void Add(OperationContextFieldName fieldName, object fieldValue)
{
_fieldValueTable[(int)fieldName] = fieldValue;
}
public object GetValueByField(OperationContextFieldName fieldName)
{
return _fieldValueTable[(int)fieldName];
}
public bool Contains(OperationContextFieldName fieldName)
{
return _fieldValueTable[(int)fieldName] != null;
}
public long ClientOperationTimeout
{
get => (GetValueByField(OperationContextFieldName.ClientOperationTimeout) as long?) ?? -1;
}
public void RemoveValueByField(OperationContextFieldName fieldName)
{
_fieldValueTable[(int)fieldName] = null;
}
public bool IsOperation(OperationContextOperationType operationType)
{
return (OperationContextOperationType)GetValueByField(OperationContextFieldName.OperationType) == operationType;
}
private void CreateOperationId()
{
long opCounter = Interlocked.Increment(ref s_operationCounter);
var operationId = IsFromPool
? OperationID.Create(PoolManager, s_operationUniqueID, opCounter)
: new OperationID() { OpCounter = opCounter, OperationId = s_operationUniqueID };
Add(OperationContextFieldName.OperationId, operationId);
}
#region ILeasable
public override void MarkFree(int moduleRefId)
{
}
public override void ResetLeasable()
{
Array.Clear(_fieldValueTable, 0, _fieldCount);
_cancelationToken = default(CancellationToken);
s_isReplicationOperaton = default(bool);
NeedUserPayload = true;
CloneCacheEntry = true;
UseObjectPool = true;
}
public override void ReturnLeasableToPool()
{
}
#endregion
#region ICompactSerializable Members
public void Deserialize(Runtime.Serialization.IO.CompactReader reader)
{
_fieldValueTable = (object[])reader.ReadObject();
}
public void Serialize(Runtime.Serialization.IO.CompactWriter writer)
{
writer.WriteObject(_fieldValueTable);
}
#endregion
#region ICloneable Members
public object Clone()
{
return DeepClone(this.PoolManager);
}
public OperationContext DeepClone(PoolManager poolManager)
{
OperationContext operationContext = null;
if (poolManager == null)
operationContext = new OperationContext();
else
operationContext = poolManager.GetOperationContextPool()?.Rent(initialize: true);
for (int i = 0; i < _fieldValueTable.Length; i++)
{
var value = _fieldValueTable[i];
var cloned = (value as ICloneable)?.Clone();
operationContext._fieldValueTable[i] = cloned ?? value;
}
return operationContext;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
namespace NAudio.Wave
{
/// <summary>
/// Represents a wave out device
/// </summary>
public class WaveOut : IWavePlayer, IWavePosition
{
private IntPtr hWaveOut;
private WaveOutBuffer[] buffers;
private IWaveProvider waveStream;
private volatile PlaybackState playbackState;
private WaveInterop.WaveCallback callback;
private float volume = 1;
private WaveCallbackInfo callbackInfo;
private object waveOutLock;
private int queuedBuffers;
private SynchronizationContext syncContext;
/// <summary>
/// Indicates playback has stopped automatically
/// </summary>
public event EventHandler<StoppedEventArgs> PlaybackStopped;
/// <summary>
/// Retrieves the capabilities of a waveOut device
/// </summary>
/// <param name="devNumber">Device to test</param>
/// <returns>The WaveOut device capabilities</returns>
public static WaveOutCapabilities GetCapabilities(int devNumber)
{
WaveOutCapabilities caps = new WaveOutCapabilities();
int structSize = Marshal.SizeOf(caps);
MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, out caps, structSize), "waveOutGetDevCaps");
return caps;
}
/// <summary>
/// Returns the number of Wave Out devices available in the system
/// </summary>
public static Int32 DeviceCount
{
get
{
return WaveInterop.waveOutGetNumDevs();
}
}
/// <summary>
/// Gets or sets the desired latency in milliseconds
/// Should be set before a call to Init
/// </summary>
public int DesiredLatency { get; set; }
/// <summary>
/// Gets or sets the number of buffers used
/// Should be set before a call to Init
/// </summary>
public int NumberOfBuffers { get; set; }
/// <summary>
/// Gets or sets the device number
/// Should be set before a call to Init
/// This must be between 0 and <see>DeviceCount</see> - 1.
/// </summary>
public int DeviceNumber { get; set; }
/// <summary>
/// Creates a default WaveOut device
/// Will use window callbacks if called from a GUI thread, otherwise function
/// callbacks
/// </summary>
public WaveOut()
: this(SynchronizationContext.Current == null ? WaveCallbackInfo.FunctionCallback() : WaveCallbackInfo.NewWindow())
{
}
/// <summary>
/// Creates a WaveOut device using the specified window handle for callbacks
/// </summary>
/// <param name="windowHandle">A valid window handle</param>
public WaveOut(IntPtr windowHandle)
: this(WaveCallbackInfo.ExistingWindow(windowHandle))
{
}
/// <summary>
/// Opens a WaveOut device
/// </summary>
public WaveOut(WaveCallbackInfo callbackInfo)
{
this.syncContext = SynchronizationContext.Current;
// set default values up
this.DeviceNumber = 0;
this.DesiredLatency = 300;
this.NumberOfBuffers = 2;
this.callback = new WaveInterop.WaveCallback(Callback);
this.waveOutLock = new object();
this.callbackInfo = callbackInfo;
callbackInfo.Connect(this.callback);
}
/// <summary>
/// Initialises the WaveOut device
/// </summary>
/// <param name="waveProvider">WaveProvider to play</param>
public void Init(IWaveProvider waveProvider)
{
this.waveStream = waveProvider;
int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers);
MmResult result;
lock (waveOutLock)
{
result = callbackInfo.WaveOutOpen(out hWaveOut, DeviceNumber, waveStream.WaveFormat, callback);
}
MmException.Try(result, "waveOutOpen");
buffers = new WaveOutBuffer[NumberOfBuffers];
playbackState = PlaybackState.Stopped;
for (int n = 0; n < NumberOfBuffers; n++)
{
buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
}
}
/// <summary>
/// Start playing the audio from the WaveStream
/// </summary>
public void Play()
{
if (playbackState == PlaybackState.Stopped)
{
playbackState = PlaybackState.Playing;
Debug.Assert(queuedBuffers == 0, "Buffers already queued on play");
EnqueueBuffers();
}
else if (playbackState == PlaybackState.Paused)
{
EnqueueBuffers();
Resume();
playbackState = PlaybackState.Playing;
}
}
private void EnqueueBuffers()
{
for (int n = 0; n < NumberOfBuffers; n++)
{
if (!buffers[n].InQueue)
{
if (buffers[n].OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
else
{
playbackState = PlaybackState.Stopped;
break;
}
//Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] requeued", n));
}
else
{
//Debug.WriteLine(String.Format("Resume from Pause: Buffer [{0}] already queued", n));
}
}
}
/// <summary>
/// Pause the audio
/// </summary>
public void Pause()
{
if (playbackState == PlaybackState.Playing)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutPause(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutPause");
}
playbackState = PlaybackState.Paused;
}
}
/// <summary>
/// Resume playing after a pause from the same position
/// </summary>
public void Resume()
{
if (playbackState == PlaybackState.Paused)
{
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutRestart(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutRestart");
}
playbackState = PlaybackState.Playing;
}
}
/// <summary>
/// Stop and reset the WaveOut device
/// </summary>
public void Stop()
{
if (playbackState != PlaybackState.Stopped)
{
// in the call to waveOutReset with function callbacks
// some drivers will block here until OnDone is called
// for every buffer
playbackState = PlaybackState.Stopped; // set this here to avoid a problem with some drivers whereby
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutReset(hWaveOut);
}
if (result != MmResult.NoError)
{
throw new MmException(result, "waveOutReset");
}
// with function callbacks, waveOutReset will call OnDone,
// and so PlaybackStopped must not be raised from the handler
// we know playback has definitely stopped now, so raise callback
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback)
{
RaisePlaybackStoppedEvent(null);
}
}
}
/// <summary>
/// Gets the current position in bytes from the wave output device.
/// (n.b. this is not the same thing as the position within your reader
/// stream - it calls directly into waveOutGetPosition)
/// </summary>
/// <returns>Position in bytes</returns>
public long GetPosition()
{
lock (waveOutLock)
{
MmTime mmTime = new MmTime();
mmTime.wType = MmTime.TIME_BYTES; // request results in bytes, TODO: perhaps make this a little more flexible and support the other types?
MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, out mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition");
if (mmTime.wType != MmTime.TIME_BYTES)
throw new Exception(string.Format("waveOutGetPosition: wType -> Expected {0}, Received {1}", MmTime.TIME_BYTES, mmTime.wType));
return mmTime.cb;
}
}
/// <summary>
/// Gets a <see cref="Wave.WaveFormat"/> instance indicating the format the hardware is using.
/// </summary>
public WaveFormat OutputWaveFormat
{
get { return this.waveStream.WaveFormat; }
}
/// <summary>
/// Playback State
/// </summary>
public PlaybackState PlaybackState
{
get { return playbackState; }
}
/// <summary>
/// Volume for this device 1.0 is full scale
/// </summary>
public float Volume
{
get
{
return volume;
}
set
{
if (value < 0) throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
if (value > 1) throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
volume = value;
float left = volume;
float right = volume;
int stereoVolume = (int)(left * 0xFFFF) + ((int)(right * 0xFFFF) << 16);
MmResult result;
lock (waveOutLock)
{
result = WaveInterop.waveOutSetVolume(hWaveOut, stereoVolume);
}
MmException.Try(result,"waveOutSetVolume");
}
}
#region Dispose Pattern
/// <summary>
/// Closes this WaveOut device
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
/// <summary>
/// Closes the WaveOut device and disposes of buffers
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
protected void Dispose(bool disposing)
{
Stop();
if (disposing)
{
if (buffers != null)
{
for (int n = 0; n < buffers.Length; n++)
{
if (buffers[n] != null)
{
buffers[n].Dispose();
}
}
buffers = null;
}
}
lock (waveOutLock)
{
WaveInterop.waveOutClose(hWaveOut);
}
if (disposing)
{
callbackInfo.Disconnect();
}
}
/// <summary>
/// Finalizer. Only called when user forgets to call <see>Dispose</see>
/// </summary>
~WaveOut()
{
System.Diagnostics.Debug.Assert(false, "WaveOut device was not closed");
Dispose(false);
}
#endregion
// made non-static so that playing can be stopped here
private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved)
{
if (uMsg == WaveInterop.WaveMessage.WaveOutDone)
{
GCHandle hBuffer = (GCHandle)wavhdr.userData;
WaveOutBuffer buffer = (WaveOutBuffer)hBuffer.Target;
Interlocked.Decrement(ref queuedBuffers);
Exception exception = null;
// check that we're not here through pressing stop
if (PlaybackState == PlaybackState.Playing)
{
// to avoid deadlocks in Function callback mode,
// we lock round this whole thing, which will include the
// reading from the stream.
// this protects us from calling waveOutReset on another
// thread while a WaveOutWrite is in progress
lock (waveOutLock)
{
try
{
if (buffer.OnDone())
{
Interlocked.Increment(ref queuedBuffers);
}
}
catch (Exception e)
{
// one likely cause is soundcard being unplugged
exception = e;
}
}
}
if (queuedBuffers == 0)
{
if (callbackInfo.Strategy == WaveCallbackStrategy.FunctionCallback && playbackState == Wave.PlaybackState.Stopped)
{
// the user has pressed stop
// DO NOT raise the playback stopped event from here
// since on the main thread we are still in the waveOutReset function
// Playback stopped will be raised elsewhere
}
else
{
playbackState = PlaybackState.Stopped; // set explicitly for when we reach the end of the audio
RaisePlaybackStoppedEvent(exception);
}
}
}
}
private void RaisePlaybackStoppedEvent(Exception e)
{
var handler = PlaybackStopped;
if (handler != null)
{
if (this.syncContext == null)
{
handler(this, new StoppedEventArgs(e));
}
else
{
this.syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null);
}
}
}
}
}
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Integer : java.lang.Number, Comparable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Integer()
{
InitJNI();
}
internal Integer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _numberOfLeadingZeros12987;
public static int numberOfLeadingZeros(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._numberOfLeadingZeros12987, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _numberOfTrailingZeros12988;
public static int numberOfTrailingZeros(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._numberOfTrailingZeros12988, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _bitCount12989;
public static int bitCount(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._bitCount12989, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _equals12990;
public sealed override bool equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Integer._equals12990, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._equals12990, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _toString12991;
public static global::java.lang.String toString(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._toString12991, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toString12992;
public static global::java.lang.String toString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._toString12992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toString12993;
public sealed override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.Integer._toString12993)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._toString12993)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _hashCode12994;
public sealed override int hashCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Integer._hashCode12994);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._hashCode12994);
}
internal static global::MonoJavaBridge.MethodId _reverseBytes12995;
public static int reverseBytes(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._reverseBytes12995, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _compareTo12996;
public int compareTo(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Integer._compareTo12996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._compareTo12996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _compareTo12997;
public int compareTo(java.lang.Integer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Integer._compareTo12997, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._compareTo12997, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _toHexString12998;
public static global::java.lang.String toHexString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._toHexString12998, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _valueOf12999;
public static global::java.lang.Integer valueOf(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._valueOf12999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _valueOf13000;
public static global::java.lang.Integer valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._valueOf13000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _valueOf13001;
public static global::java.lang.Integer valueOf(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._valueOf13001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _decode13002;
public static global::java.lang.Integer decode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._decode13002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _reverse13003;
public static int reverse(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._reverse13003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _byteValue13004;
public sealed override byte byteValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallByteMethod(this.JvmHandle, global::java.lang.Integer._byteValue13004);
else
return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._byteValue13004);
}
internal static global::MonoJavaBridge.MethodId _shortValue13005;
public sealed override short shortValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallShortMethod(this.JvmHandle, global::java.lang.Integer._shortValue13005);
else
return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._shortValue13005);
}
internal static global::MonoJavaBridge.MethodId _intValue13006;
public sealed override int intValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Integer._intValue13006);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._intValue13006);
}
internal static global::MonoJavaBridge.MethodId _longValue13007;
public sealed override long longValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.lang.Integer._longValue13007);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._longValue13007);
}
internal static global::MonoJavaBridge.MethodId _floatValue13008;
public sealed override float floatValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.Integer._floatValue13008);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._floatValue13008);
}
internal static global::MonoJavaBridge.MethodId _doubleValue13009;
public sealed override double doubleValue()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.Integer._doubleValue13009);
else
return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.Integer.staticClass, global::java.lang.Integer._doubleValue13009);
}
internal static global::MonoJavaBridge.MethodId _parseInt13010;
public static int parseInt(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._parseInt13010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _parseInt13011;
public static int parseInt(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._parseInt13011, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _toOctalString13012;
public static global::java.lang.String toOctalString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._toOctalString13012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toBinaryString13013;
public static global::java.lang.String toBinaryString(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._toBinaryString13013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getInteger13014;
public static global::java.lang.Integer getInteger(java.lang.String arg0, java.lang.Integer arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._getInteger13014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _getInteger13015;
public static global::java.lang.Integer getInteger(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._getInteger13015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _getInteger13016;
public static global::java.lang.Integer getInteger(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Integer.staticClass, global::java.lang.Integer._getInteger13016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Integer;
}
internal static global::MonoJavaBridge.MethodId _highestOneBit13017;
public static int highestOneBit(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._highestOneBit13017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _lowestOneBit13018;
public static int lowestOneBit(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._lowestOneBit13018, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _rotateLeft13019;
public static int rotateLeft(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._rotateLeft13019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _rotateRight13020;
public static int rotateRight(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._rotateRight13020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _signum13021;
public static int signum(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(java.lang.Integer.staticClass, global::java.lang.Integer._signum13021, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _Integer13022;
public Integer(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Integer.staticClass, global::java.lang.Integer._Integer13022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Integer13023;
public Integer(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Integer.staticClass, global::java.lang.Integer._Integer13023, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int MIN_VALUE
{
get
{
return -2147483648;
}
}
public static int MAX_VALUE
{
get
{
return 2147483647;
}
}
internal static global::MonoJavaBridge.FieldId _TYPE13024;
public static global::java.lang.Class TYPE
{
get
{
return default(global::java.lang.Class);
}
}
public static int SIZE
{
get
{
return 32;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Integer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Integer"));
global::java.lang.Integer._numberOfLeadingZeros12987 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "numberOfLeadingZeros", "(I)I");
global::java.lang.Integer._numberOfTrailingZeros12988 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "numberOfTrailingZeros", "(I)I");
global::java.lang.Integer._bitCount12989 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "bitCount", "(I)I");
global::java.lang.Integer._equals12990 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::java.lang.Integer._toString12991 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toString", "(II)Ljava/lang/String;");
global::java.lang.Integer._toString12992 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toString", "(I)Ljava/lang/String;");
global::java.lang.Integer._toString12993 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "toString", "()Ljava/lang/String;");
global::java.lang.Integer._hashCode12994 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "hashCode", "()I");
global::java.lang.Integer._reverseBytes12995 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "reverseBytes", "(I)I");
global::java.lang.Integer._compareTo12996 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "compareTo", "(Ljava/lang/Object;)I");
global::java.lang.Integer._compareTo12997 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "compareTo", "(Ljava/lang/Integer;)I");
global::java.lang.Integer._toHexString12998 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toHexString", "(I)Ljava/lang/String;");
global::java.lang.Integer._valueOf12999 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(Ljava/lang/String;I)Ljava/lang/Integer;");
global::java.lang.Integer._valueOf13000 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Integer;");
global::java.lang.Integer._valueOf13001 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "valueOf", "(I)Ljava/lang/Integer;");
global::java.lang.Integer._decode13002 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/Integer;");
global::java.lang.Integer._reverse13003 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "reverse", "(I)I");
global::java.lang.Integer._byteValue13004 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "byteValue", "()B");
global::java.lang.Integer._shortValue13005 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "shortValue", "()S");
global::java.lang.Integer._intValue13006 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "intValue", "()I");
global::java.lang.Integer._longValue13007 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "longValue", "()J");
global::java.lang.Integer._floatValue13008 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "floatValue", "()F");
global::java.lang.Integer._doubleValue13009 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "doubleValue", "()D");
global::java.lang.Integer._parseInt13010 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "parseInt", "(Ljava/lang/String;)I");
global::java.lang.Integer._parseInt13011 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "parseInt", "(Ljava/lang/String;I)I");
global::java.lang.Integer._toOctalString13012 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toOctalString", "(I)Ljava/lang/String;");
global::java.lang.Integer._toBinaryString13013 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "toBinaryString", "(I)Ljava/lang/String;");
global::java.lang.Integer._getInteger13014 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;Ljava/lang/Integer;)Ljava/lang/Integer;");
global::java.lang.Integer._getInteger13015 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;)Ljava/lang/Integer;");
global::java.lang.Integer._getInteger13016 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "getInteger", "(Ljava/lang/String;I)Ljava/lang/Integer;");
global::java.lang.Integer._highestOneBit13017 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "highestOneBit", "(I)I");
global::java.lang.Integer._lowestOneBit13018 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "lowestOneBit", "(I)I");
global::java.lang.Integer._rotateLeft13019 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "rotateLeft", "(II)I");
global::java.lang.Integer._rotateRight13020 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "rotateRight", "(II)I");
global::java.lang.Integer._signum13021 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Integer.staticClass, "signum", "(I)I");
global::java.lang.Integer._Integer13022 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "<init>", "(I)V");
global::java.lang.Integer._Integer13023 = @__env.GetMethodIDNoThrow(global::java.lang.Integer.staticClass, "<init>", "(Ljava/lang/String;)V");
}
}
}
| |
// Copyright 2019 DeepMind Technologies 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.
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
namespace Mujoco {
[TestFixture]
public class MjGizmosDrawArcTests {
[SetUp]
public void SetUp() {
MjGizmos.DrawLine = MockDrawLine;
MjGizmos.NumCircleSegments = 4;
_lineFrom = new List<Vector3>();
_lineTo = new List<Vector3>();
}
[TearDown]
public void TearDown() {
MjGizmos.DrawLine = Gizmos.DrawLine;
MjGizmos.NumCircleSegments = 32;
}
private List<Vector3> _lineFrom;
private List<Vector3> _lineTo;
private void MockDrawLine(Vector3 from, Vector3 to) {
_lineFrom.Add(from);
_lineTo.Add(to);
}
[Test]
public void LineCountOfDrawnCircle() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.up, 1.0f, 0.0f);
Assert.That(_lineFrom, Has.Count.EqualTo(MjGizmos.NumCircleSegments));
Assert.That(_lineTo, Has.Count.EqualTo(MjGizmos.NumCircleSegments));
}
[Test]
public void LineAdjacencyOfDrawnCircle() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.up, 1.0f, 0.0f);
Assert.That((_lineFrom[0] - _lineTo[3]).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[1] - _lineTo[0]).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[2] - _lineTo[1]).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[3] - _lineTo[2]).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void CircleVertexPositions() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.up, 1.0f, 0.0f);
Assert.That((_lineFrom[0] - new Vector3(0, 0, -1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[1] - new Vector3(-1, 0, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[2] - new Vector3(0, 0, 1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[3] - new Vector3(1, 0, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void VerticesOfOffsetCircle() {
MjGizmos.DrawArc(Vector3.one, 1.0f, Vector3.up, 1.0f, 0.0f);
Assert.That((_lineFrom[0] - new Vector3(1, 1, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[1] - new Vector3(0, 1, 1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[2] - new Vector3(1, 1, 2)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[3] - new Vector3(2, 1, 1)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void DrawingRotatedCircle() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.right, 1.0f, 0.0f);
Assert.That((_lineFrom[0] - new Vector3(0, 0, 1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[1] - new Vector3(0, -1, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[2] - new Vector3(0, 0, -1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineFrom[3] - new Vector3(0, 1, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void DrawingHalfCircle() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.up, 0.25f, 0.0f);
Assert.That(_lineFrom, Has.Count.EqualTo(1));
Assert.That(_lineTo, Has.Count.EqualTo(1));
Assert.That((_lineFrom[0] - new Vector3(0, 0, -1)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineTo[0] - new Vector3(-1, 0, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void DrawingHalfCircleWithOffsetCircumference() {
MjGizmos.DrawArc(Vector3.zero, 1.0f, Vector3.up, 0.25f, 90);
Assert.That((_lineFrom[0] - new Vector3(-1, 0, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_lineTo[0] - new Vector3(0, 0, 1)).magnitude, Is.LessThan(1e-3f));
}
}
[TestFixture]
public class MjGizmosCapsuleTests {
[SetUp]
public void SetUp() {
MjGizmos.DrawLine = MockDrawLine;
MjGizmos.DrawArc = MockDrawArc;
MjGizmos.NumCircleSegments = 4;
_arc = new List<Tuple<Vector3, float, Vector3, float, float>>();
}
[TearDown]
public void TearDown() {
MjGizmos.DrawLine = Gizmos.DrawLine;
MjGizmos.DrawArc = MjGizmos.DrawArcInternal;
MjGizmos.NumCircleSegments = 32;
}
private List<Tuple<Vector3, float, Vector3, float, float>> _arc;
private void MockDrawLine(Vector3 from, Vector3 to) {}
private void MockDrawArc(Vector3 position, float radius, Vector3 axis, float length,
float startAngle) {
_arc.Add(Tuple.Create(position, radius, axis, length, startAngle));
}
[Test]
public void NumberOfArcsUsedToDrawCapsule() {
MjGizmos.DrawWireCapsule(Vector3.zero, 0.5f, 1.0f);
Assert.That(_arc, Has.Count.EqualTo(6));
}
[Test]
public void CapsuleBaseCirclesOrigins() {
MjGizmos.DrawWireCapsule(Vector3.zero, 0.5f, 1.0f);
Assert.That((_arc[0].Item1 - new Vector3(0, 0.5f, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_arc[1].Item1 - new Vector3(0, -0.5f, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void CapsuleBaseCirclesRadiuses() {
MjGizmos.DrawWireCapsule(Vector3.zero, 0.5f, 1.0f);
Assert.That(_arc[0].Item2, Is.EqualTo(0.5f));
Assert.That(_arc[1].Item2, Is.EqualTo(0.5f));
}
[Test]
public void CapsuleBaseArcsOrigins() {
MjGizmos.DrawWireCapsule(Vector3.zero, 0.5f, 1.0f);
Assert.That((_arc[2].Item1 - new Vector3(0, -0.5f, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_arc[3].Item1 - new Vector3(0, 0.5f, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_arc[4].Item1 - new Vector3(0, 0.5f, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_arc[5].Item1 - new Vector3(0, -0.5f, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void CapsuleBaseArcsRadiuses() {
MjGizmos.DrawWireCapsule(Vector3.zero, 0.5f, 1.0f);
Assert.That(_arc[2].Item2, Is.EqualTo(0.5f));
Assert.That(_arc[3].Item2, Is.EqualTo(0.5f));
Assert.That(_arc[4].Item2, Is.EqualTo(0.5f));
Assert.That(_arc[5].Item2, Is.EqualTo(0.5f));
}
}
[TestFixture]
public class MjGizmosCylinderTests {
[SetUp]
public void SetUp() {
MjGizmos.DrawLine = MockDrawLine;
MjGizmos.DrawArc = MockDrawArc;
MjGizmos.NumCircleSegments = 4;
_arc = new List<Tuple<Vector3, float, Vector3, float, float>>();
}
[TearDown]
public void TearDown() {
MjGizmos.DrawLine = Gizmos.DrawLine;
MjGizmos.DrawArc = MjGizmos.DrawArcInternal;
MjGizmos.NumCircleSegments = 32;
}
private List<Tuple<Vector3, float, Vector3, float, float>> _arc;
private void MockDrawLine(Vector3 from, Vector3 to) {}
private void MockDrawArc(Vector3 position, float radius, Vector3 axis, float length,
float startAngle) {
_arc.Add(Tuple.Create(position, radius, axis, length, startAngle));
}
[Test]
public void NumberOfArcsUsedToDrawCylinder() {
MjGizmos.DrawWireCylinder(Vector3.zero, 0.5f, 1.0f);
Assert.That(_arc, Has.Count.EqualTo(2));
}
[Test]
public void CylinderBaseCirclesOrigins() {
MjGizmos.DrawWireCylinder(Vector3.zero, 0.5f, 1.0f);
Assert.That((_arc[0].Item1 - new Vector3(0, 0.5f, 0)).magnitude, Is.LessThan(1e-3f));
Assert.That((_arc[1].Item1 - new Vector3(0, -0.5f, 0)).magnitude, Is.LessThan(1e-3f));
}
[Test]
public void CylinderBaseCirclesRadiuses() {
MjGizmos.DrawWireCylinder(Vector3.zero, 0.5f, 1.0f);
Assert.That(_arc[0].Item2, Is.EqualTo(0.5f));
Assert.That(_arc[1].Item2, Is.EqualTo(0.5f));
}
}
[TestFixture]
public class MjGizmosPlaneTests {
[SetUp]
public void SetUp() {
MjGizmos.DrawLine = MockDrawLine;
_lines = new List<Tuple<Vector3, Vector3>>();
}
[TearDown]
public void TearDown() {
MjGizmos.DrawLine = Gizmos.DrawLine;
_lines.Clear();
}
private List<Tuple<Vector3, Vector3>> _lines;
private void MockDrawLine(Vector3 start, Vector3 end) {
_lines.Add(Tuple.Create(start, end));
}
[Test]
public void DrawingPlaneAroundArbitraryCenter() {
MjGizmos.DrawWirePlane(new Vector3(1, 2, 3), 1, 1);
Assert.That(_lines, Has.Count.EqualTo(5));
Assert.That(_lines[0].Item1, Is.EqualTo(new Vector3(0.5f, 2, 2.5f)));
Assert.That(_lines[0].Item2, Is.EqualTo(new Vector3(1.5f, 2, 2.5f)));
Assert.That(_lines[1].Item1, Is.EqualTo(new Vector3(1.5f, 2, 2.5f)));
Assert.That(_lines[1].Item2, Is.EqualTo(new Vector3(1.5f, 2, 3.5f)));
Assert.That(_lines[2].Item1, Is.EqualTo(new Vector3(1.5f, 2, 3.5f)));
Assert.That(_lines[2].Item2, Is.EqualTo(new Vector3(0.5f, 2, 3.5f)));
Assert.That(_lines[3].Item1, Is.EqualTo(new Vector3(0.5f, 2, 3.5f)));
Assert.That(_lines[3].Item2, Is.EqualTo(new Vector3(0.5f, 2, 2.5f)));
Assert.That(_lines[4].Item1, Is.EqualTo(new Vector3(0.5f, 2, 2.5f)));
Assert.That(_lines[4].Item2, Is.EqualTo(new Vector3(1.5f, 2, 3.5f)));
}
[Test]
public void DrawingPlaneWithCorrectDimensions() {
MjGizmos.DrawWirePlane(Vector3.zero, width: 2, height: 4);
Assert.That(_lines[0].Item1, Is.EqualTo(new Vector3(-1, 0, -2)));
Assert.That(_lines[0].Item2, Is.EqualTo(new Vector3(1, 0, -2)));
Assert.That(_lines[1].Item1, Is.EqualTo(new Vector3(1, 0, -2)));
Assert.That(_lines[1].Item2, Is.EqualTo(new Vector3(1, 0, 2)));
Assert.That(_lines[2].Item1, Is.EqualTo(new Vector3(1, 0, 2)));
Assert.That(_lines[2].Item2, Is.EqualTo(new Vector3(-1, 0, 2)));
Assert.That(_lines[3].Item1, Is.EqualTo(new Vector3(-1, 0, 2)));
Assert.That(_lines[3].Item2, Is.EqualTo(new Vector3(-1, 0, -2)));
Assert.That(_lines[4].Item1, Is.EqualTo(new Vector3(-1, 0, -2)));
Assert.That(_lines[4].Item2, Is.EqualTo(new Vector3(1, 0, 2)));
}
}
}
| |
using System;
using Jasper.AzureServiceBus.Internal;
using Jasper.Serialization;
using Jasper.Util;
using Microsoft.Azure.ServiceBus;
using Shouldly;
using TestingSupport;
using TestMessages;
using Xunit;
namespace Jasper.AzureServiceBus.Tests
{
public class DefaultEnvelopeMapperTests
{
private readonly Lazy<Envelope> _mapped;
private readonly Message theMessage = new()
{
Body = new byte[] {1, 2, 3, 4}
};
private readonly Envelope theOriginal = new()
{
Id = Guid.NewGuid(),
Data = new byte[] {2, 3, 4, 5, 6}
};
public DefaultEnvelopeMapperTests()
{
_mapped = new Lazy<Envelope>(() =>
{
var mapper = new DefaultAzureServiceBusProtocol();
var message = mapper.WriteFromEnvelope(theOriginal);
return mapper.ReadEnvelope(message);
});
}
private Envelope theEnvelope => _mapped.Value;
[Fact]
public void accepted_types()
{
theOriginal.AcceptedContentTypes = new[] {"text/json", "text/xml"};
theEnvelope.AcceptedContentTypes
.ShouldHaveTheSameElementsAs(theOriginal.AcceptedContentTypes);
}
[Fact]
public void ack_requestd_true()
{
theOriginal.AckRequested = true;
theEnvelope.AckRequested.ShouldBeTrue();
}
[Fact]
public void ack_requested_false()
{
theOriginal.AckRequested = false;
theEnvelope.AckRequested.ShouldBeFalse();
}
[Fact]
public void content_type()
{
theOriginal.ContentType = "application/json";
theEnvelope.ContentType.ShouldBe(theOriginal.ContentType);
}
[Fact]
public void deliver_by_value()
{
theOriginal.DeliverBy = DateTimeOffset.UtcNow.Date.AddDays(5);
theEnvelope.DeliverBy.ShouldBe(theOriginal.DeliverBy);
}
[Fact]
public void id()
{
theEnvelope.Id.ShouldBe(theOriginal.Id);
}
[Fact]
public void map_over_the_body()
{
theEnvelope.Data.ShouldBe(theOriginal.Data);
}
[Fact]
public void message_type()
{
theOriginal.MessageType = "somemessagetype";
theEnvelope.MessageType.ShouldBe(theOriginal.MessageType);
}
[Fact]
public void original_id()
{
theOriginal.CorrelationId = Guid.NewGuid();
theEnvelope.CorrelationId.ShouldBe(theOriginal.CorrelationId);
}
[Fact]
public void other_random_headers()
{
theOriginal.Headers.Add("color", "blue");
theOriginal.Headers.Add("direction", "north");
theEnvelope.Headers["color"].ShouldBe("blue");
theEnvelope.Headers["direction"].ShouldBe("north");
}
[Fact]
public void parent_id()
{
theOriginal.CausationId = Guid.NewGuid();
theEnvelope.CausationId.ShouldBe(theOriginal.CausationId);
}
[Fact]
public void reply_requested()
{
theOriginal.ReplyRequested = "somemessagetype";
theEnvelope.ReplyRequested.ShouldBe(theOriginal.ReplyRequested);
}
[Fact]
public void reply_uri()
{
theOriginal.ReplyUri = "tcp://localhost:4444".ToUri();
theEnvelope.ReplyUri.ShouldBe(theOriginal.ReplyUri);
}
[Fact]
public void saga_id()
{
theOriginal.SagaId = Guid.NewGuid().ToString();
theEnvelope.SagaId.ShouldBe(theOriginal.SagaId);
}
[Fact]
public void source()
{
theOriginal.Source = "someapp";
theEnvelope.Source.ShouldBe(theOriginal.Source);
}
}
public class mapping_from_envelope
{
private readonly Lazy<Message> _properties;
private readonly Envelope theEnvelope = new(new Message1())
{
Data = new byte[] {1, 2, 3, 4}
};
public mapping_from_envelope()
{
_properties = new Lazy<Message>(() =>
{
return new DefaultAzureServiceBusProtocol().WriteFromEnvelope(theEnvelope);
});
}
private Message theMessage => _properties.Value;
[Fact]
public void ack_requested_false()
{
theEnvelope.AckRequested = false;
theMessage.UserProperties.ContainsKey(EnvelopeSerializer.AckRequestedKey).ShouldBeFalse();
}
[Fact]
public void ack_requested_true()
{
theEnvelope.AckRequested = true;
theMessage.UserProperties[EnvelopeSerializer.AckRequestedKey].ShouldBe("true");
}
[Fact]
public void content_type()
{
theEnvelope.ContentType = "application/json";
theMessage.ContentType.ShouldBe(theEnvelope.ContentType);
}
[Fact]
public void deliver_by()
{
var deliveryBy = DateTimeOffset.UtcNow.Date.AddDays(5);
theEnvelope.DeliverBy = deliveryBy;
var expected = deliveryBy.ToUniversalTime().Subtract(DateTime.UtcNow);
var difference = theMessage.TimeToLive.Subtract(expected);
difference.TotalSeconds.ShouldBeLessThan(1);
}
[Fact]
public void message_type()
{
theEnvelope.MessageType = "something";
theMessage.UserProperties[EnvelopeSerializer.MessageTypeKey].ShouldBe(theEnvelope.MessageType);
}
[Fact]
public void parent_id()
{
theEnvelope.CausationId = Guid.NewGuid();
theMessage.UserProperties[EnvelopeSerializer.CausationIdKey].ShouldBe(theEnvelope.CausationId.ToString());
}
[Fact]
public void reply_requested_true()
{
theEnvelope.ReplyRequested = "somereplymessage";
theMessage.UserProperties[EnvelopeSerializer.ReplyRequestedKey].ShouldBe(theEnvelope.ReplyRequested);
}
[Fact]
public void reply_uri()
{
theEnvelope.ReplyUri = "tcp://localhost:5005".ToUri();
theMessage.UserProperties[EnvelopeSerializer.ReplyUriKey].ShouldBe(theEnvelope.ReplyUri.ToString());
}
[Fact]
public void saga_id_key()
{
theEnvelope.SagaId = "somesaga";
theMessage.UserProperties[EnvelopeSerializer.SagaIdKey].ShouldBe(theEnvelope.SagaId);
}
[Fact]
public void source_key()
{
theEnvelope.Source = "SomeApp";
theMessage.UserProperties[EnvelopeSerializer.SourceKey].ShouldBe(theEnvelope.Source);
}
[Fact]
public void the_message_id()
{
theEnvelope.Id = Guid.NewGuid();
theMessage.MessageId.ShouldBe(theEnvelope.Id.ToString());
}
[Fact]
public void the_original_id()
{
theEnvelope.CorrelationId = Guid.NewGuid();
theMessage.UserProperties[EnvelopeSerializer.CorrelationIdKey]
.ShouldBe(theEnvelope.CorrelationId.ToString());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.