context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal partial class FindPal
{
private const int NamedKeyUsageFlagsCount = 9;
private static readonly Dictionary<string, X509KeyUsageFlags> s_keyUsages =
new Dictionary<string, X509KeyUsageFlags>(NamedKeyUsageFlagsCount, StringComparer.OrdinalIgnoreCase)
{
{ "DigitalSignature", X509KeyUsageFlags.DigitalSignature },
{ "NonRepudiation", X509KeyUsageFlags.NonRepudiation },
{ "KeyEncipherment", X509KeyUsageFlags.KeyEncipherment },
{ "DataEncipherment", X509KeyUsageFlags.DataEncipherment },
{ "KeyAgreement", X509KeyUsageFlags.KeyAgreement },
{ "KeyCertSign", X509KeyUsageFlags.KeyCertSign },
{ "CrlSign", X509KeyUsageFlags.CrlSign },
{ "EncipherOnly", X509KeyUsageFlags.EncipherOnly },
{ "DecipherOnly", X509KeyUsageFlags.DecipherOnly },
};
#if DEBUG
static FindPal()
{
Debug.Assert(s_keyUsages.Count == NamedKeyUsageFlagsCount);
}
#endif
public static X509Certificate2Collection FindFromCollection(
X509Certificate2Collection coll,
X509FindType findType,
object findValue,
bool validOnly)
{
X509Certificate2Collection results = new X509Certificate2Collection();
using (IFindPal findPal = OpenPal(coll, results, validOnly))
{
switch (findType)
{
case X509FindType.FindByThumbprint:
{
byte[] thumbPrint = ConfirmedCast<string>(findValue).DecodeHexString();
findPal.FindByThumbprint(thumbPrint);
break;
}
case X509FindType.FindBySubjectName:
{
string subjectName = ConfirmedCast<string>(findValue);
findPal.FindBySubjectName(subjectName);
break;
}
case X509FindType.FindBySubjectDistinguishedName:
{
string subjectDistinguishedName = ConfirmedCast<string>(findValue);
findPal.FindBySubjectDistinguishedName(subjectDistinguishedName);
break;
}
case X509FindType.FindByIssuerName:
{
string issuerName = ConfirmedCast<string>(findValue);
findPal.FindByIssuerName(issuerName);
break;
}
case X509FindType.FindByIssuerDistinguishedName:
{
string issuerDistinguishedName = ConfirmedCast<string>(findValue);
findPal.FindByIssuerDistinguishedName(issuerDistinguishedName);
break;
}
case X509FindType.FindBySerialNumber:
{
string decimalOrHexString = ConfirmedCast<string>(findValue);
// FindBySerialNumber allows the input format to be either in
// hex or decimal. Since we can't know which one was intended,
// it compares against both interpretations and treats a match
// of either as a successful find.
// String is big-endian, BigInteger constructor requires little-endian.
byte[] hexBytes = decimalOrHexString.DecodeHexString();
Array.Reverse(hexBytes);
BigInteger hexValue = PositiveBigIntegerFromByteArray(hexBytes);
BigInteger decimalValue = LaxParseDecimalBigInteger(decimalOrHexString);
findPal.FindBySerialNumber(hexValue, decimalValue);
break;
}
case X509FindType.FindByTimeValid:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeValid(dateTime);
break;
}
case X509FindType.FindByTimeNotYetValid:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeNotYetValid(dateTime);
break;
}
case X509FindType.FindByTimeExpired:
{
DateTime dateTime = ConfirmedCast<DateTime>(findValue);
findPal.FindByTimeExpired(dateTime);
break;
}
case X509FindType.FindByTemplateName:
{
string expected = ConfirmedCast<string>(findValue);
findPal.FindByTemplateName(expected);
break;
}
case X509FindType.FindByApplicationPolicy:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
findPal.FindByApplicationPolicy(oidValue);
break;
}
case X509FindType.FindByCertificatePolicy:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.Policy);
findPal.FindByCertificatePolicy(oidValue);
break;
}
case X509FindType.FindByExtension:
{
string oidValue = ConfirmedOidValue(findPal, findValue, OidGroup.ExtensionOrAttribute);
findPal.FindByExtension(oidValue);
break;
}
case X509FindType.FindByKeyUsage:
{
X509KeyUsageFlags keyUsage = ConfirmedX509KeyUsage(findValue);
findPal.FindByKeyUsage(keyUsage);
break;
}
case X509FindType.FindBySubjectKeyIdentifier:
{
byte[] keyIdentifier = ConfirmedCast<string>(findValue).DecodeHexString();
findPal.FindBySubjectKeyIdentifier(keyIdentifier);
break;
}
default:
throw new CryptographicException(SR.Cryptography_X509_InvalidFindType);
}
}
return results;
}
private static T ConfirmedCast<T>(object findValue)
{
Debug.Assert(findValue != null);
if (findValue.GetType() != typeof(T))
throw new CryptographicException(SR.Cryptography_X509_InvalidFindValue);
return (T)findValue;
}
private static string ConfirmedOidValue(IFindPal findPal, object findValue, OidGroup oidGroup)
{
string maybeOid = ConfirmedCast<string>(findValue);
if (maybeOid.Length == 0)
{
throw new ArgumentException(SR.Argument_InvalidOidValue);
}
return findPal.NormalizeOid(maybeOid, oidGroup);
}
private static X509KeyUsageFlags ConfirmedX509KeyUsage(object findValue)
{
if (findValue is X509KeyUsageFlags)
return (X509KeyUsageFlags)findValue;
if (findValue is int)
return (X509KeyUsageFlags)(int)findValue;
if (findValue is uint)
return (X509KeyUsageFlags)(uint)findValue;
string findValueString = findValue as string;
if (findValueString != null)
{
X509KeyUsageFlags usageFlags;
if (s_keyUsages.TryGetValue(findValueString, out usageFlags))
{
return usageFlags;
}
}
throw new CryptographicException(SR.Cryptography_X509_InvalidFindValue);
}
//
// verify the passed keyValue is valid as per X.208
//
// The first number must be 0, 1 or 2.
// Enforce all characters are digits and dots.
// Enforce that no dot starts or ends the Oid, and disallow double dots.
// Enforce there is at least one dot separator.
//
internal static void ValidateOidValue(string keyValue)
{
if (keyValue == null)
throw new ArgumentNullException("keyValue");
int len = keyValue.Length;
if (len < 2)
throw new ArgumentException(SR.Argument_InvalidOidValue);
// should not start with a dot. The first digit must be 0, 1 or 2.
char c = keyValue[0];
if (c != '0' && c != '1' && c != '2')
throw new ArgumentException(SR.Argument_InvalidOidValue);
if (keyValue[1] != '.' || keyValue[len - 1] == '.') // should not end in a dot
throw new ArgumentException(SR.Argument_InvalidOidValue);
// While characters 0 and 1 were both validated, start at character 1 to validate
// that there aren't two dots in a row.
for (int i = 1; i < len; i++)
{
// ensure every character is either a digit or a dot
if (char.IsDigit(keyValue[i]))
continue;
if (keyValue[i] != '.' || keyValue[i + 1] == '.') // disallow double dots
throw new ArgumentException(SR.Argument_InvalidOidValue);
}
}
internal static BigInteger PositiveBigIntegerFromByteArray(byte[] bytes)
{
// To prevent the big integer from misinterpreted as a negative number,
// add a "leading 0" to the byte array if it would considered negative.
//
// Since BigInteger(bytes[]) requires a little-endian byte array,
// the "leading 0" actually goes at the end of the array.
// An empty array is 0 (non-negative), so no over-allocation is required.
//
// If the last indexed value doesn't have the sign bit set (0x00-0x7F) then
// the number would be positive anyways, so no over-allocation is required.
if (bytes.Length == 0 || bytes[bytes.Length - 1] < 0x80)
{
return new BigInteger(bytes);
}
// Since the sign bit is set, put a new 0x00 on the end to move that bit from
// the sign bit to a data bit.
byte[] newBytes = new byte[bytes.Length + 1];
Array.Copy(bytes, 0, newBytes, 0, bytes.Length);
return new BigInteger(newBytes);
}
private static BigInteger LaxParseDecimalBigInteger(string decimalString)
{
BigInteger ten = new BigInteger(10);
BigInteger accum = BigInteger.Zero;
foreach (char c in decimalString)
{
if (c >= '0' && c <= '9')
{
accum = BigInteger.Multiply(accum, ten);
accum = BigInteger.Add(accum, c - '0');
}
}
return accum;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Algorithm;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Positions;
using QuantConnect.Tests.Engine.DataFeeds;
namespace QuantConnect.Tests.Common.Securities
{
[TestFixture]
public class FutureMarginBuyingPowerModelTests
{
// Test class to enable calling protected methods
private FutureMarginModel _futureMarginModel;
[Test]
public void TestMarginForSymbolWithOneLinerHistory()
{
const decimal price = 1.2345m;
var time = new DateTime(2016, 1, 1);
var expDate = new DateTime(2017, 1, 1);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Softs.Coffee;
var symbol = Symbol.CreateFuture(ticker, Market.ICE, expDate);
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
futureSecurity.BuyingPowerModel = new FutureMarginModel(security: futureSecurity);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, 1);
var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));
futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
}
[Test]
public void TestMarginForSymbolWithNoHistory()
{
const decimal price = 1.2345m;
var time = new DateTime(2016, 1, 1);
var expDate = new DateTime(2017, 1, 1);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history at all
var ticker = "NOT-A-SYMBOL";
var symbol = Symbol.CreateFuture(ticker, Market.USA, expDate);
var futureSecurity = new Future(SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, 1);
var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));
futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel, timeKeeper: timeKeeper);
Assert.AreEqual(0m, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
}
[Test]
public void TestMarginForSymbolWithHistory()
{
const decimal price = 1.2345m;
var time = new DateTime(2013, 1, 1);
var expDate = new DateTime(2017, 1, 1);
var tz = TimeZones.NewYork;
// For this symbol we dont have history
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var symbol = Symbol.CreateFuture(ticker, Market.CME, expDate);
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, 1);
futureSecurity.BuyingPowerModel = new FutureMarginModel(security: futureSecurity);
var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));
futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel, timeKeeper: timeKeeper);
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement,
buyingPowerModel.GetMaintenanceMargin(futureSecurity));
// now we move forward to exact date when margin req changed
time = new DateTime(2014, 06, 13);
timeKeeper.SetUtcDateTime(time.ConvertToUtc(tz));
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
// now we fly beyond the last line of the history file (currently) to see how margin model resolves future dates
time = new DateTime(2016, 06, 04);
timeKeeper.SetUtcDateTime(time.ConvertToUtc(tz));
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
}
[TestCase(1)]
[TestCase(10)]
[TestCase(-1)]
[TestCase(-10)]
public void GetMaintenanceMargin(decimal quantity)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
const decimal price = 1.2345m;
var time = new DateTime(2013, 1, 1);
var futureSecurity = algorithm.AddFuture(ticker);
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, quantity);
var res = buyingPowerModel.GetMaintenanceMargin(futureSecurity);
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement * futureSecurity.Holdings.AbsoluteQuantity, res);
// We increase the quantity * 2, maintenance margin should DOUBLE
futureSecurity.Holdings.SetHoldings(1.5m, quantity * 2);
res = buyingPowerModel.GetMaintenanceMargin(futureSecurity);
Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement * futureSecurity.Holdings.AbsoluteQuantity, res);
}
[TestCase(1)]
[TestCase(-1)]
public void GetInitialMarginRequirement(decimal quantity)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
const decimal price = 1.2345m;
var time = new DateTime(2013, 1, 1);
var futureSecurity = algorithm.AddFuture(ticker);
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, quantity);
var initialMargin = buyingPowerModel.GetInitialMarginRequirement(futureSecurity, futureSecurity.Holdings.Quantity);
var overnightMargin = Math.Abs(buyingPowerModel.GetMaintenanceMargin(futureSecurity));
// initial margin is greater than the maintenance margin
Assert.Greater(Math.Abs(initialMargin), overnightMargin);
}
[TestCase(10)]
[TestCase(-10)]
public void GetInitialMarginRequiredForOrder(decimal quantity)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
const decimal price = 1.2345m;
var time = new DateTime(2013, 1, 1);
var futureSecurity = algorithm.AddFuture(ticker);
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.SetMarketPrice(new Tick { Value = price, Time = time });
futureSecurity.Holdings.SetHoldings(1.5m, quantity);
var initialMargin = buyingPowerModel.GetInitialMarginRequiredForOrder(
new InitialMarginRequiredForOrderParameters(algorithm.Portfolio.CashBook,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantity, algorithm.UtcTime))).Value;
var initialMarginExpected = buyingPowerModel.GetInitialMarginRequirement(futureSecurity, quantity);
Assert.AreEqual(initialMarginExpected
+ 18.50m * Math.Sign(quantity), // fees -> 10 quantity * 1.85
initialMargin);
}
[TestCase(100)]
[TestCase(-100)]
public void MarginUsedForPositionWhenPriceDrops(decimal quantity)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.Holdings.SetHoldings(20, quantity);
Update(futureSecurity, 20, algorithm);
var marginForPosition = buyingPowerModel.GetReservedBuyingPowerForPosition(
new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower;
// Drop 40% price from $20 to $12
Update(futureSecurity, 12, algorithm);
var marginForPositionAfter = buyingPowerModel.GetReservedBuyingPowerForPosition(
new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower;
Assert.AreEqual(marginForPosition, marginForPositionAfter);
}
[TestCase(100)]
[TestCase(-100)]
public void MarginUsedForPositionWhenPriceIncreases(decimal quantity)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.Holdings.SetHoldings(20, quantity);
Update(futureSecurity, 20, algorithm);
var marginForPosition = buyingPowerModel.GetReservedBuyingPowerForPosition(
new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower;
// Increase from $20 to $40
Update(futureSecurity, 40, algorithm);
var marginForPositionAfter = buyingPowerModel.GetReservedBuyingPowerForPosition(
new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower;
Assert.AreEqual(marginForPosition, marginForPositionAfter);
}
[Test]
public void PortfolioStatusForPositionWhenPriceDrops()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
futureSecurity.BuyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.Holdings.SetHoldings(20, 100);
Update(futureSecurity, 20, algorithm);
var marginUsed = algorithm.Portfolio.TotalMarginUsed;
Assert.IsTrue(marginUsed > 0);
Assert.IsTrue(algorithm.Portfolio.TotalPortfolioValue > 0);
Assert.IsTrue(algorithm.Portfolio.MarginRemaining > 0);
// Drop 40% price from $20 to $12
Update(futureSecurity, 12, algorithm);
var expected = (12 - 20) * 100 * futureSecurity.SymbolProperties.ContractMultiplier - 1.85m * 100;
Assert.AreEqual(futureSecurity.Holdings.UnrealizedProfit, expected);
// we have a massive loss because of futures leverage
Assert.IsTrue(algorithm.Portfolio.TotalPortfolioValue < 0);
Assert.IsTrue(algorithm.Portfolio.MarginRemaining < 0);
// margin used didn't change because for futures it relies on the maintenance margin
Assert.AreEqual(marginUsed, algorithm.Portfolio.TotalMarginUsed);
}
[Test]
public void PortfolioStatusPositionWhenPriceIncreases()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
futureSecurity.BuyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);
futureSecurity.Holdings.SetHoldings(20, 100);
Update(futureSecurity, 20, algorithm);
var marginUsed = algorithm.Portfolio.TotalMarginUsed;
Assert.IsTrue(marginUsed > 0);
Assert.IsTrue(algorithm.Portfolio.TotalPortfolioValue > 0);
Assert.IsTrue(algorithm.Portfolio.MarginRemaining > 0);
// Increase from $20 to $40
Update(futureSecurity, 40, algorithm);
var expected = (40 - 20) * 100 * futureSecurity.SymbolProperties.ContractMultiplier - 1.85m * 100;
Assert.AreEqual(futureSecurity.Holdings.UnrealizedProfit, expected);
// we have a massive win because of futures leverage
Assert.IsTrue(algorithm.Portfolio.TotalPortfolioValue > 0);
Assert.IsTrue(algorithm.Portfolio.MarginRemaining > 0);
// margin used didn't change because for futures it relies on the maintenance margin
Assert.AreEqual(marginUsed, algorithm.Portfolio.TotalMarginUsed);
}
[Test]
public void GetLeverage()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
Update(futureSecurity, 100, algorithm);
var leverage = futureSecurity.BuyingPowerModel.GetLeverage(futureSecurity);
Assert.AreEqual(1, leverage);
}
[TestCase(1)]
[TestCase(2)]
public void SetLeverageThrowsException(int leverage)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
Assert.Throws<InvalidOperationException>(() => futureSecurity.BuyingPowerModel.SetLeverage(futureSecurity, leverage));
}
[Test]
public void MarginRequirementsChangeWithDate()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
var model = futureSecurity.BuyingPowerModel as FutureMarginModel;
Update(futureSecurity, 100, algorithm, new DateTime(2001, 01, 07));
var initial = model.InitialOvernightMarginRequirement;
var maintenance = model.MaintenanceOvernightMarginRequirement;
Assert.AreEqual(810, initial);
Assert.AreEqual(600, maintenance);
// date previous to margin change
Update(futureSecurity, 100, algorithm, new DateTime(2001, 12, 10));
Assert.AreEqual(810, initial);
Assert.AreEqual(600, maintenance);
// new margins!
Update(futureSecurity, 100, algorithm, new DateTime(2001, 12, 11));
Assert.AreEqual(945, model.InitialOvernightMarginRequirement);
Assert.AreEqual(700, model.MaintenanceOvernightMarginRequirement);
}
[TestCase(-1.1)]
[TestCase(1.1)]
public void GetMaximumOrderQuantityForTargetBuyingPower_ThrowsForInvalidTarget(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
Assert.Throws<InvalidOperationException>(() => futureSecurity.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(
new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algorithm.Portfolio,
futureSecurity,
target,
0)));
}
[TestCase(1)]
[TestCase(0.5)]
[TestCase(-1)]
[TestCase(-0.5)]
public void GetMaximumOrderQuantityForTargetBuyingPower_NoHoldings(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
Update(futureSecurity, 100, algorithm);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
// set closed market for simpler math
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var expected = (algorithm.Portfolio.TotalPortfolioValue * Math.Abs(target)) / _futureMarginModel.InitialOvernightMarginRequirement - 1 * Math.Abs(target); // -1 fees
expected -= expected % futureSecurity.SymbolProperties.LotSize;
Assert.AreEqual(expected * Math.Sign(target), quantity);
var request = GetOrderRequest(futureSecurity.Symbol, quantity);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, expected, DateTime.UtcNow))).IsSufficient);
}
[TestCase(1)]
[TestCase(-1)]
public void HasSufficientBuyingPowerForOrderInvalidTargets(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
// set closed market for simpler math
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
Update(futureSecurity, 100, algorithm);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var request = GetOrderRequest(futureSecurity.Symbol, quantity);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
var result = model.HasSufficientBuyingPowerForOrder(new HasSufficientBuyingPowerForOrderParameters(
algorithm.Portfolio,
futureSecurity,
// we get the maximum target value 1/-1 and add a lot size it shouldn't be a valid order
new MarketOrder(futureSecurity.Symbol, quantity + futureSecurity.SymbolProperties.LotSize * Math.Sign(quantity), DateTime.UtcNow)));
Assert.IsFalse(result.IsSufficient);
}
[TestCase(1)]
[TestCase(-1)]
public void GetMaximumOrderQuantityForTargetBuyingPower_TwoStep(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
futureSecurity.BuyingPowerModel = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
// set closed market for simpler math
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
Update(futureSecurity, 100, algorithm);
var expectedFinalQuantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target / 2);
futureSecurity.Holdings.SetHoldings(100, quantity);
algorithm.Portfolio.InvalidateTotalPortfolioValue();
var quantity2 = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var request = GetOrderRequest(futureSecurity.Symbol, quantity2);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(futureSecurity.BuyingPowerModel.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantity2, DateTime.UtcNow))).IsSufficient);
// two step operation is the same as 1 step
Assert.AreEqual(expectedFinalQuantity, quantity + quantity2);
}
[TestCase(1)]
[TestCase(0.5)]
[TestCase(-1)]
[TestCase(-0.5)]
public void GetMaximumOrderQuantityForTargetBuyingPower_WithHoldingsSameDirection(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
// set closed market for simpler math
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
futureSecurity.Holdings.SetHoldings(100, 10 * Math.Sign(target));
Update(futureSecurity, 100, algorithm);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var expected = (algorithm.Portfolio.TotalPortfolioValue * Math.Abs(target) - Math.Abs(model.GetInitialMarginRequirement(futureSecurity, futureSecurity.Holdings.Quantity)))
/ _futureMarginModel.InitialOvernightMarginRequirement - 1 * Math.Abs(target); // -1 fees
expected -= expected % futureSecurity.SymbolProperties.LotSize;
Log.Trace($"Expected {expected}");
Assert.AreEqual(expected * Math.Sign(target), quantity);
var request = GetOrderRequest(futureSecurity.Symbol, quantity);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, expected * Math.Sign(target), DateTime.UtcNow))).IsSufficient);
}
[TestCase(1)]
[TestCase(0.5)]
[TestCase(-1)]
[TestCase(-0.5)]
public void GetMaximumOrderQuantityForTargetBuyingPower_WithHoldingsInverseDirection(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
// set closed market for simpler math
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
futureSecurity.Holdings.SetHoldings(100, 10 * -1 * Math.Sign(target));
Update(futureSecurity, 100, algorithm);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
futureSecurity.BuyingPowerModel = _futureMarginModel;
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var expected = (algorithm.Portfolio.TotalPortfolioValue * Math.Abs(target) + Math.Abs(model.GetInitialMarginRequirement(futureSecurity, futureSecurity.Holdings.Quantity)))
/ _futureMarginModel.InitialOvernightMarginRequirement - 1 * Math.Abs(target); // -1 fees
expected -= expected % futureSecurity.SymbolProperties.LotSize;
Log.Trace($"Expected {expected}");
Assert.AreEqual(expected * Math.Sign(target), quantity);
var request = GetOrderRequest(futureSecurity.Symbol, quantity);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, expected * Math.Sign(target), DateTime.UtcNow))).IsSufficient);
}
[TestCase(1)]
[TestCase(0.5)]
[TestCase(-1)]
[TestCase(-0.5)]
public void IntradayVersusOvernightMargins(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
var lotSize = futureSecurity.SymbolProperties.LotSize;
Update(futureSecurity, 100, algorithm);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
// Close market
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
var quantityClosedMarket = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
Assert.AreEqual(quantityClosedMarket.DiscretelyRoundBy(lotSize), quantityClosedMarket,
"Calculated order quantity was not whole number multiple of the lot size"
);
var request = GetOrderRequest(futureSecurity.Symbol, quantityClosedMarket);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantityClosedMarket, DateTime.UtcNow))).IsSufficient);
var initialOvernight = _futureMarginModel.InitialOvernightMarginRequirement;
var maintenanceOvernight = _futureMarginModel.MaintenanceOvernightMarginRequirement;
// Open market
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 3));
var fourtyPercentQuantity = (quantityClosedMarket * 0.4m).DiscretelyRoundBy(lotSize);
futureSecurity.Holdings.SetHoldings(100, fourtyPercentQuantity);
var halfQuantity = (quantityClosedMarket / 2).DiscretelyRoundBy(lotSize);
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, halfQuantity, DateTime.UtcNow))).IsSufficient);
Assert.Greater(initialOvernight, _futureMarginModel.InitialIntradayMarginRequirement);
Assert.Greater(maintenanceOvernight, _futureMarginModel.MaintenanceIntradayMarginRequirement);
}
[TestCase(1)]
[TestCase(-1)]
public void ClosingSoonIntradayClosedMarketMargins(decimal target)
{
var algorithm = new QCAlgorithm();
algorithm.SetFinishedWarmingUp();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var orderProcessor = new FakeOrderProcessor();
algorithm.Transactions.SetOrderProcessor(orderProcessor);
var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
var futureSecurity = algorithm.AddFuture(ticker);
Update(futureSecurity, 100, algorithm);
var localTime = new DateTime(2020, 2, 3);
var utcTime = localTime.ConvertToUtc(futureSecurity.Exchange.TimeZone);
var timeKeeper = new TimeKeeper(utcTime, futureSecurity.Exchange.TimeZone);
var model = GetModel(futureSecurity, out _futureMarginModel, algorithm.Portfolio);
// this is important
_futureMarginModel.EnableIntradayMargins = true;
// Open market
futureSecurity.Exchange.SetLocalDateTimeFrontier(localTime);
var quantity = algorithm.CalculateOrderQuantity(futureSecurity.Symbol, target);
var request = GetOrderRequest(futureSecurity.Symbol, quantity);
request.SetOrderId(0);
orderProcessor.AddTicket(new OrderTicket(algorithm.Transactions, request));
Assert.IsTrue(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantity, DateTime.UtcNow))).IsSufficient);
// Closing soon market
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 3, 15,50, 0));
Assert.IsFalse(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantity, DateTime.UtcNow))).IsSufficient);
Assert.IsTrue(futureSecurity.Exchange.ExchangeOpen);
Assert.IsTrue(futureSecurity.Exchange.ClosingSoon);
// Close market
futureSecurity.Exchange.SetLocalDateTimeFrontier(new DateTime(2020, 2, 1));
Assert.IsFalse(futureSecurity.Exchange.ExchangeOpen);
Assert.IsFalse(model.HasSufficientBuyingPowerForOrder(
new HasSufficientBuyingPowerForOrderParameters(algorithm.Portfolio,
futureSecurity,
new MarketOrder(futureSecurity.Symbol, quantity, DateTime.UtcNow))).IsSufficient);
}
[TestCase(Market.CME)]
[TestCase(Market.ICE)]
[TestCase(Market.CBOT)]
[TestCase(Market.CFE)]
[TestCase(Market.COMEX)]
[TestCase(Market.NYMEX)]
[TestCase(Market.Globex)]
public void FutureMarginModel_MarginEntriesValid(string market)
{
var marginsDirectory = new DirectoryInfo(Path.Combine(Globals.DataFolder, "future", market, "margins"));
var minimumDate = new DateTime(1990, 1, 1);
if (!marginsDirectory.Exists)
{
return;
}
foreach (var marginFile in marginsDirectory.GetFiles("*.csv", SearchOption.TopDirectoryOnly))
{
var lineNumber = 0;
var errorMessageTemplate = $"Error encountered in file {marginFile.Name} on line ";
var csv = File.ReadLines(marginFile.FullName).Where(x => !x.StartsWithInvariant("#") && !string.IsNullOrWhiteSpace(x)).Skip(1).Select(x =>
{
lineNumber++;
var data = x.Split(',');
if (data.Length < 3)
{
var errorMessage = errorMessageTemplate + lineNumber.ToStringInvariant();
Assert.Fail(errorMessage);
}
DateTime date;
decimal initial;
decimal maintenance;
var dateValid = Parse.TryParseExact(data[0], DateFormat.EightCharacter, DateTimeStyles.None, out date);
var initialValid = Parse.TryParse(data[1], NumberStyles.Any, out initial);
var maintenanceValid = Parse.TryParse(data[2], NumberStyles.Any, out maintenance);
if (!dateValid || !initialValid || !maintenanceValid)
{
var errorMessage = errorMessageTemplate + lineNumber.ToStringInvariant();
Assert.Fail(errorMessage);
}
return new Tuple<DateTime, decimal, decimal>(date, initial, maintenance);
});
lineNumber = 0;
foreach (var line in csv)
{
lineNumber++;
var dateInvalid = $"Date is less than 1998-01-01 in {marginFile.Name} on line {lineNumber}";
var initialInvalid = $"Initial is <= 0 in {marginFile.Name} on line {lineNumber}";
var maintenanceInvalid = $"Maintenance is <= 0 in {marginFile.Name} on line {lineNumber}";
Assert.GreaterOrEqual(line.Item1, minimumDate, dateInvalid);
Assert.Greater(line.Item2, 0m, initialInvalid);
Assert.Greater(line.Item3, 0m, maintenanceInvalid);
}
}
}
[TestCase(Market.CME)]
[TestCase(Market.ICE)]
[TestCase(Market.CBOT)]
[TestCase(Market.CFE)]
[TestCase(Market.COMEX)]
[TestCase(Market.NYMEX)]
[TestCase(Market.Globex)]
public void FutureMarginModel_MarginEntriesHaveIncrementingDates(string market)
{
var marginsDirectory = new DirectoryInfo(Path.Combine(Globals.DataFolder, "future", market, "margins"));
if (!marginsDirectory.Exists)
{
return;
}
foreach (var marginFile in marginsDirectory.GetFiles("*.csv", SearchOption.TopDirectoryOnly))
{
var csv = File.ReadLines(marginFile.FullName).Where(x => !x.StartsWithInvariant("#") && !string.IsNullOrWhiteSpace(x)).Skip(1).Select(x =>
{
var data = x.Split(',');
DateTime date;
Parse.TryParseExact(data[0], DateFormat.EightCharacter, DateTimeStyles.None, out date);
var initial = Parse.Decimal(data[1]);
var maintenance = Parse.Decimal(data[2]);
return new Tuple<DateTime, decimal, decimal>(date, initial, maintenance);
});
var previous = DateTime.MinValue;
foreach (var line in csv)
{
Assert.Greater(line.Item1, previous, marginFile.Name);
previous = line.Item1;
}
}
}
[TestCase(Market.CME)]
[TestCase(Market.ICE)]
[TestCase(Market.CBOT)]
[TestCase(Market.CFE)]
[TestCase(Market.COMEX)]
//[TestCase(Market.NYMEX)] NYMEX contracts can have volatile margin requirements, since some are tied to a percentage of the contract's value.
[TestCase(Market.Globex)]
public void FutureMarginModel_MarginEntriesAreContinuous(string market)
{
var marginsDirectory = new DirectoryInfo(Path.Combine(Globals.DataFolder, "future", market, "margins"));
if (!marginsDirectory.Exists)
{
return;
}
var exclusions = new Dictionary<string, int>
{
{ "6E.csv", 1 },
{ "6S.csv", 2 },
{ "A8K.csv", 1 },
{ "AJY.csv", 1 },
{ "ANL.csv", 2 },
{ "AUP.csv", 46 },
{ "CB.csv", 20 },
{ "CSC.csv", 30 },
{ "DC.csv", 50 },
{ "DY.csv", 30 },
{ "EH.csv", 1 },
{ "EVC.csv", 1 },
{ "EWG.csv", 1 },
{ "EWN.csv", 2 },
{ "FRC.csv", 1 },
{ "GDK.csv", 30 },
{ "GE.csv", 20 },
{ "GF.csv", 2 },
{ "GNF.csv", 10 },
{ "HO.csv", 1 },
{ "ME.csv", 1 },
{ "MSF.csv", 1 },
{ "NKN.csv", 2 },
{ "PL.csv", 1 },
{ "RB.csv", 1 },
{ "ZC.csv", 2 },
{ "ZM.csv", 1 },
{ "ZW.csv", 2 }
};
var lines = new List<string>();
foreach (var marginFile in marginsDirectory.GetFiles("*.csv", SearchOption.TopDirectoryOnly))
{
var greaterMessage = $"A jump less than -80% was encountered in {marginFile.Name}";
var lessMessage = $"A jump greater than +80% was encountered in {marginFile.Name}";
var maxExclusions = exclusions.ContainsKey(marginFile.Name) ? exclusions[marginFile.Name] : 0;
var csv = File.ReadLines(marginFile.FullName).Where(x => !x.StartsWithInvariant("#") && !string.IsNullOrWhiteSpace(x)).Skip(1).Select(x =>
{
var data = x.Split(',');
DateTime date;
Parse.TryParseExact(data[0], DateFormat.EightCharacter, DateTimeStyles.None, out date);
var initial = Parse.Decimal(data[1]);
var maintenance = Parse.Decimal(data[2]);
return new Tuple<DateTime, decimal, decimal>(date, initial, maintenance);
}).ToList();
var errorsEncountered = 0;
for (var i = 1; i < csv.Count; i++)
{
var previous = csv[i - 1].Item2;
var current = csv[i].Item2;
var percentChange = (current - previous) / previous;
var lessThan = percentChange < -0.8m;
var greaterThan = percentChange > 0.8m;
if (lessThan || greaterThan)
{
errorsEncountered++;
if (errorsEncountered > maxExclusions)
{
Assert.Fail(lessThan ? lessMessage : greaterMessage);
}
}
}
}
}
[TestCase(Market.CME)]
[TestCase(Market.ICE)]
[TestCase(Market.CBOT)]
[TestCase(Market.CFE)]
[TestCase(Market.COMEX)]
[TestCase(Market.NYMEX)]
[TestCase(Market.Globex)]
public void FutureMarginModel_InitialMarginGreaterThanMaintenance(string market)
{
var marginsDirectory = new DirectoryInfo(Path.Combine(Globals.DataFolder, "future", market, "margins"));
if (!marginsDirectory.Exists)
{
return;
}
foreach (var marginFile in marginsDirectory.GetFiles("*.csv", SearchOption.TopDirectoryOnly))
{
var errorMessage = $"Initial value greater than maintenance value in {marginFile.Name}";
var csv = File.ReadLines(marginFile.FullName).Where(x => !x.StartsWithInvariant("#") && !string.IsNullOrWhiteSpace(x)).Skip(1).Select(x =>
{
var data = x.Split(',');
DateTime date;
Parse.TryParseExact(data[0], DateFormat.EightCharacter, DateTimeStyles.None, out date);
var initial = Parse.Decimal(data[1]);
var maintenance = Parse.Decimal(data[2]);
return new Tuple<DateTime, decimal, decimal>(date, initial, maintenance);
});
// Having an initial margin equal to the maintenance is a valid case.
// Using '>' and not '>=' here is intentional.
Assert.IsFalse(csv.Where(x => x.Item3 > x.Item2).Any(), errorMessage);
}
}
private static void Update(Security security, decimal close, QCAlgorithm algorithm, DateTime? time = null)
{
security.SetMarketPrice(new TradeBar
{
Time = time ?? new DateTime(2020, 5, 1),
Symbol = security.Symbol,
Open = close,
High = close,
Low = close,
Close = close
});
algorithm.Portfolio.InvalidateTotalPortfolioValue();
}
private static SubmitOrderRequest GetOrderRequest(Symbol symbol, decimal quantity)
{
return new SubmitOrderRequest(OrderType.Market,
SecurityType.Future,
symbol,
quantity,
1,
1,
DateTime.UtcNow,
"");
}
private static IBuyingPowerModel GetModel(
Security security,
out FutureMarginModel futureMarginModel,
SecurityPortfolioManager portfolio = null,
TimeKeeper timeKeeper = null
)
{
futureMarginModel = security.BuyingPowerModel as FutureMarginModel;
return new BuyingPowerModelComparator(futureMarginModel,
new SecurityPositionGroupBuyingPowerModel(), portfolio, timeKeeper
);
}
}
}
| |
#region License
//L
// 2007 - 2013 Copyright Northwestern University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
//L
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ClearCanvas.Common.Utilities;
using Component = AIM.Annotation.Template.Component;
namespace AIM.Annotation.View.WinForms.Template
{
public partial class ComponentContainerControl : UserControl, INotifyPropertyChanged
{
public event EventHandler IsValidChanged;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private readonly Dictionary<int, List<aim_dotnet.AnatomicEntity>> _anatomicEntities = new Dictionary<int, List<aim_dotnet.AnatomicEntity>>();
private readonly Dictionary<int, List<aim_dotnet.ImagingObservation>> _imagingObservations = new Dictionary<int, List<aim_dotnet.ImagingObservation>>();
private readonly Dictionary<int, List<aim_dotnet.Inference>> _inferences = new Dictionary<int, List<aim_dotnet.Inference>>();
private readonly Dictionary<int, List<aim_dotnet.Calculation>> _calculations = new Dictionary<int, List<aim_dotnet.Calculation>>();
private readonly Dictionary<int, List<aim_dotnet.GeometricShape>> _geometricShapes = new Dictionary<int, List<aim_dotnet.GeometricShape>>();
private Annotation.Template.Template _template;
private readonly Label _lblEmptyTemplate;
private bool _fireChangeEvent = true;
private ComponentContainerScrollMessageFiler _filter;
private bool _filterInstalled;
public ComponentContainerControl()
{
InitializeComponent();
SuspendLayout();
_lblEmptyTemplate =
new Label
{
Text = @"No template is selected or template is empty",
Location = new Point(10, 10),
AutoSize = true
};
Controls.Add(_lblEmptyTemplate);
ResumeLayout(false);
PerformLayout();
HandleDestroyed += OnHandleDestroyed;
}
public Annotation.Template.Template SelectedTemplate
{
get { return _template; }
set
{
if (_template != value)
{
_template = value;
SuspendLayout();
if (Controls.Contains(_lblEmptyTemplate))
Controls.Remove(_lblEmptyTemplate);
var oldComponentQuestionControls = new List<ComponentQuestionControl>(ComponentQuestionControls);
foreach (var component in oldComponentQuestionControls)
{
component.ComponentChanged -= OnComponentDataChanged;
component.SizeChanged -= OnControlSizeChanged;
Controls.Remove(component);
}
Controls.Clear();
AutoScrollPosition = new Point(0, 0);
_anatomicEntities.Clear();
_imagingObservations.Clear();
_inferences.Clear();
_calculations.Clear();
_geometricShapes.Clear();
if (_template == null || _template.Components == null || _template.Components.Count == 0)
{
Controls.Add(_lblEmptyTemplate);
}
else
{
var ptX = Margin.Left;
var ptY = Margin.Top;
var tabIndex = 0;
var sortedComponents = CollectionUtils.Sort(_template.Components, (comp1, comp2) => comp1.ItemNumber.CompareTo(comp2.ItemNumber));
string prevGroupLabel = null;
var labelCount = 0;
foreach (var component in sortedComponents)
{
const int groupShiftX = 10;
var widthDecrement = 0;
var curGroupLabel = component.GroupLabel == null ? null : component.GroupLabel.Trim();
if (!string.IsNullOrEmpty(curGroupLabel))
{
if (prevGroupLabel != curGroupLabel)
{
var groupLabel = new Label();
groupLabel.Text = curGroupLabel;
groupLabel.Font = new Font(groupLabel.Font.FontFamily, 9.0F, FontStyle.Bold);
groupLabel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
groupLabel.Location = new Point(ptX, ptY);
groupLabel.Name = string.Format("groupLabel{0}", labelCount++);
groupLabel.Size = new Size(Width - ptX, groupLabel.Height);
groupLabel.AutoEllipsis = true;
groupLabel.TextAlign = ContentAlignment.MiddleLeft;
Controls.Add(groupLabel);
ptY += groupLabel.Height;
}
ptX += groupShiftX;
widthDecrement = groupShiftX;
}
prevGroupLabel = curGroupLabel;
var componentQuestionControl = new ComponentQuestionControl(component);
componentQuestionControl.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
componentQuestionControl.Margin = new Padding(4);
componentQuestionControl.Location = new Point(ptX, ptY);
componentQuestionControl.Name = string.Format("componentQuestionControl{0}", tabIndex);
componentQuestionControl.Size = new Size(Width - Margin.Horizontal - widthDecrement, componentQuestionControl.Height);
componentQuestionControl.TabIndex = tabIndex++;
componentQuestionControl.ComponentChanged += OnComponentDataChanged;
componentQuestionControl.SizeChanged += OnControlSizeChanged;
ptY += componentQuestionControl.Height + 3;
Controls.Add(componentQuestionControl);
if (!string.IsNullOrEmpty(curGroupLabel))
ptX -= groupShiftX;
var oldFireChangeEvent = _fireChangeEvent;
_fireChangeEvent = false;
_fireChangeEvent = oldFireChangeEvent;
}
}
ResumeLayout(false);
PerformLayout();
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedAnatomicEntities"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedImagingObservations"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedInferences"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedCalculations"));
EventsHelper.Fire(IsValidChanged, this, EventArgs.Empty);
}
}
}
public bool IsValid
{
get
{
foreach (var component in SelectedTemplate.Components)
{
var curItemNumber = component.ItemNumber;
if (!CollectionUtils.Contains(_anatomicEntities.Keys, itemNumber => itemNumber == curItemNumber) &&
!CollectionUtils.Contains(_imagingObservations.Keys, itemNumber => itemNumber == curItemNumber) &&
!CollectionUtils.Contains(_inferences.Keys, itemNumber => itemNumber == curItemNumber) &&
!CollectionUtils.Contains(_calculations.Keys, itemNumber => itemNumber == curItemNumber) &&
!CollectionUtils.Contains(_geometricShapes.Keys, itemNumber => itemNumber == curItemNumber))
return false;
}
return true;
}
set { }
}
public List<aim_dotnet.AnatomicEntity> SelectedAnatomicEntities
{
get { return SortDictionaryAndFlattend(_anatomicEntities); }
set { }
}
public List<aim_dotnet.ImagingObservation> SelectedImagingObservations
{
get { return SortDictionaryAndFlattend(_imagingObservations); }
set { }
}
public List<aim_dotnet.Inference> SelectedInferences
{
get { return SortDictionaryAndFlattend(_inferences); }
set { }
}
public List<aim_dotnet.Calculation> SelectedCalculations
{
get { return null; }
set { }
}
public List<aim_dotnet.GeometricShape> SelectedGeometricShapes
{
get { return null; }
set { }
}
public List<T> SortDictionaryAndFlattend<T>(Dictionary<int, List<T>> dictionary)
{
if (dictionary == null)
return null;
var sortedList = new List<T>();
var dictKeys = CollectionUtils.Sort(dictionary.Keys, (i1, i2) => i1.CompareTo(i2));
foreach (var idx in dictKeys)
{
sortedList = CollectionUtils.Concat<T>(
new[]
{
sortedList,
dictionary[idx]
});
}
return sortedList;
}
private IEnumerable<ComponentQuestionControl> ComponentQuestionControls
{
get
{
foreach (Control component in Controls)
{
if (component is ComponentQuestionControl)
yield return (ComponentQuestionControl)component;
}
}
}
public void Reset()
{
var oldFireChangeEvent = _fireChangeEvent;
_fireChangeEvent = false;
foreach (var questionControl in ComponentQuestionControls)
questionControl.Reset();
_fireChangeEvent = oldFireChangeEvent;
if (_fireChangeEvent)
{
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedAnatomicEntities"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedImagingObservations"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedInferences"));
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedCalculations"));
EventsHelper.Fire(IsValidChanged, this, EventArgs.Empty);
}
}
private void OnControlSizeChanged(object sender, EventArgs e)
{
var senderCtrl = sender as Control;
if (senderCtrl == null)
return;
var nextCtrlY = 0;
CollectionUtils.ForEach<Control>(
Controls,
ctrl =>
{
if (senderCtrl.Location.Y < ctrl.Location.Y)
nextCtrlY = nextCtrlY == 0 ? ctrl.Location.Y : Math.Min(nextCtrlY, ctrl.Location.Y);
});
if (nextCtrlY > 0)
{
var requiredAdjustment = nextCtrlY - senderCtrl.Location.Y - senderCtrl.Height;
if (Math.Abs(requiredAdjustment) > 5)
{
CollectionUtils.ForEach<Control>(
Controls,
ctrl =>
{
if (ctrl.Location.Y > senderCtrl.Location.Y)
ctrl.Location = new Point(ctrl.Location.X, ctrl.Location.Y - requiredAdjustment);
});
}
}
}
private void OnComponentDataChanged(object sender, ComponentChangedEventArgs e)
{
if (e.AnatomicEntities != null)
{
if (e.AnatomicEntities.Count > 0)
_anatomicEntities[e.ItemNumber] = e.AnatomicEntities;
else
_anatomicEntities.Remove(e.ItemNumber);
if (_fireChangeEvent)
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedAnatomicEntities"));
}
else if (e.ImagingObservations != null)
{
if (e.ImagingObservations.Count > 0)
_imagingObservations[e.ItemNumber] = e.ImagingObservations;
else
_imagingObservations.Remove(e.ItemNumber);
if (_fireChangeEvent)
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedImagingObservations"));
}
else if (e.Inferences != null)
{
if (e.Inferences.Count > 0)
_inferences[e.ItemNumber] = e.Inferences;
else
_inferences.Remove(e.ItemNumber);
if (_fireChangeEvent)
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedInferences"));
}
else if (e.Calculations != null)
{
if (e.Calculations.Count > 0)
_calculations[e.ItemNumber] = e.Calculations;
else
_calculations.Remove(e.ItemNumber);
if (_fireChangeEvent)
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedCalculations"));
}
else if (e.GeometricShapes != null)
{
if (e.GeometricShapes.Count > 0)
_geometricShapes[e.ItemNumber] = e.GeometricShapes;
else
_geometricShapes.Remove(e.ItemNumber);
if (_fireChangeEvent)
EventsHelper.Fire(PropertyChanged, this, new PropertyChangedEventArgs("SelectedGeometricShapes"));
}
if (_fireChangeEvent)
EventsHelper.Fire(IsValidChanged, this, EventArgs.Empty);
}
#region Mouse Wheel Scrolling Support
private bool _lastNotificationWasGotFocus = false;
protected override void OnControlAdded(ControlEventArgs e)
{
SubscribeEvents(e.Control);
base.OnControlAdded(e);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
UnsubscribeEvents(e.Control);
base.OnControlRemoved(e);
}
private void SubscribeEvents(Control control)
{
control.GotFocus += OnControlGotFocus;
control.LostFocus += OnControlLostFocus;
control.ControlAdded += OnControlAdded;
control.ControlRemoved += OnControlRemoved;
foreach (Control innerControl in control.Controls)
{
SubscribeEvents(innerControl);
}
}
private void UnsubscribeEvents(Control control)
{
control.GotFocus -= OnControlGotFocus;
control.LostFocus -= OnControlLostFocus;
control.ControlAdded -= OnControlAdded;
control.ControlRemoved -= OnControlRemoved;
foreach (Control innerControl in control.Controls)
{
UnsubscribeEvents(innerControl);
}
}
private void OnControlAdded(object sender, ControlEventArgs e)
{
SubscribeEvents(e.Control);
}
private void OnControlRemoved(object sender, ControlEventArgs e)
{
UnsubscribeEvents(e.Control);
}
protected override void OnGotFocus(EventArgs e)
{
CheckContainsFocus();
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
CheckLostFocus();
base.OnLostFocus(e);
}
private void OnControlGotFocus(object sender, EventArgs e)
{
CheckContainsFocus();
}
private void OnControlLostFocus(object sender, EventArgs e)
{
CheckLostFocus();
}
private void CheckContainsFocus()
{
if (_lastNotificationWasGotFocus == false)
{
_lastNotificationWasGotFocus = true;
OnContainsFocus();
}
}
private void CheckLostFocus()
{
if (ContainsFocus == false)
{
_lastNotificationWasGotFocus = false;
OnLostFocus();
}
}
private void OnContainsFocus()
{
if (!_filterInstalled)
{
if (_filter == null)
_filter = new ComponentContainerScrollMessageFiler(this);
Application.AddMessageFilter(_filter);
_filterInstalled = true;
}
}
private void OnLostFocus()
{
if (_filterInstalled)
{
Application.RemoveMessageFilter(_filter);
_filterInstalled = false;
}
}
private void OnHandleDestroyed(object sender, EventArgs e)
{
if (_filterInstalled)
{
Application.RemoveMessageFilter(_filter);
_filterInstalled = false;
_filter = null;
}
}
#endregion
}
internal class ComponentContainerScrollMessageFiler : IMessageFilter
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int WM_MOUSEWHEEL = 0x20A;
private readonly ComponentContainerControl _containerControl;
public ComponentContainerScrollMessageFiler(ComponentContainerControl containerControl)
{
_containerControl = containerControl;
}
public bool PreFilterMessage(ref Message m)
{
switch(m.Msg)
{
case WM_MOUSEWHEEL:
var cursorPos = Cursor.Position;
if (_containerControl.RectangleToScreen(_containerControl.ClientRectangle).Contains(cursorPos))
{
var ctrl = Control.FromHandle(m.HWnd);
if ((ctrl == null ||
((ctrl is ComboBox || ctrl is CheckedListBox || ctrl is TextBox) &&
!ctrl.RectangleToScreen(ctrl.ClientRectangle).Contains(cursorPos))) &&
!(ctrl is ComboBox && ((ComboBox)ctrl).DroppedDown))
{
SendMessage(_containerControl.Handle, m.Msg, m.WParam, m.LParam);
return true;
}
}
break;
}
return false;
}
}
}
| |
#if OS_WINDOWS
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Listener;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.Win32;
using Moq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener
{
public sealed class AgentAutoLogonTestL0
{
private Mock<INativeWindowsServiceHelper> _windowsServiceHelper;
private Mock<IPromptManager> _promptManager;
private Mock<IProcessInvoker> _processInvoker;
private Mock<IConfigurationStore> _store;
private MockRegistryManager _mockRegManager;
private AutoLogonSettings _autoLogonSettings;
private CommandSettings _command;
private string _sid = "001";
private string _sidForDifferentUser = "007";
private string _userName = "ironMan";
private string _domainName = "avengers";
private bool _powerCfgCalledForACOption = false;
private bool _powerCfgCalledForDCOption = false;
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void TestAutoLogonConfiguration()
{
using (var hc = new TestHostContext(this))
{
SetupTestEnv(hc, _sid);
var iConfigManager = new AutoLogonManager();
iConfigManager.Initialize(hc);
await iConfigManager.ConfigureAsync(_command);
VerifyRegistryChanges(_sid);
Assert.True(_powerCfgCalledForACOption);
Assert.True(_powerCfgCalledForDCOption);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void TestAutoLogonConfigurationForDifferentUser()
{
using (var hc = new TestHostContext(this))
{
SetupTestEnv(hc, _sidForDifferentUser);
var iConfigManager = new AutoLogonManager();
iConfigManager.Initialize(hc);
await iConfigManager.ConfigureAsync(_command);
VerifyRegistryChanges(_sidForDifferentUser);
Assert.True(_powerCfgCalledForACOption);
Assert.True(_powerCfgCalledForDCOption);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void TestAutoLogonUnConfigure()
{
//strategy-
//1. fill some existing values in the registry
//2. run configure
//3. make sure the old values are there in the backup
//4. unconfigure
//5. make sure original values are reverted back
using (var hc = new TestHostContext(this))
{
SetupTestEnv(hc, _sid);
SetupRegistrySettings(_sid);
var iConfigManager = new AutoLogonManager();
iConfigManager.Initialize(hc);
await iConfigManager.ConfigureAsync(_command);
//make sure the backup was taken for the keys
RegistryVerificationForBackup(_sid);
// Debugger.Launch();
iConfigManager.Unconfigure();
//original values were reverted
RegistryVerificationForUnConfigure(_sid);
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Agent")]
public async void TestAutoLogonUnConfigureForDifferentUser()
{
//strategy-
//1. fill some existing values in the registry
//2. run configure
//3. make sure the old values are there in the backup
//4. unconfigure
//5. make sure original values are reverted back
using (var hc = new TestHostContext(this))
{
SetupTestEnv(hc, _sidForDifferentUser);
SetupRegistrySettings(_sidForDifferentUser);
var iConfigManager = new AutoLogonManager();
iConfigManager.Initialize(hc);
await iConfigManager.ConfigureAsync(_command);
//make sure the backup was taken for the keys
RegistryVerificationForBackup(_sidForDifferentUser);
iConfigManager.Unconfigure();
//original values were reverted
RegistryVerificationForUnConfigure(_sidForDifferentUser);
}
}
private void RegistryVerificationForBackup(string securityId)
{
//screen saver (user specific)
ValidateRegistryValue(RegistryHive.Users,
$"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}",
GetBackupValueName(RegistryConstants.UserSettings.ValueNames.ScreenSaver),
"1");
//HKLM setting
ValidateRegistryValue(RegistryHive.LocalMachine,
RegistryConstants.MachineSettings.SubKeys.AutoLogon,
GetBackupValueName(RegistryConstants.MachineSettings.ValueNames.AutoLogon),
"0");
//autologon password (delete key)
ValidateRegistryValue(RegistryHive.LocalMachine,
RegistryConstants.MachineSettings.SubKeys.AutoLogon,
GetBackupValueName(RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword),
"xyz");
}
private string GetBackupValueName(string valueName)
{
return string.Concat(RegistryConstants.BackupKeyPrefix, valueName);
}
private void RegistryVerificationForUnConfigure(string securityId)
{
//screen saver (user specific)
ValidateRegistryValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}", RegistryConstants.UserSettings.ValueNames.ScreenSaver, "1");
//HKLM setting
ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon, "0");
//autologon password (delete key)
ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword, "xyz");
//when done with reverting back the original settings we need to make sure we dont leave behind any extra setting
//user specific
ValidateRegistryValue(RegistryHive.Users,
$"{securityId}\\{RegistryConstants.UserSettings.SubKeys.StartupProcess}",
RegistryConstants.UserSettings.ValueNames.StartupProcess,
null);
}
private void SetupRegistrySettings(string securityId)
{
//HKLM setting
_mockRegManager.SetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon, "0");
//setting that we delete
_mockRegManager.SetValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword, "xyz");
//screen saver (user specific)
_mockRegManager.SetValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}", RegistryConstants.UserSettings.ValueNames.ScreenSaver, "1");
}
private void SetupTestEnv(TestHostContext hc, string securityId)
{
_powerCfgCalledForACOption = _powerCfgCalledForDCOption = false;
_autoLogonSettings = null;
_windowsServiceHelper = new Mock<INativeWindowsServiceHelper>();
hc.SetSingleton<INativeWindowsServiceHelper>(_windowsServiceHelper.Object);
_promptManager = new Mock<IPromptManager>();
hc.SetSingleton<IPromptManager>(_promptManager.Object);
hc.SetSingleton<IWhichUtil>(new WhichUtil());
_promptManager
.Setup(x => x.ReadValue(
Constants.Agent.CommandLine.Args.WindowsLogonAccount, // argName
It.IsAny<string>(), // description
It.IsAny<bool>(), // secret
It.IsAny<string>(), // defaultValue
Validators.NTAccountValidator, // validator
It.IsAny<bool>())) // unattended
.Returns(string.Format(@"{0}\{1}", _domainName, _userName));
_windowsServiceHelper.Setup(x => x.IsValidAutoLogonCredential(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true);
_windowsServiceHelper.Setup(x => x.SetAutoLogonPassword(It.IsAny<string>()));
_windowsServiceHelper.Setup(x => x.GetSecurityId(It.IsAny<string>(), It.IsAny<string>())).Returns(() => securityId);
_windowsServiceHelper.Setup(x => x.IsRunningInElevatedMode()).Returns(true);
_processInvoker = new Mock<IProcessInvoker>();
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object);
_processInvoker.Setup(x => x.ExecuteAsync(
It.IsAny<String>(),
"powercfg.exe",
"/Change monitor-timeout-ac 0",
null,
It.IsAny<CancellationToken>())).Returns(Task.FromResult<int>(SetPowerCfgFlags(true)));
_processInvoker.Setup(x => x.ExecuteAsync(
It.IsAny<String>(),
"powercfg.exe",
"/Change monitor-timeout-dc 0",
null,
It.IsAny<CancellationToken>())).Returns(Task.FromResult<int>(SetPowerCfgFlags(false)));
_mockRegManager = new MockRegistryManager();
hc.SetSingleton<IWindowsRegistryManager>(_mockRegManager);
_command = new CommandSettings(
hc,
new[]
{
"--windowslogonaccount", "wont be honored",
"--windowslogonpassword", "sssh",
"--norestart"
});
_store = new Mock<IConfigurationStore>();
_store.Setup(x => x.SaveAutoLogonSettings(It.IsAny<AutoLogonSettings>()))
.Callback((AutoLogonSettings settings) =>
{
_autoLogonSettings = settings;
});
_store.Setup(x => x.IsAutoLogonConfigured()).Returns(() => _autoLogonSettings != null);
_store.Setup(x => x.GetAutoLogonSettings()).Returns(() => _autoLogonSettings);
hc.SetSingleton<IConfigurationStore>(_store.Object);
hc.SetSingleton<IAutoLogonRegistryManager>(new AutoLogonRegistryManager());
}
private int SetPowerCfgFlags(bool isForACOption)
{
if (isForACOption)
{
_powerCfgCalledForACOption = true;
}
else
{
_powerCfgCalledForDCOption = true;
}
return 0;
}
public void VerifyRegistryChanges(string securityId)
{
ValidateRegistryValue(RegistryHive.LocalMachine,
RegistryConstants.MachineSettings.SubKeys.AutoLogon,
RegistryConstants.MachineSettings.ValueNames.AutoLogon,
"1");
ValidateRegistryValue(RegistryHive.LocalMachine,
RegistryConstants.MachineSettings.SubKeys.AutoLogon,
RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName,
_userName);
ValidateRegistryValue(RegistryHive.LocalMachine,
RegistryConstants.MachineSettings.SubKeys.AutoLogon,
RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword,
null);
ValidateRegistryValue(RegistryHive.Users,
$"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}",
RegistryConstants.UserSettings.ValueNames.ScreenSaver,
"0");
}
public void ValidateRegistryValue(RegistryHive hive, string subKeyName, string name, string expectedValue)
{
var actualValue = _mockRegManager.GetValue(hive, subKeyName, name);
var validationPassed = string.Equals(expectedValue, actualValue, StringComparison.OrdinalIgnoreCase);
Assert.True(validationPassed, $"Validation failed for '{subKeyName}\\{name}'. Expected - {expectedValue} Actual - {actualValue}");
}
}
public class MockRegistryManager : AgentService, IWindowsRegistryManager
{
private Dictionary<string, string> _regStore;
public MockRegistryManager()
{
_regStore = new Dictionary<string, string>();
}
public string GetValue(RegistryHive hive, string subKeyName, string name)
{
var key = string.Concat(hive.ToString(), subKeyName, name);
return _regStore.ContainsKey(key) ? _regStore[key] : null;
}
public void SetValue(RegistryHive hive, string subKeyName, string name, string value)
{
var key = string.Concat(hive.ToString(), subKeyName, name);
if (_regStore.ContainsKey(key))
{
_regStore[key] = value;
}
else
{
_regStore.Add(key, value);
}
}
public void DeleteValue(RegistryHive hive, string subKeyName, string name)
{
var key = string.Concat(hive.ToString(), subKeyName, name);
_regStore.Remove(key);
}
public bool SubKeyExists(RegistryHive hive, string subKeyName)
{
return true;
}
}
}
#endif
| |
/*
* C# port of Mozilla Character Set Detector
* https://code.google.com/p/chardetsharp/
*
* Original Mozilla License Block follows
*
*/
#region License Block
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// The Original Code is Mozilla Universal charset detector code.
//
// The Initial Developer of the Original Code is
// Netscape Communications Corporation.
// Portions created by the Initial Developer are Copyright (C) 2001
// the Initial Developer. All Rights Reserved.
//
// Contributor(s):
//
// Alternatively, the contents of this file may be used under the terms of
// either the GNU General Public License Version 2 or later (the "GPL"), or
// the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
// in which case the provisions of the GPL or the LGPL are applicable instead
// of those above. If you wish to allow use of your version of this file only
// under the terms of either the GPL or the LGPL, and not to allow others to
// use your version of this file under the terms of the MPL, indicate your
// decision by deleting the provisions above and replace them with the notice
// and other provisions required by the GPL or the LGPL. If you do not delete
// the provisions above, a recipient may use your version of this file under
// the terms of any one of the MPL, the GPL or the LGPL.
#endregion
namespace Cloney.Core.CharsetDetection
{
internal partial class SequenceModel
{
//*****************************************************************
// 255: Control characters that usually does not exist in any text
// 254: Carriage/Return
// 253: symbol (punctuation) that does not belong to word
// 252: 0 - 9
//*****************************************************************
static readonly byte[] KOI8R_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, //80
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, //90
223,224,225, 68,226,227,228,229,230,231,232,233,234,235,236,237, //a0
238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253, //b0
27, 3, 21, 28, 13, 2, 39, 19, 26, 4, 23, 11, 8, 12, 5, 1, //c0
15, 16, 9, 7, 6, 14, 24, 10, 17, 18, 20, 25, 30, 29, 22, 54, //d0
59, 37, 44, 58, 41, 48, 53, 46, 55, 42, 60, 36, 49, 38, 31, 34, //e0
35, 43, 45, 32, 40, 52, 56, 33, 61, 62, 51, 57, 47, 63, 50, 70, //f0
};
static readonly byte[] win1251_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253,
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
};
static readonly byte[] latin5_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
};
static readonly byte[] macCyrillic_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
239,240,241,242,243,244,245,246,247,248,249,250,251,252, 68, 16,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27,255,
};
static readonly byte[] IBM855_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
191,192,193,194, 68,195,196,197,198,199,200,201,202,203,204,205,
206,207,208,209,210,211,212,213,214,215,216,217, 27, 59, 54, 70,
3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46,218,219,
220,221,222,223,224, 26, 55, 4, 42,225,226,227,228, 23, 60,229,
230,231,232,233,234,235, 11, 36,236,237,238,239,240,241,242,243,
8, 49, 12, 38, 5, 31, 1, 34, 15,244,245,246,247, 35, 16,248,
43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61,249,
250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50,251,252,255,
};
static readonly byte[] IBM866_CharToOrderMap = new byte[] {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
};
//Model Table:
//total sequences: 100%
//first 512 sequences: 97.6601%
//first 1024 sequences: 2.3389%
//rest sequences: 0.1237%
//negative sequences: 0.0009%
static readonly byte[] RussianLangModel = new byte[] {
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,1,3,3,3,2,3,2,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,2,2,0,0,2,
3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,2,3,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,2,2,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,2,3,3,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,2,2,2,3,1,3,3,1,3,3,3,3,2,2,3,0,2,2,2,3,3,2,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,3,3,3,2,2,3,2,3,3,3,2,1,2,2,0,1,2,2,2,2,2,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,2,3,3,2,1,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,1,2,3,2,2,3,2,3,3,3,3,2,2,3,0,3,2,2,3,1,1,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,3,3,3,3,2,2,2,0,3,3,3,2,2,2,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,2,3,2,2,0,1,3,2,1,2,2,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,2,1,1,3,0,1,1,1,1,2,1,1,0,2,2,2,1,2,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,2,2,2,2,1,3,2,3,2,3,2,1,2,2,0,1,1,2,1,2,1,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,2,2,2,0,2,2,2,2,3,1,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,2,3,2,2,3,3,3,3,3,3,3,3,3,1,3,2,0,0,3,3,3,3,2,3,3,3,3,2,3,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,3,2,2,3,3,0,2,1,0,3,2,3,2,3,0,0,1,2,0,0,1,0,1,2,1,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,3,0,2,3,3,3,3,2,3,3,3,3,1,2,2,0,0,2,3,2,2,2,3,2,3,2,2,3,0,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,0,2,3,2,3,0,1,2,3,3,2,0,2,3,0,0,2,3,2,2,0,1,3,1,3,2,2,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,3,0,2,3,3,3,3,3,3,3,3,2,1,3,2,0,0,2,2,3,3,3,2,3,3,0,2,2,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,2,3,3,2,2,2,3,3,0,0,1,1,1,1,1,2,0,0,1,1,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,2,3,3,3,3,3,3,3,0,3,2,3,3,2,3,2,0,2,1,0,1,1,0,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,3,2,2,2,2,3,1,3,2,3,1,1,2,1,0,2,2,2,2,1,3,1,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
2,2,3,3,3,3,3,1,2,2,1,3,1,0,3,0,0,3,0,0,0,1,1,0,1,2,1,0,0,0,0,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,2,1,1,3,3,3,2,2,1,2,2,3,1,1,2,0,0,2,2,1,3,0,0,2,1,1,2,1,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,3,3,3,1,2,2,2,1,2,1,3,3,1,1,2,1,2,1,2,2,0,2,0,0,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,3,2,1,3,2,2,3,2,0,3,2,0,3,0,1,0,1,1,0,0,1,1,1,1,0,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,2,3,3,3,2,2,2,3,3,1,2,1,2,1,0,1,0,1,1,0,1,0,0,2,1,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
3,1,1,2,1,2,3,3,2,2,1,2,2,3,0,2,1,0,0,2,2,3,2,1,2,2,2,2,2,3,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,1,1,0,1,1,2,2,1,1,3,0,0,1,3,1,1,1,0,0,0,1,0,1,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,1,3,3,3,2,0,0,0,2,1,0,1,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,1,0,0,2,3,2,2,2,1,2,2,2,1,2,1,0,0,1,1,1,0,2,0,1,1,1,0,0,1,1,
1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,0,0,0,0,1,0,0,0,0,3,0,1,2,1,0,0,0,0,0,0,0,1,1,0,0,1,1,
1,0,1,0,1,2,0,0,1,1,2,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0,
2,2,3,2,2,2,3,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,1,0,1,1,1,0,2,1,
1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0,
3,3,3,2,2,2,2,3,2,2,1,1,2,2,2,2,1,1,3,1,2,1,2,0,0,1,1,0,1,0,2,1,
1,1,1,1,1,2,1,0,1,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0,
2,0,0,1,0,3,2,2,2,2,1,2,1,2,1,2,0,0,0,2,1,2,2,1,1,2,2,0,1,1,0,2,
1,1,1,1,1,0,1,1,1,2,1,1,1,2,1,0,1,2,1,1,1,1,0,1,1,1,0,0,1,0,0,1,
1,3,2,2,2,1,1,1,2,3,0,0,0,0,2,0,2,2,1,0,0,0,0,0,0,1,0,0,0,0,1,1,
1,0,1,1,0,1,0,1,1,0,1,1,0,2,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
2,3,2,3,2,1,2,2,2,2,1,0,0,0,2,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,2,1,
1,1,2,1,0,2,0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,
3,0,0,1,0,2,2,2,3,2,2,2,2,2,2,2,0,0,0,2,1,2,1,1,1,2,2,0,0,0,1,2,
1,1,1,1,1,0,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,
2,3,2,3,3,2,0,1,1,1,0,0,1,0,2,0,1,1,3,1,0,0,0,0,0,0,0,1,0,0,2,1,
1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,
2,3,3,3,3,1,2,2,2,2,0,1,1,0,2,1,1,1,2,1,0,1,1,0,0,1,0,1,0,0,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,2,0,0,1,1,2,2,1,0,0,2,0,1,1,3,0,0,1,0,0,0,0,0,1,0,1,2,1,
1,1,2,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0,
1,3,2,3,2,1,0,0,2,2,2,0,1,0,2,0,1,1,1,0,1,0,0,0,3,0,1,1,0,0,2,1,
1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,2,1,1,0,1,0,0,0,1,0,1,0,0,1,1,0,
3,1,2,1,1,2,2,2,2,2,2,1,2,2,1,1,0,0,0,2,2,2,0,0,0,1,2,1,0,1,0,1,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1,
3,0,0,0,0,2,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,1,0,1,
1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,
1,3,3,2,2,0,0,0,2,2,0,0,0,1,2,0,1,1,2,0,0,0,0,0,0,0,0,1,0,0,2,1,
0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
2,3,2,3,2,0,0,0,0,1,1,0,0,0,2,0,2,0,2,0,0,0,0,0,1,0,0,1,0,0,1,1,
1,1,2,0,1,2,1,0,1,1,2,1,1,1,1,1,2,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0,
1,3,2,2,2,1,0,0,2,2,1,0,1,2,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,
0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,0,2,3,1,2,2,2,2,2,2,1,1,0,0,0,1,0,1,0,2,1,1,1,0,0,0,0,1,
1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
2,0,2,0,0,1,0,3,2,1,2,1,2,2,0,1,0,0,0,2,1,0,0,2,1,1,1,1,0,2,0,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,
1,2,2,2,2,1,0,0,1,0,0,0,0,0,2,0,1,1,1,1,0,0,0,0,1,0,1,2,0,0,2,0,
1,0,1,1,1,2,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,
2,1,2,2,2,0,3,0,1,1,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,
1,2,2,3,2,2,0,0,1,1,2,0,1,2,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,
0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
2,2,1,1,2,1,2,2,2,2,2,1,2,2,0,1,0,0,0,1,2,2,2,1,2,1,1,1,1,1,2,1,
1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1,
1,2,2,2,2,0,1,0,2,2,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,0,0,2,2,2,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,
0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,0,0,0,1,0,0,1,1,2,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,1,
0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,1,1,2,0,2,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,
0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
1,0,2,1,2,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
1,0,0,0,0,2,0,1,2,1,0,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,
0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,
0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
};
public static readonly SequenceModel Koi8rModel = new SequenceModel(
KOI8R_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"KOI8-R"
);
public static readonly SequenceModel Win1251Model = new SequenceModel(
win1251_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"windows-1251"
);
public static readonly SequenceModel Latin5Model = new SequenceModel(
latin5_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"ISO-8859-5"
);
public static readonly SequenceModel MacCyrillicModel = new SequenceModel(
macCyrillic_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"x-mac-cyrillic"
);
public static readonly SequenceModel Ibm855Model = new SequenceModel(
IBM855_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"IBM855"
);
public static readonly SequenceModel Ibm866Model = new SequenceModel(
IBM866_CharToOrderMap,
RussianLangModel,
(float)0.976601,
false,
"IBM866"
);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static partial class SignerInfoTests
{
[Fact]
public static void SignerInfo_SignedAttributes_Cached_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.SignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Empty(attrs);
}
[Fact]
public static void SignerInfo_SignedAttributes_Cached_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.SignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.SignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Equal(4, attrs.Count);
}
[Fact]
public static void SignerInfo_UnsignedAttributes_Cached_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Empty(attrs);
Assert.Empty(attrs2);
}
[Fact]
public static void SignerInfo_UnsignedAttributes_Cached_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
CryptographicAttributeObjectCollection attrs = signer.UnsignedAttributes;
CryptographicAttributeObjectCollection attrs2 = signer.UnsignedAttributes;
Assert.Same(attrs, attrs2);
Assert.Single(attrs);
}
[Fact]
public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
SignerInfoCollection counterSigners = signer.CounterSignerInfos;
SignerInfoCollection counterSigners2 = signer.CounterSignerInfos;
Assert.NotSame(counterSigners, counterSigners2);
Assert.Empty(counterSigners);
Assert.Empty(counterSigners2);
}
[Fact]
public static void SignerInfo_CounterSignerInfos_UniquePerCall_WhenNonEmpty()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
SignerInfoCollection counterSigners = signer.CounterSignerInfos;
SignerInfoCollection counterSigners2 = signer.CounterSignerInfos;
Assert.NotSame(counterSigners, counterSigners2);
Assert.Single(counterSigners);
Assert.Single(counterSigners2);
for (int i = 0; i < counterSigners.Count; i++)
{
SignerInfo counterSigner = counterSigners[i];
SignerInfo counterSigner2 = counterSigners2[i];
Assert.NotSame(counterSigner, counterSigner2);
Assert.NotSame(counterSigner.Certificate, counterSigner2.Certificate);
Assert.Equal(counterSigner.Certificate, counterSigner2.Certificate);
#if netcoreapp
byte[] signature = counterSigner.GetSignature();
byte[] signature2 = counterSigner2.GetSignature();
Assert.NotSame(signature, signature2);
Assert.Equal(signature, signature2);
#endif
}
}
#if netcoreapp
[Fact]
public static void SignerInfo_GetSignature_UniquePerCall()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
byte[] signature = signer.GetSignature();
byte[] signature2 = signer.GetSignature();
Assert.NotSame(signature, signature2);
Assert.Equal(signature, signature2);
}
#endif
[Fact]
public static void SignerInfo_DigestAlgorithm_NotSame()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
Oid oid = signer.DigestAlgorithm;
Oid oid2 = signer.DigestAlgorithm;
Assert.NotSame(oid, oid2);
}
#if netcoreapp
[Fact]
public static void SignerInfo_SignatureAlgorithm_NotSame()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
Oid oid = signer.SignatureAlgorithm;
Oid oid2 = signer.SignatureAlgorithm;
Assert.NotSame(oid, oid2);
}
#endif
[Fact]
public static void SignerInfo_Certificate_Same()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);
SignerInfo signer = cms.SignerInfos[0];
X509Certificate2 cert = signer.Certificate;
X509Certificate2 cert2 = signer.Certificate;
Assert.Same(cert, cert2);
}
[Fact]
public static void CheckSignature_ThrowsOnNullStore()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
SignerInfo signer = cms.SignerInfos[0];
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => signer.CheckSignature(null, true));
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => signer.CheckSignature(null, false));
}
[Fact]
public static void CheckSignature_ExtraStore_IsAdditional()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo signer = cms.SignerInfos[0];
Assert.NotNull(signer.Certificate);
// Assert.NotThrows
signer.CheckSignature(true);
// Assert.NotThrows
signer.CheckSignature(new X509Certificate2Collection(), true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesIssuerAndSerialNumber()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[1];
Assert.Equal(
SubjectIdentifierType.IssuerAndSerialNumber,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.NotEqual(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Equal(countBefore, cms.Certificates.Count);
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesSubjectKeyIdentifier()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Equal(
SubjectIdentifierType.SubjectKeyIdentifier,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.Equal(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
// This certificate is still in use, since we counter-signed ourself,
// and the remaining countersigner is us.
Assert.Equal(countBefore, cms.Certificates.Count);
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_MatchesNoSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1CounterSignedWithNoSignature);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Single(signerInfo.CounterSignerInfos);
Assert.Equal(SubjectIdentifierType.NoSignature, counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
// cms.CheckSignature fails because there's a NoSignature countersigner:
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
signerInfo.RemoveCounterSignature(counterSigner);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Single(signerInfo.CounterSignerInfos);
Assert.Empty(cms.SignerInfos[0].CounterSignerInfos);
// This certificate is still in use, since we counter-signed ourself,
// and the remaining countersigner is us.
Assert.Equal(countBefore, cms.Certificates.Count);
// And we succeed now, because we got rid of the NoSignature signer.
cms.CheckSignature(true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_UsesLiveState()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
SignerInfo counterSigner = signerInfo.CounterSignerInfos[0];
Assert.Equal(
SubjectIdentifierType.SubjectKeyIdentifier,
counterSigner.SignerIdentifier.Type);
int countBefore = cms.Certificates.Count;
Assert.Equal(signerInfo.Certificate, counterSigner.Certificate);
signerInfo.RemoveCounterSignature(counterSigner);
Assert.Single(cms.SignerInfos);
// Removing a CounterSigner doesn't update the current object, it updates
// the underlying SignedCms object, and a new signer has to be retrieved.
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Equal(countBefore, cms.Certificates.Count);
// Even though the CounterSignerInfos collection still contains this, the live
// document doesn't.
Assert.Throws<CryptographicException>(
() => signerInfo.RemoveCounterSignature(counterSigner));
// Assert.NotThrows
cms.CheckSignature(true);
cms.CheckHash();
}
[Fact]
public static void RemoveCounterSignature_WithNoMatch()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signerInfo = cms.SignerInfos[0];
// Even though we counter-signed ourself, the counter-signer version of us
// is SubjectKeyIdentifier, and we're IssuerAndSerialNumber, so no match.
Assert.Throws<CryptographicException>(
() => signerInfo.RemoveCounterSignature(signerInfo));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug")]
[ActiveIssue(31977, TargetFrameworkMonikers.Uap)]
public static void RemoveCounterSignature_EncodedInSingleAttribute(int indexToRemove)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1TwoCounterSignaturesInSingleAttribute);
SignerInfo signerInfo = cms.SignerInfos[0];
Assert.Equal(2, signerInfo.CounterSignerInfos.Count);
signerInfo.RemoveCounterSignature(indexToRemove);
Assert.Equal(1, signerInfo.CounterSignerInfos.Count);
cms.CheckSignature(true);
}
[Fact]
public static void RemoveCounterSignature_Null()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count);
AssertExtensions.Throws<ArgumentNullException>(
"counterSignerInfo",
() => cms.SignerInfos[0].RemoveCounterSignature(null));
Assert.Equal(2, cms.SignerInfos[0].CounterSignerInfos.Count);
}
[Fact]
public static void RemoveCounterSignature_Negative()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
ArgumentOutOfRangeException ex = AssertExtensions.Throws<ArgumentOutOfRangeException>(
"childIndex",
() => signer.RemoveCounterSignature(-1));
Assert.Equal(null, ex.ActualValue);
}
[Fact]
public static void RemoveCounterSignature_TooBigByValue()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(2));
signer.RemoveCounterSignature(1);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(1));
}
[Fact]
public static void RemoveCounterSignature_TooBigByValue_Past0()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
signer.RemoveCounterSignature(0);
signer.RemoveCounterSignature(0);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(0));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFx bug in matching logic")]
public static void RemoveCounterSignature_TooBigByMatch()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
SignerInfo counterSigner = signer.CounterSignerInfos[1];
// This succeeeds, but reduces the real count to 1.
signer.RemoveCounterSignature(counterSigner);
Assert.Equal(2, signer.CounterSignerInfos.Count);
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(counterSigner));
}
[Fact]
public static void RemoveCounterSignature_BySignerInfo_OnRemovedSigner()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
SignerInfo counterSigner = signer.CounterSignerInfos[0];
cms.RemoveSignature(signer);
Assert.NotEmpty(signer.CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(counterSigner));
}
[Fact]
public static void RemoveCounterSignature_ByIndex_OnRemovedSigner()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);
SignerInfo signer = cms.SignerInfos[0];
cms.RemoveSignature(signer);
Assert.NotEmpty(signer.CounterSignerInfos);
Assert.Throws<CryptographicException>(
() => signer.RemoveCounterSignature(0));
}
[Fact]
public static void AddCounterSigner_DuplicateCert_RSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedAttrCount = 1;
// One of them is a V3 signer.
#if netfx
expectedAttrCount = 2;
#endif
Assert.Equal(expectedAttrCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedAttrCount - 1].Oid.Value);
Assert.Equal(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Single(cms.Certificates);
counterSigner.CheckSignature(true);
firstSigner2.CheckSignature(true);
cms.CheckSignature(true);
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier)]
public static void AddCounterSigner_RSA(SubjectIdentifierType identifierType)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(identifierType, counterSigner.SignerIdentifier.Type);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if netfx
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
counterSigner.CheckSignature(true);
firstSigner2.CheckSignature(true);
cms.CheckSignature(true);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Not supported by crypt32")]
public static void AddCounterSignerToUnsortedAttributeSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.DigiCertTimeStampToken);
// Assert.NoThrows
cms.CheckSignature(true);
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
SignerInfo signerInfo = signers[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
signerInfo.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.IssuerAndSerialNumber,
cert));
signerInfo.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.SubjectKeyIdentifier,
cert));
}
// Assert.NoThrows
cms.CheckSignature(true);
byte[] exported = cms.Encode();
cms = new SignedCms();
cms.Decode(exported);
// Assert.NoThrows
cms.CheckSignature(true);
}
[Fact]
[ActiveIssue(31977, TargetFrameworkMonikers.Uap)]
public static void AddCounterSigner_DSA()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
// Best compatibility for DSA is SHA-1 (FIPS 186-2)
signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
Assert.Single(cms.SignerInfos);
Assert.Equal(2, cms.Certificates.Count);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
Assert.Equal(1, counterSigner.Version);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if netfx
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
#if netcoreapp
byte[] signature = counterSigner.GetSignature();
Assert.NotEmpty(signature);
// DSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms.Decode(encoded);
cms.CheckSignature(true);
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha1)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha1)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha256)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha256)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha384)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha384)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, Oids.Sha512)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, Oids.Sha512)]
public static void AddCounterSigner_ECDSA(SubjectIdentifierType identifierType, string digestOid)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.Certificates);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
using (X509Certificate2 signerCert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
signer.DigestAlgorithm = new Oid(digestOid, digestOid);
firstSigner.ComputeCounterSignature(signer);
}
Assert.Empty(firstSigner.CounterSignerInfos);
Assert.Empty(firstSigner.UnsignedAttributes);
SignerInfo firstSigner2 = cms.SignerInfos[0];
Assert.Single(firstSigner2.CounterSignerInfos);
Assert.Single(firstSigner2.UnsignedAttributes);
Assert.Single(cms.SignerInfos);
Assert.Equal(2, cms.Certificates.Count);
SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0];
int expectedVersion = identifierType == SubjectIdentifierType.IssuerAndSerialNumber ? 1 : 3;
Assert.Equal(expectedVersion, counterSigner.Version);
// On NetFx there will be two attributes, because Windows emits the
// content-type attribute even for counter-signers.
int expectedCount = 1;
#if netfx
expectedCount = 2;
#endif
Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count);
Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value);
Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate);
Assert.Equal(2, cms.Certificates.Count);
#if netcoreapp
byte[] signature = counterSigner.GetSignature();
Assert.NotEmpty(signature);
// DSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
// ECDSA Oids are all under 1.2.840.10045.4.
Assert.StartsWith("1.2.840.10045.4.", counterSigner.SignatureAlgorithm.Value);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms.Decode(encoded);
cms.CheckSignature(true);
}
[Fact]
public static void AddFirstCounterSigner_NoSignature_NoPrivateKey()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
{
Action sign = () =>
firstSigner.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.NoSignature,
cert)
{
IncludeOption = X509IncludeOption.None,
});
if (PlatformDetection.IsFullFramework)
{
Assert.ThrowsAny<CryptographicException>(sign);
}
else
{
sign();
cms.CheckHash();
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
firstSigner.CheckSignature(true);
}
}
}
[Fact]
public static void AddFirstCounterSigner_NoSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
// A certificate shouldn't really be required here, but on .NET Framework
// it will prompt for the counter-signer's certificate if it's null,
// even if the signature type is NoSignature.
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
firstSigner.ComputeCounterSignature(
new CmsSigner(
SubjectIdentifierType.NoSignature,
cert)
{
IncludeOption = X509IncludeOption.None,
});
}
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
firstSigner = cms.SignerInfos[0];
firstSigner.CheckSignature(verifySignatureOnly: true);
Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash());
SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0];
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true));
if (PlatformDetection.IsFullFramework)
{
// NetFX's CheckHash only looks at top-level SignerInfos to find the
// crypt32 CMS signer ID, so it fails on any check from a countersigner.
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash());
}
else
{
firstCounterSigner.CheckHash();
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondCounterSignature_NoSignature_WithCert(bool addExtraCert)
{
AddSecondCounterSignature_NoSignature(withCertificate: true, addExtraCert);
}
[Theory]
// On .NET Framework it will prompt for the counter-signer's certificate if it's null,
// even if the signature type is NoSignature, so don't run the test there.
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondCounterSignature_NoSignature_WithoutCert(bool addExtraCert)
{
AddSecondCounterSignature_NoSignature(withCertificate: false, addExtraCert);
}
private static void AddSecondCounterSignature_NoSignature(bool withCertificate, bool addExtraCert)
{
X509Certificate2Collection certs;
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo firstSigner = cms.SignerInfos[0];
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
using (X509Certificate2 cert2 = Certificates.DHKeyAgree1.GetCertificate())
{
firstSigner.ComputeCounterSignature(
new CmsSigner(cert)
{
IncludeOption = X509IncludeOption.None,
});
CmsSigner counterSigner;
if (withCertificate)
{
counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature, cert);
}
else
{
counterSigner = new CmsSigner(SubjectIdentifierType.NoSignature);
}
if (addExtraCert)
{
counterSigner.Certificates.Add(cert2);
}
firstSigner.ComputeCounterSignature(counterSigner);
certs = cms.Certificates;
if (addExtraCert)
{
Assert.Equal(2, certs.Count);
Assert.NotEqual(cert2.RawData, certs[0].RawData);
Assert.Equal(cert2.RawData, certs[1].RawData);
}
else
{
Assert.Equal(1, certs.Count);
Assert.NotEqual(cert2.RawData, certs[0].RawData);
}
}
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
firstSigner = cms.SignerInfos[0];
firstSigner.CheckSignature(verifySignatureOnly: true);
Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckHash());
// The NoSignature CounterSigner sorts first.
SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0];
Assert.Equal(SubjectIdentifierType.NoSignature, firstCounterSigner.SignerIdentifier.Type);
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckSignature(true));
if (PlatformDetection.IsFullFramework)
{
// NetFX's CheckHash only looks at top-level SignerInfos to find the
// crypt32 CMS signer ID, so it fails on any check from a countersigner.
Assert.ThrowsAny<CryptographicException>(() => firstCounterSigner.CheckHash());
}
else
{
firstCounterSigner.CheckHash();
}
certs = cms.Certificates;
if (addExtraCert)
{
Assert.Equal(2, certs.Count);
Assert.Equal("CN=DfHelleKeyAgreement1", certs[1].SubjectName.Name);
}
else
{
Assert.Equal(1, certs.Count);
}
Assert.Equal("CN=RSAKeyTransferCapi1", certs[0].SubjectName.Name);
}
[Fact]
[ActiveIssue(31977, TargetFrameworkMonikers.Uap)]
public static void EnsureExtraCertsAdded()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.OneDsa1024);
int preCount = cms.Certificates.Count;
using (X509Certificate2 unrelated1 = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated1Copy = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated2 = Certificates.RSAKeyTransfer2.GetCertificate())
using (X509Certificate2 unrelated3 = Certificates.RSAKeyTransfer3.GetCertificate())
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
signer.Certificates.Add(unrelated1);
signer.Certificates.Add(unrelated2);
signer.Certificates.Add(unrelated3);
signer.Certificates.Add(unrelated1Copy);
cms.SignerInfos[0].ComputeCounterSignature(signer);
bool ExpectCopyRemoved =
#if netfx
false
#else
true
#endif
;
int expectedAddedCount = 4;
if (!ExpectCopyRemoved)
{
expectedAddedCount++;
}
// Since adding a counter-signer DER-normalizes the document the certificates
// get rewritten to be smallest cert first.
X509Certificate2Collection certs = cms.Certificates;
List<X509Certificate2> certList = new List<X509Certificate2>(certs.OfType<X509Certificate2>());
int lastSize = -1;
for (int i = 0; i < certList.Count; i++)
{
byte[] rawData = certList[i].RawData;
Assert.True(
rawData.Length >= lastSize,
$"Certificate {i} has an encoded size ({rawData.Length}) no smaller than its predecessor ({lastSize})");
}
Assert.Contains(unrelated1, certList);
Assert.Contains(unrelated2, certList);
Assert.Contains(unrelated3, certList);
Assert.Contains(signerCert, certList);
Assert.Equal(ExpectCopyRemoved ? 1 : 2, certList.Count(c => c.Equals(unrelated1)));
}
cms.CheckSignature(true);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
namespace System.Linq
{
internal static class Enumerable
{
public static IEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, false);
}
}
internal abstract class OrderedEnumerable<TElement> : IEnumerable<TElement>
{
internal IEnumerable<TElement> source;
public IEnumerator<TElement> GetEnumerator()
{
Buffer<TElement> buffer = new Buffer<TElement>(source);
if (buffer.count > 0)
{
EnumerableSorter<TElement> sorter = GetEnumerableSorter(null);
int[] map = sorter.Sort(buffer.items, buffer.count);
sorter = null;
for (int i = 0; i < buffer.count; i++) yield return buffer.items[map[i]];
}
}
internal abstract EnumerableSorter<TElement> GetEnumerableSorter(EnumerableSorter<TElement> next);
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class OrderedEnumerable<TElement, TKey> : OrderedEnumerable<TElement>
{
internal OrderedEnumerable<TElement> parent;
internal Func<TElement, TKey> keySelector;
internal IComparer<TKey> comparer;
internal bool descending;
internal OrderedEnumerable(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
this.source = source;
this.parent = null;
this.keySelector = keySelector;
this.comparer = comparer ?? Comparer<TKey>.Default;
this.descending = descending;
}
internal override EnumerableSorter<TElement> GetEnumerableSorter(EnumerableSorter<TElement> next)
{
EnumerableSorter<TElement> sorter = new EnumerableSorter<TElement, TKey>(keySelector, comparer, descending, next);
if (parent != null) sorter = parent.GetEnumerableSorter(sorter);
return sorter;
}
}
internal abstract class EnumerableSorter<TElement>
{
internal abstract void ComputeKeys(TElement[] elements, int count);
internal abstract int CompareKeys(int index1, int index2);
internal int[] Sort(TElement[] elements, int count)
{
ComputeKeys(elements, count);
int[] map = new int[count];
for (int i = 0; i < count; i++) map[i] = i;
QuickSort(map, 0, count - 1);
return map;
}
void QuickSort(int[] map, int left, int right)
{
do
{
int i = left;
int j = right;
int x = map[i + ((j - i) >> 1)];
do
{
while (i < map.Length && CompareKeys(x, map[i]) > 0) i++;
while (j >= 0 && CompareKeys(x, map[j]) < 0) j--;
if (i > j) break;
if (i < j)
{
int temp = map[i];
map[i] = map[j];
map[j] = temp;
}
i++;
j--;
} while (i <= j);
if (j - left <= right - i)
{
if (left < j) QuickSort(map, left, j);
left = i;
}
else
{
if (i < right) QuickSort(map, i, right);
right = j;
}
} while (left < right);
}
}
internal class EnumerableSorter<TElement, TKey> : EnumerableSorter<TElement>
{
internal Func<TElement, TKey> keySelector;
internal IComparer<TKey> comparer;
internal bool descending;
internal EnumerableSorter<TElement> next;
internal TKey[] keys;
internal EnumerableSorter(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, EnumerableSorter<TElement> next)
{
this.keySelector = keySelector;
this.comparer = comparer;
this.descending = descending;
this.next = next;
}
internal override void ComputeKeys(TElement[] elements, int count)
{
keys = new TKey[count];
for (int i = 0; i < count; i++) keys[i] = keySelector(elements[i]);
if (next != null) next.ComputeKeys(elements, count);
}
internal override int CompareKeys(int index1, int index2)
{
int c = comparer.Compare(keys[index1], keys[index2]);
if (c == 0)
{
if (next == null) return index1 - index2;
return next.CompareKeys(index1, index2);
}
return descending ? -c : c;
}
}
struct Buffer<TElement>
{
internal TElement[] items;
internal int count;
internal Buffer(IEnumerable<TElement> source)
{
TElement[] items = null;
int count = 0;
ICollection<TElement> collection = source as ICollection<TElement>;
if (collection != null)
{
count = collection.Count;
if (count > 0)
{
items = new TElement[count];
collection.CopyTo(items, 0);
}
}
else
{
foreach (TElement item in source)
{
if (items == null)
{
items = new TElement[4];
}
else if (items.Length == count)
{
TElement[] newItems = new TElement[checked(count * 2)];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
items[count] = item;
count++;
}
}
this.items = items;
this.count = count;
}
internal TElement[] ToArray()
{
if (count == 0) return new TElement[0];
if (items.Length == count) return items;
TElement[] result = new TElement[count];
Array.Copy(items, 0, result, 0, count);
return result;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Core;
using ASC.Core.Users;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
using ASC.Web.Core;
using ASC.Web.Core.Utility.Settings;
using ASC.Web.Projects;
using ASC.Web.Projects.Classes;
using Autofac;
namespace ASC.Projects.Engine
{
public class ProjectSecurityCommon
{
public bool Can(Guid userId)
{
return !IsVisitor(userId) && IsProjectsEnabled(userId);
}
public bool Can()
{
return Can(CurrentUserId);
}
public Guid CurrentUserId { get; private set; }
public bool CurrentUserAdministrator { get; private set; }
private bool CurrentUserIsVisitor { get; set; }
internal bool CurrentUserIsOutsider { get; set; }
public bool CurrentUserIsProjectsEnabled { get; private set; }
public bool CurrentUserIsCRMEnabled { get; private set; }
public bool IsPrivateDisabled { get; private set; }
public IDaoFactory DaoFactory { get; set; }
public EngineFactory EngineFactory { get; set; }
public ProjectSecurityCommon()
{
CurrentUserId = SecurityContext.CurrentAccount.ID;
CurrentUserAdministrator = CoreContext.UserManager.IsUserInGroup(CurrentUserId, Constants.GroupAdmin.ID) ||
WebItemSecurity.IsProductAdministrator(WebItemManager.ProjectsProductID, CurrentUserId);
CurrentUserIsVisitor = CoreContext.UserManager.GetUsers(CurrentUserId).IsVisitor();
CurrentUserIsOutsider = IsOutsider(CurrentUserId);
IsPrivateDisabled = TenantAccessSettings.Load().Anyone;
CurrentUserIsProjectsEnabled = IsModuleEnabled(WebItemManager.ProjectsProductID, CurrentUserId);
CurrentUserIsCRMEnabled = IsModuleEnabled(WebItemManager.CRMProductID, CurrentUserId);
}
public bool IsAdministrator(Guid userId)
{
if (userId == CurrentUserId) return CurrentUserAdministrator;
return CoreContext.UserManager.IsUserInGroup(userId, Constants.GroupAdmin.ID) ||
WebItemSecurity.IsProductAdministrator(WebItemManager.ProjectsProductID, userId);
}
public bool IsProjectsEnabled()
{
return IsProjectsEnabled(CurrentUserId);
}
public bool IsProjectsEnabled(Guid userID)
{
if (userID == CurrentUserId) return CurrentUserIsProjectsEnabled;
return IsModuleEnabled(WebItemManager.ProjectsProductID, userID);
}
public bool IsCrmEnabled()
{
return IsCrmEnabled(CurrentUserId);
}
public bool IsCrmEnabled(Guid userID)
{
if (userID == CurrentUserId) return CurrentUserIsCRMEnabled;
return IsModuleEnabled(WebItemManager.CRMProductID, userID);
}
private bool IsModuleEnabled(Guid module, Guid userId)
{
var projects = WebItemManager.Instance[module];
if (projects != null)
{
return !projects.IsDisabled(userId);
}
return false;
}
public bool IsVisitor(Guid userId)
{
if (userId == CurrentUserId) return CurrentUserIsVisitor;
return CoreContext.UserManager.GetUsers(userId).IsVisitor();
}
public bool IsOutsider(Guid userId)
{
return CoreContext.UserManager.GetUsers(userId).IsOutsider();
}
public bool IsProjectManager(Project project)
{
return IsProjectManager(project, CurrentUserId);
}
public bool IsProjectManager(Project project, Guid userId)
{
return (IsAdministrator(userId) || (project != null && project.Responsible == userId)) &&
!CurrentUserIsVisitor;
}
public bool IsProjectCreator(Project project)
{
return IsProjectCreator(project, CurrentUserId);
}
public bool IsProjectCreator(Project project, Guid userId)
{
return (project != null && project.CreateBy == userId);
}
public bool IsInTeam(Project project)
{
return IsInTeam(project, CurrentUserId);
}
public bool IsInTeam(Project project, Guid userId, bool includeAdmin = true)
{
var isAdmin = includeAdmin && IsAdministrator(userId);
return isAdmin || (project != null && DaoFactory.ProjectDao.IsInTeam(project.ID, userId));
}
public bool IsFollow(Project project, Guid userID)
{
var isAdmin = IsAdministrator(userID);
var isPrivate = project != null && (!project.Private || isAdmin);
return isPrivate && DaoFactory.ProjectDao.IsFollow(project.ID, userID);
}
public bool GetTeamSecurity(Project project, ProjectTeamSecurity security)
{
return GetTeamSecurity(project, CurrentUserId, security);
}
public bool GetTeamSecurity(Project project, Guid userId, ProjectTeamSecurity security)
{
if (IsProjectManager(project, userId) || project == null || !project.Private) return true;
var dao = DaoFactory.ProjectDao;
var s = dao.GetTeamSecurity(project.ID, userId);
return (s & security) != security && dao.IsInTeam(project.ID, userId);
}
public bool GetTeamSecurityForParticipants(Project project, Guid userId, ProjectTeamSecurity security)
{
if (IsProjectManager(project, userId) || !project.Private) return true;
var s = DaoFactory.ProjectDao.GetTeamSecurity(project.ID, userId);
return (s & security) != security;
}
}
public abstract class ProjectSecurityTemplate<T> where T : DomainObject<int>
{
public ProjectSecurityCommon Common { get; set; }
public virtual bool CanCreateEntities(Project project)
{
return project != null && project.Status == ProjectStatus.Open && Common.Can();
}
public virtual bool CanReadEntities(Project project, Guid userId)
{
return Common.IsProjectsEnabled(userId);
}
public bool CanReadEntities(Project project)
{
return CanReadEntities(project, Common.CurrentUserId);
}
public virtual bool CanReadEntity(T entity, Guid userId)
{
return entity != null && Common.Can(userId);
}
public bool CanReadEntity(T entity)
{
return CanReadEntity(entity, Common.CurrentUserId);
}
public virtual bool CanUpdateEntity(T entity)
{
return Common.Can() && entity != null;
}
public virtual bool CanDeleteEntity(T entity)
{
return Common.Can() && entity != null;
}
public virtual bool CanCreateComment(T entity)
{
return false;
}
public virtual bool CanEditFiles(T entity)
{
return false;
}
public virtual bool CanEditComment(T entity, Comment comment)
{
return false;
}
public virtual bool CanGoToFeed(T entity, Guid userId)
{
return false;
}
}
public sealed class ProjectSecurityProject : ProjectSecurityTemplate<Project>
{
public override bool CanCreateEntities(Project project)
{
return Common.Can() && (Common.CurrentUserAdministrator || ProjectsCommonSettings.Load().EverebodyCanCreate);
}
public override bool CanReadEntity(Project project, Guid userId)
{
if (!Common.IsProjectsEnabled(userId)) return false;
if (project == null) return false;
if (project.Private && Common.IsPrivateDisabled) return false;
return !project.Private || Common.IsProjectCreator(project, userId) || Common.IsInTeam(project, userId);
}
public override bool CanUpdateEntity(Project project)
{
return base.CanUpdateEntity(project) && Common.IsProjectManager(project) || Common.IsProjectCreator(project);
}
public override bool CanDeleteEntity(Project project)
{
return base.CanDeleteEntity(project) && Common.CurrentUserAdministrator || Common.IsProjectCreator(project);
}
public override bool CanGoToFeed(Project project, Guid userId)
{
if (project == null || !Common.IsProjectsEnabled(userId))
{
return false;
}
return WebItemSecurity.IsProductAdministrator(EngineFactory.ProductId, userId)
|| Common.IsInTeam(project, userId, false)
|| Common.IsFollow(project, userId)
|| Common.IsProjectCreator(project, userId);
}
public bool CanEditTeam(Project project)
{
return Common.Can() && (Common.IsProjectManager(project) || Common.IsProjectCreator(project));
}
public bool CanReadFiles(Project project)
{
return CanReadFiles(project, SecurityContext.CurrentAccount.ID);
}
public bool CanReadFiles(Project project, Guid userId)
{
return Common.IsProjectsEnabled(userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Files);
}
public override bool CanEditComment(Project project, Comment comment)
{
if (!Common.IsProjectsEnabled()) return false;
if (project == null || comment == null) return false;
return comment.CreateBy == Common.CurrentUserId || Common.IsProjectManager(project);
}
public bool CanReadContacts(Project project)
{
return Common.IsCrmEnabled() && Common.IsProjectsEnabled() &&
Common.GetTeamSecurity(project, ProjectTeamSecurity.Contacts);
}
public bool CanLinkContact(Project project)
{
return Common.IsProjectsEnabled() && CanUpdateEntity(project);
}
}
public sealed class ProjectSecurityTask : ProjectSecurityTemplate<Task>
{
public ProjectSecurityProject ProjectSecurityProject { get; set; }
public ProjectSecurityMilestone ProjectSecurityMilestone { get; set; }
public override bool CanCreateEntities(Project project)
{
if (!base.CanCreateEntities(project)) return false;
if (Common.IsProjectManager(project)) return true;
return Common.IsInTeam(project) && CanReadEntities(project);
}
public override bool CanReadEntities(Project project, Guid userId)
{
return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Tasks);
}
public override bool CanReadEntity(Task task, Guid userId)
{
if (task == null || !ProjectSecurityProject.CanReadEntity(task.Project, userId)) return false;
if (task.Responsibles.Contains(userId)) return true;
if (!CanReadEntities(task.Project, userId)) return false;
if (task.Milestone != 0 && !ProjectSecurityMilestone.CanReadEntities(task.Project, userId))
{
var m = Common.DaoFactory.MilestoneDao.GetById(task.Milestone);
if (!ProjectSecurityMilestone.CanReadEntity(m, userId)) return false;
}
return true;
}
public override bool CanUpdateEntity(Task task)
{
if (!base.CanUpdateEntity(task)) return false;
if (task.Project.Status == ProjectStatus.Closed) return false;
if (Common.IsProjectManager(task.Project)) return true;
return Common.IsInTeam(task.Project) &&
(task.CreateBy == Common.CurrentUserId ||
!task.Responsibles.Any() ||
task.Responsibles.Contains(Common.CurrentUserId));
}
public override bool CanDeleteEntity(Task task)
{
if (!base.CanDeleteEntity(task)) return false;
if (Common.IsProjectManager(task.Project)) return true;
return Common.IsInTeam(task.Project) && task.CreateBy == Common.CurrentUserId;
}
public override bool CanCreateComment(Task entity)
{
return CanReadEntity(entity) &&
Common.IsProjectsEnabled() &&
SecurityContext.IsAuthenticated &&
!Common.CurrentUserIsOutsider;
}
public bool CanEdit(Task task, Subtask subtask)
{
if (subtask == null || !Common.Can()) return false;
if (CanUpdateEntity(task)) return true;
return Common.IsInTeam(task.Project) &&
(subtask.CreateBy == Common.CurrentUserId ||
subtask.Responsible == Common.CurrentUserId);
}
public override bool CanGoToFeed(Task task, Guid userId)
{
if (task == null || !Common.IsProjectsEnabled(userId)) return false;
if (task.CreateBy == userId) return true;
if (!Common.IsInTeam(task.Project, userId, false) && !Common.IsFollow(task.Project, userId)) return false;
if (task.Responsibles.Contains(userId)) return true;
if (task.Milestone != 0 && !ProjectSecurityMilestone.CanReadEntities(task.Project, userId))
{
var milestone = Common.DaoFactory.MilestoneDao.GetById(task.Milestone);
if (milestone.Responsible == userId)
{
return true;
}
}
return Common.GetTeamSecurityForParticipants(task.Project, userId, ProjectTeamSecurity.Tasks);
}
public override bool CanEditFiles(Task entity)
{
if (!Common.IsProjectsEnabled()) return false;
if (entity.Project.Status == ProjectStatus.Closed) return false;
if (Common.IsProjectManager(entity.Project)) return true;
return CanUpdateEntity(entity);
}
public override bool CanEditComment(Task entity, Comment comment)
{
if (entity == null) return false;
return ProjectSecurityProject.CanEditComment(entity.Project, comment);
}
public bool CanCreateSubtask(Task task)
{
if (task == null || !Common.Can()) return false;
if (Common.IsProjectManager(task.Project)) return true;
return Common.IsInTeam(task.Project) &&
((task.CreateBy == Common.CurrentUserId) ||
!task.Responsibles.Any() ||
task.Responsibles.Contains(Common.CurrentUserId));
}
public bool CanCreateTimeSpend(Task task)
{
if (task == null || !Common.Can()) return false;
if (task.Project.Status != ProjectStatus.Open) return false;
if (Common.IsInTeam(task.Project)) return true;
return task.Responsibles.Contains(Common.CurrentUserId) ||
task.SubTasks.Select(r => r.Responsible).Contains(Common.CurrentUserId);
}
}
public sealed class ProjectSecurityMilestone : ProjectSecurityTemplate<Milestone>
{
public ProjectSecurityProject ProjectSecurityProject { get; set; }
public override bool CanCreateEntities(Project project)
{
return base.CanCreateEntities(project) && Common.IsProjectManager(project);
}
public override bool CanReadEntities(Project project, Guid userId)
{
return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Milestone);
}
public override bool CanReadEntity(Milestone entity, Guid userId)
{
if (entity == null || !ProjectSecurityProject.CanReadEntity(entity.Project, userId)) return false;
if (entity.Responsible == userId) return true;
return CanReadEntities(entity.Project, userId);
}
public override bool CanUpdateEntity(Milestone milestone)
{
if (!base.CanUpdateEntity(milestone)) return false;
if (milestone.Project.Status == ProjectStatus.Closed) return false;
if (Common.IsProjectManager(milestone.Project)) return true;
if (!CanReadEntity(milestone)) return false;
return Common.IsInTeam(milestone.Project) &&
(milestone.CreateBy == Common.CurrentUserId ||
milestone.Responsible == Common.CurrentUserId);
}
public override bool CanDeleteEntity(Milestone milestone)
{
if (!base.CanDeleteEntity(milestone)) return false;
if (Common.IsProjectManager(milestone.Project)) return true;
return Common.IsInTeam(milestone.Project) && milestone.CreateBy == Common.CurrentUserId;
}
public override bool CanGoToFeed(Milestone milestone, Guid userId)
{
if (milestone == null || !Common.IsProjectsEnabled(userId)) return false;
if (!Common.IsInTeam(milestone.Project, userId, false) && !Common.IsFollow(milestone.Project, userId)) return false;
return milestone.Responsible == userId || Common.GetTeamSecurityForParticipants(milestone.Project, userId, ProjectTeamSecurity.Milestone);
}
}
public sealed class ProjectSecurityMessage : ProjectSecurityTemplate<Message>
{
public ProjectSecurityProject ProjectSecurityProject { get; set; }
public override bool CanCreateEntities(Project project)
{
if (!base.CanCreateEntities(project)) return false;
if (Common.IsProjectManager(project)) return true;
return Common.IsInTeam(project) && CanReadEntities(project);
}
public override bool CanReadEntities(Project project, Guid userId)
{
return base.CanReadEntities(project, userId) && Common.GetTeamSecurity(project, userId, ProjectTeamSecurity.Messages);
}
public override bool CanReadEntity(Message entity, Guid userId)
{
if (entity == null || !ProjectSecurityProject.CanReadEntity(entity.Project, userId)) return false;
return CanReadEntities(entity.Project, userId);
}
public override bool CanUpdateEntity(Message message)
{
if (!base.CanUpdateEntity(message)) return false;
if (Common.IsProjectManager(message.Project)) return true;
if (!CanReadEntity(message)) return false;
return Common.IsInTeam(message.Project) && message.CreateBy == Common.CurrentUserId;
}
public override bool CanDeleteEntity(Message message)
{
return CanUpdateEntity(message);
}
public override bool CanCreateComment(Message message)
{
return CanReadEntity(message) &&
(message == null || message.Status == MessageStatus.Open) &&
Common.IsProjectsEnabled() &&
SecurityContext.IsAuthenticated &&
!Common.CurrentUserIsOutsider;
}
public override bool CanGoToFeed(Message message, Guid userId)
{
if (message == null || !Common.IsProjectsEnabled(userId)) return false;
if (message.CreateBy == userId) return true;
if (!Common.IsInTeam(message.Project, userId, false) && !Common.IsFollow(message.Project, userId)) return false;
var isSubscriber = Common.EngineFactory.MessageEngine.GetSubscribers(message).Any(r => new Guid(r.ID).Equals(userId));
return isSubscriber && Common.GetTeamSecurityForParticipants(message.Project, userId, ProjectTeamSecurity.Messages);
}
public override bool CanEditComment(Message message, Comment comment)
{
return message.Status == MessageStatus.Open && ProjectSecurityProject.CanEditComment(message.Project, comment);
}
public override bool CanEditFiles(Message entity)
{
if (!Common.IsProjectsEnabled()) return false;
if (entity.Status == MessageStatus.Archived || entity.Project.Status == ProjectStatus.Closed) return false;
if (Common.IsProjectManager(entity.Project)) return true;
return Common.IsInTeam(entity.Project);
}
}
public sealed class ProjectSecurityTimeTracking : ProjectSecurityTemplate<TimeSpend>
{
public ProjectSecurityTask ProjectSecurityTask { get; set; }
public override bool CanCreateEntities(Project project)
{
if (!base.CanCreateEntities(project)) return false;
if (project.Status == ProjectStatus.Closed) return false;
return Common.IsInTeam(project);
}
public override bool CanReadEntities(Project project, Guid userId)
{
return ProjectSecurityTask.CanReadEntities(project, userId);
}
public override bool CanReadEntity(TimeSpend entity, Guid userId)
{
return ProjectSecurityTask.CanReadEntity(entity.Task, userId);
}
public override bool CanUpdateEntity(TimeSpend timeSpend)
{
if (!base.CanUpdateEntity(timeSpend)) return false;
if (Common.IsProjectManager(timeSpend.Task.Project)) return true;
if (timeSpend.PaymentStatus == PaymentStatus.Billed) return false;
return timeSpend.Person == Common.CurrentUserId || timeSpend.CreateBy == Common.CurrentUserId;
}
public override bool CanDeleteEntity(TimeSpend timeSpend)
{
if (!base.CanDeleteEntity(timeSpend)) return false;
if (Common.IsProjectManager(timeSpend.Task.Project)) return true;
if (timeSpend.PaymentStatus == PaymentStatus.Billed) return false;
return Common.IsInTeam(timeSpend.Task.Project) &&
(timeSpend.CreateBy == Common.CurrentUserId || timeSpend.Person == Common.CurrentUserId);
}
public bool CanEditPaymentStatus(TimeSpend timeSpend)
{
return timeSpend != null && Common.Can() && Common.IsProjectManager(timeSpend.Task.Project);
}
}
public class ProjectSecurity
{
public ILifetimeScope Scope { get; set; }
public bool CanCreate<T>(Project project) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanCreateEntities(project);
}
public bool CanEdit<T>(T entity) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanUpdateEntity(entity);
}
public bool CanRead<T>(T entity) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntity(entity);
}
public bool CanRead<T>(T entity, Guid userId) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntity(entity, userId);
}
public bool CanRead<T>(Project project) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanReadEntities(project);
}
public bool CanDelete<T>(T entity) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanDeleteEntity(entity);
}
public bool CanEditComment(ProjectEntity entity, Comment comment)
{
var task = entity as Task;
if (task != null)
{
return Scope.Resolve<ProjectSecurityTask>().CanEditComment(task, comment);
}
var message = entity as Message;
return Scope.Resolve<ProjectSecurityMessage>().CanEditComment(message, comment);
}
public bool CanEditComment(Project entity, Comment comment)
{
return Scope.Resolve<ProjectSecurityProject>().CanEditComment(entity, comment);
}
public bool CanCreateComment(ProjectEntity entity)
{
var task = entity as Task;
if (task != null)
{
return Scope.Resolve<ProjectSecurityTask>().CanCreateComment(task);
}
var message = entity as Message;
return Scope.Resolve<ProjectSecurityMessage>().CanCreateComment(message);
}
public bool CanCreateComment(Project project)
{
return Scope.Resolve<ProjectSecurityProject>().CanCreateComment(project);
}
public bool CanEdit(Task task, Subtask subtask)
{
return Scope.Resolve<ProjectSecurityTask>().CanEdit(task, subtask);
}
public bool CanReadFiles(Project project, Guid userId)
{
return Scope.Resolve<ProjectSecurityProject>().CanReadFiles(project, userId);
}
public bool CanReadFiles(Project project)
{
return Scope.Resolve<ProjectSecurityProject>().CanReadFiles(project);
}
public bool CanEditFiles<T>(T entity) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanEditFiles(entity);
}
public bool CanEditTeam(Project project)
{
return Scope.Resolve<ProjectSecurityProject>().CanEditTeam(project);
}
public bool CanLinkContact(Project project)
{
return Scope.Resolve<ProjectSecurityProject>().CanLinkContact(project);
}
public bool CanReadContacts(Project project)
{
return Scope.Resolve<ProjectSecurityProject>().CanReadContacts(project);
}
public bool CanEditPaymentStatus(TimeSpend timeSpend)
{
return Scope.Resolve<ProjectSecurityTimeTracking>().CanEditPaymentStatus(timeSpend);
}
public bool CanCreateSubtask(Task task)
{
return Scope.Resolve<ProjectSecurityTask>().CanCreateSubtask(task);
}
public bool CanCreateTimeSpend(Task task)
{
return Scope.Resolve<ProjectSecurityTask>().CanCreateTimeSpend(task);
}
public bool CanEditTemplate(Template template)
{
return CurrentUserAdministrator || template.CreateBy.Equals(SecurityContext.CurrentAccount.ID);
}
public bool CanGoToFeed<T>(T entity, Guid userId) where T : DomainObject<int>
{
return Scope.Resolve<ProjectSecurityTemplate<T>>().CanGoToFeed(entity, userId);
}
public bool CanGoToFeed(ParticipantFull participant, Guid userId)
{
var common = Scope.Resolve<ProjectSecurityCommon>();
if (participant == null || !IsProjectsEnabled(userId)) return false;
return common.IsInTeam(participant.Project, userId, false) || common.IsFollow(participant.Project, userId);
}
public bool IsInTeam(Project project, Guid userId, bool includeAdmin = true)
{
return Scope.Resolve<ProjectSecurityCommon>().IsInTeam(project, userId, includeAdmin);
}
public void DemandCreate<T>(Project project) where T : DomainObject<int>
{
if (!CanCreate<T>(project)) throw CreateSecurityException();
}
public void DemandEdit<T>(T entity) where T : DomainObject<int>
{
if (!CanEdit(entity)) throw CreateSecurityException();
}
public void DemandEdit(Task task, Subtask subtask)
{
if (!CanEdit(task, subtask)) throw CreateSecurityException();
}
public void DemandDelete<T>(T entity) where T : DomainObject<int>
{
if (!CanDelete(entity)) throw CreateSecurityException();
}
public void DemandEditComment(ProjectEntity entity, Comment comment)
{
if (!CanEditComment(entity, comment)) throw CreateSecurityException();
}
public void DemandEditComment(Project entity, Comment comment)
{
if (!CanEditComment(entity, comment)) throw CreateSecurityException();
}
public void DemandCreateComment(Project project)
{
if (!CanCreateComment(project)) throw CreateSecurityException();
}
public void DemandCreateComment(ProjectEntity entity)
{
if (!CanCreateComment(entity)) throw CreateSecurityException();
}
public void DemandLinkContact(Project project)
{
if (!Scope.Resolve<ProjectSecurityProject>().CanLinkContact(project))
{
throw CreateSecurityException();
}
}
public void DemandEditTeam(Project project)
{
if (!CanEditTeam(project)) throw CreateSecurityException();
}
public void DemandReadFiles(Project project)
{
if (!CanReadFiles(project)) throw CreateSecurityException();
}
public static void DemandAuthentication()
{
if (!SecurityContext.CurrentAccount.IsAuthenticated)
{
throw CreateSecurityException();
}
}
public bool CurrentUserAdministrator
{
get
{
return Scope.Resolve<ProjectSecurityCommon>().CurrentUserAdministrator;
}
}
public bool IsPrivateDisabled
{
get
{
return Scope.Resolve<ProjectSecurityCommon>().IsPrivateDisabled;
}
}
public bool IsVisitor()
{
return IsVisitor(SecurityContext.CurrentAccount.ID);
}
public bool IsVisitor(Guid userId)
{
return Scope.Resolve<ProjectSecurityCommon>().IsVisitor(userId);
}
public bool IsAdministrator()
{
return IsAdministrator(SecurityContext.CurrentAccount.ID);
}
public bool IsAdministrator(Guid userId)
{
return Scope.Resolve<ProjectSecurityCommon>().IsAdministrator(userId);
}
public bool IsProjectsEnabled()
{
return IsProjectsEnabled(SecurityContext.CurrentAccount.ID);
}
public bool IsProjectsEnabled(Guid userId)
{
return Scope.Resolve<ProjectSecurityCommon>().IsProjectsEnabled(userId);
}
public void GetProjectSecurityInfo(Project project)
{
var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
var milestoneSecurity = Scope.Resolve<ProjectSecurityMilestone>();
var messageSecurity = Scope.Resolve<ProjectSecurityMessage>();
var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
var timeSpendSecurity = Scope.Resolve<ProjectSecurityTimeTracking>();
project.Security = GetProjectSecurityInfoWithSecurity(project, projectSecurity, milestoneSecurity, messageSecurity, taskSecurity, timeSpendSecurity);
}
public void GetProjectSecurityInfo(IEnumerable<Project> projects)
{
var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
var milestoneSecurity = Scope.Resolve<ProjectSecurityMilestone>();
var messageSecurity = Scope.Resolve<ProjectSecurityMessage>();
var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
var timeSpendSecurity = Scope.Resolve<ProjectSecurityTimeTracking>();
foreach (var project in projects)
{
project.Security = GetProjectSecurityInfoWithSecurity(project, projectSecurity, milestoneSecurity, messageSecurity, taskSecurity, timeSpendSecurity);
}
}
public void GetTaskSecurityInfo(Task task)
{
var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
task.Security = GetTaskSecurityInfoWithSecurity(task, projectSecurity, taskSecurity);
}
public void GetTaskSecurityInfo(IEnumerable<Task> tasks)
{
var projectSecurity = Scope.Resolve<ProjectSecurityProject>();
var taskSecurity = Scope.Resolve<ProjectSecurityTask>();
foreach (var task in tasks)
{
task.Security = GetTaskSecurityInfoWithSecurity(task, projectSecurity, taskSecurity);
}
}
private ProjectSecurityInfo GetProjectSecurityInfoWithSecurity(Project project, ProjectSecurityProject projectSecurity, ProjectSecurityMilestone milestoneSecurity, ProjectSecurityMessage messageSecurity, ProjectSecurityTask taskSecurity, ProjectSecurityTimeTracking timeSpendSecurity)
{
return new ProjectSecurityInfo
{
CanCreateMilestone = milestoneSecurity.CanCreateEntities(project),
CanCreateMessage = messageSecurity.CanCreateEntities(project),
CanCreateTask = taskSecurity.CanCreateEntities(project),
CanCreateTimeSpend = timeSpendSecurity.CanCreateEntities(project),
CanEditTeam = projectSecurity.CanEditTeam(project),
CanReadFiles = projectSecurity.CanReadFiles(project),
CanReadMilestones = milestoneSecurity.CanReadEntities(project),
CanReadMessages = messageSecurity.CanReadEntities(project),
CanReadTasks = taskSecurity.CanReadEntities(project),
IsInTeam = milestoneSecurity.Common.IsInTeam(project, SecurityContext.CurrentAccount.ID, false),
CanLinkContact = projectSecurity.CanLinkContact(project),
CanReadContacts = projectSecurity.CanReadContacts(project),
CanEdit = projectSecurity.CanUpdateEntity(project),
CanDelete = projectSecurity.CanDeleteEntity(project),
};
}
private TaskSecurityInfo GetTaskSecurityInfoWithSecurity(Task task, ProjectSecurityProject projectSecurity, ProjectSecurityTask taskSecurity)
{
return new TaskSecurityInfo
{
CanEdit = taskSecurity.CanUpdateEntity(task),
CanCreateSubtask = taskSecurity.CanCreateSubtask(task),
CanCreateTimeSpend = taskSecurity.CanCreateTimeSpend(task),
CanDelete = taskSecurity.CanDeleteEntity(task),
CanReadFiles = projectSecurity.CanReadFiles(task.Project)
};
}
public static Exception CreateSecurityException()
{
throw new System.Security.SecurityException("Access denied.");
}
public static Exception CreateGuestSecurityException()
{
throw new System.Security.SecurityException("A guest cannot be appointed as responsible.");
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.Eventing.Reader;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Diagnostics.Eventing
{
internal static class UnsafeNativeMethods
{
private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll";
private const string EventProviderDllName = "api-ms-win-eventing-provider-l1-1-0.dll";
private const string WEVTAPI = "wevtapi.dll";
private static readonly IntPtr s_NULL = IntPtr.Zero;
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
// ErrorCode & format
// for win32 error message formatting
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
[DllImport(FormatMessageDllName, CharSet = CharSet.Unicode, BestFitMapping = false)]
[SecurityCritical]
internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
int dwMessageId, int dwLanguageId, StringBuilder lpBuffer,
int nSize, IntPtr va_list_arguments);
// Gets an error message for a Win32 error code.
[SecurityCritical]
internal static string GetMessage(int errorCode)
{
StringBuilder sb = new(512);
int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
UnsafeNativeMethods.s_NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.s_NULL);
if (result != 0)
{
// result is the # of characters copied to the StringBuilder on NT,
// but on Win9x, it appears to be the number of MBCS buffer.
// Just give up and return the String as-is...
string s = sb.ToString();
return s;
}
else
{
return "UnknownError_Num " + errorCode;
}
}
// ETW Methods
// Callback
[SecurityCritical]
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] void* filterData,
[In] void* callbackContext
);
// Registration APIs
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventRegister(
[In] in Guid providerId,
[In] EtwEnableCallback enableCallback,
[In] void* callbackContext,
[In][Out] ref long registrationHandle
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventUnregister([In] long registrationHandle);
// Control (Is Enabled) APIs
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventEnabled([In] long registrationHandle, [In] in System.Diagnostics.Eventing.EventDescriptor eventDescriptor);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern int EventProviderEnabled([In] long registrationHandle, [In] byte level, [In] long keywords);
// Writing (Publishing/Logging) APIs
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] in EventDescriptor eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
// Writing (Publishing/Logging) APIs
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWrite(
[In] long registrationHandle,
[In] EventDescriptor* eventDescriptor,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteTransfer(
[In] long registrationHandle,
[In] in EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] uint userDataCount,
[In] void* userData
);
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keywords,
[In] char* message
);
// ActivityId Control APIs
[DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
[SecurityCritical]
internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId);
// EventLog
[Flags]
internal enum EvtQueryFlags
{
EvtQueryChannelPath = 0x1,
EvtQueryFilePath = 0x2,
EvtQueryForwardDirection = 0x100,
EvtQueryReverseDirection = 0x200,
EvtQueryTolerateQueryErrors = 0x1000
}
/// <summary>
/// Evt Variant types.
/// </summary>
internal enum EvtVariantType
{
EvtVarTypeNull = 0,
EvtVarTypeString = 1,
EvtVarTypeAnsiString = 2,
EvtVarTypeSByte = 3,
EvtVarTypeByte = 4,
EvtVarTypeInt16 = 5,
EvtVarTypeUInt16 = 6,
EvtVarTypeInt32 = 7,
EvtVarTypeUInt32 = 8,
EvtVarTypeInt64 = 9,
EvtVarTypeUInt64 = 10,
EvtVarTypeSingle = 11,
EvtVarTypeDouble = 12,
EvtVarTypeBoolean = 13,
EvtVarTypeBinary = 14,
EvtVarTypeGuid = 15,
EvtVarTypeSizeT = 16,
EvtVarTypeFileTime = 17,
EvtVarTypeSysTime = 18,
EvtVarTypeSid = 19,
EvtVarTypeHexInt32 = 20,
EvtVarTypeHexInt64 = 21,
// these types used internally
EvtVarTypeEvtHandle = 32,
EvtVarTypeEvtXml = 35,
// Array = 128
EvtVarTypeStringArray = 129,
EvtVarTypeUInt32Array = 136
}
internal enum EvtMasks
{
EVT_VARIANT_TYPE_MASK = 0x7f,
EVT_VARIANT_TYPE_ARRAY = 128
}
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
public short Month;
[MarshalAs(UnmanagedType.U2)]
public short DayOfWeek;
[MarshalAs(UnmanagedType.U2)]
public short Day;
[MarshalAs(UnmanagedType.U2)]
public short Hour;
[MarshalAs(UnmanagedType.U2)]
public short Minute;
[MarshalAs(UnmanagedType.U2)]
public short Second;
[MarshalAs(UnmanagedType.U2)]
public short Milliseconds;
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
[SecurityCritical]
internal struct EvtVariant
{
[FieldOffset(0)]
public uint UInteger;
[FieldOffset(0)]
public int Integer;
[FieldOffset(0)]
public byte UInt8;
[FieldOffset(0)]
public short Short;
[FieldOffset(0)]
public ushort UShort;
[FieldOffset(0)]
public uint Bool;
[FieldOffset(0)]
public byte ByteVal;
[FieldOffset(0)]
public byte SByte;
[FieldOffset(0)]
public ulong ULong;
[FieldOffset(0)]
public long Long;
[FieldOffset(0)]
public float Single;
[FieldOffset(0)]
public double Double;
[FieldOffset(0)]
public IntPtr StringVal;
[FieldOffset(0)]
public IntPtr AnsiString;
[FieldOffset(0)]
public IntPtr SidVal;
[FieldOffset(0)]
public IntPtr Binary;
[FieldOffset(0)]
public IntPtr Reference;
[FieldOffset(0)]
public IntPtr Handle;
[FieldOffset(0)]
public IntPtr GuidReference;
[FieldOffset(0)]
public ulong FileTime;
[FieldOffset(0)]
public IntPtr SystemTime;
[FieldOffset(0)]
public IntPtr SizeT;
[FieldOffset(8)]
public uint Count; // number of elements (not length) in bytes.
[FieldOffset(12)]
public uint Type;
}
internal enum EvtEventPropertyId
{
EvtEventQueryIDs = 0,
EvtEventPath = 1
}
/// <summary>
/// The query flags to get information about query.
/// </summary>
internal enum EvtQueryPropertyId
{
EvtQueryNames = 0, // String; // Variant will be array of EvtVarTypeString
EvtQueryStatuses = 1 // UInt32; // Variant will be Array of EvtVarTypeUInt32
}
/// <summary>
/// Publisher Metadata properties.
/// </summary>
internal enum EvtPublisherMetadataPropertyId
{
EvtPublisherMetadataPublisherGuid = 0, // EvtVarTypeGuid
EvtPublisherMetadataResourceFilePath = 1, // EvtVarTypeString
EvtPublisherMetadataParameterFilePath = 2, // EvtVarTypeString
EvtPublisherMetadataMessageFilePath = 3, // EvtVarTypeString
EvtPublisherMetadataHelpLink = 4, // EvtVarTypeString
EvtPublisherMetadataPublisherMessageID = 5, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferences = 6, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataChannelReferencePath = 7, // EvtVarTypeString
EvtPublisherMetadataChannelReferenceIndex = 8, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceID = 9, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceFlags = 10, // EvtVarTypeUInt32
EvtPublisherMetadataChannelReferenceMessageID = 11, // EvtVarTypeUInt32
EvtPublisherMetadataLevels = 12, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataLevelName = 13, // EvtVarTypeString
EvtPublisherMetadataLevelValue = 14, // EvtVarTypeUInt32
EvtPublisherMetadataLevelMessageID = 15, // EvtVarTypeUInt32
EvtPublisherMetadataTasks = 16, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataTaskName = 17, // EvtVarTypeString
EvtPublisherMetadataTaskEventGuid = 18, // EvtVarTypeGuid
EvtPublisherMetadataTaskValue = 19, // EvtVarTypeUInt32
EvtPublisherMetadataTaskMessageID = 20, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodes = 21, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataOpcodeName = 22, // EvtVarTypeString
EvtPublisherMetadataOpcodeValue = 23, // EvtVarTypeUInt32
EvtPublisherMetadataOpcodeMessageID = 24, // EvtVarTypeUInt32
EvtPublisherMetadataKeywords = 25, // EvtVarTypeEvtHandle, ObjectArray
EvtPublisherMetadataKeywordName = 26, // EvtVarTypeString
EvtPublisherMetadataKeywordValue = 27, // EvtVarTypeUInt64
EvtPublisherMetadataKeywordMessageID = 28 // EvtVarTypeUInt32
// EvtPublisherMetadataPropertyIdEND
}
internal enum EvtChannelReferenceFlags
{
EvtChannelReferenceImported = 1
}
internal enum EvtEventMetadataPropertyId
{
EventMetadataEventID, // EvtVarTypeUInt32
EventMetadataEventVersion, // EvtVarTypeUInt32
EventMetadataEventChannel, // EvtVarTypeUInt32
EventMetadataEventLevel, // EvtVarTypeUInt32
EventMetadataEventOpcode, // EvtVarTypeUInt32
EventMetadataEventTask, // EvtVarTypeUInt32
EventMetadataEventKeyword, // EvtVarTypeUInt64
EventMetadataEventMessageID, // EvtVarTypeUInt32
EventMetadataEventTemplate // EvtVarTypeString
// EvtEventMetadataPropertyIdEND
}
// CHANNEL CONFIGURATION
internal enum EvtChannelConfigPropertyId
{
EvtChannelConfigEnabled = 0, // EvtVarTypeBoolean
EvtChannelConfigIsolation, // EvtVarTypeUInt32, EVT_CHANNEL_ISOLATION_TYPE
EvtChannelConfigType, // EvtVarTypeUInt32, EVT_CHANNEL_TYPE
EvtChannelConfigOwningPublisher, // EvtVarTypeString
EvtChannelConfigClassicEventlog, // EvtVarTypeBoolean
EvtChannelConfigAccess, // EvtVarTypeString
EvtChannelLoggingConfigRetention, // EvtVarTypeBoolean
EvtChannelLoggingConfigAutoBackup, // EvtVarTypeBoolean
EvtChannelLoggingConfigMaxSize, // EvtVarTypeUInt64
EvtChannelLoggingConfigLogFilePath, // EvtVarTypeString
EvtChannelPublishingConfigLevel, // EvtVarTypeUInt32
EvtChannelPublishingConfigKeywords, // EvtVarTypeUInt64
EvtChannelPublishingConfigControlGuid, // EvtVarTypeGuid
EvtChannelPublishingConfigBufferSize, // EvtVarTypeUInt32
EvtChannelPublishingConfigMinBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigMaxBuffers, // EvtVarTypeUInt32
EvtChannelPublishingConfigLatency, // EvtVarTypeUInt32
EvtChannelPublishingConfigClockType, // EvtVarTypeUInt32, EVT_CHANNEL_CLOCK_TYPE
EvtChannelPublishingConfigSidType, // EvtVarTypeUInt32, EVT_CHANNEL_SID_TYPE
EvtChannelPublisherList, // EvtVarTypeString | EVT_VARIANT_TYPE_ARRAY
EvtChannelConfigPropertyIdEND
}
// LOG INFORMATION
internal enum EvtLogPropertyId
{
EvtLogCreationTime = 0, // EvtVarTypeFileTime
EvtLogLastAccessTime, // EvtVarTypeFileTime
EvtLogLastWriteTime, // EvtVarTypeFileTime
EvtLogFileSize, // EvtVarTypeUInt64
EvtLogAttributes, // EvtVarTypeUInt32
EvtLogNumberOfLogRecords, // EvtVarTypeUInt64
EvtLogOldestRecordNumber, // EvtVarTypeUInt64
EvtLogFull, // EvtVarTypeBoolean
}
internal enum EvtExportLogFlags
{
EvtExportLogChannelPath = 1,
EvtExportLogFilePath = 2,
EvtExportLogTolerateQueryErrors = 0x1000
}
// RENDERING
internal enum EvtRenderContextFlags
{
EvtRenderContextValues = 0, // Render specific properties
EvtRenderContextSystem = 1, // Render all system properties (System)
EvtRenderContextUser = 2 // Render all user properties (User/EventData)
}
internal enum EvtRenderFlags
{
EvtRenderEventValues = 0, // Variants
EvtRenderEventXml = 1, // XML
EvtRenderBookmark = 2 // Bookmark
}
internal enum EvtFormatMessageFlags
{
EvtFormatMessageEvent = 1,
EvtFormatMessageLevel = 2,
EvtFormatMessageTask = 3,
EvtFormatMessageOpcode = 4,
EvtFormatMessageKeyword = 5,
EvtFormatMessageChannel = 6,
EvtFormatMessageProvider = 7,
EvtFormatMessageId = 8,
EvtFormatMessageXml = 9
}
internal enum EvtSystemPropertyId
{
EvtSystemProviderName = 0, // EvtVarTypeString
EvtSystemProviderGuid, // EvtVarTypeGuid
EvtSystemEventID, // EvtVarTypeUInt16
EvtSystemQualifiers, // EvtVarTypeUInt16
EvtSystemLevel, // EvtVarTypeUInt8
EvtSystemTask, // EvtVarTypeUInt16
EvtSystemOpcode, // EvtVarTypeUInt8
EvtSystemKeywords, // EvtVarTypeHexInt64
EvtSystemTimeCreated, // EvtVarTypeFileTime
EvtSystemEventRecordId, // EvtVarTypeUInt64
EvtSystemActivityID, // EvtVarTypeGuid
EvtSystemRelatedActivityID, // EvtVarTypeGuid
EvtSystemProcessID, // EvtVarTypeUInt32
EvtSystemThreadID, // EvtVarTypeUInt32
EvtSystemChannel, // EvtVarTypeString
EvtSystemComputer, // EvtVarTypeString
EvtSystemUserID, // EvtVarTypeSid
EvtSystemVersion, // EvtVarTypeUInt8
EvtSystemPropertyIdEND
}
// SESSION
internal enum EvtLoginClass
{
EvtRpcLogin = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct EvtRpcLogin
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Server;
[MarshalAs(UnmanagedType.LPWStr)]
public string User;
[MarshalAs(UnmanagedType.LPWStr)]
public string Domain;
[SecurityCritical]
public CoTaskMemUnicodeSafeHandle Password;
public int Flags;
}
// SEEK
[Flags]
internal enum EvtSeekFlags
{
EvtSeekRelativeToFirst = 1,
EvtSeekRelativeToLast = 2,
EvtSeekRelativeToCurrent = 3,
EvtSeekRelativeToBookmark = 4,
EvtSeekOriginMask = 7,
EvtSeekStrict = 0x10000
}
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtQuery(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.LPWStr)] string query,
int flags);
// SEEK
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSeek(
EventLogHandle resultSet,
long position,
EventLogHandle bookmark,
int timeout,
[MarshalAs(UnmanagedType.I4)] EvtSeekFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNext(
EventLogHandle queryHandle,
int eventSize,
[MarshalAs(UnmanagedType.LPArray)] IntPtr[] events,
int timeout,
int flags,
ref int returned);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtCancel(EventLogHandle handle);
[DllImport(WEVTAPI)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClose(IntPtr handle);
/*
[DllImport(WEVTAPI, EntryPoint = "EvtClose", SetLastError = true)]
public static extern bool EvtClose(
IntPtr eventHandle
);
*/
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventInfo(
EventLogHandle eventHandle,
// int propertyId
[MarshalAs(UnmanagedType.I4)] EvtEventPropertyId propertyId,
int bufferSize,
IntPtr bufferPtr,
out int bufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetQueryInfo(
EventLogHandle queryHandle,
[MarshalAs(UnmanagedType.I4)] EvtQueryPropertyId propertyId,
int bufferSize,
IntPtr buffer,
ref int bufferRequired
);
// PUBLISHER METADATA
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherMetadata(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string publisherId,
[MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetPublisherMetadataProperty(
EventLogHandle publisherMetadataHandle,
[MarshalAs(UnmanagedType.I4)] EvtPublisherMetadataPropertyId propertyId,
int flags,
int publisherMetadataPropertyBufferSize,
IntPtr publisherMetadataPropertyBuffer,
out int publisherMetadataPropertyBufferUsed
);
// NEW
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArraySize(
EventLogHandle objectArray,
out int objectArraySize
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetObjectArrayProperty(
EventLogHandle objectArray,
int propertyId,
int arrayIndex,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// NEW 2
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenEventMetadataEnum(
EventLogHandle publisherMetadata,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
// public static extern IntPtr EvtNextEventMetadata(
internal static extern EventLogHandle EvtNextEventMetadata(
EventLogHandle eventMetadataEnum,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetEventMetadataProperty(
EventLogHandle eventMetadata,
[MarshalAs(UnmanagedType.I4)] EvtEventMetadataPropertyId propertyId,
int flags,
int eventMetadataPropertyBufferSize,
IntPtr eventMetadataPropertyBuffer,
out int eventMetadataPropertyBufferUsed
);
// Channel Configuration Native Api
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextChannelPath(
EventLogHandle channelEnum,
int channelPathBufferSize,
// StringBuilder channelPathBuffer,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder channelPathBuffer,
out int channelPathBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenPublisherEnum(
EventLogHandle session,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtNextPublisherId(
EventLogHandle publisherEnum,
int publisherIdBufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder publisherIdBuffer,
out int publisherIdBufferUsed
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenChannelConfig(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string channelPath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSaveChannelConfig(
EventLogHandle channelConfig,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtSetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)] EvtChannelConfigPropertyId propertyId,
int flags,
ref EvtVariant propertyValue
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetChannelConfigProperty(
EventLogHandle channelConfig,
[MarshalAs(UnmanagedType.I4)] EvtChannelConfigPropertyId propertyId,
int flags,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// Log Information Native API
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string path,
[MarshalAs(UnmanagedType.I4)] PathType flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtGetLogInfo(
EventLogHandle log,
[MarshalAs(UnmanagedType.I4)] EvtLogPropertyId propertyId,
int propertyValueBufferSize,
IntPtr propertyValueBuffer,
out int propertyValueBufferUsed
);
// LOG MANIPULATION
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtExportLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string channelPath,
[MarshalAs(UnmanagedType.LPWStr)] string query,
[MarshalAs(UnmanagedType.LPWStr)] string targetFilePath,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtArchiveExportedLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string logFilePath,
int locale,
int flags
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtClearLog(
EventLogHandle session,
[MarshalAs(UnmanagedType.LPWStr)] string channelPath,
[MarshalAs(UnmanagedType.LPWStr)] string targetFilePath,
int flags
);
// RENDERING
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateRenderContext(
int valuePathsCount,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)]
string[] valuePaths,
[MarshalAs(UnmanagedType.I4)] EvtRenderContextFlags flags
);
[DllImport(WEVTAPI, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer,
out int buffUsed,
out int propCount
);
[DllImport(WEVTAPI, EntryPoint = "EvtRender", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtRender(
EventLogHandle context,
EventLogHandle eventHandle,
EvtRenderFlags flags,
int buffSize,
IntPtr buffer,
out int buffUsed,
out int propCount
);
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
internal struct EvtStringVariant
{
[MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)]
public string StringVal;
[FieldOffset(8)]
public uint Count;
[FieldOffset(12)]
public uint Type;
}
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessage(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
EvtStringVariant[] values,
[MarshalAs(UnmanagedType.I4)] EvtFormatMessageFlags flags,
int bufferSize,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder buffer,
out int bufferUsed
);
[DllImport(WEVTAPI, EntryPoint = "EvtFormatMessage", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtFormatMessageBuffer(
EventLogHandle publisherMetadataHandle,
EventLogHandle eventHandle,
uint messageId,
int valueCount,
IntPtr values,
[MarshalAs(UnmanagedType.I4)] EvtFormatMessageFlags flags,
int bufferSize,
IntPtr buffer,
out int bufferUsed
);
// SESSION
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtOpenSession(
[MarshalAs(UnmanagedType.I4)] EvtLoginClass loginClass,
ref EvtRpcLogin login,
int timeout,
int flags
);
// BOOKMARK
[DllImport(WEVTAPI, EntryPoint = "EvtCreateBookmark", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern EventLogHandle EvtCreateBookmark(
[MarshalAs(UnmanagedType.LPWStr)] string bookmarkXml
);
[DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EvtUpdateBookmark(
EventLogHandle bookmark,
EventLogHandle eventHandle
);
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Globalization;
using System.Linq;
namespace Avalonia
{
/// <summary>
/// Defines a size.
/// </summary>
public struct Size
{
/// <summary>
/// A size representing infinity.
/// </summary>
public static readonly Size Infinity = new Size(double.PositiveInfinity, double.PositiveInfinity);
/// <summary>
/// A size representing zero
/// </summary>
public static readonly Size Empty = new Size(0, 0);
/// <summary>
/// The width.
/// </summary>
private readonly double _width;
/// <summary>
/// The height.
/// </summary>
private readonly double _height;
/// <summary>
/// Initializes a new instance of the <see cref="Size"/> structure.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public Size(double width, double height)
{
_width = width;
_height = height;
}
/// <summary>
/// Gets the width.
/// </summary>
public double Width => _width;
/// <summary>
/// Gets the height.
/// </summary>
public double Height => _height;
/// <summary>
/// Checks for equality between two <see cref="Size"/>s.
/// </summary>
/// <param name="left">The first size.</param>
/// <param name="right">The second size.</param>
/// <returns>True if the sizes are equal; otherwise false.</returns>
public static bool operator ==(Size left, Size right)
{
return left._width == right._width && left._height == right._height;
}
/// <summary>
/// Checks for unequality between two <see cref="Size"/>s.
/// </summary>
/// <param name="left">The first size.</param>
/// <param name="right">The second size.</param>
/// <returns>True if the sizes are unequal; otherwise false.</returns>
public static bool operator !=(Size left, Size right)
{
return !(left == right);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator *(Size size, Vector scale)
{
return new Size(size._width * scale.X, size._height * scale.Y);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator /(Size size, Vector scale)
{
return new Size(size._width / scale.X, size._height / scale.Y);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator *(Size size, double scale)
{
return new Size(size._width * scale, size._height * scale);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator /(Size size, double scale)
{
return new Size(size._width / scale, size._height / scale);
}
public static Size operator +(Size size, Size toAdd)
{
return new Size(size._width + toAdd._width, size._height + toAdd._height);
}
public static Size operator -(Size size, Size toSubstract)
{
return new Size(size._width - toSubstract._width, size._height - toSubstract._height);
}
/// <summary>
/// Parses a <see cref="Size"/> string.
/// </summary>
/// <param name="s">The string.</param>
/// <param name="culture">The current culture.</param>
/// <returns>The <see cref="Size"/>.</returns>
public static Size Parse(string s, CultureInfo culture)
{
var parts = s.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.ToList();
if (parts.Count == 2)
{
return new Size(double.Parse(parts[0], culture), double.Parse(parts[1], culture));
}
else
{
throw new FormatException("Invalid Size.");
}
}
/// <summary>
/// Constrains the size.
/// </summary>
/// <param name="constraint">The size to constrain to.</param>
/// <returns>The constrained size.</returns>
public Size Constrain(Size constraint)
{
return new Size(
Math.Min(_width, constraint._width),
Math.Min(_height, constraint._height));
}
/// <summary>
/// Deflates the size by a <see cref="Thickness"/>.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The deflated size.</returns>
/// <remarks>The deflated size cannot be less than 0.</remarks>
public Size Deflate(Thickness thickness)
{
return new Size(
Math.Max(0, _width - thickness.Left - thickness.Right),
Math.Max(0, _height - thickness.Top - thickness.Bottom));
}
/// <summary>
/// Checks for equality between a size and an object.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>
/// True if <paramref name="obj"/> is a size that equals the current size.
/// </returns>
public override bool Equals(object obj)
{
if (obj is Size)
{
var other = (Size)obj;
return Width == other.Width && Height == other.Height;
}
return false;
}
/// <summary>
/// Returns a hash code for a <see cref="Size"/>.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + Width.GetHashCode();
hash = (hash * 23) + Height.GetHashCode();
return hash;
}
}
/// <summary>
/// Inflates the size by a <see cref="Thickness"/>.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The inflated size.</returns>
public Size Inflate(Thickness thickness)
{
return new Size(
_width + thickness.Left + thickness.Right,
_height + thickness.Top + thickness.Bottom);
}
/// <summary>
/// Returns a new <see cref="Size"/> with the same height and the specified width.
/// </summary>
/// <param name="width">The width.</param>
/// <returns>The new <see cref="Size"/>.</returns>
public Size WithWidth(double width)
{
return new Size(width, _height);
}
/// <summary>
/// Returns a new <see cref="Size"/> with the same width and the specified height.
/// </summary>
/// <param name="height">The height.</param>
/// <returns>The new <see cref="Size"/>.</returns>
public Size WithHeight(double height)
{
return new Size(_width, height);
}
/// <summary>
/// Returns the string representation of the size.
/// </summary>
/// <returns>The string representation of the size.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _width, _height);
}
}
}
| |
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Threading.Tasks;
namespace appMpower.Db
{
public class PooledCommand : IDbCommand
{
private OdbcCommand _odbcCommand;
private PooledConnection _pooledConnection;
public PooledCommand(PooledConnection pooledConnection)
{
_odbcCommand = (OdbcCommand)pooledConnection.CreateCommand();
_pooledConnection = pooledConnection;
}
public PooledCommand(string commandText, PooledConnection pooledConnection)
{
pooledConnection.GetCommand(commandText, this);
}
internal PooledCommand(OdbcCommand odbcCommand, PooledConnection pooledConnection)
{
_odbcCommand = odbcCommand;
_pooledConnection = pooledConnection;
}
internal OdbcCommand OdbcCommand
{
get
{
return _odbcCommand;
}
set
{
_odbcCommand = value;
}
}
internal PooledConnection PooledConnection
{
get
{
return _pooledConnection;
}
set
{
_pooledConnection = value;
}
}
public string CommandText
{
get
{
return _odbcCommand.CommandText;
}
set
{
_odbcCommand.CommandText = value;
}
}
public int CommandTimeout
{
get
{
return _odbcCommand.CommandTimeout;
}
set
{
_odbcCommand.CommandTimeout = value;
}
}
public CommandType CommandType
{
get
{
return _odbcCommand.CommandType;
}
set
{
_odbcCommand.CommandType = value;
}
}
#nullable enable
public IDbConnection? Connection
{
get
{
return _odbcCommand.Connection;
}
set
{
_odbcCommand.Connection = (OdbcConnection?)value;
}
}
#nullable disable
public IDataParameterCollection Parameters
{
get
{
return _odbcCommand.Parameters;
}
}
#nullable enable
public IDbTransaction? Transaction
{
get
{
return _odbcCommand.Transaction;
}
set
{
_odbcCommand.Transaction = (OdbcTransaction?)value;
}
}
#nullable disable
public UpdateRowSource UpdatedRowSource
{
get
{
return _odbcCommand.UpdatedRowSource;
}
set
{
_odbcCommand.UpdatedRowSource = value;
}
}
public void Cancel()
{
_odbcCommand.Cancel();
}
public IDbDataParameter CreateParameter()
{
return _odbcCommand.CreateParameter();
}
public IDbDataParameter CreateParameter(string name, DbType dbType, object value)
{
OdbcParameter odbcParameter = null;
if (this.Parameters.Contains(name))
{
odbcParameter = (OdbcParameter)this.Parameters[name];
odbcParameter.Value = value;
}
else
{
odbcParameter = _odbcCommand.CreateParameter();
odbcParameter.ParameterName = name;
odbcParameter.DbType = dbType;
odbcParameter.Value = value;
this.Parameters.Add(odbcParameter);
}
return odbcParameter;
}
public int ExecuteNonQuery()
{
return _odbcCommand.ExecuteNonQuery();
}
public IDataReader ExecuteReader()
{
return _odbcCommand.ExecuteReader();
}
public async Task<int> ExecuteNonQueryAsync()
{
return await _odbcCommand.ExecuteNonQueryAsync();
}
public async Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior)
{
return await _odbcCommand.ExecuteReaderAsync(behavior);
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
return _odbcCommand.ExecuteReader(behavior);
}
#nullable enable
public object? ExecuteScalar()
{
return _odbcCommand.ExecuteScalar();
}
#nullable disable
public void Prepare()
{
_odbcCommand.Prepare();
}
public void Release()
{
_pooledConnection.ReleaseCommand(this);
}
public void Dispose()
{
_pooledConnection.ReleaseCommand(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Runtime.Serialization.Json
{
internal class JsonReaderDelegator : XmlReaderDelegator
{
private DateTimeFormat _dateTimeFormat;
private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper;
public JsonReaderDelegator(XmlReader reader)
: base(reader)
{
}
public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat)
: this(reader)
{
_dateTimeFormat = dateTimeFormat;
}
internal XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
if (this.dictionaryReader == null)
{
return null;
}
else
{
return dictionaryReader.Quotas;
}
}
}
private DateTimeArrayJsonHelperWithString DateTimeArrayHelper
{
get
{
if (_dateTimeArrayHelper == null)
{
_dateTimeArrayHelper = new DateTimeArrayJsonHelperWithString(_dateTimeFormat);
}
return _dateTimeArrayHelper;
}
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal char ReadContentAsChar()
{
return XmlConvert.ToChar(ReadContentAsString());
}
internal override XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
internal override char ReadElementContentAsChar()
{
return XmlConvert.ToChar(ReadElementContentAsString());
}
public byte[] ReadContentAsBase64()
{
if (isEndOfEmptyElement)
return Array.Empty<byte>();
byte[] buffer;
if (dictionaryReader == null)
{
XmlDictionaryReader tempDictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
buffer = ByteArrayHelperWithString.Instance.ReadArray(tempDictionaryReader, JsonGlobals.itemString, string.Empty, tempDictionaryReader.Quotas.MaxArrayLength);
}
else
{
buffer = ByteArrayHelperWithString.Instance.ReadArray(dictionaryReader, JsonGlobals.itemString, string.Empty, dictionaryReader.Quotas.MaxArrayLength);
}
return buffer;
}
internal override byte[] ReadElementContentAsBase64()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
bool isEmptyElement = reader.IsStartElement() && reader.IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
reader.Read();
buffer = Array.Empty<byte>();
}
else
{
reader.ReadStartElement();
buffer = ReadContentAsBase64();
reader.ReadEndElement();
}
return buffer;
}
internal DateTime ReadContentAsDateTime()
{
return ParseJsonDate(ReadContentAsString(), _dateTimeFormat);
}
internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat)
{
if (dateTimeFormat == null)
{
return ParseJsonDateInDefaultFormat(originalDateTimeValue);
}
else
{
return DateTime.ParseExact(originalDateTimeValue, dateTimeFormat.FormatString, dateTimeFormat.FormatProvider, dateTimeFormat.DateTimeStyles);
}
}
internal static DateTime ParseJsonDateInDefaultFormat(string originalDateTimeValue)
{
// Dates are represented in JSON as "\/Date(number of ticks)\/".
// The number of ticks is the number of milliseconds since January 1, 1970.
string dateTimeValue;
if (!string.IsNullOrEmpty(originalDateTimeValue))
{
dateTimeValue = originalDateTimeValue.Trim();
}
else
{
dateTimeValue = originalDateTimeValue;
}
if (string.IsNullOrEmpty(dateTimeValue) ||
!dateTimeValue.StartsWith(JsonGlobals.DateTimeStartGuardReader, StringComparison.Ordinal) ||
!dateTimeValue.EndsWith(JsonGlobals.DateTimeEndGuardReader, StringComparison.Ordinal))
{
throw new FormatException(SR.Format(SR.JsonInvalidDateTimeString, originalDateTimeValue, JsonGlobals.DateTimeStartGuardWriter, JsonGlobals.DateTimeEndGuardWriter));
}
string ticksvalue = dateTimeValue.Substring(6, dateTimeValue.Length - 8);
long millisecondsSinceUnixEpoch;
DateTimeKind dateTimeKind = DateTimeKind.Utc;
int indexOfTimeZoneOffset = ticksvalue.IndexOf('+', 1);
if (indexOfTimeZoneOffset == -1)
{
indexOfTimeZoneOffset = ticksvalue.IndexOf('-', 1);
}
if (indexOfTimeZoneOffset != -1)
{
dateTimeKind = DateTimeKind.Local;
ticksvalue = ticksvalue.Substring(0, indexOfTimeZoneOffset);
}
try
{
millisecondsSinceUnixEpoch = Int64.Parse(ticksvalue, CultureInfo.InvariantCulture);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "Int64", exception);
}
// Convert from # milliseconds since epoch to # of 100-nanosecond units, which is what DateTime understands
long ticks = millisecondsSinceUnixEpoch * 10000 + JsonGlobals.unixEpochTicks;
try
{
DateTime dateTime = new DateTime(ticks, DateTimeKind.Utc);
switch (dateTimeKind)
{
case DateTimeKind.Local:
return dateTime.ToLocalTime();
case DateTimeKind.Unspecified:
return DateTime.SpecifyKind(dateTime.ToLocalTime(), DateTimeKind.Unspecified);
case DateTimeKind.Utc:
default:
return dateTime;
}
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(ticksvalue, "DateTime", exception);
}
}
internal override DateTime ReadElementContentAsDateTime()
{
return ParseJsonDate(ReadElementContentAsString(), _dateTimeFormat);
}
internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context,
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if ((dictionaryReader == null) || (arrayLength != -1))
{
array = null;
return false;
}
array = this.DateTimeArrayHelper.ReadArray(dictionaryReader, XmlDictionaryString.GetString(itemName), XmlDictionaryString.GetString(itemNamespace), GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
return true;
}
private class DateTimeArrayJsonHelperWithString : ArrayHelper<string, DateTime>
{
private DateTimeFormat _dateTimeFormat;
public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat)
{
_dateTimeFormat = dateTimeFormat;
}
protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
XmlJsonReader.CheckArray(array, offset, count);
int actual = 0;
while (actual < count && reader.IsStartElement(JsonGlobals.itemString, string.Empty))
{
array[offset + actual] = JsonReaderDelegator.ParseJsonDate(reader.ReadElementContentAsString(), _dateTimeFormat);
actual++;
}
return actual;
}
protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
throw NotImplemented.ByDesign;
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal ulong ReadContentAsUnsignedLong()
{
string value = reader.ReadContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
// Overridden because base reader relies on XmlConvert.ToUInt64 for conversion to ulong
internal override UInt64 ReadElementContentAsUnsignedLong()
{
if (isEndOfEmptyElement)
{
throw new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"));
}
string value = reader.ReadElementContentAsString();
if (value == null || value.Length == 0)
{
throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64")));
}
try
{
return ulong.Parse(value, NumberStyles.Float, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (FormatException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
catch (OverflowException exception)
{
throw XmlExceptionHelper.CreateConversionException(value, "UInt64", exception);
}
}
}
}
| |
namespace Loon.Java
{
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Reflection;
using System.Globalization;
using System.Threading;
using Loon.Core;
public class JavaRuntime
{
private List<ShutdownHook> shutdownHooks = new List<ShutdownHook>();
private static NumberFormatInfo formatProvider;
public static NumberFormatInfo NumberFormat
{
get
{
if (formatProvider == null)
{
formatProvider = new NumberFormatInfo();
formatProvider.NumberDecimalSeparator = ".";
}
return formatProvider;
}
}
public static object NewInstance(string className)
{
Type type = JavaRuntime.ClassforName(className);
return Activator.CreateInstance(type);
}
public static object NewInstance(Type clazz)
{
return Activator.CreateInstance(clazz);
}
private static string assemblyName;
public static string GetAssemblyName()
{
if (assemblyName == null)
{
JavaRuntime.assemblyName = new AssemblyName(Assembly.GetExecutingAssembly().FullName).Name;
}
return assemblyName;
}
private static JavaRuntime instance;
public static Uri GetResource(Assembly ass, string resourceName)
{
string str = @"Resources\";
string name = (ass.GetName().Name + "." + str + resourceName).Replace(@"\", ".").Replace("/", ".");
if (ass.GetManifestResourceStream(name) != null)
{
return new Uri(name);
}
return null;
}
public static Stream GetResourceAsStream(Assembly ass, string file)
{
string str = @"src\resources\";
string name = (ass.GetName().Name + "." + str + file).Replace(@"\", ".").Replace("/", ".");
return ass.GetManifestResourceStream(name);
}
public static Stream GetResourceAsStream(Assembly ass, string path, string file)
{
string name = (ass.GetName().Name + "." + path + file).Replace(@"\", ".").Replace("/", ".");
return ass.GetManifestResourceStream(name);
}
public static StreamWriter NewStreamWriter(Stream stream)
{
return new StreamWriter(stream);
}
public static StreamWriter NewStreamWriter(StreamWriter writer)
{
return writer;
}
public static StreamWriter NewStreamWriter(TextWriter writer)
{
if (writer is StreamWriter)
{
return (StreamWriter)writer;
}
if (writer is StringWriter)
{
throw new Exception("In .NET a StringWriter can'b be a StreamWriter");
}
throw new Exception("Text writer is not a stream !");
}
public static StreamWriter NewStreamWriter(Stream stream, bool autoflush)
{
StreamWriter writer = new StreamWriter(stream);
writer.AutoFlush = autoflush;
return writer;
}
public static StreamWriter NewStreamWriter(StreamWriter writer, bool autoflush)
{
writer.AutoFlush = autoflush;
return writer;
}
public static StreamWriter NewStreamWriter(TextWriter writer, bool autoflush)
{
if (writer is StreamWriter)
{
StreamWriter writer2 = (StreamWriter)writer;
writer2.AutoFlush = autoflush;
return writer2;
}
if (writer is StringWriter)
{
throw new Exception("In .NET a StringWriter can'b be a StreamWriter");
}
throw new Exception("Text writer is not a stream !");
}
public static JavaRuntime GetJavaRuntime()
{
if (instance == null)
{
instance = new JavaRuntime();
}
return instance;
}
public static ConstructorInfo GetConstructor(Type type, params Type[] paramsType)
{
if (paramsType.Length == 0)
{
return type.GetConstructor(new Type[0]);
}
return type.GetConstructor(paramsType);
}
public static MethodInfo GetMethod(Type type, string name)
{
char ch = name.Substring(0, 1).ToUpper()[0];
string str = ch + name.Remove(0, 1);
return type.GetMethod(str, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
}
public static MethodInfo GetMethod(Type type, string name, params Type[] paramsType)
{
char ch = name.Substring(0, 1).ToUpper()[0];
string str = ch + name.Remove(0, 1);
if (paramsType.Length == 0)
{
return type.GetMethod(str, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
}
return type.GetMethod(str, paramsType);
}
public static Type ClassforName(string className)
{
return ClassforName(Assembly.GetExecutingAssembly(), className);
}
public static Type ClassforName(Assembly a, string className)
{
Type type = a.GetType(className);
if (type != null)
{
return type;
}
int length = className.LastIndexOf(".");
if (length > 0)
{
string str = className.Substring(length + 1);
string name = className.Substring(0, length) + "+" + str;
Type type2 = a.GetType(name);
if (type2 != null)
{
return type2;
}
}
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
type = assembly.GetType(className);
if (type == null)
{
length = className.LastIndexOf(".");
if (length > 0)
{
string str3 = className.Substring(length + 1);
string str4 = className.Substring(0, length) + "+" + str3;
Type type3 = assembly.GetType(str4);
if (type3 != null)
{
return type3;
}
}
}
if (type != null)
{
return type;
}
}
return Type.GetType(className);
}
public static object Invoke(ConstructorInfo cInfo, params object[] parameters)
{
return cInfo.Invoke(parameters);
}
public static T Invoke<T>(ConstructorInfo cInfo, params object[] parameters)
{
return (T)cInfo.Invoke(parameters);
}
public static object Invoke(MethodInfo cInfo, object obj, params object[] parameters)
{
return cInfo.Invoke(obj, parameters);
}
public static T Invoke<T>(MethodInfo cInfo, object obj, params object[] parameters)
{
return (T)cInfo.Invoke(obj, parameters);
}
public static int IdentityHashCode(object o)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(o);
}
public void AddShutdownHook(Runnable r)
{
ShutdownHook item = new ShutdownHook();
item.Runnable = r;
this.shutdownHooks.Add(item);
}
public int AvailableProcessors()
{
return Environment.ProcessorCount;
}
public static long CurrentTimeMillis()
{
return Environment.TickCount;
}
public long MaxMemory()
{
return int.MaxValue;
}
private class ShutdownHook
{
public Runnable Runnable;
~ShutdownHook()
{
this.Runnable.Run();
}
}
public static byte[] GetBytesForString(string str)
{
return Encoding.UTF8.GetBytes(str);
}
public static byte[] GetBytesForString(string str, string encoding)
{
return Encoding.GetEncoding(encoding).GetBytes(str);
}
public static FieldInfo[] GetDeclaredFields(Type t)
{
return t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
}
public static void Wait(object o)
{
Monitor.Wait(o);
}
public static void Wait(object o, long milis)
{
Monitor.Wait(o, (int)milis);
}
public static void Wait(object o, TimeSpan t)
{
Monitor.Wait(o, t);
}
public static void NotifyAll(object o)
{
Monitor.PulseAll(o);
}
public static void Notify(object o)
{
Monitor.Pulse(o);
}
public static void PrintStackTrace(Exception ex)
{
Loon.Utils.Debug.Log.Exception(ex);
}
public static string Substring(string str, int index)
{
return str.Substring(index);
}
public static string Substring(string str, int index, int endIndex)
{
return str.Substring(index, endIndex - index);
}
public static Type GetType(string name)
{
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
Type t = a.GetType(name);
if (t != null)
{
return t;
}
}
throw new InvalidOperationException("Type not found: " + name);
}
public static void SetCharAt(StringBuilder sb, int index, char c)
{
sb[index] = c;
}
public static bool EqualsIgnoreCase(string s1, string s2)
{
return s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase);
}
public static long NanoTime()
{
return Environment.TickCount * 1000 * 1000;
}
public static int CompareOrdinal(string s1, string s2)
{
return string.CompareOrdinal(s1, s2);
}
public static string GetStringForBytes(byte[] chars)
{
return Encoding.UTF8.GetString(chars, 0, chars.Length);
}
public static string GetStringForBytes(byte[] chars, string encoding)
{
return GetEncoding(encoding).GetString(chars, 0, chars.Length);
}
public static string GetStringForBytes(byte[] chars, int start, int len)
{
return Encoding.UTF8.GetString(chars, start, len);
}
public static string GetStringForBytes(byte[] chars, int start, int len, string encoding)
{
return GetEncoding(encoding).GetChars(chars, start, len).ToString();
}
public static Encoding GetEncoding(string name)
{
Encoding e = Encoding.GetEncoding(name.Replace('_', '-'));
if (e is UTF8Encoding)
{
return new UTF8Encoding(false, true);
}
return e;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 AddDouble()
{
var test = new SimpleBinaryOpTest__AddDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Double> _fld1;
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddDouble testClass)
{
var result = Avx.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddDouble testClass)
{
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Add(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__AddDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Add(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Add(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Add(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Add), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Double>* pClsVar1 = &_clsVar1)
fixed (Vector256<Double>* pClsVar2 = &_clsVar2)
{
var result = Avx.Add(
Avx.LoadVector256((Double*)(pClsVar1)),
Avx.LoadVector256((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddDouble();
var result = Avx.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddDouble();
fixed (Vector256<Double>* pFld1 = &test._fld1)
fixed (Vector256<Double>* pFld2 = &test._fld2)
{
var result = Avx.Add(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Double>* pFld1 = &_fld1)
fixed (Vector256<Double>* pFld2 = &_fld2)
{
var result = Avx.Add(
Avx.LoadVector256((Double*)(pFld1)),
Avx.LoadVector256((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Add(
Avx.LoadVector256((Double*)(&test._fld1)),
Avx.LoadVector256((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(left[0] + right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] + right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Add)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace HTLib2.KDTree
{
/// <summary>
/// This class implements a <code>PriorityQueue</code>. This class
/// is implemented in such a way that objects are added using an
/// <code>add</code> function. The <code>add</code> function takes
/// two parameters an object and a long.
/// <p>
/// The object represents an item in the queue, the long indicates
/// its priority in the queue. The remove function in this class
/// returns the object first in the queue and that object is removed
/// from the queue permanently.
///
/// @author Simon Levy
/// Translation by Marco A. Alvarez
/// </summary>
class PriorityQueue
{
/**
* The maximum priority possible in this priority queue.
*/
private double maxPriority = Double.MaxValue;
/**
* This contains the list of objects in the queue.
*/
private Object[] data;
/**
* This contains the list of prioritys in the queue.
*/
private double[] value;
/**
* Holds the number of elements currently in the queue.
*/
private int count;
/**
* This holds the number elements this queue can have.
*/
private int capacity;
/**
* Creates a new <code>PriorityQueue</code> object. The
* <code>PriorityQueue</code> object allows objects to be
* entered into the queue and to leave in the order of
* priority i.e the highest priority get's to leave first.
*/
public PriorityQueue()
{
init(20);
}
/**
* Creates a new <code>PriorityQueue</code> object. The
* <code>PriorityQueue</code> object allows objects to
* be entered into the queue an to leave in the order of
* priority i.e the highest priority get's to leave first.
*
* @param capacity the initial capacity of the queue before
* a resize
*/
public PriorityQueue(int capacity)
{
init(capacity);
}
/**
* Creates a new <code>PriorityQueue</code> object. The
* <code>PriorityQueue</code> object allows objects to
* be entered into the queue an to leave in the order of
* priority i.e the highest priority get's to leave first.
*
* @param capacity the initial capacity of the queue before
* a resize
* @param maxPriority is the maximum possible priority for
* an object
*/
public PriorityQueue(int capacity, double maxPriority)
{
this.maxPriority = maxPriority;
init(capacity);
}
/**
* This is an initializer for the object. It basically initializes
* an array of long called value to represent the prioritys of
* the objects, it also creates an array of objects to be used
* in parallel with the array of longs, to represent the objects
* entered, these can be used to sequence the data.
*
* @param size the initial capacity of the queue, it can be
* resized
*/
private void init(int size)
{
capacity = size;
data = new Object[capacity + 1];
value = new double[capacity + 1];
value[0] = maxPriority;
data[0] = null;
}
/**
* This function adds the given object into the <code>PriorityQueue</code>,
* its priority is the long priority. The way in which priority can be
* associated with the elements of the queue is by keeping the priority
* and the elements array entrys parallel.
*
* @param element is the object that is to be entered into this
* <code>PriorityQueue</code>
* @param priority this is the priority that the object holds in the
* <code>PriorityQueue</code>
*/
public void add(Object element, double priority)
{
if (count++ >= capacity)
{
expandCapacity();
}
/* put this as the last element */
value[count] = priority;
data[count] = element;
bubbleUp(count);
}
/**
* Remove is a function to remove the element in the queue with the
* maximum priority. Once the element is removed then it can never be
* recovered from the queue with further calls. The lowest priority
* object will leave last.
*
* @return the object with the highest priority or if it's empty
* null
*/
public Object remove()
{
if (count == 0)
return null;
Object element = data[1];
/* swap the last element into the first */
data[1] = data[count];
value[1] = value[count];
/* let the GC clean up */
data[count] = null;
value[count] = 0L;
count--;
bubbleDown(1);
return element;
}
public Object front()
{
return data[1];
}
public double getMaxPriority()
{
return value[1];
}
/**
* Bubble down is used to put the element at subscript 'pos' into
* it's rightful place in the heap (i.e heap is another name
* for <code>PriorityQueue</code>). If the priority of an element
* at subscript 'pos' is less than it's children then it must
* be put under one of these children, i.e the ones with the
* maximum priority must come first.
*
* @param pos is the position within the arrays of the element
* and priority
*/
private void bubbleDown(int pos)
{
Object element = data[pos];
double priority = value[pos];
int child;
/* hole is position '1' */
for (; pos * 2 <= count; pos = child)
{
child = pos * 2;
/* if 'child' equals 'count' then there
is only one leaf for this parent */
if (child != count)
/* left_child > right_child */
if (value[child] < value[child + 1])
child++; /* choose the biggest child */
/* percolate down the data at 'pos', one level
i.e biggest child becomes the parent */
if (priority < value[child])
{
value[pos] = value[child];
data[pos] = data[child];
}
else
{
break;
}
}
value[pos] = priority;
data[pos] = element;
}
/**
* Bubble up is used to place an element relatively low in the
* queue to it's rightful place higher in the queue, but only
* if it's priority allows it to do so, similar to bubbleDown
* only in the other direction this swaps out its parents.
*
* @param pos the position in the arrays of the object
* to be bubbled up
*/
private void bubbleUp(int pos)
{
Object element = data[pos];
double priority = value[pos];
/* when the parent is not less than the child, end*/
while (value[pos / 2] < priority)
{
/* overwrite the child with the parent */
value[pos] = value[pos / 2];
data[pos] = data[pos / 2];
pos /= 2;
}
value[pos] = priority;
data[pos] = element;
}
/**
* This ensures that there is enough space to keep adding elements
* to the priority queue. It is however advised to make the capacity
* of the queue large enough so that this will not be used as it is
* an expensive method. This will copy across from 0 as 'off' equals
* 0 is contains some important data.
*/
private void expandCapacity()
{
capacity = count * 2;
Object[] elements = new Object[capacity + 1];
double[] prioritys = new double[capacity + 1];
Array.Copy(data, 0, elements, 0, data.Length);
Array.Copy(value, 0, prioritys, 0, data.Length);
data = elements;
value = prioritys;
}
/**
* This method will empty the queue. This also helps garbage
* collection by releasing any reference it has to the elements
* in the queue. This starts from offset 1 as off equals 0
* for the elements array.
*/
public void clear()
{
for (int i = 1; i < count; i++)
{
data[i] = null; /* help gc */
}
count = 0;
}
/**
* The number of elements in the queue. The length
* indicates the number of elements that are currently
* in the queue.
*
* @return the number of elements in the queue
*/
public int length()
{
return count;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace OpenLiveWriter.Interop.Windows
{
/// <summary>
/// Imports from Kernel32.dll
/// </summary>
public class Kernel32
{
/// <summary>
/// Infinite timeout value
/// </summary>
public static readonly uint INFINITE = 0xFFFFFFFF;
/// <summary>
/// Invalid handle value
/// </summary>
public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetDllDirectory(string pathName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint SetErrorMode(uint uMode);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void ExitProcess(
UInt32 uExitCode
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool TerminateProcess(
IntPtr hProcess,
UInt32 uExitCode
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetCurrentProcessId();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetModuleHandle(
IntPtr lpModuleName
);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint GetModuleFileName(
IntPtr hModule,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpFilename,
uint nSize
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetProcessWorkingSetSize(
IntPtr hProcess,
int dwMinimumWorkingSetSize,
int dwMaximumWorkingSetSize
);
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetLongPathName(
[In] string lpFileName,
[Out] StringBuilder lpBuffer,
[In] int nBufferLength);
/// <summary>
/// Converts a potentially short filename to a long filename.
/// If the file does not exist, <c>null</c> is returned.
/// </summary>
public static string GetLongPathName(string fileName)
{
return GetLongPathName(fileName, MAX_PATH);
}
protected static string GetLongPathName(string fileName, int bufferLen)
{
StringBuilder buffer = new StringBuilder(bufferLen);
int requiredBuffer = GetLongPathName(fileName, buffer, bufferLen);
if (requiredBuffer == 0)
{
// error... probably file does not exist
return null;
}
if (requiredBuffer > bufferLen)
{
// The buffer we used was not long enough... try again
return GetLongPathName(fileName, requiredBuffer);
}
else
{
return buffer.ToString();
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetShortPathName(
[In] string lpFileName,
[Out] StringBuilder lpBuffer,
[In] int nBufferLength);
/// <summary>
/// Converts a potentially long filename to a short filename.
/// If the file does not exist, <c>null</c> is returned.
/// </summary>
public static string GetShortPathName(string fileName)
{
return GetShortPathName(fileName, MAX_PATH);
}
protected static string GetShortPathName(string fileName, int bufferLen)
{
StringBuilder buffer = new StringBuilder(bufferLen);
int requiredBuffer = GetShortPathName(fileName, buffer, bufferLen);
if (requiredBuffer == 0)
{
// error... probably file does not exist
return null;
}
if (requiredBuffer > bufferLen)
{
// The buffer we used was not long enough... try again
return GetShortPathName(fileName, requiredBuffer);
}
else
{
return buffer.ToString();
}
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetThreadLocale(int lcid);
// used to get supported code pages
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool EnumSystemCodePages(CodePageDelegate lpCodePageEnumProc,
uint dwFlags);
public const uint CP_INSTALLED = 0x00000001; // installed code page ids
public const uint CP_SUPPORTED = 0x00000002; // supported code page ids
/// <summary>
/// Delegate used for EnumSystemCodePages
/// </summary>
public delegate bool CodePageDelegate([MarshalAs(UnmanagedType.LPTStr)] string codePageName);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr LocalFree(
IntPtr hMem
);
/// <summary>
/// Get the Terminal Services/Fast User Switching session ID
/// for a process ID.
/// </summary>
[DllImport("kernel32.dll")]
public static extern bool ProcessIdToSessionId(
[In] uint dwProcessId,
[Out] out uint pSessionId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFileMapping(
IntPtr hFile,
IntPtr lpAttributes,
uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow,
[In, MarshalAs(UnmanagedType.LPTStr)] string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr MapViewOfFile(
IntPtr hFileMappingObject,
uint dwDesiredAccess,
uint dwFileOffsetHigh,
uint dwFileOffsetLow,
uint dwNumberOfBytesToMap);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void ZeroMemory(
IntPtr Destination,
uint Length);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int UnmapViewOfFile(
IntPtr lpBaseAddress);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool ReplaceFile(
[MarshalAs(UnmanagedType.LPTStr)] string lpReplacedFileName,
[MarshalAs(UnmanagedType.LPTStr)] string lpReplacementFileName,
[MarshalAs(UnmanagedType.LPTStr)] string lpBackupFileName,
uint dwReplaceFlags,
IntPtr lpExclude,
IntPtr lpReserved);
/// <summary>
/// Get an error code for the last error on this thread.
/// IntPtr can be converted to a 32 bit Int.
/// </summary>
[DllImport("kernel32.dll")]
[Obsolete("Use Marshal.GetLastWin32Error() with [DllImport(SetLastError = true)] instead!", true)]
public static extern uint GetLastError();
/// <summary>
/// Locks a global memory object and returns a pointer to the first byte
/// of the object's memory block.
/// </summary>
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr GlobalLock(IntPtr hMem);
/// <summary>
/// Decrements the lock count associated with the HGLOBAL memory block
/// </summary>
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern UIntPtr GlobalSize(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes);
[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = true)]
public static extern void CopyMemory(IntPtr Destination, IntPtr Source, UIntPtr Length);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateMutex(
IntPtr lpMutexAttributes,
int bInitialOwner,
[MarshalAs(UnmanagedType.LPTStr)] string lpName
);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int ReleaseMutex(
IntPtr hMutex
);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr CreateEvent(
IntPtr lpEventAttributes,
int bManualReset,
int bInitialState,
[MarshalAs(UnmanagedType.LPTStr)] string lpName);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenEvent(
uint dwDesiredAccess,
int bInheritHandle,
[MarshalAs(UnmanagedType.LPTStr)] string lpName);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int SetEvent(IntPtr hEvent);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int ResetEvent(IntPtr hEvent);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern uint WaitForSingleObject(
IntPtr hHandle,
uint dwMilliseconds
);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(
IntPtr hObject
);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern uint WaitForMultipleObjects(
uint nCount,
IntPtr[] pHandles,
bool bWaitAll,
uint dwMilliseconds
);
/// <summary>
/// Get the drive type for a particular drive.
/// </summary>
[DllImport("kernel32.dll")]
public static extern long GetDriveType(string driveLetter);
/// <summary>
/// Read a string from an INI file
/// </summary>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpdefault,
StringBuilder sbout,
int nsize,
string lpFileName);
/// <summary>
/// The drive types returned by GetDriveType
/// </summary>
public struct DRIVE
{
public const int UNKNOWN = 0;
public const int NO_ROOT_DIR = 1;
public const int REMOVABLE = 2;
public const int FIXED = 3;
public const int REMOTE = 4;
public const int CDROM = 5;
public const int RAMDISK = 6;
}
/// <summary>
/// Get the unique ID of the currently executing thread
/// </summary>
[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
/// <summary>
/// Gets a temp file using a path and a prefix string. Note that stringbuilder
/// should be at least kernel32.MAX_PATH size. uUnique should be 0 to make unique
/// temp file names, non zero to not necessarily create unique temp file names.
/// </summary>
[DllImport("kernel32.dll")]
public static extern int GetTempFileName(
string lpPathName,
string lpPrefixString,
Int32 uUnique,
StringBuilder lpTempFileName);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern bool WriteFile(
SafeFileHandle hFile, IntPtr lpBuffer,
uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten,
IntPtr lpOverlapped);
// The Max Path constant
public const int MAX_PATH = 260;
/// <summary>
/// The QueryPerformanceCounter function retrieves the current value of the high-resolution
/// performance counter.
/// </summary>
[DllImport("kernel32.dll")]
public static extern bool QueryPerformanceCounter(ref long performanceCount);
/// <summary>
/// The QueryPerformanceFrequency function retrieves the frequency of the high-resolution
/// performance counter, if one exists. The frequency cannot change while the system is running.
/// </summary>
[DllImport("kernel32.dll")]
public static extern bool QueryPerformanceFrequency(ref long frequency);
/// <summary>
/// The GetTickCount function retrieves the number of milliseconds that have elapsed since the
/// system was started. It is limited to the resolution of the system timer. To obtain the system
/// timer resolution, use the GetSystemTimeAdjustment function.
/// </summary>
/// <remarks>
/// The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if
/// the system is run continuously for 49.7 days.
/// </remarks>
[DllImport("kernel32.dll")]
public static extern uint GetTickCount();
[DllImport("kernel32.dll")]
public static extern bool FileTimeToLocalFileTime([In] ref System.Runtime.InteropServices.ComTypes.FILETIME lpFileTime,
out System.Runtime.InteropServices.ComTypes.FILETIME lpLocalFileTime);
[DllImport("kernel32.dll")]
public static extern bool LocalFileTimeToFileTime([In] ref System.Runtime.InteropServices.ComTypes.FILETIME lpLocalFileTime,
out System.Runtime.InteropServices.ComTypes.FILETIME lpFileTime);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
}
public class GlobalMemoryStatus
{
public GlobalMemoryStatus()
{
_memoryStatus.Length = Marshal.SizeOf(typeof(MEMORYSTATUSEX));
if (!GlobalMemoryStatusEx(ref _memoryStatus))
throw new Win32Exception(Marshal.GetLastWin32Error());
}
public int MemoryLoad { get { return _memoryStatus.MemoryLoad; } }
public long TotalPhysical { get { return _memoryStatus.TotalPhysical; } }
public long AvailablePhysical { get { return _memoryStatus.AvailablePhysical; } }
public long TotalPageFile { get { return _memoryStatus.TotalPageFile; } }
public long AvailablePageFile { get { return _memoryStatus.AvailablePageFile; } }
public long TotalVirtual { get { return _memoryStatus.TotalVirtual; } }
public long AvailableVirtual { get { return _memoryStatus.AvailableVirtual; } }
public long AvailableExtendedVirtual { get { return _memoryStatus.AvailableExtendedVirtual; } }
private struct MEMORYSTATUSEX
{
public int Length;
public int MemoryLoad;
public long TotalPhysical;
public long AvailablePhysical;
public long TotalPageFile;
public long AvailablePageFile;
public long TotalVirtual;
public long AvailableVirtual;
public long AvailableExtendedVirtual;
}
[DllImport("Kernel32.dll", SetLastError = true)]
static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
private MEMORYSTATUSEX _memoryStatus = new MEMORYSTATUSEX();
}
/// <summary>
/// Disposable wrapper class for getting access to the contents of an HGLOBAL
/// </summary>
public class HGlobalLock : IDisposable
{
/// <summary>
/// Initialize by locking the HGLOBAL
/// </summary>
/// <param name="hGlobal">HGLOBAL to lock and then access</param>
public HGlobalLock(IntPtr hGlobal)
{
this.hGlobal = hGlobal;
Lock();
}
/// <summary>
/// Unlock on dispose
/// </summary>
public void Dispose()
{
Unlock();
}
/// <summary>
/// Underlying memory pointed to by the hGlobal
/// </summary>
public IntPtr Memory
{
get
{
Debug.Assert(pData != IntPtr.Zero);
return pData;
}
}
/// <summary>
/// Get the size of of the locked global memory handle
/// </summary>
public UIntPtr Size
{
get
{
UIntPtr size = Kernel32.GlobalSize(hGlobal);
if (size == UIntPtr.Zero)
{
throw new Win32Exception(
Marshal.GetLastWin32Error(), "Unexpected error calling GlobalSize");
}
return size;
}
}
/// <summary>
/// Lock the HGLOBAL so as to access the underlying memory block
/// </summary>
public void Lock()
{
Debug.Assert(pData == IntPtr.Zero);
pData = Kernel32.GlobalLock(hGlobal);
if (pData == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Error occurred while tyring to lock global memory");
}
}
/// <summary>
/// Unlock the HGLOBAL
/// </summary>
public void Unlock()
{
if (pData != IntPtr.Zero)
{
bool success = Kernel32.GlobalUnlock(hGlobal);
int lastError = Marshal.GetLastWin32Error();
if (!success && lastError != ERROR.SUCCESS)
{
throw new Win32Exception(lastError,
"Unexpected error occurred calling GlobalUnlock");
}
pData = IntPtr.Zero;
}
}
/// <summary>
/// Clone the underlying memory and return a new HGLOBAL that references
/// the cloned memory (this HGLOBAL will need to be freed using GlobalFree)
/// </summary>
/// <returns>cloned memory block</returns>
public IntPtr Clone()
{
// allocate output memory
IntPtr hglobOut = Kernel32.GlobalAlloc(GMEM.FIXED, Size);
if (hglobOut == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error(),
"Unexpected error occurred calling GlobalAlloc");
}
// got the memory, copy into it and return it
Kernel32.CopyMemory(hglobOut, Memory, Size);
return hglobOut;
}
/// <summary>
/// Underlying HGLOBAL
/// </summary>
private IntPtr hGlobal = IntPtr.Zero;
/// <summary>
/// Pointer to data (aquired by locking the HGLOBAL)
/// </summary>
private IntPtr pData = IntPtr.Zero;
}
/// <summary>
/// SetErrorMode flags
/// </summary>
public struct SEM
{
public const uint FAILCRITICALERRORS = 0x0001;
public const uint NOGPFAULTERRORBOX = 0x0002;
public const uint NOALIGNMENTFAULTEXCEPT = 0x0004;
public const uint NOOPENFILEERRORBOX = 0x8000;
}
/// <summary>
/// ReplaceFile flags
/// </summary>
public struct REPLACEFILE
{
public const uint WRITE_THROUGH = 0x00000001;
public const uint IGNORE_MERGE_ERRORS = 0x00000002;
}
/// <summary>
/// Thread priority constants
/// </summary>
public struct THREAD_PRIORITY
{
public const int NORMAL = 0;
}
public struct GMEM
{
public const uint FIXED = 0x0000;
public const uint MOVEABLE = 0x0002;
public const uint ZEROINIT = 0x0040;
public const uint SHARE = 0x2000;
}
public struct PAGE
{
public const uint READONLY = 0x02;
public const uint READWRITE = 0x04;
public const uint WRITECOPY = 0x08;
}
public struct SEC
{
public const uint IMAGE = 0x1000000;
public const uint RESERVE = 0x4000000;
public const uint COMMIT = 0x8000000;
public const uint NOCACHE = 0x10000000;
}
public struct FILE_MAP
{
public const uint COPY = 0x0001;
public const uint WRITE = 0x0002;
public const uint READ = 0x0004;
}
public struct FILE_ATTRIBUTE
{
public const uint READONLY = 0x00000001;
public const uint HIDDEN = 0x00000002;
public const uint SYSTEM = 0x00000004;
public const uint DIRECTORY = 0x00000010;
public const uint ARCHIVE = 0x00000020;
public const uint DEVICE = 0x00000040;
public const uint NORMAL = 0x00000080;
public const uint TEMPORARY = 0x00000100;
}
/// <summary>
/// The SECURITY_ATTRIBUTES structure contains the security descriptor for
/// an object and specifies whether the handle retrieved by specifying this
/// structure is inheritable
/// </summary>
public struct SECURITY_ATTRIBUTES
{
/// <summary>
/// Specifies the size, in bytes, of this structure. Set this value to
/// the size of the SECURITY_ATTRIBUTES structure.
/// </summary>
public uint nLength;
/// <summary>
/// Pointer to a security descriptor for the object that controls the
/// sharing of it. If NULL is specified for this member, the object
/// is assigned the default security descriptor of the calling process.
/// </summary>
public IntPtr lpSecurityDescriptor;
/// <summary>
/// Specifies whether the returned handle is inherited when a new
/// process is created. If this member is TRUE, the new process inherits
/// the handle.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool bInheritHandle;
}
/// <summary>
/// Wait constants used in synchronization functions
/// </summary>
public struct WAIT
{
public const uint FAILED = 0xFFFFFFFF;
public const uint OBJECT_0 = 0x00000000;
public const uint ABANDONED = 0x00000080;
public const uint TIMEOUT = 258;
}
/// <summary>
/// Constants used for getting access to synchronization events
/// </summary>
public struct EVENT
{
public const uint MODIFY_STATE = 0x0002;
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace VaultAtlas.UI
{
public class MRUMenuItem
{
public class MruMenu
{
protected MenuItem recentFileMenuItem;
protected ClickedHandler clickedHandler;
protected String registryKeyName;
protected int numEntries = 0;
protected int maxEntries = 4;
protected int maxShortenPathLength = 48;
#region MruMenuItem
// The menu may display a shortened or otherwise invalid pathname
// This class is used to store the actual filename, preferably as
// a fully resolved name.
public class MruMenuItem : MenuItem
{
protected String filename;
public MruMenuItem()
{
filename = "";
}
public MruMenuItem(String _filename, String entryname, EventHandler eventHandler)
: base(entryname, eventHandler)
{
filename = _filename;
}
public String Filename
{
get
{
return filename;
}
set
{
filename = value;
}
}
}
#endregion
/// <summary>
/// MruMenu handles a most recently used (MRU) file list.
///
/// This class shows the MRU list in a popup menu. To display
/// the MRU list "inline" use MruMenuInline.
///
/// The class will load the last set of files from the registry
/// on construction and store them when instructed by the main
/// program.
///
/// Internally, this class uses zero-based numbering for the items.
/// The displayed numbers, however, will start with one.
/// </summary>
#region Construction
protected MruMenu() {}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler)
{
Init(_recentFileMenuItem, _clickedHandler, null, false, 4);
}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, int _maxEntries)
{
Init(_recentFileMenuItem, _clickedHandler, null, false, _maxEntries);
}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName)
{
Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, true, 4);
}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, int _maxEntries)
{
Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, true, _maxEntries);
}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, bool loadFromRegistry)
{
Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, loadFromRegistry, 4);
}
public MruMenu(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, bool loadFromRegistry, int _maxEntries)
{
Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, loadFromRegistry, _maxEntries);
}
protected void Init(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, bool loadFromRegistry, int _maxEntries)
{
if (_recentFileMenuItem == null)
throw new ArgumentNullException("recentFileMenuItem");
if (_recentFileMenuItem.Parent == null)
throw new ArgumentException("recentFileMenuItem is not part of a menu");
recentFileMenuItem = _recentFileMenuItem;
recentFileMenuItem.Checked = false;
recentFileMenuItem.Enabled = false;
recentFileMenuItem.DefaultItem = false;
maxEntries = _maxEntries;
clickedHandler = _clickedHandler;
if (_registryKeyName != null)
{
RegistryKeyName = _registryKeyName;
if (loadFromRegistry)
{
LoadFromRegistry();
}
}
}
#endregion
#region Event Handling
public delegate void ClickedHandler(int number, String filename);
protected void OnClick(object sender, System.EventArgs e)
{
MruMenuItem menuItem = (MruMenuItem) sender;
clickedHandler(menuItem.Index - StartIndex, menuItem.Filename);
}
#endregion
#region Properties
public virtual Menu.MenuItemCollection MenuItems
{
get
{
return recentFileMenuItem.MenuItems;
}
}
public virtual int StartIndex
{
get
{
return 0;
}
}
public virtual int EndIndex
{
get
{
return numEntries;
}
}
public int NumEntries
{
get
{
return numEntries;
}
}
public int MaxEntries
{
get
{
return maxEntries;
}
set
{
if (value > 16)
{
maxEntries = 16;
}
else
{
maxEntries = value < 4 ? 4 : value;
int index = StartIndex + maxEntries;
while (numEntries > maxEntries)
{
MenuItems.RemoveAt(index);
numEntries--;
}
}
}
}
public int MaxShortenPathLength
{
get
{
return maxShortenPathLength;
}
set
{
maxShortenPathLength = value < 16 ? 16 : value;
}
}
#endregion
#region Helper Methods
protected virtual void Enable()
{
recentFileMenuItem.Enabled = true;
}
protected virtual void Disable()
{
recentFileMenuItem.Enabled = false;
recentFileMenuItem.MenuItems.RemoveAt(0);
}
protected virtual void SetFirstFile(MenuItem menuItem)
{
}
public void SetFirstFile(int number)
{
if (number > 0 && numEntries > 1 && number < numEntries)
{
MenuItem menuItem = MenuItems[StartIndex + number];
menuItem.Index = StartIndex;
SetFirstFile(menuItem);
FixupPrefixes(0);
}
}
public static String FixupEntryname(int number, String entryname)
{
if (number < 9)
return "&" + (number + 1) + " " + entryname;
else if (number == 9)
return "1&0" + " " + entryname;
else
return (number + 1) + " " + entryname;
}
protected void FixupPrefixes(int startNumber)
{
if (startNumber < 0)
startNumber = 0;
if (startNumber < maxEntries)
{
for (int i = StartIndex + startNumber; i < EndIndex; i++, startNumber++)
{
MenuItems[i].Text = FixupEntryname(startNumber, MenuItems[i].Text.Substring(startNumber == 9 ? 5 : 4));
}
}
}
#endregion
#region Get Methods
public int FindFilenameNumber(String filename)
{
if (filename == null)
throw new ArgumentNullException("filename");
if (filename.Length == 0)
throw new ArgumentException("filename");
if (numEntries > 0)
{
int number = 0;
for (int i = StartIndex; i < EndIndex; i++, number++)
{
if (String.Compare(((MruMenuItem)MenuItems[i]).Filename, filename, true) == 0)
{
return number;
}
}
}
return -1;
}
public int FindFilenameMenuIndex(String filename)
{
int number = FindFilenameNumber(filename);
return number < 0 ? -1 : StartIndex + number;
}
public int GetMenuIndex(int number)
{
if (number < 0 || number >= numEntries)
throw new ArgumentOutOfRangeException("number");
return StartIndex + number;
}
public String GetFileAt(int number)
{
if (number < 0 || number >= numEntries)
throw new ArgumentOutOfRangeException("number");
return ((MruMenuItem)MenuItems[StartIndex + number]).Filename;
}
public String[] GetFiles()
{
String[] filenames = new String[numEntries];
int index = StartIndex;
for (int i = 0; i < filenames.GetLength(0); i++, index++)
{
filenames[i] = ((MruMenuItem)MenuItems[index]).Filename;
}
return filenames;
}
// This is used for testing
public String[] GetFilesFullEntryString()
{
String[] filenames = new String[numEntries];
int index = StartIndex;
for (int i = 0; i < filenames.GetLength(0); i++, index++)
{
filenames[i] = MenuItems[index].Text;
}
return filenames;
}
#endregion
#region Add Methods
public void SetFiles(String[] filenames)
{
RemoveAll();
for (int i = filenames.GetLength(0) - 1; i >= 0; i--)
{
AddFile(filenames[i]);
}
}
public void AddFiles(String[] filenames)
{
for (int i = filenames.GetLength(0) - 1; i >= 0; i--)
{
AddFile(filenames[i]);
}
}
// Shortens a pathname by either removing consecutive components of a path
// and/or by removing characters from the end of the filename and replacing
// then with three elipses (...)
//
// In all cases, the root of the passed path will be preserved in it's entirety.
//
// If a UNC path is used or the pathname and maxLength are particularly short,
// the resulting path may be longer than maxLength.
//
// This method expects fully resolved pathnames to be passed to it.
// (Use Path.GetFullPath() to obtain this.)
static public String ShortenPathname(String pathname, int maxLength)
{
if (pathname.Length <= maxLength)
return pathname;
String root = Path.GetPathRoot(pathname);
if (root.Length > 3)
root += Path.DirectorySeparatorChar;
String[] elements = pathname.Substring(root.Length).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
int filenameIndex = elements.GetLength(0) - 1;
if (elements.GetLength(0) == 1) // pathname is just a root and filename
{
if (elements[0].Length > 5) // long enough to shorten
{
// if path is a UNC path, root may be rather long
if (root.Length + 6 >= maxLength)
{
return root + elements[0].Substring(0, 3) + "...";
}
else
{
return pathname.Substring(0, maxLength - 3) + "...";
}
}
}
else if ((root.Length + 4 + elements[filenameIndex].Length) > maxLength) // pathname is just a root and filename
{
root += "...\\";
int len = elements[filenameIndex].Length;
if (len < 6)
return root + elements[filenameIndex];
if ((root.Length + 6) >= maxLength)
{
len = 3;
}
else
{
len = maxLength - root.Length - 3;
}
return root + elements[filenameIndex].Substring(0, len) + "...";
}
else if (elements.GetLength(0) == 2)
{
return root + "...\\" + elements[1];
}
else
{
int len = 0;
int begin = 0;
for (int i = 0; i < filenameIndex; i++)
{
if (elements[i].Length > len)
{
begin = i;
len = elements[i].Length;
}
}
int totalLength = pathname.Length - len + 3;
int end = begin + 1;
while (totalLength > maxLength)
{
if (begin > 0)
totalLength -= elements[--begin].Length - 1;
if (totalLength <= maxLength)
break;
if (end < filenameIndex)
totalLength -= elements[++end].Length - 1;
if (begin == 0 && end == filenameIndex)
break;
}
// assemble final string
for (int i = 0; i < begin; i++)
{
root += elements[i] + '\\';
}
root += "...\\";
for (int i = end; i < filenameIndex; i++)
{
root += elements[i] + '\\';
}
return root + elements[filenameIndex];
}
return pathname;
}
public void AddFile(String filename)
{
String pathname = Path.GetFullPath(filename);
AddFile(pathname, ShortenPathname(pathname, MaxShortenPathLength));
}
public void AddFile(String filename, String entryname)
{
if (filename == null)
throw new ArgumentNullException("filename");
if (filename.Length == 0)
throw new ArgumentException("filename");
if (numEntries > 0)
{
int index = FindFilenameMenuIndex(filename);
if (index >= 0)
{
SetFirstFile(index - StartIndex);
return;
}
}
if (numEntries < maxEntries)
{
MruMenuItem menuItem = new MruMenuItem(filename, FixupEntryname(0, entryname), new System.EventHandler(OnClick));
MenuItems.Add(StartIndex, menuItem);
SetFirstFile(menuItem);
if (numEntries++ == 0)
{
Enable();
}
else
{
FixupPrefixes(1);
}
}
else if (numEntries > 1)
{
MruMenuItem menuItem = (MruMenuItem) MenuItems[StartIndex + numEntries - 1];
menuItem.Text = FixupEntryname(0, entryname);
menuItem.Filename = filename;
menuItem.Index = StartIndex;
SetFirstFile(menuItem);
FixupPrefixes(1);
}
}
#endregion
#region Remove Methods
public void RemoveFile(int number)
{
if (number >= 0 && number < numEntries)
{
if (--numEntries == 0)
{
Disable();
}
else
{
int startIndex = StartIndex;
if (number == 0)
{
SetFirstFile(MenuItems[startIndex + 1]);
}
MenuItems.RemoveAt(startIndex + number);
if (number < numEntries)
{
FixupPrefixes(number);
}
}
}
}
public void RemoveFile(String filename)
{
if (numEntries > 0)
{
RemoveFile(FindFilenameNumber(filename));
}
}
public void RemoveAll()
{
if (numEntries > 0)
{
for (int index = EndIndex - 1; index > StartIndex; index--)
{
MenuItems.RemoveAt(index);
}
Disable();
numEntries = 0;
}
}
#endregion
#region Registry Methods
public String RegistryKeyName
{
get
{
return registryKeyName;
}
set
{
registryKeyName = value.Trim();
if (registryKeyName.Length == 0)
{
registryKeyName = null;
}
}
}
public void LoadFromRegistry(String keyName)
{
RegistryKeyName = keyName;
LoadFromRegistry();
}
public void LoadFromRegistry()
{
if (registryKeyName != null)
{
RemoveAll();
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(registryKeyName);
if (regKey != null)
{
maxEntries = (int)regKey.GetValue("max", maxEntries);
for (int number = maxEntries; number > 0; number--)
{
String filename = (String)regKey.GetValue("File" + number.ToString());
if (filename != null)
AddFile(filename);
}
regKey.Close();
}
}
}
public void SaveToRegistry(String keyName)
{
RegistryKeyName = keyName;
SaveToRegistry();
}
public void SaveToRegistry()
{
if (registryKeyName != null)
{
RegistryKey regKey = Registry.CurrentUser.CreateSubKey(registryKeyName);
if (regKey != null)
{
regKey.SetValue("max", maxEntries);
int number = 1;
int i = StartIndex;
for (; i < EndIndex; i++, number++)
{
regKey.SetValue("File" + number.ToString(), ((MruMenuItem)MenuItems[i]).Filename);
}
for (; number <= 16; number++)
{
regKey.DeleteValue("File" + number.ToString(), false);
}
regKey.Close();
}
}
}
#endregion
}
public class MruMenuInline : MruMenu
{
protected MenuItem firstMenuItem;
/// <summary>
/// MruMenuInline shows the MRU list inline (without a popup)
/// </summary>
#region Construction
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, null, false, 4);
}
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, int _maxEntries)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, null, false, _maxEntries);
}
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, true, 4);
}
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, int _maxEntries)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, _registryKeyName, true, _maxEntries);
}
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, bool loadFromRegistry)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, _registryKeyName,loadFromRegistry, 4);
}
public MruMenuInline(MenuItem _recentFileMenuItem, ClickedHandler _clickedHandler, String _registryKeyName, bool loadFromRegistry, int _maxEntries)
{
maxShortenPathLength = 128;
firstMenuItem = _recentFileMenuItem;
base.Init(_recentFileMenuItem, _clickedHandler, _registryKeyName,loadFromRegistry, _maxEntries);
}
#endregion
#region Overridden Properties
public override Menu.MenuItemCollection MenuItems
{
get
{
return firstMenuItem.Parent.MenuItems;
}
}
public override int StartIndex
{
get
{
return firstMenuItem.Index;
}
}
public override int EndIndex
{
get
{
return StartIndex + numEntries;
}
}
#endregion
#region Overridden Methods
protected override void Enable()
{
MenuItems.Remove(recentFileMenuItem);
}
protected override void SetFirstFile(MenuItem menuItem)
{
firstMenuItem = menuItem;
}
protected override void Disable()
{
MenuItems.Add(firstMenuItem.Index, recentFileMenuItem);
MenuItems.Remove(firstMenuItem);
firstMenuItem = recentFileMenuItem;
}
#endregion
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace System
{
// Provides Unix-based support for System.Console.
//
// NOTE: The test class reflects over this class to run the tests due to limitations in
// the test infrastructure that prevent OS-specific builds of test binaries. If you
// change any of the class / struct / function names, parameters, etc then you need
// to also change the test class.
internal static class ConsolePal
{
public static Stream OpenStandardInput()
{
return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDIN_FILENO)), FileAccess.Read);
}
public static Stream OpenStandardOutput()
{
return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDOUT_FILENO)), FileAccess.Write);
}
public static Stream OpenStandardError()
{
return new UnixConsoleStream(SafeFileHandleHelper.Open(() => Interop.Sys.Dup(Interop.Sys.FileDescriptors.STDERR_FILENO)), FileAccess.Write);
}
public static Encoding InputEncoding
{
get { return GetConsoleEncoding(); }
}
public static Encoding OutputEncoding
{
get { return GetConsoleEncoding(); }
}
private static SyncTextReader s_stdInReader;
private const int DefaultBufferSize = 255;
private static SyncTextReader StdInReader
{
get
{
EnsureInitialized();
return Volatile.Read(ref s_stdInReader) ??
Console.EnsureInitialized(
ref s_stdInReader,
() => SyncTextReader.GetSynchronizedTextReader(
new StdInReader(
encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream.
bufferSize: DefaultBufferSize)));
}
}
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
internal static TextReader GetOrCreateReader()
{
if (Console.IsInputRedirected)
{
Stream inputStream = OpenStandardInput();
return SyncTextReader.GetSynchronizedTextReader(
inputStream == Stream.Null ?
StreamReader.Null :
new StreamReader(
stream: inputStream,
encoding: new ConsoleEncoding(Console.InputEncoding), // This ensures no prefix is written to the stream.
detectEncodingFromByteOrderMarks: false,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true)
);
}
else
{
return StdInReader;
}
}
public static bool KeyAvailable { get { return StdInReader.KeyAvailable; } }
public static ConsoleKeyInfo ReadKey(bool intercept)
{
if (Console.IsInputRedirected)
{
// We could leverage Console.Read() here however
// windows fails when stdin is redirected.
throw new InvalidOperationException(SR.InvalidOperation_ConsoleReadKeyOnFile);
}
bool previouslyProcessed;
ConsoleKeyInfo keyInfo = StdInReader.ReadKey(out previouslyProcessed);
if (!intercept && !previouslyProcessed) Console.Write(keyInfo.KeyChar);
return keyInfo;
}
public static bool TreatControlCAsInput
{
get
{
if (Console.IsInputRedirected)
return false;
EnsureInitialized();
return !Interop.Sys.GetSignalForBreak();
}
set
{
if (!Console.IsInputRedirected)
{
EnsureInitialized();
if (!Interop.Sys.SetSignalForBreak(signalForBreak: !value))
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
}
}
private static ConsoleColor s_trackedForegroundColor = Console.UnknownColor;
private static ConsoleColor s_trackedBackgroundColor = Console.UnknownColor;
public static ConsoleColor ForegroundColor
{
get { return s_trackedForegroundColor; }
set { RefreshColors(ref s_trackedForegroundColor, value); }
}
public static ConsoleColor BackgroundColor
{
get { return s_trackedBackgroundColor; }
set { RefreshColors(ref s_trackedBackgroundColor, value); }
}
public static void ResetColor()
{
lock (Console.Out) // synchronize with other writers
{
s_trackedForegroundColor = Console.UnknownColor;
s_trackedBackgroundColor = Console.UnknownColor;
WriteResetColorString();
}
}
public static bool NumberLock { get { throw new PlatformNotSupportedException(); } }
public static bool CapsLock { get { throw new PlatformNotSupportedException(); } }
public static int CursorSize
{
get { return 100; }
set { throw new PlatformNotSupportedException(); }
}
public static string Title
{
get { throw new PlatformNotSupportedException(); }
set
{
if (Console.IsOutputRedirected)
return;
string titleFormat = TerminalFormatStrings.Instance.Title;
if (!string.IsNullOrEmpty(titleFormat))
{
string ansiStr = TermInfo.ParameterizedStrings.Evaluate(titleFormat, value);
WriteStdoutAnsiString(ansiStr);
}
}
}
public static void Beep()
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Bell);
}
}
public static void Beep(int frequency, int duration)
{
throw new PlatformNotSupportedException();
}
public static void Clear()
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Clear);
}
}
public static void SetCursorPosition(int left, int top)
{
if (Console.IsOutputRedirected)
return;
string cursorAddressFormat = TerminalFormatStrings.Instance.CursorAddress;
if (!string.IsNullOrEmpty(cursorAddressFormat))
{
string ansiStr = TermInfo.ParameterizedStrings.Evaluate(cursorAddressFormat, top, left);
WriteStdoutAnsiString(ansiStr);
}
}
public static int BufferWidth
{
get { return WindowWidth; }
set { throw new PlatformNotSupportedException(); }
}
public static int BufferHeight
{
get { return WindowHeight; }
set { throw new PlatformNotSupportedException(); }
}
public static void SetBufferSize(int width, int height)
{
throw new PlatformNotSupportedException();
}
public static int LargestWindowWidth
{
get { return WindowWidth; }
set { throw new PlatformNotSupportedException(); }
}
public static int LargestWindowHeight
{
get { return WindowHeight; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowLeft
{
get { return 0; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowTop
{
get { return 0; }
set { throw new PlatformNotSupportedException(); }
}
public static int WindowWidth
{
get
{
Interop.Sys.WinSize winsize;
return Interop.Sys.GetWindowSize(out winsize) == 0 ?
winsize.Col :
TerminalFormatStrings.Instance.Columns;
}
set { throw new PlatformNotSupportedException(); }
}
public static int WindowHeight
{
get
{
Interop.Sys.WinSize winsize;
return Interop.Sys.GetWindowSize(out winsize) == 0 ?
winsize.Row :
TerminalFormatStrings.Instance.Lines;
}
set { throw new PlatformNotSupportedException(); }
}
public static void SetWindowPosition(int left, int top)
{
throw new PlatformNotSupportedException();
}
public static void SetWindowSize(int width, int height)
{
throw new PlatformNotSupportedException();
}
public static bool CursorVisible
{
get { throw new PlatformNotSupportedException(); }
set
{
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(value ?
TerminalFormatStrings.Instance.CursorVisible :
TerminalFormatStrings.Instance.CursorInvisible);
}
}
}
// TODO: It's quite expensive to use the request/response protocol each time CursorLeft/Top is accessed.
// We should be able to (mostly) track the position of the cursor in locals, doing the request/response infrequently.
public static int CursorLeft
{
get
{
int left, top;
GetCursorPosition(out left, out top);
return left;
}
}
public static int CursorTop
{
get
{
int left, top;
GetCursorPosition(out left, out top);
return top;
}
}
/// <summary>Gets the current cursor position. This involves both writing to stdout and reading stdin.</summary>
private static unsafe void GetCursorPosition(out int left, out int top)
{
left = top = 0;
// Getting the cursor position involves both writing out a request string and
// parsing a response string from the terminal. So if anything is redirected, bail.
if (Console.IsInputRedirected || Console.IsOutputRedirected)
return;
// Get the cursor position request format string.
Debug.Assert(!string.IsNullOrEmpty(TerminalFormatStrings.CursorPositionReport));
// Synchronize with all other stdin readers. We need to do this in case multiple threads are
// trying to read/write concurrently, and to minimize the chances of resulting conflicts.
// This does mean that Console.get_CursorLeft/Top can't be used concurrently Console.Read*, etc.;
// attempting to do so will block one of them until the other completes, but in doing so we prevent
// one thread's get_CursorLeft/Top from providing input to the other's Console.Read*.
lock (StdInReader)
{
Interop.Sys.InitializeConsoleBeforeRead(minChars: 0, decisecondsTimeout: 10);
try
{
// Write out the cursor position report request.
WriteStdoutAnsiString(TerminalFormatStrings.CursorPositionReport);
// Read the cursor position report reponse, of the form \ESC[row;colR. There's a race
// condition here if the user is typing, or if other threads are accessing the console;
// to try to avoid losing such data, we push unexpected inputs into the stdin buffer, but
// even with that, there's a potential that we could misinterpret data from the user as
// being part of the cursor position response. This is inherent to the nature of the protocol.
StdInReader r = StdInReader.Inner;
byte b;
while (true) // \ESC
{
if (r.ReadStdin(&b, 1) != 1) return;
if (b == 0x1B) break;
r.AppendExtraBuffer(&b, 1);
}
while (true) // [
{
if (r.ReadStdin(&b, 1) != 1) return;
if (b == '[') break;
r.AppendExtraBuffer(&b, 1);
}
try
{
int row = 0;
while (true) // row until ';'
{
if (r.ReadStdin(&b, 1) != 1) return;
if (b == ';') break;
if (IsDigit((char)b))
{
row = checked((row * 10) + (b - '0'));
}
else
{
r.AppendExtraBuffer(&b, 1);
}
}
if (row >= 1) top = row - 1;
int col = 0;
while (true) // col until 'R'
{
if (r.ReadStdin(&b, 1) == 0) return;
if (b == 'R') break;
if (IsDigit((char)b))
{
col = checked((col * 10) + (b - '0'));
}
else
{
r.AppendExtraBuffer(&b, 1);
}
}
if (col >= 1) left = col - 1;
}
catch (OverflowException) { return; }
}
finally
{
Interop.Sys.UninitializeConsoleAfterRead();
}
}
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
throw new PlatformNotSupportedException();
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
throw new PlatformNotSupportedException();
}
/// <summary>Gets whether the specified character is a digit 0-9.</summary>
private static bool IsDigit(char c) { return c >= '0' && c <= '9'; }
/// <summary>
/// Gets whether the specified file descriptor was redirected.
/// It's considered redirected if it doesn't refer to a terminal.
/// </summary>
private static bool IsHandleRedirected(SafeFileHandle fd)
{
return !Interop.Sys.IsATty(fd);
}
/// <summary>
/// Gets whether Console.In is redirected.
/// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsInputRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDIN_FILENO);
}
/// <summary>Gets whether Console.Out is redirected.
/// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsOutputRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDOUT_FILENO);
}
/// <summary>Gets whether Console.Error is redirected.
/// We approximate the behavior by checking whether the underlying stream is our UnixConsoleStream and it's wrapping a character device.
/// </summary>
public static bool IsErrorRedirectedCore()
{
return IsHandleRedirected(Interop.Sys.FileDescriptors.STDERR_FILENO);
}
/// <summary>Creates an encoding from the current environment.</summary>
/// <returns>The encoding.</returns>
private static Encoding GetConsoleEncoding()
{
Encoding enc = EncodingHelper.GetEncodingFromCharset();
return enc ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
}
public static void SetConsoleInputEncoding(Encoding enc)
{
// No-op.
// There is no good way to set the terminal console encoding.
}
public static void SetConsoleOutputEncoding(Encoding enc)
{
// No-op.
// There is no good way to set the terminal console encoding.
}
/// <summary>
/// Refreshes the foreground and background colors in use by the terminal by resetting
/// the colors and then reissuing commands for both foreground and background, if necessary.
/// Before doing so, the <paramref name="toChange"/> ref is changed to <paramref name="value"/>
/// if <paramref name="value"/> is valid.
/// </summary>
private static void RefreshColors(ref ConsoleColor toChange, ConsoleColor value)
{
if (((int)value & ~0xF) != 0 && value != Console.UnknownColor)
{
throw new ArgumentException(SR.Arg_InvalidConsoleColor);
}
lock (Console.Out)
{
toChange = value; // toChange is either s_trackedForegroundColor or s_trackedBackgroundColor
WriteResetColorString();
if (s_trackedForegroundColor != Console.UnknownColor)
{
WriteSetColorString(foreground: true, color: s_trackedForegroundColor);
}
if (s_trackedBackgroundColor != Console.UnknownColor)
{
WriteSetColorString(foreground: false, color: s_trackedBackgroundColor);
}
}
}
/// <summary>Outputs the format string evaluated and parameterized with the color.</summary>
/// <param name="foreground">true for foreground; false for background.</param>
/// <param name="color">The color to store into the field and to use as an argument to the format string.</param>
private static void WriteSetColorString(bool foreground, ConsoleColor color)
{
// Changing the color involves writing an ANSI character sequence out to the output stream.
// We only want to do this if we know that sequence will be interpreted by the output.
// rather than simply displayed visibly.
if (Console.IsOutputRedirected)
return;
// See if we've already cached a format string for this foreground/background
// and specific color choice. If we have, just output that format string again.
int fgbgIndex = foreground ? 0 : 1;
int ccValue = (int)color;
string evaluatedString = s_fgbgAndColorStrings[fgbgIndex, ccValue]; // benign race
if (evaluatedString != null)
{
WriteStdoutAnsiString(evaluatedString);
return;
}
// We haven't yet computed a format string. Compute it, use it, then cache it.
string formatString = foreground ? TerminalFormatStrings.Instance.Foreground : TerminalFormatStrings.Instance.Background;
if (!string.IsNullOrEmpty(formatString))
{
int maxColors = TerminalFormatStrings.Instance.MaxColors; // often 8 or 16; 0 is invalid
if (maxColors > 0)
{
int ansiCode = _consoleColorToAnsiCode[ccValue] % maxColors;
evaluatedString = TermInfo.ParameterizedStrings.Evaluate(formatString, ansiCode);
WriteStdoutAnsiString(evaluatedString);
s_fgbgAndColorStrings[fgbgIndex, ccValue] = evaluatedString; // benign race
}
}
}
/// <summary>Writes out the ANSI string to reset colors.</summary>
private static void WriteResetColorString()
{
// We only want to send the reset string if we're targeting a TTY device
if (!Console.IsOutputRedirected)
{
WriteStdoutAnsiString(TerminalFormatStrings.Instance.Reset);
}
}
/// <summary>
/// The values of the ConsoleColor enums unfortunately don't map to the
/// corresponding ANSI values. We need to do the mapping manually.
/// See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
/// </summary>
private static readonly int[] _consoleColorToAnsiCode = new int[]
{
// Dark/Normal colors
0, // Black,
4, // DarkBlue,
2, // DarkGreen,
6, // DarkCyan,
1, // DarkRed,
5, // DarkMagenta,
3, // DarkYellow,
7, // Gray,
// Bright colors
8, // DarkGray,
12, // Blue,
10, // Green,
14, // Cyan,
9, // Red,
13, // Magenta,
11, // Yellow,
15 // White
};
/// <summary>Cache of the format strings for foreground/background and ConsoleColor.</summary>
private static readonly string[,] s_fgbgAndColorStrings = new string[2, 16]; // 2 == fg vs bg, 16 == ConsoleColor values
public static bool TryGetSpecialConsoleKey(char[] givenChars, int startIndex, int endIndex, out ConsoleKeyInfo key, out int keyLength)
{
int unprocessedCharCount = endIndex - startIndex;
// First process special control character codes. These override anything from terminfo.
if (unprocessedCharCount > 0)
{
// Is this an erase / backspace?
char c = givenChars[startIndex];
if (c != s_posixDisableValue && c == s_veraseCharacter)
{
key = new ConsoleKeyInfo(c, ConsoleKey.Backspace, shift: false, alt: false, control: false);
keyLength = 1;
return true;
}
}
// Then process terminfo mappings.
int minRange = TerminalFormatStrings.Instance.MinKeyFormatLength;
if (unprocessedCharCount >= minRange)
{
int maxRange = Math.Min(unprocessedCharCount, TerminalFormatStrings.Instance.MaxKeyFormatLength);
for (int i = maxRange; i >= minRange; i--)
{
var currentString = new StringOrCharArray(givenChars, startIndex, i);
// Check if the string prefix matches.
if (TerminalFormatStrings.Instance.KeyFormatToConsoleKey.TryGetValue(currentString, out key))
{
keyLength = currentString.Length;
return true;
}
}
}
// Otherwise, not a known special console key.
key = default(ConsoleKeyInfo);
keyLength = 0;
return false;
}
/// <summary>Whether keypad_xmit has already been written out to the terminal.</summary>
private static volatile bool s_initialized;
/// <summary>Value used to indicate that a special character code isn't available.</summary>
internal static byte s_posixDisableValue;
/// <summary>Special control character code used to represent an erase (backspace).</summary>
private static byte s_veraseCharacter;
/// <summary>Special control character that represents the end of a line.</summary>
internal static byte s_veolCharacter;
/// <summary>Special control character that represents the end of a line.</summary>
internal static byte s_veol2Character;
/// <summary>Special control character that represents the end of a file.</summary>
internal static byte s_veofCharacter;
/// <summary>Ensures that the console has been initialized for use.</summary>
private static void EnsureInitialized()
{
if (!s_initialized)
{
EnsureInitializedCore(); // factored out for inlinability
}
}
/// <summary>Ensures that the console has been initialized for use.</summary>
private static void EnsureInitializedCore()
{
lock (Console.Out) // ensure that writing the ANSI string and setting initialized to true are done atomically
{
if (!s_initialized)
{
// Ensure the console is configured appropriately. This will start
// signal handlers, etc.
if (!Interop.Sys.InitializeConsole())
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
}
// Provide the native lib with the correct code from the terminfo to transition us into
// "application mode". This will both transition it immediately, as well as allow
// the native lib later to handle signals that require re-entering the mode.
if (!Console.IsOutputRedirected)
{
string keypadXmit = TerminalFormatStrings.Instance.KeypadXmit;
if (keypadXmit != null)
{
Interop.Sys.SetKeypadXmit(keypadXmit);
}
}
// Load special control character codes used for input processing
var controlCharacterNames = new Interop.Sys.ControlCharacterNames[4]
{
Interop.Sys.ControlCharacterNames.VERASE,
Interop.Sys.ControlCharacterNames.VEOL,
Interop.Sys.ControlCharacterNames.VEOL2,
Interop.Sys.ControlCharacterNames.VEOF
};
var controlCharacterValues = new byte[controlCharacterNames.Length];
Interop.Sys.GetControlCharacters(controlCharacterNames, controlCharacterValues, controlCharacterNames.Length, out s_posixDisableValue);
s_veraseCharacter = controlCharacterValues[0];
s_veolCharacter = controlCharacterValues[1];
s_veol2Character = controlCharacterValues[2];
s_veofCharacter = controlCharacterValues[3];
// Mark us as initialized
s_initialized = true;
}
}
}
/// <summary>Provides format strings and related information for use with the current terminal.</summary>
internal class TerminalFormatStrings
{
/// <summary>Gets the lazily-initialized terminal information for the terminal.</summary>
public static TerminalFormatStrings Instance { get { return s_instance.Value; } }
private static readonly Lazy<TerminalFormatStrings> s_instance = new Lazy<TerminalFormatStrings>(() => new TerminalFormatStrings(TermInfo.Database.ReadActiveDatabase()));
/// <summary>The format string to use to change the foreground color.</summary>
public readonly string Foreground;
/// <summary>The format string to use to change the background color.</summary>
public readonly string Background;
/// <summary>The format string to use to reset the foreground and background colors.</summary>
public readonly string Reset;
/// <summary>The maximum number of colors supported by the terminal.</summary>
public readonly int MaxColors;
/// <summary>The number of columns in a format.</summary>
public readonly int Columns;
/// <summary>The number of lines in a format.</summary>
public readonly int Lines;
/// <summary>The format string to use to make cursor visible.</summary>
public readonly string CursorVisible;
/// <summary>The format string to use to make cursor invisible</summary>
public readonly string CursorInvisible;
/// <summary>The format string to use to set the window title.</summary>
public readonly string Title;
/// <summary>The format string to use for an audible bell.</summary>
public readonly string Bell;
/// <summary>The format string to use to clear the terminal.</summary>
public readonly string Clear;
/// <summary>The format string to use to set the position of the cursor.</summary>
public readonly string CursorAddress;
/// <summary>The format string to use to move the cursor to the left.</summary>
public readonly string CursorLeft;
/// <summary>The ANSI-compatible string for the Cursor Position report request.</summary>
/// <remarks>
/// This should really be in user string 7 in the terminfo file, but some terminfo databases
/// are missing it. As this is defined to be supported by any ANSI-compatible terminal,
/// we assume it's available; doing so means CursorTop/Left will work even if the terminfo database
/// doesn't contain it (as appears to be the case with e.g. screen and tmux on Ubuntu), at the risk
/// of outputting the sequence on some terminal that's not compatible.
/// </remarks>
public const string CursorPositionReport = "\x1B[6n";
/// <summary>
/// The dictionary of keystring to ConsoleKeyInfo.
/// Only some members of the ConsoleKeyInfo are used; in particular, the actual char is ignored.
/// </summary>
public readonly Dictionary<StringOrCharArray, ConsoleKeyInfo> KeyFormatToConsoleKey = new Dictionary<StringOrCharArray, ConsoleKeyInfo>();
/// <summary> Max key length </summary>
public readonly int MaxKeyFormatLength;
/// <summary> Min key length </summary>
public readonly int MinKeyFormatLength;
/// <summary>The ANSI string used to enter "application" / "keypad transmit" mode.</summary>
public readonly string KeypadXmit;
public TerminalFormatStrings(TermInfo.Database db)
{
if (db == null)
return;
KeypadXmit = db.GetString(TermInfo.WellKnownStrings.KeypadXmit);
Foreground = db.GetString(TermInfo.WellKnownStrings.SetAnsiForeground);
Background = db.GetString(TermInfo.WellKnownStrings.SetAnsiBackground);
Reset = db.GetString(TermInfo.WellKnownStrings.OrigPairs) ?? db.GetString(TermInfo.WellKnownStrings.OrigColors);
Bell = db.GetString(TermInfo.WellKnownStrings.Bell);
Clear = db.GetString(TermInfo.WellKnownStrings.Clear);
Columns = db.GetNumber(TermInfo.WellKnownNumbers.Columns);
Lines = db.GetNumber(TermInfo.WellKnownNumbers.Lines);
CursorVisible = db.GetString(TermInfo.WellKnownStrings.CursorVisible);
CursorInvisible = db.GetString(TermInfo.WellKnownStrings.CursorInvisible);
CursorAddress = db.GetString(TermInfo.WellKnownStrings.CursorAddress);
CursorLeft = db.GetString(TermInfo.WellKnownStrings.CursorLeft);
Title = GetTitle(db);
Debug.WriteLineIf(db.GetString(TermInfo.WellKnownStrings.CursorPositionReport) != CursorPositionReport,
"Getting the cursor position will only work if the terminal supports the CPR sequence," +
"but the terminfo database does not contain an entry for it.");
int maxColors = db.GetNumber(TermInfo.WellKnownNumbers.MaxColors);
MaxColors = // normalize to either the full range of all ANSI colors, just the dark ones, or none
maxColors >= 16 ? 16 :
maxColors >= 8 ? 8 :
0;
AddKey(db, TermInfo.WellKnownStrings.KeyF1, ConsoleKey.F1);
AddKey(db, TermInfo.WellKnownStrings.KeyF2, ConsoleKey.F2);
AddKey(db, TermInfo.WellKnownStrings.KeyF3, ConsoleKey.F3);
AddKey(db, TermInfo.WellKnownStrings.KeyF4, ConsoleKey.F4);
AddKey(db, TermInfo.WellKnownStrings.KeyF5, ConsoleKey.F5);
AddKey(db, TermInfo.WellKnownStrings.KeyF6, ConsoleKey.F6);
AddKey(db, TermInfo.WellKnownStrings.KeyF7, ConsoleKey.F7);
AddKey(db, TermInfo.WellKnownStrings.KeyF8, ConsoleKey.F8);
AddKey(db, TermInfo.WellKnownStrings.KeyF9, ConsoleKey.F9);
AddKey(db, TermInfo.WellKnownStrings.KeyF10, ConsoleKey.F10);
AddKey(db, TermInfo.WellKnownStrings.KeyF11, ConsoleKey.F11);
AddKey(db, TermInfo.WellKnownStrings.KeyF12, ConsoleKey.F12);
AddKey(db, TermInfo.WellKnownStrings.KeyF13, ConsoleKey.F13);
AddKey(db, TermInfo.WellKnownStrings.KeyF14, ConsoleKey.F14);
AddKey(db, TermInfo.WellKnownStrings.KeyF15, ConsoleKey.F15);
AddKey(db, TermInfo.WellKnownStrings.KeyF16, ConsoleKey.F16);
AddKey(db, TermInfo.WellKnownStrings.KeyF17, ConsoleKey.F17);
AddKey(db, TermInfo.WellKnownStrings.KeyF18, ConsoleKey.F18);
AddKey(db, TermInfo.WellKnownStrings.KeyF19, ConsoleKey.F19);
AddKey(db, TermInfo.WellKnownStrings.KeyF20, ConsoleKey.F20);
AddKey(db, TermInfo.WellKnownStrings.KeyF21, ConsoleKey.F21);
AddKey(db, TermInfo.WellKnownStrings.KeyF22, ConsoleKey.F22);
AddKey(db, TermInfo.WellKnownStrings.KeyF23, ConsoleKey.F23);
AddKey(db, TermInfo.WellKnownStrings.KeyF24, ConsoleKey.F24);
AddKey(db, TermInfo.WellKnownStrings.KeyBackspace, ConsoleKey.Backspace);
AddKey(db, TermInfo.WellKnownStrings.KeyBackTab, ConsoleKey.Tab, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyBegin, ConsoleKey.Home);
AddKey(db, TermInfo.WellKnownStrings.KeyClear, ConsoleKey.Clear);
AddKey(db, TermInfo.WellKnownStrings.KeyDelete, ConsoleKey.Delete);
AddKey(db, TermInfo.WellKnownStrings.KeyDown, ConsoleKey.DownArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyEnd, ConsoleKey.End);
AddKey(db, TermInfo.WellKnownStrings.KeyEnter, ConsoleKey.Enter);
AddKey(db, TermInfo.WellKnownStrings.KeyHelp, ConsoleKey.Help);
AddKey(db, TermInfo.WellKnownStrings.KeyHome, ConsoleKey.Home);
AddKey(db, TermInfo.WellKnownStrings.KeyInsert, ConsoleKey.Insert);
AddKey(db, TermInfo.WellKnownStrings.KeyLeft, ConsoleKey.LeftArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyPageDown, ConsoleKey.PageDown);
AddKey(db, TermInfo.WellKnownStrings.KeyPageUp, ConsoleKey.PageUp);
AddKey(db, TermInfo.WellKnownStrings.KeyPrint, ConsoleKey.Print);
AddKey(db, TermInfo.WellKnownStrings.KeyRight, ConsoleKey.RightArrow);
AddKey(db, TermInfo.WellKnownStrings.KeyScrollForward, ConsoleKey.PageDown, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyScrollReverse, ConsoleKey.PageUp, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySBegin, ConsoleKey.Home, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySDelete, ConsoleKey.Delete, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySHome, ConsoleKey.Home, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySelect, ConsoleKey.Select);
AddKey(db, TermInfo.WellKnownStrings.KeySLeft, ConsoleKey.LeftArrow, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySPrint, ConsoleKey.Print, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeySRight, ConsoleKey.RightArrow, shift: true, alt: false, control: false);
AddKey(db, TermInfo.WellKnownStrings.KeyUp, ConsoleKey.UpArrow);
AddPrefixKey(db, "kLFT", ConsoleKey.LeftArrow);
AddPrefixKey(db, "kRIT", ConsoleKey.RightArrow);
AddPrefixKey(db, "kUP", ConsoleKey.UpArrow);
AddPrefixKey(db, "kDN", ConsoleKey.DownArrow);
AddPrefixKey(db, "kDC", ConsoleKey.Delete);
AddPrefixKey(db, "kEND", ConsoleKey.End);
AddPrefixKey(db, "kHOM", ConsoleKey.Home);
AddPrefixKey(db, "kNXT", ConsoleKey.PageDown);
AddPrefixKey(db, "kPRV", ConsoleKey.PageUp);
if (KeyFormatToConsoleKey.Count > 0)
{
MaxKeyFormatLength = int.MinValue;
MinKeyFormatLength = int.MaxValue;
foreach (KeyValuePair<StringOrCharArray, ConsoleKeyInfo> entry in KeyFormatToConsoleKey)
{
if (entry.Key.Length > MaxKeyFormatLength)
{
MaxKeyFormatLength = entry.Key.Length;
}
if (entry.Key.Length < MinKeyFormatLength)
{
MinKeyFormatLength = entry.Key.Length;
}
}
}
}
private static string GetTitle(TermInfo.Database db)
{
// Try to get the format string from tsl/fsl and use it if they're available
string tsl = db.GetString(TermInfo.WellKnownStrings.ToStatusLine);
string fsl = db.GetString(TermInfo.WellKnownStrings.FromStatusLine);
if (tsl != null && fsl != null)
{
return tsl + "%p1%s" + fsl;
}
string term = db.Term;
if (term == null)
{
return string.Empty;
}
if (term.StartsWith("xterm", StringComparison.Ordinal)) // normalize all xterms to enable easier matching
{
term = "xterm";
}
switch (term)
{
case "aixterm":
case "dtterm":
case "linux":
case "rxvt":
case "xterm":
return "\x1B]0;%p1%s\x07";
case "cygwin":
return "\x1B];%p1%s\x07";
case "konsole":
return "\x1B]30;%p1%s\x07";
case "screen":
return "\x1Bk%p1%s\x1B";
default:
return string.Empty;
}
}
private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key)
{
AddKey(db, keyId, key, shift: false, alt: false, control: false);
}
private void AddKey(TermInfo.Database db, TermInfo.WellKnownStrings keyId, ConsoleKey key, bool shift, bool alt, bool control)
{
string keyFormat = db.GetString(keyId);
if (!string.IsNullOrEmpty(keyFormat))
KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control);
}
private void AddPrefixKey(TermInfo.Database db, string extendedNamePrefix, ConsoleKey key)
{
AddKey(db, extendedNamePrefix + "3", key, shift: false, alt: true, control: false);
AddKey(db, extendedNamePrefix + "4", key, shift: true, alt: true, control: false);
AddKey(db, extendedNamePrefix + "5", key, shift: false, alt: false, control: true);
AddKey(db, extendedNamePrefix + "6", key, shift: true, alt: false, control: true);
AddKey(db, extendedNamePrefix + "7", key, shift: false, alt: false, control: true);
}
private void AddKey(TermInfo.Database db, string extendedName, ConsoleKey key, bool shift, bool alt, bool control)
{
string keyFormat = db.GetExtendedString(extendedName);
if (!string.IsNullOrEmpty(keyFormat))
KeyFormatToConsoleKey[keyFormat] = new ConsoleKeyInfo('\0', key, shift, alt, control);
}
}
/// <summary>Reads data from the file descriptor into the buffer.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="offset">The offset at which to start writing into the buffer.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <returns>The number of bytes read, or a negative value if there's an error.</returns>
internal static unsafe int Read(SafeFileHandle fd, byte[] buffer, int offset, int count)
{
fixed (byte* bufPtr = buffer)
{
int result = Interop.CheckIo(Interop.Sys.Read(fd, (byte*)bufPtr + offset, count));
Debug.Assert(result <= count);
return result;
}
}
/// <summary>Writes data from the buffer into the file descriptor.</summary>
/// <param name="fd">The file descriptor.</param>
/// <param name="buffer">The buffer from which to write data.</param>
/// <param name="offset">The offset at which the data to write starts in the buffer.</param>
/// <param name="count">The number of bytes to write.</param>
private static unsafe void Write(SafeFileHandle fd, byte[] buffer, int offset, int count)
{
fixed (byte* bufPtr = buffer)
{
Write(fd, bufPtr + offset, count);
}
}
private static unsafe void Write(SafeFileHandle fd, byte* bufPtr, int count)
{
while (count > 0)
{
int bytesWritten = Interop.Sys.Write(fd, bufPtr, count);
if (bytesWritten < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
{
// Broken pipe... likely due to being redirected to a program
// that ended, so simply pretend we were successful.
return;
}
else
{
// Something else... fail.
throw Interop.GetExceptionForIoErrno(errorInfo);
}
}
count -= bytesWritten;
bufPtr += bytesWritten;
}
}
/// <summary>Writes a terminfo-based ANSI escape string to stdout.</summary>
/// <param name="value">The string to write.</param>
private static unsafe void WriteStdoutAnsiString(string value)
{
if (string.IsNullOrEmpty(value))
return;
// Except for extremely rare cases, ANSI escape strings should be very short.
const int StackAllocThreshold = 256;
if (value.Length <= StackAllocThreshold)
{
int dataLen = Encoding.UTF8.GetMaxByteCount(value.Length);
byte* data = stackalloc byte[dataLen];
fixed (char* chars = value)
{
int bytesToWrite = Encoding.UTF8.GetBytes(chars, value.Length, data, dataLen);
Debug.Assert(bytesToWrite <= dataLen);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, bytesToWrite);
}
}
}
else
{
byte[] data = Encoding.UTF8.GetBytes(value);
lock (Console.Out) // synchronize with other writers
{
Write(Interop.Sys.FileDescriptors.STDOUT_FILENO, data, 0, data.Length);
}
}
}
/// <summary>Provides a stream to use for Unix console input or output.</summary>
private sealed class UnixConsoleStream : ConsoleStream
{
/// <summary>The file descriptor for the opened file.</summary>
private readonly SafeFileHandle _handle;
/// <summary>The type of the underlying file descriptor.</summary>
internal readonly int _handleType;
/// <summary>Initialize the stream.</summary>
/// <param name="handle">The file handle wrapped by this stream.</param>
/// <param name="access">FileAccess.Read or FileAccess.Write.</param>
internal UnixConsoleStream(SafeFileHandle handle, FileAccess access)
: base(access)
{
Debug.Assert(handle != null, "Expected non-null console handle");
Debug.Assert(!handle.IsInvalid, "Expected valid console handle");
_handle = handle;
// Determine the type of the descriptor (e.g. regular file, character file, pipe, etc.)
Interop.Sys.FileStatus buf;
_handleType =
Interop.Sys.FStat(_handle, out buf) == 0 ?
(buf.Mode & Interop.Sys.FileTypes.S_IFMT) :
Interop.Sys.FileTypes.S_IFREG; // if something goes wrong, don't fail, just say it's a regular file
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_handle.Dispose();
}
base.Dispose(disposing);
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateRead(buffer, offset, count);
return ConsolePal.Read(_handle, buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
ValidateWrite(buffer, offset, count);
ConsolePal.Write(_handle, buffer, offset, count);
}
public override void Flush()
{
if (_handle.IsClosed)
{
throw Error.GetFileNotOpen();
}
base.Flush();
}
}
internal sealed class ControlCHandlerRegistrar
{
private static readonly Interop.Sys.CtrlCallback _handler =
c => Console.HandleBreakEvent(c == Interop.Sys.CtrlCode.Break ? ConsoleSpecialKey.ControlBreak : ConsoleSpecialKey.ControlC);
private bool _handlerRegistered;
internal void Register()
{
EnsureInitialized();
Debug.Assert(!_handlerRegistered);
Interop.Sys.RegisterForCtrl(_handler);
_handlerRegistered = true;
}
internal void Unregister()
{
Debug.Assert(_handlerRegistered);
_handlerRegistered = false;
Interop.Sys.UnregisterForCtrl();
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Numerics.Tests
{
public class QuaternionTests
{
// A test for Dot (Quaternion, Quaternion)
[Fact]
public void QuaternionDotTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
float expected = 70.0f;
float actual;
actual = Quaternion.Dot(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Dot did not return the expected value.");
}
// A test for Length ()
[Fact]
public void QuaternionLengthTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
float w = 4.0f;
Quaternion target = new Quaternion(v, w);
float expected = 5.477226f;
float actual;
actual = target.Length();
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Length did not return the expected value.");
}
// A test for LengthSquared ()
[Fact]
public void QuaternionLengthSquaredTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
float w = 4.0f;
Quaternion target = new Quaternion(v, w);
float expected = 30.0f;
float actual;
actual = target.LengthSquared();
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.LengthSquared did not return the expected value.");
}
// A test for Lerp (Quaternion, Quaternion, float)
[Fact]
public void QuaternionLerpTest()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 0.5f;
Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f));
Quaternion actual;
actual = Quaternion.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value.");
// Case a and b are same.
expected = a;
actual = Quaternion.Lerp(a, a, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value.");
}
// A test for Lerp (Quaternion, Quaternion, float)
// Lerp test when t = 0
[Fact]
public void QuaternionLerpTest1()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 0.0f;
Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W);
Quaternion actual = Quaternion.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value.");
}
// A test for Lerp (Quaternion, Quaternion, float)
// Lerp test when t = 1
[Fact]
public void QuaternionLerpTest2()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 1.0f;
Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W);
Quaternion actual = Quaternion.Lerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value.");
}
// A test for Lerp (Quaternion, Quaternion, float)
// Lerp test when the two quaternions are more than 90 degree (dot product <0)
[Fact]
public void QuaternionLerpTest3()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.Negate(a);
float t = 1.0f;
Quaternion actual = Quaternion.Lerp(a, b, t);
// Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero,
// one of the quaternion will be flipped to compute the shortest distance. When t = 1, we
// expect the result to be the same as quaternion b but flipped.
Assert.True(actual == a, "Quaternion.Lerp did not return the expected value.");
}
// A test for Conjugate(Quaternion)
[Fact]
public void QuaternionConjugateTest1()
{
Quaternion a = new Quaternion(1, 2, 3, 4);
Quaternion expected = new Quaternion(-1, -2, -3, 4);
Quaternion actual;
actual = Quaternion.Conjugate(a);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Conjugate did not return the expected value.");
}
// A test for Normalize (Quaternion)
[Fact]
public void QuaternionNormalizeTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion expected = new Quaternion(0.182574168f, 0.365148336f, 0.5477225f, 0.7302967f);
Quaternion actual;
actual = Quaternion.Normalize(a);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Normalize did not return the expected value.");
}
// A test for Normalize (Quaternion)
// Normalize zero length quaternion
[Fact]
public void QuaternionNormalizeTest1()
{
Quaternion a = new Quaternion(0.0f, 0.0f, -0.0f, 0.0f);
Quaternion actual = Quaternion.Normalize(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W)
, "Quaternion.Normalize did not return the expected value.");
}
// A test for Concatenate(Quaternion, Quaternion)
[Fact]
public void QuaternionConcatenateTest1()
{
Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f);
Quaternion actual;
actual = Quaternion.Concatenate(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Concatenate did not return the expected value.");
}
// A test for operator - (Quaternion, Quaternion)
[Fact]
public void QuaternionSubtractionTest()
{
Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f);
Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f);
Quaternion actual;
actual = a - b;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value.");
}
// A test for operator * (Quaternion, float)
[Fact]
public void QuaternionMultiplyTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
float factor = 0.5f;
Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f);
Quaternion actual;
actual = a * factor;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value.");
}
// A test for operator * (Quaternion, Quaternion)
[Fact]
public void QuaternionMultiplyTest1()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f);
Quaternion actual;
actual = a * b;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value.");
}
// A test for operator / (Quaternion, Quaternion)
[Fact]
public void QuaternionDivisionTest1()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f);
Quaternion actual;
actual = a / b;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator / did not return the expected value.");
}
// A test for operator + (Quaternion, Quaternion)
[Fact]
public void QuaternionAdditionTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f);
Quaternion actual;
actual = a + b;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator + did not return the expected value.");
}
// A test for Quaternion (float, float, float, float)
[Fact]
public void QuaternionConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
float w = 4.0f;
Quaternion target = new Quaternion(x, y, z, w);
Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z) && MathHelper.Equal(target.W, w),
"Quaternion.constructor (x,y,z,w) did not return the expected value.");
}
// A test for Quaternion (Vector3f, float)
[Fact]
public void QuaternionConstructorTest1()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
float w = 4.0f;
Quaternion target = new Quaternion(v, w);
Assert.True(MathHelper.Equal(target.X, v.X) && MathHelper.Equal(target.Y, v.Y) && MathHelper.Equal(target.Z, v.Z) && MathHelper.Equal(target.W, w),
"Quaternion.constructor (Vector3f,w) did not return the expected value.");
}
// A test for CreateFromAxisAngle (Vector3f, float)
[Fact]
public void QuaternionCreateFromAxisAngleTest()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
float angle = MathHelper.ToRadians(30.0f);
Quaternion expected = new Quaternion(0.0691723f, 0.1383446f, 0.207516879f, 0.9659258f);
Quaternion actual;
actual = Quaternion.CreateFromAxisAngle(axis, angle);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromAxisAngle did not return the expected value.");
}
// A test for CreateFromAxisAngle (Vector3f, float)
// CreateFromAxisAngle of zero vector
[Fact]
public void QuaternionCreateFromAxisAngleTest1()
{
Vector3 axis = new Vector3();
float angle = MathHelper.ToRadians(-30.0f);
float cos = (float)System.Math.Cos(angle / 2.0f);
Quaternion actual = Quaternion.CreateFromAxisAngle(axis, angle);
Assert.True(actual.X == 0.0f && actual.Y == 0.0f && actual.Z == 0.0f && MathHelper.Equal(cos, actual.W)
, "Quaternion.CreateFromAxisAngle did not return the expected value.");
}
// A test for CreateFromAxisAngle (Vector3f, float)
// CreateFromAxisAngle of angle = 30 && 750
[Fact]
public void QuaternionCreateFromAxisAngleTest2()
{
Vector3 axis = new Vector3(1, 0, 0);
float angle1 = MathHelper.ToRadians(30.0f);
float angle2 = MathHelper.ToRadians(750.0f);
Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1);
Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2);
Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value.");
}
// A test for CreateFromAxisAngle (Vector3f, float)
// CreateFromAxisAngle of angle = 30 && 390
[Fact]
public void QuaternionCreateFromAxisAngleTest3()
{
Vector3 axis = new Vector3(1, 0, 0);
float angle1 = MathHelper.ToRadians(30.0f);
float angle2 = MathHelper.ToRadians(390.0f);
Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1);
Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2);
actual1.X = -actual1.X;
actual1.W = -actual1.W;
Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value.");
}
[Fact]
public void QuaternionCreateFromYawPitchRollTest1()
{
float yawAngle = MathHelper.ToRadians(30.0f);
float pitchAngle = MathHelper.ToRadians(40.0f);
float rollAngle = MathHelper.ToRadians(50.0f);
Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawAngle);
Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchAngle);
Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollAngle);
Quaternion expected = yaw * pitch * roll;
Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle);
Assert.True(MathHelper.Equal(expected, actual));
}
// Covers more numeric rigions
[Fact]
public void QuaternionCreateFromYawPitchRollTest2()
{
const float step = 35.0f;
for (float yawAngle = -720.0f; yawAngle <= 720.0f; yawAngle += step)
{
for (float pitchAngle = -720.0f; pitchAngle <= 720.0f; pitchAngle += step)
{
for (float rollAngle = -720.0f; rollAngle <= 720.0f; rollAngle += step)
{
float yawRad = MathHelper.ToRadians(yawAngle);
float pitchRad = MathHelper.ToRadians(pitchAngle);
float rollRad = MathHelper.ToRadians(rollAngle);
Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawRad);
Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchRad);
Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollRad);
Quaternion expected = yaw * pitch * roll;
Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawRad, pitchRad, rollRad);
Assert.True(MathHelper.Equal(expected, actual), String.Format("Yaw:{0} Pitch:{1} Roll:{2}", yawAngle, pitchAngle, rollAngle));
}
}
}
}
// A test for Slerp (Quaternion, Quaternion, float)
[Fact]
public void QuaternionSlerpTest()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 0.5f;
Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f));
Quaternion actual;
actual = Quaternion.Slerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value.");
// Case a and b are same.
expected = a;
actual = Quaternion.Slerp(a, a, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value.");
}
// A test for Slerp (Quaternion, Quaternion, float)
// Slerp test where t = 0
[Fact]
public void QuaternionSlerpTest1()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 0.0f;
Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W);
Quaternion actual = Quaternion.Slerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value.");
}
// A test for Slerp (Quaternion, Quaternion, float)
// Slerp test where t = 1
[Fact]
public void QuaternionSlerpTest2()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 1.0f;
Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W);
Quaternion actual = Quaternion.Slerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value.");
}
// A test for Slerp (Quaternion, Quaternion, float)
// Slerp test where dot product is < 0
[Fact]
public void QuaternionSlerpTest3()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = -a;
float t = 1.0f;
Quaternion expected = a;
Quaternion actual = Quaternion.Slerp(a, b, t);
// Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero,
// one of the quaternion will be flipped to compute the shortest distance. When t = 1, we
// expect the result to be the same as quaternion b but flipped.
Assert.True(actual == expected, "Quaternion.Slerp did not return the expected value.");
}
// A test for Slerp (Quaternion, Quaternion, float)
// Slerp test where the quaternion is flipped
[Fact]
public void QuaternionSlerpTest4()
{
Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f));
Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f));
Quaternion b = -Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f));
float t = 0.0f;
Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W);
Quaternion actual = Quaternion.Slerp(a, b, t);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value.");
}
// A test for operator - (Quaternion)
[Fact]
public void QuaternionUnaryNegationTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f);
Quaternion actual;
actual = -a;
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value.");
}
// A test for Inverse (Quaternion)
[Fact]
public void QuaternionInverseTest()
{
Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(-0.0287356321f, -0.03448276f, -0.0402298868f, 0.04597701f);
Quaternion actual;
actual = Quaternion.Inverse(a);
Assert.Equal(expected, actual);
}
// A test for Inverse (Quaternion)
// Invert zero length quaternion
[Fact]
public void QuaternionInverseTest1()
{
Quaternion a = new Quaternion();
Quaternion actual = Quaternion.Inverse(a);
Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W)
);
}
// A test for ToString ()
[Fact]
public void QuaternionToStringTest()
{
Quaternion target = new Quaternion(-1.0f, 2.2f, 3.3f, -4.4f);
string expected = string.Format(CultureInfo.CurrentCulture
, "{{X:{0} Y:{1} Z:{2} W:{3}}}"
, -1.0f, 2.2f, 3.3f, -4.4f);
string actual = target.ToString();
Assert.Equal(expected, actual);
}
// A test for Add (Quaternion, Quaternion)
[Fact]
public void QuaternionAddTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f);
Quaternion actual;
actual = Quaternion.Add(a, b);
Assert.Equal(expected, actual);
}
// A test for Divide (Quaternion, Quaternion)
[Fact]
public void QuaternionDivideTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f);
Quaternion actual;
actual = Quaternion.Divide(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Divide did not return the expected value.");
}
// A test for Equals (object)
[Fact]
public void QuaternionEqualsTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(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.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.Equal(expected, actual);
// case 3: compare between different types.
obj = new Vector4();
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 GetHashCode ()
[Fact]
public void QuaternionGetHashCodeTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
int expected = a.X.GetHashCode() + a.Y.GetHashCode() + a.Z.GetHashCode() + a.W.GetHashCode();
int actual = a.GetHashCode();
Assert.Equal(expected, actual);
}
// A test for Multiply (Quaternion, float)
[Fact]
public void QuaternionMultiplyTest2()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
float factor = 0.5f;
Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f);
Quaternion actual;
actual = Quaternion.Multiply(a, factor);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value.");
}
// A test for Multiply (Quaternion, Quaternion)
[Fact]
public void QuaternionMultiplyTest3()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f);
Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f);
Quaternion actual;
actual = Quaternion.Multiply(a, b);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value.");
}
// A test for Negate (Quaternion)
[Fact]
public void QuaternionNegateTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f);
Quaternion actual;
actual = Quaternion.Negate(a);
Assert.Equal(expected, actual);
}
// A test for Subtract (Quaternion, Quaternion)
[Fact]
public void QuaternionSubtractTest()
{
Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f);
Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f);
Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f);
Quaternion actual;
actual = Quaternion.Subtract(a, b);
Assert.Equal(expected, actual);
}
// A test for operator != (Quaternion, Quaternion)
[Fact]
public void QuaternionInequalityTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(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.X = 10.0f;
expected = true;
actual = a != b;
Assert.Equal(expected, actual);
}
// A test for operator == (Quaternion, Quaternion)
[Fact]
public void QuaternionEqualityTest()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(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.X = 10.0f;
expected = false;
actual = a == b;
Assert.Equal(expected, actual);
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Convert Identity matrix test
[Fact]
public void QuaternionFromRotationMatrixTest1()
{
Matrix4x4 matrix = Matrix4x4.Identity;
Quaternion expected = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Convert X axis rotation matrix
[Fact]
public void QuaternionFromRotationMatrixTest2()
{
for (float angle = 0.0f; angle < 720.0f; angle += 10.0f)
{
Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), expected.ToString(), actual.ToString()));
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), matrix.ToString(), m2.ToString()));
}
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Convert Y axis rotation matrix
[Fact]
public void QuaternionFromRotationMatrixTest3()
{
for (float angle = 0.0f; angle < 720.0f; angle += 10.0f)
{
Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}",
angle.ToString()));
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}",
angle.ToString()));
}
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Convert Z axis rotation matrix
[Fact]
public void QuaternionFromRotationMatrixTest4()
{
for (float angle = 0.0f; angle < 720.0f; angle += 10.0f)
{
Matrix4x4 matrix = Matrix4x4.CreateRotationZ(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), expected.ToString(), actual.ToString()));
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), matrix.ToString(), m2.ToString()));
}
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Convert XYZ axis rotation matrix
[Fact]
public void QuaternionFromRotationMatrixTest5()
{
for (float angle = 0.0f; angle < 720.0f; angle += 10.0f)
{
Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle);
Quaternion expected =
Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) *
Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) *
Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), expected.ToString(), actual.ToString()));
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2),
string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}",
angle.ToString(), matrix.ToString(), m2.ToString()));
}
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// X axis is most large axis case
[Fact]
public void QuaternionFromRotationMatrixWithScaledMatrixTest1()
{
float angle = MathHelper.ToRadians(180.0f);
Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Y axis is most large axis case
[Fact]
public void QuaternionFromRotationMatrixWithScaledMatrixTest2()
{
float angle = MathHelper.ToRadians(180.0f);
Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationZ(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
}
// A test for CreateFromRotationMatrix (Matrix4x4)
// Z axis is most large axis case
[Fact]
public void QuaternionFromRotationMatrixWithScaledMatrixTest3()
{
float angle = MathHelper.ToRadians(180.0f);
Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle);
Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle);
Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix);
Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
// make sure convert back to matrix is same as we passed matrix.
Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual);
Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value.");
}
// A test for Equals (Quaternion)
[Fact]
public void QuaternionEqualsTest1()
{
Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f);
Quaternion b = new Quaternion(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.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.Equal(expected, actual);
}
// A test for Identity
[Fact]
public void QuaternionIdentityTest()
{
Quaternion val = new Quaternion(0, 0, 0, 1);
Assert.Equal(val, Quaternion.Identity);
}
// A test for IsIdentity
[Fact]
public void QuaternionIsIdentityTest()
{
Assert.True(Quaternion.Identity.IsIdentity);
Assert.True(new Quaternion(0, 0, 0, 1).IsIdentity);
Assert.False(new Quaternion(1, 0, 0, 1).IsIdentity);
Assert.False(new Quaternion(0, 1, 0, 1).IsIdentity);
Assert.False(new Quaternion(0, 0, 1, 1).IsIdentity);
Assert.False(new Quaternion(0, 0, 0, 0).IsIdentity);
}
// A test for Quaternion comparison involving NaN values
[Fact]
public void QuaternionEqualsNanTest()
{
Quaternion a = new Quaternion(float.NaN, 0, 0, 0);
Quaternion b = new Quaternion(0, float.NaN, 0, 0);
Quaternion c = new Quaternion(0, 0, float.NaN, 0);
Quaternion d = new Quaternion(0, 0, 0, float.NaN);
Assert.False(a == new Quaternion(0, 0, 0, 0));
Assert.False(b == new Quaternion(0, 0, 0, 0));
Assert.False(c == new Quaternion(0, 0, 0, 0));
Assert.False(d == new Quaternion(0, 0, 0, 0));
Assert.True(a != new Quaternion(0, 0, 0, 0));
Assert.True(b != new Quaternion(0, 0, 0, 0));
Assert.True(c != new Quaternion(0, 0, 0, 0));
Assert.True(d != new Quaternion(0, 0, 0, 0));
Assert.False(a.Equals(new Quaternion(0, 0, 0, 0)));
Assert.False(b.Equals(new Quaternion(0, 0, 0, 0)));
Assert.False(c.Equals(new Quaternion(0, 0, 0, 0)));
Assert.False(d.Equals(new Quaternion(0, 0, 0, 0)));
Assert.False(a.IsIdentity);
Assert.False(b.IsIdentity);
Assert.False(c.IsIdentity);
Assert.False(d.IsIdentity);
// 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));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[Fact]
public unsafe void QuaternionSizeofTest()
{
Assert.Equal(16, sizeof(Quaternion));
Assert.Equal(32, sizeof(Quaternion_2x));
Assert.Equal(20, sizeof(QuaternionPlusFloat));
Assert.Equal(40, sizeof(QuaternionPlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Quaternion_2x
{
private Quaternion _a;
private Quaternion _b;
}
[StructLayout(LayoutKind.Sequential)]
struct QuaternionPlusFloat
{
private Quaternion _v;
private float _f;
}
[StructLayout(LayoutKind.Sequential)]
struct QuaternionPlusFloat_2x
{
private QuaternionPlusFloat _a;
private QuaternionPlusFloat _b;
}
// A test to make sure the fields are laid out how we expect
[Fact]
public unsafe void QuaternionFieldOffsetTest()
{
Quaternion quat = new Quaternion();
float* basePtr = &quat.X; // Take address of first element
Quaternion* quatPtr = &quat; // Take address of whole Quaternion
Assert.Equal(new IntPtr(basePtr), new IntPtr(quatPtr));
Assert.Equal(new IntPtr(basePtr + 0), new IntPtr(&quat.X));
Assert.Equal(new IntPtr(basePtr + 1), new IntPtr(&quat.Y));
Assert.Equal(new IntPtr(basePtr + 2), new IntPtr(&quat.Z));
Assert.Equal(new IntPtr(basePtr + 3), new IntPtr(&quat.W));
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Player.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
#endregion
namespace RolePlayingGameData
{
/// <summary>
/// A member of the player's party, also represented in the world before joining.
/// </summary>
/// <remarks>
/// There is only one of a given Player in the game world at a time, and their
/// current statistics persist after combat. Thererefore, current statistics
/// are tracked here.
/// </remarks>
public class Player : FightingCharacter
{
#region Current Statistics
/// <summary>
/// The current set of persistent statistics modifiers - damage, etc.
/// </summary>
[ContentSerializerIgnore]
public StatisticsValue StatisticsModifiers = new StatisticsValue();
/// <summary>
/// The current set of statistics, including damage, etc.
/// </summary>
[ContentSerializerIgnore]
public StatisticsValue CurrentStatistics
{
get { return CharacterStatistics + StatisticsModifiers; }
}
#endregion
#region Initial Data
/// <summary>
/// The amount of gold that the player has when it joins the party.
/// </summary>
private int gold;
/// <summary>
/// The amount of gold that the player has when it joins the party.
/// </summary>
public int Gold
{
get { return gold; }
set { gold = value; }
}
#endregion
#region Dialogue Data
/// <summary>
/// The dialogue that the player says when it is greeted as an Npc in the world.
/// </summary>
private string introductionDialogue;
/// <summary>
/// The dialogue that the player says when it is greeted as an Npc in the world.
/// </summary>
public string IntroductionDialogue
{
get { return introductionDialogue; }
set { introductionDialogue = value; }
}
/// <summary>
/// The dialogue that the player says when its offer to join is accepted.
/// </summary>
private string joinAcceptedDialogue;
/// <summary>
/// The dialogue that the player says when its offer to join is accepted.
/// </summary>
public string JoinAcceptedDialogue
{
get { return joinAcceptedDialogue; }
set { joinAcceptedDialogue = value; }
}
/// <summary>
/// The dialogue that the player says when its offer to join is rejected.
/// </summary>
private string joinRejectedDialogue;
/// <summary>
/// The dialogue that the player says when its offer to join is rejected.
/// </summary>
public string JoinRejectedDialogue
{
get { return joinRejectedDialogue; }
set { joinRejectedDialogue = value; }
}
#endregion
#region Portrait Data
/// <summary>
/// The name of the active portrait texture.
/// </summary>
protected string activePortraitTextureName;
/// <summary>
/// The name of the active portrait texture.
/// </summary>
public string ActivePortraitTextureName
{
get { return activePortraitTextureName; }
set { activePortraitTextureName = value; }
}
/// <summary>
/// The active portrait texture.
/// </summary>
protected Texture2D activePortraitTexture;
/// <summary>
/// The active portrait texture.
/// </summary>
[ContentSerializerIgnore]
public Texture2D ActivePortraitTexture
{
get { return activePortraitTexture; }
}
/// <summary>
/// The name of the inactive portrait texture.
/// </summary>
protected string inactivePortraitTextureName;
/// <summary>
/// The name of the inactive portrait texture.
/// </summary>
public string InactivePortraitTextureName
{
get { return inactivePortraitTextureName; }
set { inactivePortraitTextureName = value; }
}
/// <summary>
/// The inactive portrait texture.
/// </summary>
protected Texture2D inactivePortraitTexture;
/// <summary>
/// The inactive portrait texture.
/// </summary>
[ContentSerializerIgnore]
public Texture2D InactivePortraitTexture
{
get { return inactivePortraitTexture; }
}
/// <summary>
/// The name of the unselectable portrait texture.
/// </summary>
protected string unselectablePortraitTextureName;
/// <summary>
/// The name of the unselectable portrait texture.
/// </summary>
public string UnselectablePortraitTextureName
{
get { return unselectablePortraitTextureName; }
set { unselectablePortraitTextureName = value; }
}
/// <summary>
/// The unselectable portrait texture.
/// </summary>
protected Texture2D unselectablePortraitTexture;
/// <summary>
/// The unselectable portrait texture.
/// </summary>
[ContentSerializerIgnore]
public Texture2D UnselectablePortraitTexture
{
get { return unselectablePortraitTexture; }
}
#endregion
#region Content Type Reader
/// <summary>
/// Read a Player object from the content pipeline.
/// </summary>
public class PlayerReader : ContentTypeReader<Player>
{
protected override Player Read(ContentReader input, Player existingInstance)
{
Player player = existingInstance;
if (player == null)
{
player = new Player();
}
input.ReadRawObject<FightingCharacter>(player as FightingCharacter);
player.Gold = input.ReadInt32();
player.IntroductionDialogue = input.ReadString();
player.JoinAcceptedDialogue = input.ReadString();
player.JoinRejectedDialogue = input.ReadString();
player.ActivePortraitTextureName = input.ReadString();
player.activePortraitTexture =
input.ContentManager.Load<Texture2D>(
System.IO.Path.Combine(@"Textures\Characters\Portraits",
player.ActivePortraitTextureName));
player.InactivePortraitTextureName = input.ReadString();
player.inactivePortraitTexture =
input.ContentManager.Load<Texture2D>(
System.IO.Path.Combine(@"Textures\Characters\Portraits",
player.InactivePortraitTextureName));
player.UnselectablePortraitTextureName = input.ReadString();
player.unselectablePortraitTexture =
input.ContentManager.Load<Texture2D>(
System.IO.Path.Combine(@"Textures\Characters\Portraits",
player.UnselectablePortraitTextureName));
return player;
}
}
#endregion
#region ICloneable Members
public object Clone()
{
Player player = new Player();
player.activePortraitTexture = activePortraitTexture;
player.activePortraitTextureName = activePortraitTextureName;
player.AssetName = AssetName;
player.CharacterClass = CharacterClass;
player.CharacterClassContentName = CharacterClassContentName;
player.CharacterLevel = CharacterLevel;
player.CombatAnimationInterval = CombatAnimationInterval;
player.CombatSprite = CombatSprite.Clone() as AnimatingSprite;
player.Direction = Direction;
player.EquippedEquipment.AddRange(EquippedEquipment);
player.Experience = Experience;
player.gold = gold;
player.inactivePortraitTexture = inactivePortraitTexture;
player.inactivePortraitTextureName = inactivePortraitTextureName;
player.InitialEquipmentContentNames.AddRange(InitialEquipmentContentNames);
player.introductionDialogue = introductionDialogue;
player.Inventory.AddRange(Inventory);
player.joinAcceptedDialogue = joinAcceptedDialogue;
player.joinRejectedDialogue = joinRejectedDialogue;
player.MapIdleAnimationInterval = MapIdleAnimationInterval;
player.MapPosition = MapPosition;
player.MapSprite = MapSprite.Clone() as AnimatingSprite;
player.MapWalkingAnimationInterval = MapWalkingAnimationInterval;
player.Name = Name;
player.ShadowTexture = ShadowTexture;
player.State = State;
player.unselectablePortraitTexture = unselectablePortraitTexture;
player.unselectablePortraitTextureName = unselectablePortraitTextureName;
player.WalkingSprite = WalkingSprite.Clone() as AnimatingSprite;
player.RecalculateEquipmentStatistics();
player.RecalculateTotalDefenseRanges();
player.RecalculateTotalTargetDamageRange();
player.ResetAnimation(false);
player.ResetBaseStatistics();
return player;
}
#endregion
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.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.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Slice : Node
{
protected Expression _begin;
protected Expression _end;
protected Expression _step;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Slice CloneNode()
{
return (Slice)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Slice CleanClone()
{
return (Slice)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Slice; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnSlice(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Slice)node;
if (!Node.Matches(_begin, other._begin)) return NoMatch("Slice._begin");
if (!Node.Matches(_end, other._end)) return NoMatch("Slice._end");
if (!Node.Matches(_step, other._step)) return NoMatch("Slice._step");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_begin == existing)
{
this.Begin = (Expression)newNode;
return true;
}
if (_end == existing)
{
this.End = (Expression)newNode;
return true;
}
if (_step == existing)
{
this.Step = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Slice clone = new Slice();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _begin)
{
clone._begin = _begin.Clone() as Expression;
clone._begin.InitializeParent(clone);
}
if (null != _end)
{
clone._end = _end.Clone() as Expression;
clone._end.InitializeParent(clone);
}
if (null != _step)
{
clone._step = _step.Clone() as Expression;
clone._step.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _begin)
{
_begin.ClearTypeSystemBindings();
}
if (null != _end)
{
_end.ClearTypeSystemBindings();
}
if (null != _step)
{
_step.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Begin
{
get { return _begin; }
set
{
if (_begin != value)
{
_begin = value;
if (null != _begin)
{
_begin.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression End
{
get { return _end; }
set
{
if (_end != value)
{
_end = value;
if (null != _end)
{
_end.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Step
{
get { return _step; }
set
{
if (_step != value)
{
_step = value;
if (null != _step)
{
_step.InitializeParent(this);
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace Vestris.ResourceLib
{
/// <summary>
/// Resource info manager.
/// </summary>
internal class ResourceInfo : IEnumerable<Resource>, IDisposable
{
private IntPtr _hModule = IntPtr.Zero;
private Dictionary<ResourceId, List<Resource>> _resources;
private List<ResourceId> _resourceTypes = null;
/// <summary>
/// A dictionary of resources, the key is the resource type, eg. "REGISTRY" or "16" (version).
/// </summary>
internal Dictionary<ResourceId, List<Resource>> Resources
{
get
{
return _resources;
}
}
/// <summary>
/// A shortcut for available resource types.
/// </summary>
internal List<ResourceId> ResourceTypes
{
get
{
return _resourceTypes;
}
}
/// <summary>
/// A new resource info.
/// </summary>
internal ResourceInfo()
{
}
/// <summary>
/// Unload the previously loaded module.
/// </summary>
internal void Unload()
{
if (_hModule != IntPtr.Zero)
{
Kernel32.FreeLibrary(_hModule);
_hModule = IntPtr.Zero;
}
}
/// <summary>
/// Load an executable or a DLL and read its resources.
/// </summary>
/// <param name="filename">Source filename.</param>
internal void Load(string filename)
{
Unload();
_resourceTypes = new List<ResourceId>();
_resources = new Dictionary<ResourceId, List<Resource>>();
// load DLL
_hModule = Kernel32.LoadLibraryEx(filename, IntPtr.Zero,
Kernel32.DONT_RESOLVE_DLL_REFERENCES | Kernel32.LOAD_LIBRARY_AS_DATAFILE);
if (IntPtr.Zero == _hModule)
throw new Win32Exception(Marshal.GetLastWin32Error());
// enumerate resource types
// for each type, enumerate resource names
// for each name, enumerate resource languages
// for each resource language, enumerate actual resources
if (!Kernel32.EnumResourceTypes(_hModule, EnumResourceTypesImpl, IntPtr.Zero))
throw new Win32Exception(Marshal.GetLastWin32Error());
}
/// <summary>
/// Enumerate resource types.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="lpszType">Resource type.</param>
/// <param name="lParam">Additional parameter.</param>
/// <returns>TRUE if successful.</returns>
private bool EnumResourceTypesImpl(IntPtr hModule, IntPtr lpszType, IntPtr lParam)
{
ResourceId type = new ResourceId(lpszType);
_resourceTypes.Add(type);
// enumerate resource names
if (!Kernel32.EnumResourceNames(hModule, lpszType, new Kernel32.EnumResourceNamesDelegate(EnumResourceNamesImpl), IntPtr.Zero))
throw new Win32Exception(Marshal.GetLastWin32Error());
return true;
}
/// <summary>
/// Enumerate resource names within a resource by type
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="lpszType">Resource type.</param>
/// <param name="lpszName">Resource name.</param>
/// <param name="lParam">Additional parameter.</param>
/// <returns>TRUE if successful.</returns>
private bool EnumResourceNamesImpl(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam)
{
if (!Kernel32.EnumResourceLanguages(hModule, lpszType, lpszName, new Kernel32.EnumResourceLanguagesDelegate(EnumResourceLanguages), IntPtr.Zero))
throw new Win32Exception(Marshal.GetLastWin32Error());
return true;
}
/// <summary>
/// Create a resource of a given type.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="hResourceGlobal">Pointer to the resource in memory.</param>
/// <param name="type">Resource type.</param>
/// <param name="name">Resource name.</param>
/// <param name="wIDLanguage">Language ID.</param>
/// <param name="size">Size of resource.</param>
/// <returns>A specialized or a generic resource.</returns>
protected Resource CreateResource(
IntPtr hModule,
IntPtr hResourceGlobal,
ResourceId type,
ResourceId name,
UInt16 wIDLanguage,
int size)
{
if (type.IsIntResource())
{
switch (type.ResourceType)
{
case Kernel32.ResourceTypes.RT_GROUP_ICON:
return new IconDirectoryResource(hModule, hResourceGlobal, type, name, wIDLanguage, size);
}
}
return null;
}
/// <summary>
/// Enumerate resource languages within a resource by name
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="lpszType">Resource type.</param>
/// <param name="lpszName">Resource name.</param>
/// <param name="wIDLanguage">Language ID.</param>
/// <param name="lParam">Additional parameter.</param>
/// <returns>TRUE if successful.</returns>
private bool EnumResourceLanguages(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, UInt16 wIDLanguage, IntPtr lParam)
{
List<Resource> resources = null;
ResourceId type = new ResourceId(lpszType);
if (!_resources.TryGetValue(type, out resources))
{
resources = new List<Resource>();
_resources[type] = resources;
}
ResourceId name = new ResourceId(lpszName);
IntPtr hResource = Kernel32.FindResourceEx(hModule, lpszType, lpszName, wIDLanguage);
IntPtr hResourceGlobal = Kernel32.LoadResource(hModule, hResource);
int size = Kernel32.SizeofResource(hModule, hResource);
resources.Add(CreateResource(hModule, hResourceGlobal, type, name, wIDLanguage, size));
return true;
}
/// <summary>
/// Save resource to a file.
/// </summary>
/// <param name="filename">Target filename.</param>
internal void Save(string filename)
{
throw new NotImplementedException();
}
/// <summary>
/// Dispose resource info object.
/// </summary>
public void Dispose()
{
Unload();
}
/// <summary>
/// A collection of resources.
/// </summary>
/// <param name="type">Resource type.</param>
/// <returns>A collection of resources of a given type.</returns>
internal List<Resource> this[Kernel32.ResourceTypes type]
{
get
{
return _resources[new ResourceId(type)];
}
set
{
_resources[new ResourceId(type)] = value;
}
}
/// <summary>
/// A collection of resources.
/// </summary>
/// <param name="type">Resource type.</param>
/// <returns>A collection of resources of a given type.</returns>
internal List<Resource> this[string type]
{
get
{
return _resources[new ResourceId(type)];
}
set
{
_resources[new ResourceId(type)] = value;
}
}
#region IEnumerable<Resource> Members
/// <summary>
/// Enumerates all resources within this resource info collection.
/// </summary>
/// <returns>Resources enumerator.</returns>
public IEnumerator<Resource> GetEnumerator()
{
Dictionary<ResourceId, List<Resource>>.Enumerator resourceTypesEnumerator = _resources.GetEnumerator();
while(resourceTypesEnumerator.MoveNext())
{
List<Resource>.Enumerator resourceEnumerator = resourceTypesEnumerator.Current.Value.GetEnumerator();
while (resourceEnumerator.MoveNext())
{
yield return resourceEnumerator.Current;
}
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Enumerates all resources within this resource info collection.
/// </summary>
/// <returns>Resources enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
}
| |
// Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
#if MONO
namespace SIL.Media.AlsaAudio
{
/// <summary>
/// This class implements the methods and properties used by Bloom. It reimplements a class in
/// SIL.Media/NAudio, but for Linux.
/// </summary>
public class RecordingDevice
{
private static RecordingDevice _default;
public static RecordingDevice DefaultDevice
{
get
{
if (_default == null)
{
// This sets the value as a side-effect.
var list = Devices;
if (list.Count == 0)
{
Debug.WriteLine("No input audio devices available!");
}
}
return _default;
}
private set { _default = value; }
}
public int DeviceNumber { get; set; }
public string GenericName { get; set; }
public string ProductName { get; set; }
public RecordingDevice()
{
}
public override bool Equals(object obj)
{
var that = obj as RecordingDevice;
if (that == null)
return false;
return DeviceNumber == that.DeviceNumber &&
GenericName == that.GenericName &&
ProductName == that.ProductName;
}
public override int GetHashCode()
{
return GenericName.GetHashCode() ^ ProductName.GetHashCode() + DeviceNumber;
}
public override string ToString ()
{
return string.Format ("[RecordingDevice: DeviceNumber={0}, GenericName={1}, ProductName={2}]", DeviceNumber, GenericName, ProductName);
}
public static List<RecordingDevice> Devices
{
get
{
var list = new List<RecordingDevice>();
DefaultDevice = null;
/*
/proc/asound/pcm contains lines like the following:
00-00: ALC269VB Analog : ALC269VB Analog : playback 1 : capture 1
01-03: HDMI 0 : HDMI 0 : playback 1
02-00: USB Audio : USB Audio : playback 1 : capture 1
/proc/asound/cards contains pairs of lines like the following:
0 [PCH ]: HDA-Intel - HDA Intel PCH
HDA Intel PCH at 0xf7f30000 irq 31
1 [HDMI ]: HDA-Intel - HDA ATI HDMI
HDA ATI HDMI at 0xf7e40000 irq 32
2 [Headset ]: USB-Audio - Logitech USB Headset
Logitech Logitech USB Headset at usb-0000:00:1a.0-1.4, full speed
*/
var pcmLines = System.IO.File.ReadAllLines("/proc/asound/pcm");
var cardsLines = System.IO.File.ReadAllLines("/proc/asound/cards");
if (pcmLines == null || pcmLines.Length == 0 || cardsLines == null || cardsLines.Length == 0)
{
return list;
}
foreach (var pcm in pcmLines)
{
if (pcm.Contains(" capture "))
{
var pcmPieces = pcm.Split(new char[] { ':' });
var num = pcmPieces[0];
if (num.StartsWith("0"))
num = num.Substring(1);
var idx = num.IndexOf('-');
if (idx > 0)
num = num.Substring(0, idx);
var idNum = String.Format(" {0} ", num);
for (int i = 0; i < cardsLines.Length; ++i)
{
if (cardsLines[i].StartsWith(idNum))
{
var desc = cardsLines[i];
idx = desc.IndexOf("]: ");
if (idx > 0)
desc = desc.Substring(idx + 3);
idx = desc.IndexOf(" - ");
if (idx > 0)
desc = desc.Substring(idx + 3);
var dev = new RecordingDevice()
{
DeviceNumber = Int32.Parse(num),
GenericName = pcmPieces[1].Trim(),
ProductName = desc
};
if (IsCardAssignedAsDefault(num))
DefaultDevice = dev;
if (!dev.GenericName.ToLowerInvariant().Contains("usb") &&
!dev.ProductName.ToLowerInvariant().Contains("usb"))
{
var mics = FindPluggedInMicrophones(dev.DeviceNumber);
if (mics.Count == 0)
continue;
dev.GenericName = mics[0];
}
list.Add(dev);
}
}
}
}
if (list.Count == 0)
DefaultDevice = null;
else if (_default == null)
DefaultDevice = list[0];
return list;
}
}
static bool IsCardAssignedAsDefault(string num)
{
/*
When the USB headset on card 2 is assigned as the preferred/default input device, then
/proc/asound/card0/pcm0c/info looks something like this
card: 0
device: 0
subdevice: 0
stream: CAPTURE
id: ALC269VB Analog
name: ALC269VB Analog
subname: subdevice #0
class: 0
subclass: 0
subdevices_count: 1
subdevices_avail: 1
and /proc/asound/card2/pcm0c/info looks something like this
card: 2
device: 0
subdevice: 0
stream: CAPTURE
id: USB Audio
name: USB Audio
subname: subdevice #0
class: 0
subclass: 0
subdevices_count: 1
subdevices_avail: 0
This is the only clue I've found in 2 days of searching to tell which card is
assigned as the default (preferred) input device.
*/
try
{
// get the information about the capture device of this card
var filename = String.Format("/proc/asound/card{0}/pcm0c/info", num);
var infoLines = System.IO.File.ReadAllLines(filename);
if (infoLines == null | infoLines.Length == 0)
return false;
int subdeviceCount = 0;
int subdeviceAvail = 0;
foreach (var line in infoLines)
{
if (line.StartsWith("subdevices_count: "))
subdeviceCount = Int32.Parse(line.Substring(18));
else if (line.StartsWith("subdevices_avail: "))
subdeviceAvail = Int32.Parse(line.Substring(18));
}
return subdeviceAvail < subdeviceCount;
}
catch
{
return false;
}
}
// The following low-level hackery is needed to detect whether a microphone is plugged in to a
// sound card through an external microphone jack. The code is adapted from the C sources to
// the amixer program.
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_id_malloc(ref IntPtr id);
[DllImport ("libasound.so.2")]
static extern void snd_ctl_elem_id_free(IntPtr id);
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_info_malloc(ref IntPtr info);
[DllImport ("libasound.so.2")]
static extern void snd_ctl_elem_info_free(IntPtr info);
[DllImport ("libasound.so.2")]
static extern int snd_hctl_open(ref IntPtr hctl, string name, int mode);
[DllImport ("libasound.so.2")]
static extern int snd_hctl_close(IntPtr hctl);
[DllImport ("libasound.so.2")]
static extern int snd_hctl_load(IntPtr hctl);
[DllImport ("libasound.so.2")]
static extern IntPtr snd_hctl_first_elem(IntPtr hctl);
[DllImport ("libasound.so.2")]
static extern IntPtr snd_hctl_elem_next(IntPtr elem);
[DllImport ("libasound.so.2")]
static extern int snd_hctl_elem_info(IntPtr elem, IntPtr info);
[DllImport ("libasound.so.2")]
static extern void snd_hctl_elem_get_id(IntPtr elem, IntPtr id);
[DllImport ("libasound.so.2")]
static extern uint snd_ctl_elem_info_get_count(IntPtr info);
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_info_get_type(IntPtr info);
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_value_malloc(ref IntPtr obj);
[DllImport ("libasound.so.2")]
static extern void snd_ctl_elem_value_free(IntPtr obj);
[DllImport ("libasound.so.2")]
static extern int snd_hctl_elem_read(IntPtr elem, IntPtr control);
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_value_get_boolean(IntPtr control, uint idx);
[DllImport ("libasound.so.2")]
static extern int snd_ctl_elem_info_is_readable(IntPtr info);
[DllImport ("libasound.so.2")]
static extern string snd_ctl_ascii_elem_id_get(IntPtr id);
const int SND_CTL_ELEM_TYPE_BOOLEAN = 1;
static List<string> FindPluggedInMicrophones(int cardNumber)
{
IntPtr handle = IntPtr.Zero;
IntPtr elem = IntPtr.Zero;
IntPtr id = IntPtr.Zero;
IntPtr info = IntPtr.Zero;
var retval = new List<string>();
var cardId = String.Format("hw:{0}", cardNumber);
if (snd_hctl_open(ref handle, cardId, 0) < 0)
return retval;
if (snd_hctl_load(handle) < 0)
{
snd_hctl_close(handle);
return retval;
}
try
{
snd_ctl_elem_id_malloc(ref id);
snd_ctl_elem_info_malloc(ref info);
for (elem = snd_hctl_first_elem(handle); elem != IntPtr.Zero; elem = snd_hctl_elem_next(elem))
{
if (snd_hctl_elem_info(elem, info) < 0)
break;
snd_hctl_elem_get_id(elem, id);
var str = snd_ctl_ascii_elem_id_get(id);
if (String.IsNullOrEmpty(str))
continue;
if (str.Contains("Mic ") && str.Contains(" Jack"))
{
if (CheckMicrophoneValuesForOn(elem))
{
var idx = str.IndexOf("name=");
if (idx > 0)
{
str = str.Substring(idx + 5);
str = str.Trim(new char[] {'\'', '"'});
}
retval.Add(str);
}
}
}
}
finally
{
snd_hctl_close(handle);
snd_ctl_elem_info_free(info);
snd_ctl_elem_id_free(id);
}
return retval;
}
static bool CheckMicrophoneValuesForOn(IntPtr elem)
{
IntPtr info = IntPtr.Zero; // snd_ctl_elem_info_t *
IntPtr control = IntPtr.Zero; // snd_ctl_elem_value_t *
snd_ctl_elem_info_malloc(ref info);
if (snd_hctl_elem_info(elem, info) < 0)
{
snd_ctl_elem_info_free(info);
return false;
}
if (snd_ctl_elem_info_is_readable(info) == 0)
{
snd_ctl_elem_info_free(info);
return false;
}
snd_ctl_elem_value_malloc(ref control);
bool retval = false;
if (snd_hctl_elem_read(elem, control) >= 0)
{
// Microphone jacks have a single boolean value that indicates whether a microphone
// is actually plugged in.
uint count = snd_ctl_elem_info_get_count(info);
int type = snd_ctl_elem_info_get_type(info);
if (type == SND_CTL_ELEM_TYPE_BOOLEAN && count == 1)
retval = snd_ctl_elem_value_get_boolean(control, 0) != 0;
}
snd_ctl_elem_value_free(control);
snd_ctl_elem_info_free(info);
return retval;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using System.Reflection;
using System.Reflection.Emit;
using System.IO;
using System.Security;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
internal class CodeGenerator
{
private static MethodInfo s_getTypeFromHandle;
private static MethodInfo GetTypeFromHandle
{
get
{
if (s_getTypeFromHandle == null)
{
s_getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
Debug.Assert(s_getTypeFromHandle != null);
}
return s_getTypeFromHandle;
}
}
private static MethodInfo s_objectEquals;
private static MethodInfo ObjectEquals
{
get
{
if (s_objectEquals == null)
{
s_objectEquals = Globals.TypeOfObject.GetMethod("Equals", BindingFlags.Public | BindingFlags.Static);
Debug.Assert(s_objectEquals != null);
}
return s_objectEquals;
}
}
private static MethodInfo s_arraySetValue;
private static MethodInfo ArraySetValue
{
get
{
if (s_arraySetValue == null)
{
s_arraySetValue = typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) });
Debug.Assert(s_arraySetValue != null);
}
return s_arraySetValue;
}
}
private static MethodInfo s_objectToString;
private static MethodInfo ObjectToString
{
get
{
if (s_objectToString == null)
{
s_objectToString = typeof(object).GetMethod("ToString", Array.Empty<Type>());
Debug.Assert(s_objectToString != null);
}
return s_objectToString;
}
}
private static MethodInfo s_stringFormat;
private static MethodInfo StringFormat
{
get
{
if (s_stringFormat == null)
{
s_stringFormat = typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) });
Debug.Assert(s_stringFormat != null);
}
return s_stringFormat;
}
}
private Type _delegateType;
#if USE_REFEMIT
AssemblyBuilder assemblyBuilder;
ModuleBuilder moduleBuilder;
TypeBuilder typeBuilder;
static int typeCounter;
MethodBuilder methodBuilder;
#else
private static Module s_serializationModule;
private static Module SerializationModule
{
get
{
if (s_serializationModule == null)
{
s_serializationModule = typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false
}
return s_serializationModule;
}
}
private DynamicMethod _dynamicMethod;
#endif
private ILGenerator _ilGen;
private List<ArgBuilder> _argList;
private Stack<object> _blockStack;
private Label _methodEndLabel;
private Dictionary<LocalBuilder, string> _localNames = new Dictionary<LocalBuilder, string>();
private enum CodeGenTrace { None, Save, Tron };
private CodeGenTrace _codeGenTrace;
private LocalBuilder _stringFormatArray;
internal CodeGenerator()
{
//Defaulting to None as thats the default value in WCF
_codeGenTrace = CodeGenTrace.None;
}
#if !USE_REFEMIT
internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
_dynamicMethod = dynamicMethod;
_ilGen = _dynamicMethod.GetILGenerator();
_delegateType = delegateType;
InitILGeneration(methodName, argTypes);
}
#endif
internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
BeginMethod(signature.ReturnType, methodName, paramTypes, allowPrivateMemberAccess);
_delegateType = delegateType;
}
private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
string typeName = "Type" + (typeCounter++);
InitAssemblyBuilder(typeName + "." + methodName);
this.typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
this.methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public|MethodAttributes.Static, returnType, argTypes);
this.ilGen = this.methodBuilder.GetILGenerator();
#else
_dynamicMethod = new DynamicMethod(methodName, returnType, argTypes, SerializationModule, allowPrivateMemberAccess);
_ilGen = _dynamicMethod.GetILGenerator();
#endif
InitILGeneration(methodName, argTypes);
}
private void InitILGeneration(string methodName, Type[] argTypes)
{
_methodEndLabel = _ilGen.DefineLabel();
_blockStack = new Stack<object>();
_argList = new List<ArgBuilder>();
for (int i = 0; i < argTypes.Length; i++)
_argList.Add(new ArgBuilder(i, argTypes[i]));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("Begin method " + methodName + " {");
}
internal Delegate EndMethod()
{
MarkLabel(_methodEndLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel("} End method");
Ret();
Delegate retVal = null;
#if USE_REFEMIT
Type type = typeBuilder.CreateType();
MethodInfo method = type.GetMethod(methodBuilder.Name);
retVal = Delegate.CreateDelegate(delegateType, method);
methodBuilder = null;
#else
retVal = _dynamicMethod.CreateDelegate(_delegateType);
_dynamicMethod = null;
#endif
_delegateType = null;
_ilGen = null;
_blockStack = null;
_argList = null;
return retVal;
}
internal MethodInfo CurrentMethod
{
get
{
#if USE_REFEMIT
return methodBuilder;
#else
return _dynamicMethod;
#endif
}
}
internal ArgBuilder GetArg(int index)
{
return (ArgBuilder)_argList[index];
}
internal Type GetVariableType(object var)
{
if (var is ArgBuilder)
return ((ArgBuilder)var).ArgType;
else if (var is LocalBuilder)
return ((LocalBuilder)var).LocalType;
else
return var.GetType();
}
internal LocalBuilder DeclareLocal(Type type, string name, object initialValue)
{
LocalBuilder local = DeclareLocal(type, name);
Load(initialValue);
Store(local);
return local;
}
internal LocalBuilder DeclareLocal(Type type, string name)
{
return DeclareLocal(type, name, false);
}
internal LocalBuilder DeclareLocal(Type type, string name, bool isPinned)
{
LocalBuilder local = _ilGen.DeclareLocal(type, isPinned);
if (_codeGenTrace != CodeGenTrace.None)
{
_localNames[local] = name;
EmitSourceComment("Declare local '" + name + "' of type " + type);
}
return local;
}
internal void Set(LocalBuilder local, object value)
{
Load(value);
Store(local);
}
internal object For(LocalBuilder local, object start, object end)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end);
if (forState.Index != null)
{
Load(start);
Stloc(forState.Index);
Br(forState.TestLabel);
}
MarkLabel(forState.BeginLabel);
_blockStack.Push(forState);
return forState;
}
internal void EndFor()
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
if (forState.Index != null)
{
Ldloc(forState.Index);
Ldc(1);
Add();
Stloc(forState.Index);
MarkLabel(forState.TestLabel);
Ldloc(forState.Index);
Load(forState.End);
if (GetVariableType(forState.End).IsArray)
Ldlen();
Blt(forState.BeginLabel);
}
else
Br(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void Break(object forState)
{
InternalBreakFor(forState, OpCodes.Br);
}
internal void IfFalseBreak(object forState)
{
InternalBreakFor(forState, OpCodes.Brfalse);
}
internal void InternalBreakFor(object userForState, OpCode branchInstruction)
{
foreach (object block in _blockStack)
{
ForState forState = block as ForState;
if (forState != null && (object)forState == userForState)
{
if (!forState.RequiresEndLabel)
{
forState.EndLabel = DefineLabel();
forState.RequiresEndLabel = true;
}
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(branchInstruction + " " + forState.EndLabel.GetHashCode());
_ilGen.Emit(branchInstruction, forState.EndLabel);
break;
}
}
}
internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType,
LocalBuilder enumerator, MethodInfo getCurrentMethod)
{
ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator);
Br(forState.TestLabel);
MarkLabel(forState.BeginLabel);
Call(enumerator, getCurrentMethod);
ConvertValue(elementType, GetVariableType(local));
Stloc(local);
_blockStack.Push(forState);
}
internal void EndForEach(MethodInfo moveNextMethod)
{
object stackTop = _blockStack.Pop();
ForState forState = stackTop as ForState;
if (forState == null)
ThrowMismatchException(stackTop);
MarkLabel(forState.TestLabel);
object enumerator = forState.End;
Call(enumerator, moveNextMethod);
Brtrue(forState.BeginLabel);
if (forState.RequiresEndLabel)
MarkLabel(forState.EndLabel);
}
internal void IfNotDefaultValue(object value)
{
Type type = GetVariableType(value);
TypeCode typeCode = type.GetTypeCode();
if ((typeCode == TypeCode.Object && type.IsValueType) ||
typeCode == TypeCode.DateTime || typeCode == TypeCode.Decimal)
{
LoadDefaultValue(type);
ConvertValue(type, Globals.TypeOfObject);
Load(value);
ConvertValue(type, Globals.TypeOfObject);
Call(ObjectEquals);
IfNot();
}
else
{
LoadDefaultValue(type);
Load(value);
If(Cmp.NotEqualTo);
}
}
internal void If()
{
InternalIf(false);
}
internal void IfNot()
{
InternalIf(true);
}
private OpCode GetBranchCode(Cmp cmp)
{
switch (cmp)
{
case Cmp.LessThan:
return OpCodes.Bge;
case Cmp.EqualTo:
return OpCodes.Bne_Un;
case Cmp.LessThanOrEqualTo:
return OpCodes.Bgt;
case Cmp.GreaterThan:
return OpCodes.Ble;
case Cmp.NotEqualTo:
return OpCodes.Beq;
default:
DiagnosticUtility.DebugAssert(cmp == Cmp.GreaterThanOrEqualTo, "Unexpected cmp");
return OpCodes.Blt;
}
}
internal void If(Cmp cmpOp)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void If(object value1, Cmp cmpOp, object value2)
{
Load(value1);
Load(value2);
If(cmpOp);
}
internal void Else()
{
IfState ifState = PopIfState();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
ifState.ElseBegin = ifState.EndIf;
_blockStack.Push(ifState);
}
internal void ElseIf(object value1, Cmp cmpOp, object value2)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(value1);
Load(value2);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void EndIf()
{
IfState ifState = PopIfState();
if (!ifState.ElseBegin.Equals(ifState.EndIf))
MarkLabel(ifState.ElseBegin);
MarkLabel(ifState.EndIf);
}
internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount)
{
if (methodInfo.GetParameters().Length != expectedCount)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount)));
}
internal void Call(object thisObj, MethodInfo methodInfo)
{
VerifyParameterCount(methodInfo, 0);
LoadThis(thisObj, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1)
{
VerifyParameterCount(methodInfo, 1);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2)
{
VerifyParameterCount(methodInfo, 2);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3)
{
VerifyParameterCount(methodInfo, 3);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4)
{
VerifyParameterCount(methodInfo, 4);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5)
{
VerifyParameterCount(methodInfo, 5);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
Call(methodInfo);
}
internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6)
{
VerifyParameterCount(methodInfo, 6);
LoadThis(thisObj, methodInfo);
LoadParam(param1, 1, methodInfo);
LoadParam(param2, 2, methodInfo);
LoadParam(param3, 3, methodInfo);
LoadParam(param4, 4, methodInfo);
LoadParam(param5, 5, methodInfo);
LoadParam(param6, 6, methodInfo);
Call(methodInfo);
}
internal void Call(MethodInfo methodInfo)
{
if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Callvirt, methodInfo);
}
else if (methodInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, methodInfo);
}
}
internal void Call(ConstructorInfo ctor)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Call, ctor);
}
internal void New(ConstructorInfo constructorInfo)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString());
_ilGen.Emit(OpCodes.Newobj, constructorInfo);
}
internal void InitObj(Type valueType)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Initobj " + valueType);
_ilGen.Emit(OpCodes.Initobj, valueType);
}
internal void NewArray(Type elementType, object len)
{
Load(len);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Newarr " + elementType);
_ilGen.Emit(OpCodes.Newarr, elementType);
}
internal void LoadArrayElement(object obj, object arrayIndex)
{
Type objType = GetVariableType(obj).GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
{
Ldelema(objType);
Ldobj(objType);
}
else
Ldelem(objType);
}
internal void StoreArrayElement(object obj, object arrayIndex, object value)
{
Type arrayType = GetVariableType(obj);
if (arrayType == Globals.TypeOfArray)
{
Call(obj, ArraySetValue, value, arrayIndex);
}
else
{
Type objType = arrayType.GetElementType();
Load(obj);
Load(arrayIndex);
if (IsStruct(objType))
Ldelema(objType);
Load(value);
ConvertValue(GetVariableType(value), objType);
if (IsStruct(objType))
Stobj(objType);
else
Stelem(objType);
}
}
private static bool IsStruct(Type objType)
{
return objType.IsValueType && !objType.IsPrimitive;
}
internal Type LoadMember(MemberInfo memberInfo)
{
Type memberType = null;
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
memberType = fieldInfo.FieldType;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Ldfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
memberType = property.PropertyType;
if (property != null)
{
MethodInfo getMethod = property.GetMethod;
if (getMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property)));
Call(getMethod);
}
}
else if (memberInfo is MethodInfo)
{
MethodInfo method = (MethodInfo)memberInfo;
memberType = method.ReturnType;
Call(method);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown", memberInfo.DeclaringType, memberInfo.Name)));
EmitStackTop(memberType);
return memberType;
}
internal void StoreMember(MemberInfo memberInfo)
{
if (memberInfo is FieldInfo)
{
FieldInfo fieldInfo = (FieldInfo)memberInfo;
if (fieldInfo.IsStatic)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stsfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stsfld, fieldInfo);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stfld " + fieldInfo + " on type " + fieldInfo.DeclaringType);
_ilGen.Emit(OpCodes.Stfld, fieldInfo);
}
}
else if (memberInfo is PropertyInfo)
{
PropertyInfo property = memberInfo as PropertyInfo;
if (property != null)
{
MethodInfo setMethod = property.SetMethod;
if (setMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property)));
Call(setMethod);
}
}
else if (memberInfo is MethodInfo)
Call((MethodInfo)memberInfo);
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotLoadMemberType, "Unknown")));
}
internal void LoadDefaultValue(Type type)
{
if (type.IsValueType)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
Ldc(false);
break;
case TypeCode.Char:
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
Ldc(0);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
Ldc(0L);
break;
case TypeCode.Single:
Ldc(0.0F);
break;
case TypeCode.Double:
Ldc(0.0);
break;
case TypeCode.Decimal:
case TypeCode.DateTime:
default:
LocalBuilder zero = DeclareLocal(type, "zero");
LoadAddress(zero);
InitObj(type);
Load(zero);
break;
}
}
else
Load(null);
}
internal void Load(object obj)
{
if (obj == null)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldnull");
_ilGen.Emit(OpCodes.Ldnull);
}
else if (obj is ArgBuilder)
Ldarg((ArgBuilder)obj);
else if (obj is LocalBuilder)
Ldloc((LocalBuilder)obj);
else
Ldc(obj);
}
internal void Store(object var)
{
if (var is ArgBuilder)
Starg((ArgBuilder)var);
else if (var is LocalBuilder)
Stloc((LocalBuilder)var);
else
{
DiagnosticUtility.DebugAssert("Data can only be stored into ArgBuilder or LocalBuilder.");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CanOnlyStoreIntoArgOrLocGot0, DataContract.GetClrTypeFullName(var.GetType()))));
}
}
internal void Dec(object var)
{
Load(var);
Load(1);
Subtract();
Store(var);
}
internal void LoadAddress(object obj)
{
if (obj is ArgBuilder)
LdargAddress((ArgBuilder)obj);
else if (obj is LocalBuilder)
LdlocAddress((LocalBuilder)obj);
else
Load(obj);
}
internal void ConvertAddress(Type source, Type target)
{
InternalConvert(source, target, true);
}
internal void ConvertValue(Type source, Type target)
{
InternalConvert(source, target, false);
}
internal void Castclass(Type target)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Castclass " + target);
_ilGen.Emit(OpCodes.Castclass, target);
}
internal void Box(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Box " + type);
_ilGen.Emit(OpCodes.Box, type);
}
internal void Unbox(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Unbox " + type);
_ilGen.Emit(OpCodes.Unbox, type);
}
private OpCode GetLdindOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Ldind_I1; // TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldind_I2; // TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldind_I1; // TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldind_U1; // TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldind_I2; // TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldind_U2; // TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldind_I4; // TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldind_U4; // TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldind_I8; // TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldind_I8; // TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldind_R4; // TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldind_R8; // TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldind_Ref; // TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldobj(Type type)
{
OpCode opCode = GetLdindOpCode(type.GetTypeCode());
if (!opCode.Equals(OpCodes.Nop))
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldobj " + type);
_ilGen.Emit(OpCodes.Ldobj, type);
}
}
internal void Stobj(Type type)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stobj " + type);
_ilGen.Emit(OpCodes.Stobj, type);
}
internal void Ceq()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ceq");
_ilGen.Emit(OpCodes.Ceq);
}
internal void Throw()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Throw");
_ilGen.Emit(OpCodes.Throw);
}
internal void Ldtoken(Type t)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldtoken " + t);
_ilGen.Emit(OpCodes.Ldtoken, t);
}
internal void Ldc(object o)
{
Type valueType = o.GetType();
if (o is Type)
{
Ldtoken((Type)o);
Call(GetTypeFromHandle);
}
else if (valueType.IsEnum)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceComment("Ldc " + o.GetType() + "." + o);
Ldc(Convert.ChangeType(o, Enum.GetUnderlyingType(valueType), null));
}
else
{
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
Ldc((bool)o);
break;
case TypeCode.Char:
DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract");
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.CharIsInvalidPrimitive));
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
Ldc(Convert.ToInt32(o, CultureInfo.InvariantCulture));
break;
case TypeCode.Int32:
Ldc((int)o);
break;
case TypeCode.UInt32:
Ldc((int)(uint)o);
break;
case TypeCode.UInt64:
Ldc((long)(ulong)o);
break;
case TypeCode.Int64:
Ldc((long)o);
break;
case TypeCode.Single:
Ldc((float)o);
break;
case TypeCode.Double:
Ldc((double)o);
break;
case TypeCode.String:
Ldstr((string)o);
break;
case TypeCode.Object:
case TypeCode.Decimal:
case TypeCode.DateTime:
case TypeCode.Empty:
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownConstantType, DataContract.GetClrTypeFullName(valueType))));
}
}
}
internal void Ldc(bool boolVar)
{
if (boolVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 1");
_ilGen.Emit(OpCodes.Ldc_I4_1);
}
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 0");
_ilGen.Emit(OpCodes.Ldc_I4_0);
}
}
internal void Ldc(int intVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i4 " + intVar);
switch (intVar)
{
case -1:
_ilGen.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
_ilGen.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
_ilGen.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
_ilGen.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
_ilGen.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
_ilGen.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
_ilGen.Emit(OpCodes.Ldc_I4_8);
break;
default:
_ilGen.Emit(OpCodes.Ldc_I4, intVar);
break;
}
}
internal void Ldc(long l)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.i8 " + l);
_ilGen.Emit(OpCodes.Ldc_I8, l);
}
internal void Ldc(float f)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r4 " + f);
_ilGen.Emit(OpCodes.Ldc_R4, f);
}
internal void Ldc(double d)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldc.r8 " + d);
_ilGen.Emit(OpCodes.Ldc_R8, d);
}
internal void Ldstr(string strVar)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldstr " + strVar);
_ilGen.Emit(OpCodes.Ldstr, strVar);
}
internal void LdlocAddress(LocalBuilder localBuilder)
{
if (localBuilder.LocalType.IsValueType)
Ldloca(localBuilder);
else
Ldloc(localBuilder);
}
internal void Ldloc(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloc " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloc, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void Stloc(LocalBuilder local)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Stloc " + _localNames[local]);
EmitStackTop(local.LocalType);
_ilGen.Emit(OpCodes.Stloc, local);
}
internal void Ldloca(LocalBuilder localBuilder)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldloca " + _localNames[localBuilder]);
_ilGen.Emit(OpCodes.Ldloca, localBuilder);
EmitStackTop(localBuilder.LocalType);
}
internal void LdargAddress(ArgBuilder argBuilder)
{
if (argBuilder.ArgType.IsValueType)
Ldarga(argBuilder);
else
Ldarg(argBuilder);
}
internal void Ldarg(ArgBuilder arg)
{
Ldarg(arg.Index);
}
internal void Starg(ArgBuilder arg)
{
Starg(arg.Index);
}
internal void Ldarg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarg " + slot);
switch (slot)
{
case 0:
_ilGen.Emit(OpCodes.Ldarg_0);
break;
case 1:
_ilGen.Emit(OpCodes.Ldarg_1);
break;
case 2:
_ilGen.Emit(OpCodes.Ldarg_2);
break;
case 3:
_ilGen.Emit(OpCodes.Ldarg_3);
break;
default:
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarg_S, slot);
else
_ilGen.Emit(OpCodes.Ldarg, slot);
break;
}
}
internal void Starg(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Starg " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Starg_S, slot);
else
_ilGen.Emit(OpCodes.Starg, slot);
}
internal void Ldarga(ArgBuilder argBuilder)
{
Ldarga(argBuilder.Index);
}
internal void Ldarga(int slot)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldarga " + slot);
if (slot <= 255)
_ilGen.Emit(OpCodes.Ldarga_S, slot);
else
_ilGen.Emit(OpCodes.Ldarga, slot);
}
internal void Ldlen()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ldlen");
_ilGen.Emit(OpCodes.Ldlen);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Conv.i4");
_ilGen.Emit(OpCodes.Conv_I4);
}
private OpCode GetLdelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Ldelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Ldelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Ldelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Ldelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Ldelem_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Ldelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Ldelem_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Ldelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Ldelem_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Ldelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Ldelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Ldelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Ldelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Ldelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Ldelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
{
Ldelem(Enum.GetUnderlyingType(arrayElementType));
}
else
{
OpCode opCode = GetLdelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
EmitStackTop(arrayElementType);
}
}
internal void Ldelema(Type arrayElementType)
{
OpCode opCode = OpCodes.Ldelema;
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode, arrayElementType);
EmitStackTop(arrayElementType);
}
private OpCode GetStelemOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Object:
return OpCodes.Stelem_Ref;// TypeCode.Object:
case TypeCode.Boolean:
return OpCodes.Stelem_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Stelem_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Stelem_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Stelem_I1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Stelem_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Stelem_I2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Stelem_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Stelem_I4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Stelem_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Stelem_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Stelem_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Stelem_R8;// TypeCode.Double:
case TypeCode.String:
return OpCodes.Stelem_Ref;// TypeCode.String:
default:
return OpCodes.Nop;
}
}
internal void Stelem(Type arrayElementType)
{
if (arrayElementType.IsEnum)
Stelem(Enum.GetUnderlyingType(arrayElementType));
else
{
OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType))));
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
EmitStackTop(arrayElementType);
_ilGen.Emit(opCode);
}
}
internal Label DefineLabel()
{
return _ilGen.DefineLabel();
}
internal void MarkLabel(Label label)
{
_ilGen.MarkLabel(label);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceLabel(label.GetHashCode() + ":");
}
internal void Add()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Add");
_ilGen.Emit(OpCodes.Add);
}
internal void Subtract()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Sub");
_ilGen.Emit(OpCodes.Sub);
}
internal void And()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("And");
_ilGen.Emit(OpCodes.And);
}
internal void Or()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Or");
_ilGen.Emit(OpCodes.Or);
}
internal void Not()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Not");
_ilGen.Emit(OpCodes.Not);
}
internal void Ret()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Ret");
_ilGen.Emit(OpCodes.Ret);
}
internal void Br(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Br " + label.GetHashCode());
_ilGen.Emit(OpCodes.Br, label);
}
internal void Blt(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Blt " + label.GetHashCode());
_ilGen.Emit(OpCodes.Blt, label);
}
internal void Brfalse(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brfalse " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brfalse, label);
}
internal void Brtrue(Label label)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Brtrue " + label.GetHashCode());
_ilGen.Emit(OpCodes.Brtrue, label);
}
internal void Pop()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Pop");
_ilGen.Emit(OpCodes.Pop);
}
internal void Dup()
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("Dup");
_ilGen.Emit(OpCodes.Dup);
}
private void LoadThis(object thisObj, MethodInfo methodInfo)
{
if (thisObj != null && !methodInfo.IsStatic)
{
LoadAddress(thisObj);
ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType);
}
}
private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo)
{
Load(arg);
if (arg != null)
ConvertValue(GetVariableType(arg), methodInfo.GetParameters()[oneBasedArgIndex - 1].ParameterType);
}
private void InternalIf(bool negate)
{
IfState ifState = new IfState();
ifState.EndIf = DefineLabel();
ifState.ElseBegin = DefineLabel();
if (negate)
Brtrue(ifState.ElseBegin);
else
Brfalse(ifState.ElseBegin);
_blockStack.Push(ifState);
}
private OpCode GetConvOpCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Boolean:
return OpCodes.Conv_I1;// TypeCode.Boolean:
case TypeCode.Char:
return OpCodes.Conv_I2;// TypeCode.Char:
case TypeCode.SByte:
return OpCodes.Conv_I1;// TypeCode.SByte:
case TypeCode.Byte:
return OpCodes.Conv_U1;// TypeCode.Byte:
case TypeCode.Int16:
return OpCodes.Conv_I2;// TypeCode.Int16:
case TypeCode.UInt16:
return OpCodes.Conv_U2;// TypeCode.UInt16:
case TypeCode.Int32:
return OpCodes.Conv_I4;// TypeCode.Int32:
case TypeCode.UInt32:
return OpCodes.Conv_U4;// TypeCode.UInt32:
case TypeCode.Int64:
return OpCodes.Conv_I8;// TypeCode.Int64:
case TypeCode.UInt64:
return OpCodes.Conv_I8;// TypeCode.UInt64:
case TypeCode.Single:
return OpCodes.Conv_R4;// TypeCode.Single:
case TypeCode.Double:
return OpCodes.Conv_R8;// TypeCode.Double:
default:
return OpCodes.Nop;
}
}
private void InternalConvert(Type source, Type target, bool isAddress)
{
if (target == source)
return;
if (target.IsValueType)
{
if (source.IsValueType)
{
OpCode opCode = GetConvOpCode(target.GetTypeCode());
if (opCode.Equals(OpCodes.Nop))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoConversionPossibleTo, DataContract.GetClrTypeFullName(target))));
else
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction(opCode.ToString());
_ilGen.Emit(opCode);
}
}
else if (source.IsAssignableFrom(target))
{
Unbox(target);
if (!isAddress)
Ldobj(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
else if (target.IsAssignableFrom(source))
{
if (source.IsValueType)
{
if (isAddress)
Ldobj(source);
Box(source);
}
}
else if (source.IsAssignableFrom(target))
{
Castclass(target);
}
else if (target.IsInterface || source.IsInterface)
{
Castclass(target);
}
else
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsNotAssignableFrom, DataContract.GetClrTypeFullName(target), DataContract.GetClrTypeFullName(source))));
}
private IfState PopIfState()
{
object stackTop = _blockStack.Pop();
IfState ifState = stackTop as IfState;
if (ifState == null)
ThrowMismatchException(stackTop);
return ifState;
}
#if USE_REFEMIT
void InitAssemblyBuilder(string methodName)
{
AssemblyName name = new AssemblyName();
name.Name = "Microsoft.GeneratedCode."+methodName;
//Add SecurityCritical and SecurityTreatAsSafe attributes to the generated method
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name + ".dll", false);
}
#endif
private void ThrowMismatchException(object expected)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString())));
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceInstruction(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceLabel(string line)
{
}
[Conditional("NOT_SILVERLIGHT")]
internal void EmitSourceComment(string comment)
{
}
internal void EmitStackTop(Type stackTopType)
{
if (_codeGenTrace != CodeGenTrace.Tron)
return;
}
internal Label[] Switch(int labelCount)
{
SwitchState switchState = new SwitchState(DefineLabel(), DefineLabel());
Label[] caseLabels = new Label[labelCount];
for (int i = 0; i < caseLabels.Length; i++)
caseLabels[i] = DefineLabel();
_ilGen.Emit(OpCodes.Switch, caseLabels);
Br(switchState.DefaultLabel);
_blockStack.Push(switchState);
return caseLabels;
}
internal void Case(Label caseLabel1, string caseLabelName)
{
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("case " + caseLabelName + "{");
MarkLabel(caseLabel1);
}
internal void EndCase()
{
object stackTop = _blockStack.Peek();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
Br(switchState.EndOfSwitchLabel);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end case ");
}
internal void EndSwitch()
{
object stackTop = _blockStack.Pop();
SwitchState switchState = stackTop as SwitchState;
if (switchState == null)
ThrowMismatchException(stackTop);
if (_codeGenTrace != CodeGenTrace.None)
EmitSourceInstruction("} //end switch");
if (!switchState.DefaultDefined)
MarkLabel(switchState.DefaultLabel);
MarkLabel(switchState.EndOfSwitchLabel);
}
private static MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod;
internal void ElseIfIsEmptyString(LocalBuilder strLocal)
{
IfState ifState = (IfState)_blockStack.Pop();
Br(ifState.EndIf);
MarkLabel(ifState.ElseBegin);
Load(strLocal);
Call(s_stringLength);
Load(0);
ifState.ElseBegin = DefineLabel();
_ilGen.Emit(GetBranchCode(Cmp.EqualTo), ifState.ElseBegin);
_blockStack.Push(ifState);
}
internal void IfNotIsEmptyString(LocalBuilder strLocal)
{
Load(strLocal);
Call(s_stringLength);
Load(0);
If(Cmp.NotEqualTo);
}
internal void BeginWhileCondition()
{
Label startWhile = DefineLabel();
MarkLabel(startWhile);
_blockStack.Push(startWhile);
}
internal void BeginWhileBody(Cmp cmpOp)
{
Label startWhile = (Label)_blockStack.Pop();
If(cmpOp);
_blockStack.Push(startWhile);
}
internal void EndWhile()
{
Label startWhile = (Label)_blockStack.Pop();
Br(startWhile);
EndIf();
}
internal void CallStringFormat(string msg, params object[] values)
{
NewArray(typeof(object), values.Length);
if (_stringFormatArray == null)
_stringFormatArray = DeclareLocal(typeof(object[]), "stringFormatArray");
Stloc(_stringFormatArray);
for (int i = 0; i < values.Length; i++)
StoreArrayElement(_stringFormatArray, i, values[i]);
Load(msg);
Load(_stringFormatArray);
Call(StringFormat);
}
internal void ToString(Type type)
{
if (type != Globals.TypeOfString)
{
if (type.IsValueType)
{
Box(type);
}
Call(ObjectToString);
}
}
}
internal class ArgBuilder
{
internal int Index;
internal Type ArgType;
internal ArgBuilder(int index, Type argType)
{
this.Index = index;
this.ArgType = argType;
}
}
internal class ForState
{
private LocalBuilder _indexVar;
private Label _beginLabel;
private Label _testLabel;
private Label _endLabel;
private bool _requiresEndLabel;
private object _end;
internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end)
{
_indexVar = indexVar;
_beginLabel = beginLabel;
_testLabel = testLabel;
_end = end;
}
internal LocalBuilder Index
{
get
{
return _indexVar;
}
}
internal Label BeginLabel
{
get
{
return _beginLabel;
}
}
internal Label TestLabel
{
get
{
return _testLabel;
}
}
internal Label EndLabel
{
get
{
return _endLabel;
}
set
{
_endLabel = value;
}
}
internal bool RequiresEndLabel
{
get
{
return _requiresEndLabel;
}
set
{
_requiresEndLabel = value;
}
}
internal object End
{
get
{
return _end;
}
}
}
internal enum Cmp
{
LessThan,
EqualTo,
LessThanOrEqualTo,
GreaterThan,
NotEqualTo,
GreaterThanOrEqualTo
}
internal class IfState
{
private Label _elseBegin;
private Label _endIf;
internal Label EndIf
{
get
{
return _endIf;
}
set
{
_endIf = value;
}
}
internal Label ElseBegin
{
get
{
return _elseBegin;
}
set
{
_elseBegin = value;
}
}
}
internal class SwitchState
{
private Label _defaultLabel;
private Label _endOfSwitchLabel;
private bool _defaultDefined;
internal SwitchState(Label defaultLabel, Label endOfSwitchLabel)
{
_defaultLabel = defaultLabel;
_endOfSwitchLabel = endOfSwitchLabel;
_defaultDefined = false;
}
internal Label DefaultLabel
{
get
{
return _defaultLabel;
}
}
internal Label EndOfSwitchLabel
{
get
{
return _endOfSwitchLabel;
}
}
internal bool DefaultDefined
{
get
{
return _defaultDefined;
}
set
{
_defaultDefined = value;
}
}
}
}
| |
//
// Mono.System.Xml.Schema.XmlSchemaAttributeGroup.cs
//
// Authors:
// Dwivedi, Ajay kumar Adwiv@Yahoo.com
// Enomoto, Atsushi ginga@kit.hi-ho.ne.jp
//
//
// 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 Mono.System.Xml.Serialization;
using Mono.System.Xml;
namespace Mono.System.Xml.Schema
{
/// <summary>
/// Summary description for XmlSchemaAttributeGroup.
/// </summary>
public class XmlSchemaAttributeGroup : XmlSchemaAnnotated
{
private XmlSchemaAnyAttribute anyAttribute;
private XmlSchemaObjectCollection attributes;
private string name;
private XmlSchemaAttributeGroup redefined;
private XmlQualifiedName qualifiedName;
const string xmlname = "attributeGroup";
private XmlSchemaObjectTable attributeUses;
private XmlSchemaAnyAttribute anyAttributeUse;
internal bool AttributeGroupRecursionCheck;
public XmlSchemaAttributeGroup()
{
attributes = new XmlSchemaObjectCollection();
qualifiedName = XmlQualifiedName.Empty;
}
[Mono.System.Xml.Serialization.XmlAttribute("name")]
public string Name
{
get{ return name;}
set{ name = value;}
}
[XmlElement("attribute",typeof(XmlSchemaAttribute))]
[XmlElement("attributeGroup",typeof(XmlSchemaAttributeGroupRef))]
public XmlSchemaObjectCollection Attributes
{
get{ return attributes;}
}
internal XmlSchemaObjectTable AttributeUses
{
get { return attributeUses; }
}
internal XmlSchemaAnyAttribute AnyAttributeUse
{
get { return anyAttributeUse; }
}
[XmlElement("anyAttribute")]
public XmlSchemaAnyAttribute AnyAttribute
{
get{ return anyAttribute;}
set{ anyAttribute = value;}
}
//Undocumented property
[XmlIgnore]
public XmlSchemaAttributeGroup RedefinedAttributeGroup
{
get{ return redefined;}
}
[XmlIgnore]
#if NET_2_0
public XmlQualifiedName QualifiedName
#else
internal XmlQualifiedName QualifiedName
#endif
{
get{ return qualifiedName;}
}
internal override void SetParent (XmlSchemaObject parent)
{
base.SetParent (parent);
if (this.AnyAttribute != null)
this.AnyAttribute.SetParent (this);
foreach (XmlSchemaObject obj in Attributes)
obj.SetParent (this);
}
/// <remarks>
/// An Attribute group can only be defined as a child of XmlSchema or in XmlSchemaRedefine.
/// The other attributeGroup has type XmlSchemaAttributeGroupRef.
/// 1. Name must be present
/// </remarks>
internal override int Compile(ValidationEventHandler h, XmlSchema schema)
{
// If this is already compiled this time, simply skip.
if (CompilationId == schema.CompilationId)
return errorCount;
errorCount = 0;
if (redefinedObject != null) {
errorCount += redefined.Compile (h, schema);
if (errorCount == 0)
redefined = (XmlSchemaAttributeGroup) redefinedObject;
}
XmlSchemaUtil.CompileID(Id,this, schema.IDCollection,h);
if(this.Name == null || this.Name == String.Empty) //1
error(h,"Name is required in top level simpletype");
else if(!XmlSchemaUtil.CheckNCName(this.Name)) // b.1.2
error(h,"name attribute of a simpleType must be NCName");
else
this.qualifiedName = new XmlQualifiedName(this.Name, AncestorSchema.TargetNamespace);
if(this.AnyAttribute != null)
{
errorCount += this.AnyAttribute.Compile(h, schema);
}
foreach(XmlSchemaObject obj in Attributes)
{
if(obj is XmlSchemaAttribute)
{
XmlSchemaAttribute attr = (XmlSchemaAttribute) obj;
errorCount += attr.Compile(h, schema);
}
else if(obj is XmlSchemaAttributeGroupRef)
{
XmlSchemaAttributeGroupRef gref = (XmlSchemaAttributeGroupRef) obj;
errorCount += gref.Compile(h, schema);
}
else
{
error(h,"invalid type of object in Attributes property");
}
}
this.CompilationId = schema.CompilationId;
return errorCount;
}
internal override int Validate(ValidationEventHandler h, XmlSchema schema)
{
if (IsValidated (schema.CompilationId))
return errorCount;
if (redefined == null && redefinedObject != null) {
redefinedObject.Compile (h, schema);
redefined = (XmlSchemaAttributeGroup) redefinedObject;
redefined.Validate (h, schema);
}
XmlSchemaObjectCollection actualAttributes = null;
/*
if (this.redefined != null) {
actualAttributes = new XmlSchemaObjectCollection ();
foreach (XmlSchemaObject obj in Attributes) {
XmlSchemaAttributeGroupRef grp = obj as XmlSchemaAttributeGroupRef;
if (grp != null && grp.QualifiedName == this.QualifiedName)
actualAttributes.Add (redefined);
else
actualAttributes.Add (obj);
}
}
else
*/
actualAttributes = Attributes;
attributeUses = new XmlSchemaObjectTable ();
errorCount += XmlSchemaUtil.ValidateAttributesResolved (attributeUses,
h, schema, actualAttributes, AnyAttribute,
ref anyAttributeUse, redefined, false);
ValidationId = schema.ValidationId;
return errorCount;
}
//<attributeGroup
// id = ID
// name = NCName
// ref = QName // Not present in this class.
// {any attributes with non-schema namespace . . .}>
// Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?))
//</attributeGroup>
internal static XmlSchemaAttributeGroup Read(XmlSchemaReader reader, ValidationEventHandler h)
{
XmlSchemaAttributeGroup attrgrp = new XmlSchemaAttributeGroup();
reader.MoveToElement();
if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname)
{
error(h,"Should not happen :1: XmlSchemaAttributeGroup.Read, name="+reader.Name,null);
reader.SkipToEnd();
return null;
}
attrgrp.LineNumber = reader.LineNumber;
attrgrp.LinePosition = reader.LinePosition;
attrgrp.SourceUri = reader.BaseURI;
while(reader.MoveToNextAttribute())
{
if(reader.Name == "id")
{
attrgrp.Id = reader.Value;
}
else if(reader.Name == "name")
{
attrgrp.name = reader.Value;
}
else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
{
error(h,reader.Name + " is not a valid attribute for attributeGroup in this context",null);
}
else
{
XmlSchemaUtil.ReadUnhandledAttribute(reader,attrgrp);
}
}
reader.MoveToElement();
if(reader.IsEmptyElement)
return attrgrp;
//Content: 1.annotation?, 2.(attribute | attributeGroup)*, 3.anyAttribute?
int level = 1;
while(reader.ReadNextElement())
{
if(reader.NodeType == XmlNodeType.EndElement)
{
if(reader.LocalName != xmlname)
error(h,"Should not happen :2: XmlSchemaAttributeGroup.Read, name="+reader.Name,null);
break;
}
if(level <= 1 && reader.LocalName == "annotation")
{
level = 2; //Only one annotation
XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h);
if(annotation != null)
attrgrp.Annotation = annotation;
continue;
}
if(level <= 2)
{
if(reader.LocalName == "attribute")
{
level = 2;
XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader,h);
if(attr != null)
attrgrp.Attributes.Add(attr);
continue;
}
if(reader.LocalName == "attributeGroup")
{
level = 2;
XmlSchemaAttributeGroupRef attr = XmlSchemaAttributeGroupRef.Read(reader,h);
if(attr != null)
attrgrp.attributes.Add(attr);
continue;
}
}
if(level <= 3 && reader.LocalName == "anyAttribute")
{
level = 4;
XmlSchemaAnyAttribute anyattr = XmlSchemaAnyAttribute.Read(reader,h);
if(anyattr != null)
attrgrp.AnyAttribute = anyattr;
continue;
}
reader.RaiseInvalidElementError();
}
return attrgrp;
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G11_City_Child (editable child object).<br/>
/// This is a generated base class of <see cref="G11_City_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G10_City"/> collection.
/// </remarks>
[Serializable]
public partial class G11_City_Child : BusinessBase<G11_City_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G11_City_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G11_City_Child"/> object.</returns>
internal static G11_City_Child NewG11_City_Child()
{
return DataPortal.CreateChild<G11_City_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="G11_City_Child"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID1">The City_ID1 parameter of the G11_City_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="G11_City_Child"/> object.</returns>
internal static G11_City_Child GetG11_City_Child(int city_ID1)
{
return DataPortal.FetchChild<G11_City_Child>(city_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G11_City_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G11_City_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G11_City_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G11_City_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID1">The City ID1.</param>
protected void Child_Fetch(int city_ID1)
{
var args = new DataPortalHookArgs(city_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG11_City_ChildDal>();
var data = dal.Fetch(city_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="G11_City_Child"/> object from the given <see cref="G11_City_ChildDto"/>.
/// </summary>
/// <param name="data">The G11_City_ChildDto to use.</param>
private void Fetch(G11_City_ChildDto data)
{
// Value properties
LoadProperty(City_Child_NameProperty, data.City_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G11_City_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G10_City parent)
{
var dto = new G11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IG11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G11_City_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G10_City parent)
{
if (!IsDirty)
return;
var dto = new G11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G11_City_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G10_City parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG11_City_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Discovery.Version11;
using System.ServiceModel.Discovery.VersionApril2005;
using System.ServiceModel.Discovery.VersionCD1;
using System.Xml;
using SR2 = System.ServiceModel.Discovery.SR;
[Fx.Tag.XamlVisible(false)]
public sealed class DiscoveryVersion
{
static DiscoveryVersion wsDiscoveryApril2005;
static DiscoveryVersion wsDiscoveryCD1;
static DiscoveryVersion wsDiscovery11;
[Fx.Tag.SynchronizationObject()]
static object staticLock = new object();
string name;
string discoveryNamespace;
IDiscoveryVersionImplementation discoveryVersionImplementation;
DiscoveryVersion(string name, string discoveryNamespace,
IDiscoveryVersionImplementation discoveryVersionImplementation)
{
this.name = name;
this.discoveryNamespace = discoveryNamespace;
this.discoveryVersionImplementation = discoveryVersionImplementation;
}
public static DiscoveryVersion WSDiscoveryApril2005
{
get
{
if (DiscoveryVersion.wsDiscoveryApril2005 == null)
{
lock (staticLock)
{
if (DiscoveryVersion.wsDiscoveryApril2005 == null)
{
DiscoveryVersion.wsDiscoveryApril2005 = new DiscoveryVersion(
ProtocolStrings.VersionApril2005.Name,
ProtocolStrings.VersionApril2005.Namespace,
new DiscoveryVersionApril2005Implementation());
}
}
}
return DiscoveryVersion.wsDiscoveryApril2005;
}
}
public static DiscoveryVersion WSDiscoveryCD1
{
get
{
if (DiscoveryVersion.wsDiscoveryCD1 == null)
{
lock (staticLock)
{
if (DiscoveryVersion.wsDiscoveryCD1 == null)
{
DiscoveryVersion.wsDiscoveryCD1 = new DiscoveryVersion(
ProtocolStrings.VersionCD1.Name,
ProtocolStrings.VersionCD1.Namespace,
new DiscoveryVersionCD1Implementation());
}
}
}
return DiscoveryVersion.wsDiscoveryCD1;
}
}
public static DiscoveryVersion WSDiscovery11
{
get
{
if (DiscoveryVersion.wsDiscovery11 == null)
{
lock (staticLock)
{
if (DiscoveryVersion.wsDiscovery11 == null)
{
DiscoveryVersion.wsDiscovery11 = new DiscoveryVersion(
ProtocolStrings.Version11.Name,
ProtocolStrings.Version11.Namespace,
new DiscoveryVersion11Implementation());
}
}
}
return DiscoveryVersion.wsDiscovery11;
}
}
public string Namespace
{
get
{
return this.discoveryNamespace;
}
}
public string Name
{
get
{
return this.name;
}
}
public MessageVersion MessageVersion
{
get
{
return this.discoveryVersionImplementation.MessageVersion;
}
}
[SuppressMessage(
FxCop.Category.Naming,
FxCop.Rule.IdentifiersShouldBeSpelledCorrectly,
Justification = "Adhoc is a valid name.")]
public Uri AdhocAddress
{
get
{
return this.discoveryVersionImplementation.DiscoveryAddress;
}
}
internal static DiscoveryVersion DefaultDiscoveryVersion
{
get
{
return DiscoveryVersion.FromName(ProtocolStrings.VersionNameDefault);
}
}
internal IDiscoveryVersionImplementation Implementation
{
get
{
return this.discoveryVersionImplementation;
}
}
public static DiscoveryVersion FromName(string name)
{
if (name == null)
{
throw FxTrace.Exception.ArgumentNull("name");
}
if (WSDiscovery11.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return WSDiscovery11;
}
else if (WSDiscoveryCD1.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return WSDiscoveryCD1;
}
else if (WSDiscoveryApril2005.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return WSDiscoveryApril2005;
}
throw FxTrace.Exception.AsError(new ArgumentOutOfRangeException(
SR2.DiscoveryIncorrectVersion(name, WSDiscovery11.Name, WSDiscoveryCD1.Name, WSDiscoveryApril2005.Name)));
}
public override string ToString()
{
return SR.DiscoveryVersionToString(this.Name, this.Namespace);
}
internal class SchemaQualifiedNames
{
public readonly XmlQualifiedName AppSequenceType;
public readonly XmlQualifiedName AnyType;
public readonly XmlQualifiedName AnyUriType;
public readonly XmlQualifiedName EprElement;
public readonly XmlQualifiedName MetadataVersionElement;
public readonly XmlQualifiedName ProbeMatchType;
public readonly XmlQualifiedName ProbeType;
public readonly XmlQualifiedName QNameListType;
public readonly XmlQualifiedName QNameType;
public readonly XmlQualifiedName ResolveType;
public readonly XmlQualifiedName ScopesElement;
public readonly XmlQualifiedName ScopesType;
public readonly XmlQualifiedName TypesElement;
public readonly XmlQualifiedName UnsignedIntType;
public readonly XmlQualifiedName UriListType;
public readonly XmlQualifiedName XAddrsElement;
internal SchemaQualifiedNames(string versionNameSpace, string wsaNameSpace)
{
this.AppSequenceType = new XmlQualifiedName(ProtocolStrings.SchemaNames.AppSequenceType, versionNameSpace);
this.AnyType = new XmlQualifiedName("anyType", ProtocolStrings.XsNamespace);
this.AnyUriType = new XmlQualifiedName("anyURI", ProtocolStrings.XsNamespace);
this.EprElement = new XmlQualifiedName(ProtocolStrings.SchemaNames.EprElement, wsaNameSpace);
this.MetadataVersionElement = new XmlQualifiedName(ProtocolStrings.SchemaNames.MetadataVersionElement, versionNameSpace);
this.ProbeMatchType = new XmlQualifiedName(ProtocolStrings.SchemaNames.ProbeMatchType, versionNameSpace);
this.ProbeType = new XmlQualifiedName(ProtocolStrings.SchemaNames.ProbeType, versionNameSpace);
this.QNameListType = new XmlQualifiedName(ProtocolStrings.SchemaNames.QNameListType, versionNameSpace);
this.QNameType = new XmlQualifiedName("QName", ProtocolStrings.XsNamespace);
this.ResolveType = new XmlQualifiedName(ProtocolStrings.SchemaNames.ResolveType, versionNameSpace);
this.ScopesElement = new XmlQualifiedName(ProtocolStrings.SchemaNames.ScopesElement, versionNameSpace);
this.ScopesType = new XmlQualifiedName(ProtocolStrings.SchemaNames.ScopesType, versionNameSpace);
this.TypesElement = new XmlQualifiedName(ProtocolStrings.SchemaNames.TypesElement, versionNameSpace);
this.UnsignedIntType = new XmlQualifiedName("unsignedInt", ProtocolStrings.XsNamespace);
this.UriListType = new XmlQualifiedName(ProtocolStrings.SchemaNames.UriListType, versionNameSpace);
this.XAddrsElement = new XmlQualifiedName(ProtocolStrings.SchemaNames.XAddrsElement, versionNameSpace);
}
}
}
}
| |
// 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.
//
// Description: Localization comments related class
//
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
#if !PBTCOMPILER
using System.Windows;
#endif
using MS.Utility;
// Disabling 1634 and 1691:
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling C# source code with the C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
namespace MS.Internal.Globalization
{
/// <remarks>
/// Note: the class name and property name must be kept in sync'ed with
/// Framework\System\Windows\Localization.cs file.
/// Compiler checks for them by literal string comparisons.
/// </remarks>
internal static class LocComments
{
/// <summary>
/// Helper function to determine whether this is the Localization.Attribute attached proeprty
/// </summary>
/// <param name="type">type name</param>
/// <param name="property">property name</param>
internal static bool IsLocLocalizabilityProperty(string type, string property)
{
return "Attributes" == property
&& "System.Windows.Localization" == type;
}
/// <summary>
/// Helper function to determind whether this is the Localization.Comments attached proeprty
/// </summary>
/// <param name="type">type name</param>
/// <param name="property">property name</param>
internal static bool IsLocCommentsProperty(string type, string property)
{
return "Comments" == property
&& "System.Windows.Localization" == type;
}
/// <summary>
/// Helper function to parse the Localization.Attributes value into multiple pairs
/// </summary>
/// <param name="input">content of Localization.Attributes</param>
internal static PropertyComment[] ParsePropertyLocalizabilityAttributes(string input)
{
PropertyComment[] pairs = ParsePropertyComments(input);
if (pairs != null)
{
for (int i = 0; i < pairs.Length; i++)
{
pairs[i].Value = LookupAndSetLocalizabilityAttribute((string)pairs[i].Value);
}
}
return pairs;
}
/// <summary>
/// Helper function to parse the Localization.Comments value into multiple pairs
/// </summary>
/// <param name="input">content of Localization.Comments</param>
internal static PropertyComment[] ParsePropertyComments(string input)
{
//
// Localization comments consist of repeating "[PropertyName]([Value])"
// e.g. $Content (abc) FontSize(def)
//
if (input == null) return null;
List<PropertyComment> tokens = new List<PropertyComment>(8);
StringBuilder tokenBuffer = new StringBuilder();
PropertyComment currentPair = new PropertyComment();
bool escaped = false;
for (int i = 0; i < input.Length; i++)
{
if (currentPair.PropertyName == null)
{
// parsing "PropertyName" section
if (Char.IsWhiteSpace(input[i]) && !escaped)
{
if (tokenBuffer.Length > 0)
{
// terminate the PropertyName by an unesacped whitespace
currentPair.PropertyName = tokenBuffer.ToString();
tokenBuffer = new StringBuilder();
}
// else ignore whitespace at the beginning of the PropertyName name
}
else
{
if (input[i] == CommentStart && !escaped)
{
if (i > 0)
{
// terminate the PropertyName by an unescaped CommentStart char
currentPair.PropertyName = tokenBuffer.ToString();
tokenBuffer = new StringBuilder();
i--; // put back this char and continue
}
else
{
// can't begin with unescaped comment start char.
throw new FormatException(SR.Get(SRID.InvalidLocCommentTarget, input));
}
}
else if (input[i] == EscapeChar && !escaped)
{
escaped = true;
}
else
{
tokenBuffer.Append(input[i]);
escaped = false;
}
}
}
else
{
// parsing the "Value" part
if (tokenBuffer.Length == 0)
{
if (input[i] == CommentStart && !escaped)
{
// comment must begin with unescaped CommentStart
tokenBuffer.Append(input[i]);
escaped = false;
}
else if (!Char.IsWhiteSpace(input[i]))
{
// else, only white space is allows before an unescaped comment start char
throw new FormatException(SR.Get(SRID.InvalidLocCommentValue, currentPair.PropertyName, input));
}
}
else
{
// inside the comment
if (input[i] == CommentEnd)
{
if (!escaped)
{
// terminated by unescaped Comment
currentPair.Value = tokenBuffer.ToString().Substring(1);
tokens.Add(currentPair);
tokenBuffer = new StringBuilder();
currentPair = new PropertyComment();
}
else
{
// continue on escaped end char
tokenBuffer.Append(input[i]);
escaped = false;
}
}
else if (input[i] == CommentStart && !escaped)
{
// throw if there is unescape start in comment
throw new FormatException(SR.Get(SRID.InvalidLocCommentValue, currentPair.PropertyName, input));
}
else
{
// comment
if (input[i] == EscapeChar && !escaped)
{
escaped = true;
}
else
{
tokenBuffer.Append(input[i]);
escaped = false;
}
}
}
}
}
if (currentPair.PropertyName != null || tokenBuffer.Length != 0)
{
// unmatched PropertyName and Value pair
throw new FormatException(SR.Get(SRID.UnmatchedLocComment, input));
}
return tokens.ToArray();
}
//------------------------------
// Private methods
//------------------------------
private static LocalizabilityGroup LookupAndSetLocalizabilityAttribute(string input)
{
//
// For Localization.Attributes, values are seperated by spaces, e.g.
// $Content (Modifiable Readable)
// We are breaking the content and convert it to corresponding enum values.
//
LocalizabilityGroup attributeGroup = new LocalizabilityGroup();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (Char.IsWhiteSpace(input[i]))
{
if (builder.Length > 0)
{
ParseLocalizabilityString(
builder.ToString(),
attributeGroup
);
builder = new StringBuilder();
}
}
else
{
builder.Append(input[i]);
}
}
if (builder.Length > 0)
{
ParseLocalizabilityString(
builder.ToString(),
attributeGroup
);
}
return attributeGroup;
}
private static void ParseLocalizabilityString(
string value,
LocalizabilityGroup attributeGroup
)
{
int enumValue;
if (ReadabilityIndexTable.TryGet(value, out enumValue))
{
attributeGroup.Readability = (Readability)enumValue;
return;
}
if (ModifiabilityIndexTable.TryGet(value, out enumValue))
{
attributeGroup.Modifiability = (Modifiability)enumValue;
return;
}
if (LocalizationCategoryIndexTable.TryGet(value, out enumValue))
{
attributeGroup.Category = (LocalizationCategory)enumValue;
return;
}
throw new FormatException(SR.Get(SRID.InvalidLocalizabilityValue, value));
}
private const char CommentStart = '(';
private const char CommentEnd = ')';
private const char EscapeChar = '\\';
// loc comments file recognized element
internal const string LocDocumentRoot = "LocalizableAssembly";
internal const string LocResourcesElement = "LocalizableFile";
internal const string LocCommentsElement = "LocalizationDirectives";
internal const string LocFileNameAttribute = "Name";
internal const string LocCommentIDAttribute = "Uid";
internal const string LocCommentsAttribute = "Comments";
internal const string LocLocalizabilityAttribute = "Attributes";
//
// Tables that map the enum string names into their enum indices.
// Each index table contains the list of enum names in the exact
// order of their enum indices. They must be consistent with the enum
// declarations in core.
//
private static EnumNameIndexTable ReadabilityIndexTable = new EnumNameIndexTable(
"Readability.",
new string[] {
"Unreadable",
"Readable",
"Inherit"
}
);
private static EnumNameIndexTable ModifiabilityIndexTable = new EnumNameIndexTable(
"Modifiability.",
new string[] {
"Unmodifiable",
"Modifiable",
"Inherit"
}
);
private static EnumNameIndexTable LocalizationCategoryIndexTable = new EnumNameIndexTable(
"LocalizationCategory.",
new string[] {
"None",
"Text",
"Title",
"Label",
"Button",
"CheckBox",
"ComboBox",
"ListBox",
"Menu",
"RadioButton",
"ToolTip",
"Hyperlink",
"TextFlow",
"XmlData",
"Font",
"Inherit",
"Ignore",
"NeverLocalize"
}
);
/// <summary>
/// A simple table that maps a enum name into its enum index. The string can be
/// the enum value's name by itself or preceeded by the enum's prefix to reduce
/// ambiguity.
/// </summary>
private class EnumNameIndexTable
{
private string _enumPrefix;
private string[] _enumNames;
internal EnumNameIndexTable(
string enumPrefix,
string[] enumNames
)
{
Debug.Assert(enumPrefix != null && enumNames != null);
_enumPrefix = enumPrefix;
_enumNames = enumNames;
}
internal bool TryGet(string enumName, out int enumIndex)
{
enumIndex = 0;
if (enumName.StartsWith(_enumPrefix, StringComparison.Ordinal))
{
// get the real enum name after the prefix.
enumName = enumName.Substring(_enumPrefix.Length);
}
for (int i = 0; i < _enumNames.Length; i++)
{
if (string.Compare(enumName, _enumNames[i], StringComparison.Ordinal) == 0)
{
enumIndex = i;
return true;
}
}
return false;
}
}
}
internal class PropertyComment
{
string _target;
object _value;
internal PropertyComment() { }
internal string PropertyName
{
get { return _target; }
set { _target = value; }
}
internal object Value
{
get { return _value; }
set { _value = value; }
}
}
internal class LocalizabilityGroup
{
private const int InvalidValue = -1;
internal Modifiability Modifiability;
internal Readability Readability;
internal LocalizationCategory Category;
internal LocalizabilityGroup()
{
Modifiability = (Modifiability)InvalidValue;
Readability = (Readability)InvalidValue;
Category = (LocalizationCategory)InvalidValue;
}
#if !PBTCOMPILER
// Helper to override a localizability attribute. Not needed for compiler
internal LocalizabilityAttribute Override(LocalizabilityAttribute attribute)
{
Modifiability modifiability = attribute.Modifiability;
Readability readability = attribute.Readability;
LocalizationCategory category = attribute.Category;
bool overridden = false;
if (((int)Modifiability) != InvalidValue)
{
modifiability = Modifiability;
overridden = true;
}
if (((int)Readability) != InvalidValue)
{
readability = Readability;
overridden = true;
}
if (((int)Category) != InvalidValue)
{
category = Category;
overridden = true;
}
if (overridden)
{
attribute = new LocalizabilityAttribute(category);
attribute.Modifiability = modifiability;
attribute.Readability = readability;
}
return attribute;
}
#endif
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
namespace Spine {
public class Animation {
internal ExposedList<Timeline> timelines;
internal float duration;
internal String name;
public String Name { get { return name; } }
public ExposedList<Timeline> Timelines { get { return timelines; } set { timelines = value; } }
public float Duration { get { return duration; } set { duration = value; } }
public Animation (String name, ExposedList<Timeline> timelines, float duration) {
if (name == null) throw new ArgumentNullException("name cannot be null.");
if (timelines == null) throw new ArgumentNullException("timelines cannot be null.");
this.name = name;
this.timelines = timelines;
this.duration = duration;
}
/// <summary>Poses the skeleton at the specified time for this animation.</summary>
/// <param name="lastTime">The last time the animation was applied.</param>
/// <param name="events">Any triggered events are added.</param>
public void Apply (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events) {
if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
if (loop && duration != 0) {
time %= duration;
if (lastTime > 0) lastTime %= duration;
}
ExposedList<Timeline> timelines = this.timelines;
for (int i = 0, n = timelines.Count; i < n; i++)
timelines.Items[i].Apply(skeleton, lastTime, time, events, 1);
}
/// <summary>Poses the skeleton at the specified time for this animation mixed with the current pose.</summary>
/// <param name="lastTime">The last time the animation was applied.</param>
/// <param name="events">Any triggered events are added.</param>
/// <param name="alpha">The amount of this animation that affects the current pose.</param>
public void Mix (Skeleton skeleton, float lastTime, float time, bool loop, ExposedList<Event> events, float alpha) {
if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null.");
if (loop && duration != 0) {
time %= duration;
if (lastTime > 0) lastTime %= duration;
}
ExposedList<Timeline> timelines = this.timelines;
for (int i = 0, n = timelines.Count; i < n; i++)
timelines.Items[i].Apply(skeleton, lastTime, time, events, alpha);
}
/// <param name="target">After the first and before the last entry.</param>
internal static int binarySearch (float[] values, float target, int step) {
int low = 0;
int high = values.Length / step - 2;
if (high == 0) return step;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1) * step] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1) * step;
current = (int)((uint)(low + high) >> 1);
}
}
/// <param name="target">After the first and before the last entry.</param>
internal static int binarySearch (float[] values, float target) {
int low = 0;
int high = values.Length - 2;
if (high == 0) return 1;
int current = (int)((uint)high >> 1);
while (true) {
if (values[(current + 1)] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1);
current = (int)((uint)(low + high) >> 1);
}
}
internal static int linearSearch (float[] values, float target, int step) {
for (int i = 0, last = values.Length - step; i <= last; i += step)
if (values[i] > target) return i;
return -1;
}
}
public interface Timeline {
/// <summary>Sets the value(s) for the specified time.</summary>
/// <param name="events">May be null to not collect fired events.</param>
void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> events, float alpha);
}
/// <summary>Base class for frames that use an interpolation bezier curve.</summary>
abstract public class CurveTimeline : Timeline {
protected const float LINEAR = 0, STEPPED = 1, BEZIER = 2;
protected const int BEZIER_SEGMENTS = 10, BEZIER_SIZE = BEZIER_SEGMENTS * 2 - 1;
private float[] curves; // type, x, y, ...
public int FrameCount { get { return curves.Length / BEZIER_SIZE + 1; } }
public CurveTimeline (int frameCount) {
curves = new float[(frameCount - 1) * BEZIER_SIZE];
}
abstract public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha);
public void SetLinear (int frameIndex) {
curves[frameIndex * BEZIER_SIZE] = LINEAR;
}
public void SetStepped (int frameIndex) {
curves[frameIndex * BEZIER_SIZE] = STEPPED;
}
/// <summary>Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
/// cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
/// the difference between the keyframe's values.</summary>
public void SetCurve (int frameIndex, float cx1, float cy1, float cx2, float cy2) {
float subdiv1 = 1f / BEZIER_SEGMENTS, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1;
float pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3;
float tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1;
float dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3;
float ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5;
float dddfx = tmp2x * pre5, dddfy = tmp2y * pre5;
int i = frameIndex * BEZIER_SIZE;
float[] curves = this.curves;
curves[i++] = BEZIER;
float x = dfx, y = dfy;
for (int n = i + BEZIER_SIZE - 1; i < n; i += 2) {
curves[i] = x;
curves[i + 1] = y;
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
x += dfx;
y += dfy;
}
}
public float GetCurvePercent (int frameIndex, float percent) {
float[] curves = this.curves;
int i = frameIndex * BEZIER_SIZE;
float type = curves[i];
if (type == LINEAR) return percent;
if (type == STEPPED) return 0;
i++;
float x = 0;
for (int start = i, n = i + BEZIER_SIZE - 1; i < n; i += 2) {
x = curves[i];
if (x >= percent) {
float prevX, prevY;
if (i == start) {
prevX = 0;
prevY = 0;
} else {
prevX = curves[i - 2];
prevY = curves[i - 1];
}
return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
}
}
float y = curves[i - 1];
return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1.
}
public float GetCurveType (int frameIndex) {
return curves[frameIndex * BEZIER_SIZE];
}
}
public class RotateTimeline : CurveTimeline {
protected const int PREV_FRAME_TIME = -2;
protected const int FRAME_VALUE = 1;
internal int boneIndex;
internal float[] frames;
public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, value, ...
public RotateTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount << 1];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float angle) {
frameIndex *= 2;
frames[frameIndex] = time;
frames[frameIndex + 1] = angle;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
float amount;
if (time >= frames[frames.Length - 2]) { // Time is after last frame.
amount = bone.data.rotation + frames[frames.Length - 1] - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time, 2);
float prevFrameValue = frames[frameIndex - 1];
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime);
percent = GetCurvePercent((frameIndex >> 1) - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
amount = frames[frameIndex + FRAME_VALUE] - prevFrameValue;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
}
}
public class TranslateTimeline : CurveTimeline {
protected const int PREV_FRAME_TIME = -3;
protected const int FRAME_X = 1;
protected const int FRAME_Y = 2;
internal int boneIndex;
internal float[] frames;
public int BoneIndex { get { return boneIndex; } set { boneIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, value, value, ...
public TranslateTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * 3];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float x, float y) {
frameIndex *= 3;
frames[frameIndex] = time;
frames[frameIndex + 1] = x;
frames[frameIndex + 2] = y;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
if (time >= frames[frames.Length - 3]) { // Time is after last frame.
bone.x += (bone.data.x + frames[frames.Length - 2] - bone.x) * alpha;
bone.y += (bone.data.y + frames[frames.Length - 1] - bone.y) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time, 3);
float prevFrameX = frames[frameIndex - 2];
float prevFrameY = frames[frameIndex - 1];
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime);
percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + FRAME_X] - prevFrameX) * percent - bone.x) * alpha;
bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + FRAME_Y] - prevFrameY) * percent - bone.y) * alpha;
}
}
public class ScaleTimeline : TranslateTimeline {
public ScaleTimeline (int frameCount)
: base(frameCount) {
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
Bone bone = skeleton.bones.Items[boneIndex];
if (time >= frames[frames.Length - 3]) { // Time is after last frame.
bone.scaleX += (bone.data.scaleX * frames[frames.Length - 2] - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * frames[frames.Length - 1] - bone.scaleY) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time, 3);
float prevFrameX = frames[frameIndex - 2];
float prevFrameY = frames[frameIndex - 1];
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime);
percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + FRAME_X] - prevFrameX) * percent) - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + FRAME_Y] - prevFrameY) * percent) - bone.scaleY) * alpha;
}
}
public class ColorTimeline : CurveTimeline {
protected const int PREV_FRAME_TIME = -5;
protected const int FRAME_R = 1;
protected const int FRAME_G = 2;
protected const int FRAME_B = 3;
protected const int FRAME_A = 4;
internal int slotIndex;
internal float[] frames;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, r, g, b, a, ...
public ColorTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * 5];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float r, float g, float b, float a) {
frameIndex *= 5;
frames[frameIndex] = time;
frames[frameIndex + 1] = r;
frames[frameIndex + 2] = g;
frames[frameIndex + 3] = b;
frames[frameIndex + 4] = a;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
float r, g, b, a;
if (time >= frames[frames.Length - 5]) {
// Time is after last frame.
int i = frames.Length - 1;
r = frames[i - 3];
g = frames[i - 2];
b = frames[i - 1];
a = frames[i];
} else {
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time, 5);
float prevFrameR = frames[frameIndex - 4];
float prevFrameG = frames[frameIndex - 3];
float prevFrameB = frames[frameIndex - 2];
float prevFrameA = frames[frameIndex - 1];
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime);
percent = GetCurvePercent(frameIndex / 5 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
r = prevFrameR + (frames[frameIndex + FRAME_R] - prevFrameR) * percent;
g = prevFrameG + (frames[frameIndex + FRAME_G] - prevFrameG) * percent;
b = prevFrameB + (frames[frameIndex + FRAME_B] - prevFrameB) * percent;
a = prevFrameA + (frames[frameIndex + FRAME_A] - prevFrameA) * percent;
}
Slot slot = skeleton.slots.Items[slotIndex];
if (alpha < 1) {
slot.r += (r - slot.r) * alpha;
slot.g += (g - slot.g) * alpha;
slot.b += (b - slot.b) * alpha;
slot.a += (a - slot.a) * alpha;
} else {
slot.r = r;
slot.g = g;
slot.b = b;
slot.a = a;
}
}
}
public class AttachmentTimeline : Timeline {
internal int slotIndex;
internal float[] frames;
private String[] attachmentNames;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public String[] AttachmentNames { get { return attachmentNames; } set { attachmentNames = value; } }
public int FrameCount { get { return frames.Length; } }
public AttachmentTimeline (int frameCount) {
frames = new float[frameCount];
attachmentNames = new String[frameCount];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, String attachmentName) {
frames[frameIndex] = time;
attachmentNames[frameIndex] = attachmentName;
}
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) {
if (lastTime > time) Apply(skeleton, lastTime, int.MaxValue, null, 0);
return;
} else if (lastTime > time) //
lastTime = -1;
int frameIndex = (time >= frames[frames.Length - 1] ? frames.Length : Animation.binarySearch(frames, time)) - 1;
if (frames[frameIndex] < lastTime) return;
String attachmentName = attachmentNames[frameIndex];
skeleton.slots.Items[slotIndex].Attachment =
attachmentName == null ? null : skeleton.GetAttachment(slotIndex, attachmentName);
}
}
public class EventTimeline : Timeline {
internal float[] frames;
private Event[] events;
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public Event[] Events { get { return events; } set { events = value; } }
public int FrameCount { get { return frames.Length; } }
public EventTimeline (int frameCount) {
frames = new float[frameCount];
events = new Event[frameCount];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, Event e) {
frames[frameIndex] = e.Time;
events[frameIndex] = e;
}
/// <summary>Fires events for frames > lastTime and <= time.</summary>
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
if (firedEvents == null) return;
float[] frames = this.frames;
int frameCount = frames.Length;
if (lastTime > time) { // Fire events after last time for looped animations.
Apply(skeleton, lastTime, int.MaxValue, firedEvents, alpha);
lastTime = -1f;
} else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame.
return;
if (time < frames[0]) return; // Time is before first frame.
int frameIndex;
if (lastTime < frames[0])
frameIndex = 0;
else {
frameIndex = Animation.binarySearch(frames, lastTime);
float frame = frames[frameIndex];
while (frameIndex > 0) { // Fire multiple events with the same frame.
if (frames[frameIndex - 1] != frame) break;
frameIndex--;
}
}
for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++)
firedEvents.Add(events[frameIndex]);
}
}
public class DrawOrderTimeline : Timeline {
internal float[] frames;
private int[][] drawOrders;
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public int[][] DrawOrders { get { return drawOrders; } set { drawOrders = value; } }
public int FrameCount { get { return frames.Length; } }
public DrawOrderTimeline (int frameCount) {
frames = new float[frameCount];
drawOrders = new int[frameCount][];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
/// <param name="drawOrder">May be null to use bind pose draw order.</param>
public void SetFrame (int frameIndex, float time, int[] drawOrder) {
frames[frameIndex] = time;
drawOrders[frameIndex] = drawOrder;
}
public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
int frameIndex;
if (time >= frames[frames.Length - 1]) // Time is after last frame.
frameIndex = frames.Length - 1;
else
frameIndex = Animation.binarySearch(frames, time) - 1;
ExposedList<Slot> drawOrder = skeleton.drawOrder;
ExposedList<Slot> slots = skeleton.slots;
int[] drawOrderToSetupIndex = drawOrders[frameIndex];
if (drawOrderToSetupIndex == null) {
drawOrder.Clear();
for (int i = 0, n = slots.Count; i < n; i++)
drawOrder.Add(slots.Items[i]);
} else {
for (int i = 0, n = drawOrderToSetupIndex.Length; i < n; i++)
drawOrder.Items[i] = slots.Items[drawOrderToSetupIndex[i]];
}
}
}
public class FFDTimeline : CurveTimeline {
internal int slotIndex;
internal float[] frames;
private float[][] frameVertices;
internal Attachment attachment;
public int SlotIndex { get { return slotIndex; } set { slotIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, ...
public float[][] Vertices { get { return frameVertices; } set { frameVertices = value; } }
public Attachment Attachment { get { return attachment; } set { attachment = value; } }
public FFDTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount];
frameVertices = new float[frameCount][];
}
/// <summary>Sets the time and value of the specified keyframe.</summary>
public void SetFrame (int frameIndex, float time, float[] vertices) {
frames[frameIndex] = time;
frameVertices[frameIndex] = vertices;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
Slot slot = skeleton.slots.Items[slotIndex];
if (slot.attachment != attachment) return;
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
float[][] frameVertices = this.frameVertices;
int vertexCount = frameVertices[0].Length;
float[] vertices = slot.attachmentVertices;
if (vertices.Length < vertexCount) {
vertices = new float[vertexCount];
slot.attachmentVertices = vertices;
}
if (vertices.Length != vertexCount) alpha = 1; // Don't mix from uninitialized slot vertices.
slot.attachmentVerticesCount = vertexCount;
if (time >= frames[frames.Length - 1]) { // Time is after last frame.
float[] lastVertices = frameVertices[frames.Length - 1];
if (alpha < 1) {
for (int i = 0; i < vertexCount; i++) {
float vertex = vertices[i];
vertices[i] = vertex + (lastVertices[i] - vertex) * alpha;
}
} else
Array.Copy(lastVertices, 0, vertices, 0, vertexCount);
return;
}
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time);
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime);
percent = GetCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
float[] prevVertices = frameVertices[frameIndex - 1];
float[] nextVertices = frameVertices[frameIndex];
if (alpha < 1) {
for (int i = 0; i < vertexCount; i++) {
float prev = prevVertices[i];
float vertex = vertices[i];
vertices[i] = vertex + (prev + (nextVertices[i] - prev) * percent - vertex) * alpha;
}
} else {
for (int i = 0; i < vertexCount; i++) {
float prev = prevVertices[i];
vertices[i] = prev + (nextVertices[i] - prev) * percent;
}
}
}
}
public class IkConstraintTimeline : CurveTimeline {
private const int PREV_FRAME_TIME = -3;
private const int PREV_FRAME_MIX = -2;
private const int PREV_FRAME_BEND_DIRECTION = -1;
private const int FRAME_MIX = 1;
internal int ikConstraintIndex;
internal float[] frames;
public int IkConstraintIndex { get { return ikConstraintIndex; } set { ikConstraintIndex = value; } }
public float[] Frames { get { return frames; } set { frames = value; } } // time, mix, bendDirection, ...
public IkConstraintTimeline (int frameCount)
: base(frameCount) {
frames = new float[frameCount * 3];
}
/** Sets the time, mix and bend direction of the specified keyframe. */
public void SetFrame (int frameIndex, float time, float mix, int bendDirection) {
frameIndex *= 3;
frames[frameIndex] = time;
frames[frameIndex + 1] = mix;
frames[frameIndex + 2] = bendDirection;
}
override public void Apply (Skeleton skeleton, float lastTime, float time, ExposedList<Event> firedEvents, float alpha) {
float[] frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
IkConstraint ikConstraint = skeleton.ikConstraints.Items[ikConstraintIndex];
if (time >= frames[frames.Length - 3]) { // Time is after last frame.
ikConstraint.mix += (frames[frames.Length - 2] - ikConstraint.mix) * alpha;
ikConstraint.bendDirection = (int)frames[frames.Length - 1];
return;
}
// Interpolate between the previous frame and the current frame.
int frameIndex = Animation.binarySearch(frames, time, 3);
float prevFrameMix = frames[frameIndex + PREV_FRAME_MIX];
float frameTime = frames[frameIndex];
float percent = 1 - (time - frameTime) / (frames[frameIndex + PREV_FRAME_TIME] - frameTime);
percent = GetCurvePercent(frameIndex / 3 - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
float mix = prevFrameMix + (frames[frameIndex + FRAME_MIX] - prevFrameMix) * percent;
ikConstraint.mix += (mix - ikConstraint.mix) * alpha;
ikConstraint.bendDirection = (int)frames[frameIndex + PREV_FRAME_BEND_DIRECTION];
}
}
}
| |
/*============================================================
**
**
** Purpose:
** This public class is used for reading event records from event log.
**
============================================================*/
using System.IO;
using System.Collections.Generic;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// This public class is used for reading event records from event log.
/// </summary>
public class EventLogReader : IDisposable
{
private EventLogQuery _eventQuery;
private int _batchSize;
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle _handle;
/// <summary>
/// events buffer holds batched event (handles).
/// </summary>
private IntPtr[] _eventsBuffer;
/// <summary>
/// The current index where the function GetNextEvent is (inside the eventsBuffer).
/// </summary>
private int _currentIndex;
/// <summary>
/// The number of events read from the batch into the eventsBuffer
/// </summary>
private int _eventCount;
/// <summary>
/// When the reader finishes (will always return only ERROR_NO_MORE_ITEMS).
/// For subscription, this means we need to wait for next event.
/// </summary>
private bool _isEof;
/// <summary>
/// Maintains cached display / metadata information returned from
/// EventRecords that were obtained from this reader.
/// </summary>
private ProviderMetadataCachedInformation _cachedMetadataInformation;
public EventLogReader(string path)
: this(new EventLogQuery(path, PathType.LogName), null)
{
}
public EventLogReader(string path, PathType pathType)
: this(new EventLogQuery(path, pathType), null)
{
}
public EventLogReader(EventLogQuery eventQuery)
: this(eventQuery, null)
{
}
[System.Security.SecurityCritical]
public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark)
{
if (eventQuery == null)
throw new ArgumentNullException("eventQuery");
string logfile = null;
if (eventQuery.ThePathType == PathType.FilePath)
logfile = eventQuery.Path;
_cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50);
//explicit data
_eventQuery = eventQuery;
//implicit
_batchSize = 64;
_eventsBuffer = new IntPtr[_batchSize];
//
// compute the flag.
//
int flag = 0;
if (_eventQuery.ThePathType == PathType.LogName)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath;
else
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath;
if (_eventQuery.ReverseDirection)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryReverseDirection;
if (_eventQuery.TolerateQueryErrors)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryTolerateQueryErrors;
_handle = NativeWrapper.EvtQuery(_eventQuery.Session.Handle,
_eventQuery.Path, _eventQuery.Query,
flag);
EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark);
if (!bookmarkHandle.IsInvalid)
{
using (bookmarkHandle)
{
NativeWrapper.EvtSeek(_handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
}
public int BatchSize
{
get
{
return _batchSize;
}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value");
_batchSize = value;
}
}
[System.Security.SecurityCritical]
private bool GetNextBatch(TimeSpan ts)
{
int timeout;
if (ts == TimeSpan.MaxValue)
timeout = -1;
else
timeout = (int)ts.TotalMilliseconds;
// batchSize was changed by user, reallocate buffer.
if (_batchSize != _eventsBuffer.Length) _eventsBuffer = new IntPtr[_batchSize];
int newEventCount = 0;
bool results = NativeWrapper.EvtNext(_handle, _batchSize, _eventsBuffer, timeout, 0, ref newEventCount);
if (!results)
{
_eventCount = 0;
_currentIndex = 0;
return false; //no more events in the result set
}
_currentIndex = 0;
_eventCount = newEventCount;
return true;
}
public EventRecord ReadEvent()
{
return ReadEvent(TimeSpan.MaxValue);
}
// security critical because allocates SafeHandle.
// marked as safe because performs Demand check.
[System.Security.SecurityCritical]
public EventRecord ReadEvent(TimeSpan timeout)
{
if (_isEof)
throw new InvalidOperationException();
if (_currentIndex >= _eventCount)
{
// buffer is empty, get next batch.
GetNextBatch(timeout);
if (_currentIndex >= _eventCount)
{
_isEof = true;
return null;
}
}
EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(_eventsBuffer[_currentIndex], true), _eventQuery.Session, _cachedMetadataInformation);
_currentIndex++;
return eventInstance;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
[System.Security.SecurityCritical]
internal void SeekReset()
{
//
//close all unread event handles in the buffer
//
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
//reset the indexes used by Next
_currentIndex = 0;
_eventCount = 0;
_isEof = false;
}
// marked as SecurityCritical because it allocates SafeHandle.
[System.Security.SecurityCritical]
internal void SeekCommon(long offset)
{
//
// modify offset that we're going to send to service to account for the
// fact that we've already read some events in our buffer that the user
// hasn't seen yet.
//
offset = offset - (_eventCount - _currentIndex);
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent);
}
public void Seek(EventBookmark bookmark)
{
Seek(bookmark, 0);
}
[System.Security.SecurityCritical]
public void Seek(EventBookmark bookmark, long offset)
{
if (bookmark == null)
throw new ArgumentNullException("bookmark");
SeekReset();
using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark))
{
NativeWrapper.EvtSeek(_handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
[System.Security.SecurityCritical]
public void Seek(SeekOrigin origin, long offset)
{
switch (origin)
{
case SeekOrigin.Begin:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst);
return;
case SeekOrigin.End:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast);
return;
case SeekOrigin.Current:
if (offset >= 0)
{
//we can reuse elements in the batch.
if (_currentIndex + offset < _eventCount)
{
//
// We don't call Seek here, we can reposition within the batch.
//
// close all event handles between [currentIndex, currentIndex + offset)
int index = _currentIndex;
while (index < _currentIndex + offset)
{
NativeWrapper.EvtClose(_eventsBuffer[index]);
index++;
}
_currentIndex = (int)(_currentIndex + offset);
//leave the eventCount unchanged
//leave the same Eof
}
else
{
SeekCommon(offset);
}
}
else
{
//if inside the current buffer, we still cannot read the events, as the handles.
//may have already been closed.
if (_currentIndex + offset >= 0)
{
SeekCommon(offset);
}
else //outside the current buffer
{
SeekCommon(offset);
}
}
return;
}
}
public void CancelReading()
{
NativeWrapper.EvtCancel(_handle);
}
public IList<EventLogStatus> LogStatus
{
[System.Security.SecurityCritical]
get
{
List<EventLogStatus> list = null;
string[] channelNames = null;
int[] errorStatuses = null;
EventLogHandle queryHandle = _handle;
if (queryHandle.IsInvalid)
throw new InvalidOperationException();
channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames);
errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses);
if (channelNames.Length != errorStatuses.Length)
throw new InvalidOperationException();
list = new List<EventLogStatus>(channelNames.Length);
for (int i = 0; i < channelNames.Length; i++)
{
EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]);
list.Add(cs);
}
return list.AsReadOnly();
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Provides properties that describe user authorization to a workspace.
/// </summary>
[DataContract]
public partial class WorkspaceUserAuthorization : IEquatable<WorkspaceUserAuthorization>, IValidatableObject
{
public WorkspaceUserAuthorization()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="WorkspaceUserAuthorization" /> class.
/// </summary>
/// <param name="CanDelete">.</param>
/// <param name="CanMove">.</param>
/// <param name="CanTransact">.</param>
/// <param name="CanView">.</param>
/// <param name="Created">The UTC DateTime when the workspace user authorization was created..</param>
/// <param name="CreatedById">.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="Modified">.</param>
/// <param name="ModifiedById">.</param>
/// <param name="WorkspaceUserId">.</param>
/// <param name="WorkspaceUserInformation">WorkspaceUserInformation.</param>
public WorkspaceUserAuthorization(string CanDelete = default(string), string CanMove = default(string), string CanTransact = default(string), string CanView = default(string), string Created = default(string), string CreatedById = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string Modified = default(string), string ModifiedById = default(string), string WorkspaceUserId = default(string), WorkspaceUser WorkspaceUserInformation = default(WorkspaceUser))
{
this.CanDelete = CanDelete;
this.CanMove = CanMove;
this.CanTransact = CanTransact;
this.CanView = CanView;
this.Created = Created;
this.CreatedById = CreatedById;
this.ErrorDetails = ErrorDetails;
this.Modified = Modified;
this.ModifiedById = ModifiedById;
this.WorkspaceUserId = WorkspaceUserId;
this.WorkspaceUserInformation = WorkspaceUserInformation;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canDelete", EmitDefaultValue=false)]
public string CanDelete { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canMove", EmitDefaultValue=false)]
public string CanMove { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canTransact", EmitDefaultValue=false)]
public string CanTransact { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="canView", EmitDefaultValue=false)]
public string CanView { get; set; }
/// <summary>
/// The UTC DateTime when the workspace user authorization was created.
/// </summary>
/// <value>The UTC DateTime when the workspace user authorization was created.</value>
[DataMember(Name="created", EmitDefaultValue=false)]
public string Created { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="createdById", EmitDefaultValue=false)]
public string CreatedById { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="modified", EmitDefaultValue=false)]
public string Modified { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="modifiedById", EmitDefaultValue=false)]
public string ModifiedById { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="workspaceUserId", EmitDefaultValue=false)]
public string WorkspaceUserId { get; set; }
/// <summary>
/// Gets or Sets WorkspaceUserInformation
/// </summary>
[DataMember(Name="workspaceUserInformation", EmitDefaultValue=false)]
public WorkspaceUser WorkspaceUserInformation { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class WorkspaceUserAuthorization {\n");
sb.Append(" CanDelete: ").Append(CanDelete).Append("\n");
sb.Append(" CanMove: ").Append(CanMove).Append("\n");
sb.Append(" CanTransact: ").Append(CanTransact).Append("\n");
sb.Append(" CanView: ").Append(CanView).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" CreatedById: ").Append(CreatedById).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Modified: ").Append(Modified).Append("\n");
sb.Append(" ModifiedById: ").Append(ModifiedById).Append("\n");
sb.Append(" WorkspaceUserId: ").Append(WorkspaceUserId).Append("\n");
sb.Append(" WorkspaceUserInformation: ").Append(WorkspaceUserInformation).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as WorkspaceUserAuthorization);
}
/// <summary>
/// Returns true if WorkspaceUserAuthorization instances are equal
/// </summary>
/// <param name="other">Instance of WorkspaceUserAuthorization to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(WorkspaceUserAuthorization other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.CanDelete == other.CanDelete ||
this.CanDelete != null &&
this.CanDelete.Equals(other.CanDelete)
) &&
(
this.CanMove == other.CanMove ||
this.CanMove != null &&
this.CanMove.Equals(other.CanMove)
) &&
(
this.CanTransact == other.CanTransact ||
this.CanTransact != null &&
this.CanTransact.Equals(other.CanTransact)
) &&
(
this.CanView == other.CanView ||
this.CanView != null &&
this.CanView.Equals(other.CanView)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.CreatedById == other.CreatedById ||
this.CreatedById != null &&
this.CreatedById.Equals(other.CreatedById)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.Modified == other.Modified ||
this.Modified != null &&
this.Modified.Equals(other.Modified)
) &&
(
this.ModifiedById == other.ModifiedById ||
this.ModifiedById != null &&
this.ModifiedById.Equals(other.ModifiedById)
) &&
(
this.WorkspaceUserId == other.WorkspaceUserId ||
this.WorkspaceUserId != null &&
this.WorkspaceUserId.Equals(other.WorkspaceUserId)
) &&
(
this.WorkspaceUserInformation == other.WorkspaceUserInformation ||
this.WorkspaceUserInformation != null &&
this.WorkspaceUserInformation.Equals(other.WorkspaceUserInformation)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.CanDelete != null)
hash = hash * 59 + this.CanDelete.GetHashCode();
if (this.CanMove != null)
hash = hash * 59 + this.CanMove.GetHashCode();
if (this.CanTransact != null)
hash = hash * 59 + this.CanTransact.GetHashCode();
if (this.CanView != null)
hash = hash * 59 + this.CanView.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.CreatedById != null)
hash = hash * 59 + this.CreatedById.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Modified != null)
hash = hash * 59 + this.Modified.GetHashCode();
if (this.ModifiedById != null)
hash = hash * 59 + this.ModifiedById.GetHashCode();
if (this.WorkspaceUserId != null)
hash = hash * 59 + this.WorkspaceUserId.GetHashCode();
if (this.WorkspaceUserInformation != null)
hash = hash * 59 + this.WorkspaceUserInformation.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Data;
using System;
namespace OpenSim.Framework.Communications
{
/// <summary>
/// Abstract base class used by local and grid implementations of an inventory service.
/// </summary>
public abstract class InventoryServiceBase : IInventoryServices, IInterServiceInventoryServices
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<IInventoryDataPlugin> m_plugins = new List<IInventoryDataPlugin>();
#region Plugin methods
/// <summary>
/// Add a new inventory data plugin - plugins will be requested in the order they were added.
/// </summary>
/// <param name="plugin">The plugin that will provide data</param>
public void AddPlugin(IInventoryDataPlugin plugin)
{
m_plugins.Add(plugin);
}
/// <summary>
/// Adds a list of inventory data plugins, as described by `provider'
/// and `connect', to `m_plugins'.
/// </summary>
/// <param name="provider">
/// The filename of the inventory server plugin DLL.
/// </param>
/// <param name="connect">
/// The connection string for the storage backend.
/// </param>
public void AddPlugin(string provider, string connect)
{
m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IInventoryDataPlugin>(provider, connect));
}
#endregion
#region IInventoryServices methods
public string Host
{
get { return "default"; }
}
public InventoryFolderBase FindFolderForType(UUID userId, int type)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryFolderBase folder = plugin.findUserFolderForType(userId, type);
if (folder != null) return folder;
}
foreach (IInventoryDataPlugin plugin in m_plugins)
{
return plugin.getUserRootFolder(userId);
}
//can't happen, there will always be at least one plugin
throw new NotImplementedException();
}
/// <summary>
/// Searches the parentage tree for an ancestor folder with a matching type (e.g. Trash)
/// </summary>
/// <param name="type"></param>
/// <returns>The top-level parent folder</returns>
public InventoryFolderBase FindTopLevelFolderFor(UUID owner, UUID folderID)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryFolderBase folder = plugin.findUserTopLevelFolderFor(owner, folderID);
if (folder != null) return folder;
}
// not found
return null;
}
public List<InventoryItemBase> RequestItemsInMultipleFolders(IEnumerable<InventoryFolderBase> folders)
{
List<InventoryItemBase> folderItems = new List<InventoryItemBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
IList<InventoryItemBase> items = plugin.getItemsInFolders(folders);
folderItems.AddRange(items);
}
return folderItems;
}
public List<InventoryItemBase> RequestAllItems(UUID userId)
{
List<InventoryItemBase> userItems = new List<InventoryItemBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
IList<InventoryItemBase> items = plugin.getAllItems(userId);
userItems.AddRange(items);
}
return userItems;
}
public List<InventoryFolderBase> GetRecursiveFolderList(UUID parentFolder)
{
List<InventoryFolderBase> subFolders = new List<InventoryFolderBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
IList<InventoryFolderBase> folders = plugin.getFolderHierarchy(parentFolder);
subFolders.AddRange(folders);
}
return subFolders;
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
// m_log.DebugFormat("[AGENT INVENTORY]: Getting inventory skeleton for {0}", userId);
InventoryFolderBase rootFolder = RequestRootFolder(userId);
// Agent has no inventory structure yet.
if (null == rootFolder)
{
return null;
}
List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>();
userFolders.Add(rootFolder);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
//IList<InventoryFolderBase> folders = plugin.getUserRootFolders(userId, rootFolder.ID);
IList<InventoryFolderBase> folders = plugin.getFolderHierarchy(rootFolder.ID);
userFolders.AddRange(folders);
}
// foreach (InventoryFolderBase folder in userFolders)
// {
// m_log.DebugFormat("[AGENT INVENTORY]: Got folder {0} {1}", folder.name, folder.folderID);
// }
return userFolders;
}
// See IInventoryServices
public virtual bool HasInventoryForUser(UUID userID)
{
return false;
}
// See IInventoryServices
public virtual InventoryFolderBase RequestRootFolder(UUID userID)
{
// Retrieve the first root folder we get from the list of plugins.
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryFolderBase rootFolder = plugin.getUserRootFolder(userID);
if (rootFolder != null)
return rootFolder;
}
// Return nothing if no plugin was able to supply a root folder
return null;
}
// See IInventoryServices
public bool CreateNewUserInventory(UUID user)
{
InventoryFolderBase existingRootFolder = RequestRootFolder(user);
if (null != existingRootFolder)
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Did not create a new inventory for user {0} since they already have "
+ "a root inventory folder with id {1}",
user, existingRootFolder.ID);
}
else
{
UsersInventory inven = new UsersInventory();
inven.CreateNewInventorySet(user);
AddNewInventorySet(inven);
return true;
}
return false;
}
// See IInventoryServices
public abstract void RequestInventoryForUser(UUID userID, InventoryReceiptCallback callback);
public abstract void RequestFolderContents(UUID userId, UUID folderId, FolderContentsCallback callback);
public abstract InventoryCollection GetRecursiveFolderContents(UUID userId, UUID folderId);
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
List<InventoryItemBase> activeGestures = new List<InventoryItemBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
activeGestures.AddRange(plugin.fetchActiveGestures(userId));
}
return activeGestures;
}
#endregion
#region Methods used by GridInventoryService
public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID)
{
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
inventoryList.AddRange(plugin.getInventoryFolders(parentFolderID));
}
return inventoryList;
}
public List<InventoryItemBase> RequestFolderItems(UUID folderID)
{
List<InventoryItemBase> itemsList = new List<InventoryItemBase>();
foreach (IInventoryDataPlugin plugin in m_plugins)
{
itemsList.AddRange(plugin.getInventoryInFolder(folderID));
}
return itemsList;
}
#endregion
// See IInventoryServices
public virtual bool AddFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.addInventoryFolder(folder);
}
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.updateInventoryFolder(folder);
}
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool MoveFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.moveInventoryFolder(folder);
}
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool AddItem(InventoryItemBase item)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.addInventoryItem(item);
}
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateItem(InventoryItemBase item)
{
m_log.InfoFormat(
"[AGENT INVENTORY]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.updateInventoryItem(item);
}
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool DeleteItem(InventoryItemBase item)
{
m_log.InfoFormat(
"[AGENT INVENTORY]: Deleting item {0} {1} from folder {2}", item.Name, item.ID, item.Folder);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.deleteInventoryItem(item.ID);
}
// FIXME: Should return false on failure
return true;
}
public virtual InventoryItemBase QueryItem(InventoryItemBase item)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryItemBase result = plugin.queryInventoryItem(item.ID);
if (result != null)
return result;
}
return null;
}
public virtual InventoryFolderBase QueryFolder(InventoryFolderBase item)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryFolderBase result = plugin.queryInventoryFolder(item.ID);
if (result != null)
return result;
}
return null;
}
/// <summary>
/// Purge a folder of all items items and subfolders.
///
/// FIXME: Really nasty in a sense, because we have to query the database to get information we may
/// already know... Needs heavy refactoring.
/// </summary>
/// <param name="folder"></param>
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[AGENT INVENTORY]: Purging folder {0} of its contents", folder.ID);
List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID);
m_log.DebugFormat(
"[AGENT INVENTORY]: Purging folder {0} of subfolders", folder.ID);
foreach (InventoryFolderBase subFolder in subFolders)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.deleteInventoryFolder(subFolder.ID);
}
}
m_log.InfoFormat(
"[AGENT INVENTORY]: Purging all items from folder {0}", folder.ID);
foreach (IInventoryDataPlugin plugin in m_plugins)
{
plugin.deleteItemsInFolder(folder.ID);
}
return true;
}
private void AddNewInventorySet(UsersInventory inventory)
{
foreach (InventoryFolderBase folder in inventory.Folders.Values)
{
AddFolder(folder);
}
}
public InventoryItemBase GetInventoryItem(UUID itemID)
{
foreach (IInventoryDataPlugin plugin in m_plugins)
{
InventoryItemBase item = plugin.getInventoryItem(itemID);
if (item != null)
return item;
}
return null;
}
/// <summary>
/// Used to create a new user inventory.
/// </summary>
private class UsersInventory
{
public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>();
public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>();
public virtual void CreateNewInventorySet(UUID user)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = UUID.Zero;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "My Inventory";
folder.Type = (short)AssetType.Folder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
UUID rootFolder = folder.ID;
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Animations";
folder.Type = (short)AssetType.Animation;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Body Parts";
folder.Type = (short)AssetType.Bodypart;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Calling Cards";
folder.Type = (short)AssetType.CallingCard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Clothing";
folder.Type = (short)AssetType.Clothing;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Gestures";
folder.Type = (short)AssetType.Gesture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Landmarks";
folder.Type = (short)AssetType.Landmark;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Lost And Found";
folder.Type = (short)FolderType.LostAndFound;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Notecards";
folder.Type = (short)AssetType.Notecard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Objects";
folder.Type = (short)AssetType.Object;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Photo Album";
folder.Type = (short)FolderType.Snapshot;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Scripts";
folder.Type = (short)AssetType.LSLText;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Sounds";
folder.Type = (short)AssetType.Sound;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Textures";
folder.Type = (short)AssetType.Texture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Trash";
folder.Type = (short)FolderType.Trash;
folder.Version = 1;
Folders.Add(folder.ID, folder);
}
}
}
}
| |
// 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.Xml;
using System.Text;
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
using XmlReaderTest.Common;
using Xunit;
namespace XmlReaderTest
{
public partial class FactoryReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new FactoryReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XMLExceptionReader()
{
RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void LinePosReader()
{
RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void LookupNamespaceReader()
{
RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void BaseURIReader()
{
RunTest(() => new TCBaseURIReader() { Attribute = new TestCase() { Name = "BaseURI", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadOuterXmlReader()
{
RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeXmlDeclarationReader()
{
RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStateReader()
{
RunTest(() => new TCReadStateReader() { Attribute = new TestCase() { Name = "ReadState", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void Normalization()
{
RunTest(() => new TCNormalization() { Attribute = new TestCase() { Name = "FactoryReader Normalization", Desc = "FactoryReader" } });
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ListInitExpressionTests
{
private class NonEnumerableAddable
{
public readonly List<int> Store = new List<int>();
public void Add(int value)
{
Store.Add(value);
}
}
private class EnumerableStaticAdd : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
yield break;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public static void Add(string value)
{
}
}
private class AnyTypeList : IEnumerable<object>
{
private readonly List<object> _inner = new List<object>();
public void Add<T>(T item) => _inner.Add(item);
public void AddIntRegardless<T>(int item) => _inner.Add(item);
public IEnumerator<object> GetEnumerator() => _inner.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
private struct ListValueType : IEnumerable<int>
{
private List<int> _store;
private List<int> EnsureStore() => _store ?? (_store = new List<int>());
public int Add(int value)
{
EnsureStore().Add(value);
return value;
}
public IEnumerator<int> GetEnumerator() => EnsureStore().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Fact]
public void NullNewMethod()
{
ConstantExpression validExpression = Expression.Constant(1);
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, validExpression));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, Enumerable.Repeat(validExpression, 1)));
MethodInfo validMethod = typeof(List<int>).GetMethod("Add");
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, validMethod, validExpression));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, validMethod, Enumerable.Repeat(validExpression, 1)));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, default(MethodInfo), validExpression));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, null, Enumerable.Repeat(validExpression, 1)));
ElementInit validElementInit = Expression.ElementInit(validMethod, validExpression);
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, validElementInit));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => Expression.ListInit(null, Enumerable.Repeat(validElementInit, 1)));
}
[Fact]
public void NullInitializers()
{
NewExpression validNew = Expression.New(typeof(List<int>));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, default(IEnumerable<Expression>)));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, default(ElementInit[])));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, default(IEnumerable<ElementInit>)));
MethodInfo validMethod = typeof(List<int>).GetMethod("Add");
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, validMethod, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, validMethod, default(IEnumerable<Expression>)));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, null, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => Expression.ListInit(validNew, null, default(IEnumerable<Expression>)));
}
private static IEnumerable<object[]> ZeroInitializerInits()
{
NewExpression validNew = Expression.New(typeof(List<int>));
yield return new object[] {Expression.ListInit(validNew, new Expression[0])};
yield return new object[] {Expression.ListInit(validNew, Enumerable.Empty<Expression>())};
yield return new object[] {Expression.ListInit(validNew, new ElementInit[0])};
yield return new object[] {Expression.ListInit(validNew, Enumerable.Empty<ElementInit>())};
MethodInfo validMethod = typeof(List<int>).GetMethod("Add");
yield return new object[] {Expression.ListInit(validNew, validMethod)};
yield return new object[] {Expression.ListInit(validNew, validMethod, Enumerable.Empty<Expression>())};
yield return new object[] {Expression.ListInit(validNew, null, new Expression[0])};
yield return new object[] {Expression.ListInit(validNew, null, Enumerable.Empty<Expression>())};
}
[Theory, PerCompilationType(nameof(ZeroInitializerInits))]
public void ZeroInitializers(Expression init, bool useInterpreter)
{
Expression<Func<List<int>>> exp = Expression.Lambda<Func<List<int>>>(init);
Func<List<int>> func = exp.Compile(useInterpreter);
Assert.Empty(func());
}
[Fact]
public void TypeWithoutAdd()
{
NewExpression newExp = Expression.New(typeof(string).GetConstructor(new[] { typeof(char[]) }), Expression.Constant("aaaa".ToCharArray()));
Assert.Throws<InvalidOperationException>(() => Expression.ListInit(newExp, Expression.Constant('a')));
Assert.Throws<InvalidOperationException>(() => Expression.ListInit(newExp, Enumerable.Repeat(Expression.Constant('a'), 1)));
Assert.Throws<InvalidOperationException>(() => Expression.ListInit(newExp, default(MethodInfo), Expression.Constant('a')));
Assert.Throws<InvalidOperationException>(() => Expression.ListInit(newExp, default(MethodInfo), Enumerable.Repeat(Expression.Constant('a'), 1)));
}
[Fact]
public void InitializeNonEnumerable()
{
// () => new NonEnumerableAddable { 1, 2, 4, 16, 42 } isn't allowed because list initialization
// is allowed only with enumerable types.
AssertExtensions.Throws<ArgumentException>("newExpression", () => Expression.ListInit(Expression.New(typeof(NonEnumerableAddable)), Expression.Constant(1)));
}
[Fact]
public void StaticAddMethodOnType()
{
NewExpression newExp = Expression.New(typeof(EnumerableStaticAdd));
MethodInfo adder = typeof(EnumerableStaticAdd).GetMethod(nameof(EnumerableStaticAdd.Add));
// this exception behavior (rather than ArgumentException) is compatible with the .NET Framework
Assert.Throws<InvalidOperationException>(() => Expression.ListInit(newExp, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("addMethod", () => Expression.ListInit(newExp, adder, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("addMethod", () => Expression.ElementInit(adder, Expression.Constant("")));
AssertExtensions.Throws<ArgumentException>("addMethod", () => Expression.ElementInit(adder, Enumerable.Repeat(Expression.Constant(""), 1)));
}
[Fact]
public void AdderOnWrongType()
{
// This logically includes cases of methods of open generic types, since the NewExpression cannot be of such a type.
NewExpression newExp = Expression.New(typeof(List<int>));
MethodInfo adder = typeof(HashSet<int>).GetMethod(nameof(HashSet<int>.Add));
Assert.Throws<ArgumentException>(null, () => Expression.ListInit(newExp, adder, Expression.Constant(0)));
}
[Fact]
public void OpenGenericAddMethod()
{
NewExpression newExp = Expression.New(typeof(AnyTypeList));
MethodInfo adder = typeof(AnyTypeList).GetMethod(nameof(AnyTypeList.Add));
Assert.Throws<ArgumentException>(() => Expression.ListInit(newExp, adder, Expression.Constant(0)));
adder = typeof(AnyTypeList).GetMethod(nameof(AnyTypeList.Add)).MakeGenericMethod(typeof(List<int>));
Assert.Throws<ArgumentException>(() => Expression.ListInit(newExp, adder, Expression.Constant(0)));
adder = typeof(AnyTypeList).GetMethod(nameof(AnyTypeList.AddIntRegardless));
AssertExtensions.Throws<ArgumentException>("addMethod", () => Expression.ListInit(newExp, adder, Expression.Constant(0)));
adder = typeof(AnyTypeList).GetMethod(nameof(AnyTypeList.AddIntRegardless)).MakeGenericMethod(typeof(List<>));
AssertExtensions.Throws<ArgumentException>("addMethod", () => Expression.ListInit(newExp, adder, Expression.Constant(0)));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void GenericAddMethod(bool useInterpreter)
{
NewExpression newExp = Expression.New(typeof(AnyTypeList));
MethodInfo adder = typeof(AnyTypeList).GetMethod(nameof(AnyTypeList.Add)).MakeGenericMethod(typeof(int));
Expression<Func<AnyTypeList>> lambda =
Expression.Lambda<Func<AnyTypeList>>(
Expression.ListInit(
newExp, adder, Expression.Constant(3), Expression.Constant(2), Expression.Constant(1)));
Func<AnyTypeList> func = lambda.Compile(useInterpreter);
Assert.Equal(new object[] {3, 2, 1}, func());
}
[Fact]
public void InitializersWrappedExactly()
{
NewExpression newExp = Expression.New(typeof(List<int>));
ConstantExpression[] expressions = new[] { Expression.Constant(1), Expression.Constant(2), Expression.Constant(int.MaxValue) };
ListInitExpression listInit = Expression.ListInit(newExp, expressions);
Assert.Equal(expressions, listInit.Initializers.Select(i => i.GetArgument(0)));
}
[Fact]
public void CanReduce()
{
ListInitExpression listInit = Expression.ListInit(
Expression.New(typeof(List<int>)),
Expression.Constant(0)
);
Assert.True(listInit.CanReduce);
Assert.NotSame(listInit, listInit.ReduceAndCheck());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InitializeVoidAdd(bool useInterpreter)
{
Expression<Func<List<int>>> listInit = () => new List<int> { 1, 2, 4, 16, 42 };
Func<List<int>> func = listInit.Compile(useInterpreter);
Assert.Equal(new[] { 1, 2, 4, 16, 42 }, func());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InitializeNonVoidAdd(bool useInterpreter)
{
Expression<Func<HashSet<int>>> hashInit = () => new HashSet<int> { 1, 2, 4, 16, 42 };
Func<HashSet<int>> func = hashInit.Compile(useInterpreter);
Assert.Equal(new[] { 1, 2, 4, 16, 42 }, func().OrderBy(i => i));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InitializeTwoParameterAdd(bool useInterpreter)
{
Expression<Func<Dictionary<string, int>>> dictInit = () => new Dictionary<string, int>
{
{ "a", 1 }, {"b", 2 }, {"c", 3 }
};
Func<Dictionary<string, int>> func = dictInit.Compile(useInterpreter);
var expected = new Dictionary<string, int>
{
{ "a", 1 }, {"b", 2 }, {"c", 3 }
};
Assert.Equal(expected.OrderBy(kvp => kvp.Key), func().OrderBy(kvp => kvp.Key));
}
[Fact]
public void UpdateSameReturnsSame()
{
ListInitExpression init = Expression.ListInit(
Expression.New(typeof(List<int>)),
Expression.Constant(1),
Expression.Constant(2),
Expression.Constant(3));
Assert.Same(init, init.Update(init.NewExpression, init.Initializers.ToArray()));
}
[Fact]
public void UpdateNullThrows()
{
ListInitExpression init = Expression.ListInit(
Expression.New(typeof(List<int>)),
Expression.Constant(1),
Expression.Constant(2),
Expression.Constant(3));
AssertExtensions.Throws<ArgumentNullException>("newExpression", () => init.Update(null, init.Initializers));
AssertExtensions.Throws<ArgumentNullException>("initializers", () => init.Update(init.NewExpression, null));
}
[Fact]
public void UpdateDifferentNewReturnsDifferent()
{
ListInitExpression init = Expression.ListInit(
Expression.New(typeof(List<int>)),
Expression.Constant(1),
Expression.Constant(2),
Expression.Constant(3));
Assert.NotSame(init, init.Update(Expression.New(typeof(List<int>)), init.Initializers));
}
[Fact]
public void UpdateDifferentInitializersReturnsDifferent()
{
MethodInfo meth = typeof(List<int>).GetMethod("Add");
ElementInit[] inits = new[]
{
Expression.ElementInit(meth, Expression.Constant(1)),
Expression.ElementInit(meth, Expression.Constant(2)),
Expression.ElementInit(meth, Expression.Constant(3))
};
ListInitExpression init = Expression.ListInit(Expression.New(typeof(List<int>)), inits);
inits = new[]
{
Expression.ElementInit(meth, Expression.Constant(1)),
Expression.ElementInit(meth, Expression.Constant(2)),
Expression.ElementInit(meth, Expression.Constant(3))
};
Assert.NotSame(init, init.Update(init.NewExpression, inits));
}
[Fact]
public void UpdateDoesntRepeatEnumeration()
{
MethodInfo meth = typeof(List<int>).GetMethod("Add");
ElementInit[] inits = new[]
{
Expression.ElementInit(meth, Expression.Constant(1)),
Expression.ElementInit(meth, Expression.Constant(2)),
Expression.ElementInit(meth, Expression.Constant(3))
};
ListInitExpression init = Expression.ListInit(Expression.New(typeof(List<int>)), inits);
IEnumerable<ElementInit> newInits = new RunOnceEnumerable<ElementInit>(
new[]
{
Expression.ElementInit(meth, Expression.Constant(1)),
Expression.ElementInit(meth, Expression.Constant(2)),
Expression.ElementInit(meth, Expression.Constant(3))
});
Assert.NotSame(init, init.Update(init.NewExpression, newInits));
}
[Fact]
public static void ToStringTest()
{
ListInitExpression e1 = Expression.ListInit(Expression.New(typeof(List<int>)), Expression.Parameter(typeof(int), "x"));
Assert.Equal("new List`1() {Void Add(Int32)(x)}", e1.ToString());
ListInitExpression e2 = Expression.ListInit(Expression.New(typeof(List<int>)), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y"));
Assert.Equal("new List`1() {Void Add(Int32)(x), Void Add(Int32)(y)}", e2.ToString());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void ValueTypeList(bool useInterpreter)
{
Expression<Func<ListValueType>> lambda = Expression.Lambda<Func<ListValueType>>(
Expression.ListInit(
Expression.New(typeof(ListValueType)),
Expression.Constant(5),
Expression.Constant(6),
Expression.Constant(7),
Expression.Constant(8)
)
);
Func<ListValueType> func = lambda.Compile(useInterpreter);
Assert.Equal(new[] { 5, 6, 7, 8 }, func());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void EmptyValueTypeList(bool useInterpreter)
{
Expression<Func<ListValueType>> lambda = Expression.Lambda<Func<ListValueType>>(
Expression.ListInit(
Expression.New(typeof(ListValueType)),
Array.Empty<Expression>()
)
);
Func<ListValueType> func = lambda.Compile(useInterpreter);
Assert.Empty(func());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using BTDB.Buffer;
using BTDB.StreamLayer;
namespace BTDB.KVDBLayer
{
public class InMemoryFileCollection : IFileCollection
{
// disable invalid warning about using volatile inside Interlocked.CompareExchange
#pragma warning disable 420
volatile Dictionary<uint, File> _files = new Dictionary<uint, File>();
int _maxFileId;
public InMemoryFileCollection()
{
_maxFileId = 0;
}
class File : IFileCollectionFile
{
readonly InMemoryFileCollection _owner;
readonly uint _index;
byte[][] _data = Array.Empty<byte[]>();
readonly Writer _writer;
long _flushedSize;
const int OneBufSize = 128 * 1024;
public File(InMemoryFileCollection owner, uint index)
{
_owner = owner;
_index = index;
_writer = new Writer(this);
}
public uint Index => _index;
sealed class Reader : ISpanReader
{
readonly File _file;
ulong _ofs;
readonly ulong _totalSize;
public Reader(File file)
{
_file = file;
_totalSize = file.GetSize();
_ofs = 0;
}
public void Init(ref SpanReader spanReader)
{
var bufOfs = (int)(_ofs % OneBufSize);
spanReader.Buf = _file._data[(int)(_ofs / OneBufSize)]
.AsSpan(bufOfs, (int)Math.Min(_totalSize - _ofs, (ulong)(OneBufSize - bufOfs)));
_ofs += (uint)spanReader.Buf.Length;
}
public bool FillBufAndCheckForEof(ref SpanReader spanReader)
{
if (spanReader.Buf.Length != 0) return false;
Init(ref spanReader);
return 0 == spanReader.Buf.Length;
}
public long GetCurrentPosition(in SpanReader spanReader)
{
return (long)_ofs - spanReader.Buf.Length;
}
public bool ReadBlock(ref SpanReader spanReader, ref byte buffer, uint length)
{
while (length > 0)
{
if (FillBufAndCheckForEof(ref spanReader)) return true;
var lenTillEnd = (uint)Math.Min(length, spanReader.Buf.Length);
Unsafe.CopyBlockUnaligned(ref buffer,
ref PackUnpack.UnsafeGetAndAdvance(ref spanReader.Buf, (int)lenTillEnd), lenTillEnd);
length -= lenTillEnd;
}
return false;
}
public bool SkipBlock(ref SpanReader spanReader, uint length)
{
_ofs += length;
if (_ofs <= _totalSize) return false;
_ofs = _totalSize;
return true;
}
public void SetCurrentPosition(ref SpanReader spanReader, long position)
{
_ofs = (ulong)position;
spanReader.Buf = new ReadOnlySpan<byte>();
}
public void Sync(ref SpanReader spanReader)
{
_ofs -= (uint)spanReader.Buf.Length;
}
}
public ISpanReader GetExclusiveReader()
{
return new Reader(this);
}
public void AdvisePrefetch()
{
}
public void RandomRead(Span<byte> data, ulong position, bool doNotCache)
{
var storage = Volatile.Read(ref _data);
while (!data.IsEmpty)
{
var buf = storage[(int)(position / OneBufSize)];
var bufOfs = (int)(position % OneBufSize);
var copy = Math.Min(data.Length, OneBufSize - bufOfs);
buf.AsSpan(bufOfs, copy).CopyTo(data);
data = data.Slice(copy);
position += (ulong)copy;
}
}
sealed class Writer : ISpanWriter
{
readonly File _file;
ulong _ofs;
public Writer(File file)
{
_file = file;
_ofs = 0;
}
internal void SimulateCorruptionBySetSize(int size)
{
if (size > OneBufSize || _ofs > OneBufSize) throw new ArgumentOutOfRangeException();
Array.Clear(_file._data[0], size, (int)_ofs - size);
_ofs = (uint)size;
}
public void Init(ref SpanWriter spanWriter)
{
if (_ofs == (ulong)_file._data.Length * OneBufSize)
{
var buf = new byte[OneBufSize];
var storage = _file._data;
Array.Resize(ref storage, storage.Length + 1);
storage[^1] = buf;
Volatile.Write(ref _file._data, storage);
spanWriter.InitialBuffer = buf;
spanWriter.Buf = spanWriter.InitialBuffer;
return;
}
spanWriter.InitialBuffer = _file._data[^1].AsSpan((int)(_ofs % OneBufSize));
spanWriter.Buf = spanWriter.InitialBuffer;
}
public void Sync(ref SpanWriter spanWriter)
{
_ofs += (ulong)(spanWriter.InitialBuffer.Length - spanWriter.Buf.Length);
}
public bool Flush(ref SpanWriter spanWriter)
{
if (spanWriter.Buf.Length != 0) return false;
_ofs += (ulong)spanWriter.InitialBuffer.Length;
Init(ref spanWriter);
return true;
}
public long GetCurrentPosition(in SpanWriter spanWriter)
{
return (long)_ofs + (spanWriter.InitialBuffer.Length - spanWriter.Buf.Length);
}
public long GetCurrentPositionWithoutWriter()
{
return (long)_ofs;
}
public void WriteBlock(ref SpanWriter spanWriter, ref byte buffer, uint length)
{
while (length > 0)
{
if (spanWriter.Buf.Length == 0)
{
Flush(ref spanWriter);
}
var l = Math.Min((uint)spanWriter.Buf.Length, length);
Unsafe.CopyBlockUnaligned(ref PackUnpack.UnsafeGetAndAdvance(ref spanWriter.Buf, (int)l),
ref buffer, l);
buffer = ref Unsafe.AddByteOffset(ref buffer, (IntPtr)l);
length -= l;
}
}
public void WriteBlockWithoutWriter(ref byte buffer, uint length)
{
var writer = new SpanWriter(this);
writer.WriteBlock(ref buffer, length);
writer.Sync();
}
public void SetCurrentPosition(ref SpanWriter spanWriter, long position)
{
throw new NotSupportedException();
}
}
public ISpanWriter GetAppenderWriter()
{
return _writer;
}
public ISpanWriter GetExclusiveAppenderWriter()
{
return _writer;
}
public void Flush()
{
_flushedSize = _writer.GetCurrentPositionWithoutWriter();
Interlocked.MemoryBarrier();
}
public void HardFlush()
{
Flush();
}
public void SetSize(long size)
{
if ((ulong)size != GetSize())
throw new InvalidOperationException(
"For in memory collection SetSize should never be set to something else than GetSize");
}
public void Truncate()
{
}
public void HardFlushTruncateSwitchToReadOnlyMode()
{
Flush();
}
public void HardFlushTruncateSwitchToDisposedMode()
{
Flush();
}
public ulong GetSize()
{
Volatile.Read(ref _data);
return (ulong)_flushedSize;
}
public void Remove()
{
Dictionary<uint, File> newFiles;
Dictionary<uint, File> oldFiles;
do
{
oldFiles = _owner._files;
if (!oldFiles!.TryGetValue(_index, out _)) return;
newFiles = new Dictionary<uint, File>(oldFiles);
newFiles.Remove(_index);
} while (Interlocked.CompareExchange(ref _owner._files, newFiles, oldFiles) != oldFiles);
}
internal void SimulateCorruptionBySetSize(int size)
{
_writer.SimulateCorruptionBySetSize(size);
}
}
public IFileCollectionFile AddFile(string humanHint)
{
var index = (uint)Interlocked.Increment(ref _maxFileId);
var file = new File(this, index);
Dictionary<uint, File> newFiles;
Dictionary<uint, File> oldFiles;
do
{
oldFiles = _files;
newFiles = new Dictionary<uint, File>(oldFiles!) { { index, file } };
} while (Interlocked.CompareExchange(ref _files, newFiles, oldFiles) != oldFiles);
return file;
}
public uint GetCount()
{
return (uint)_files.Count;
}
public IFileCollectionFile? GetFile(uint index)
{
return _files.TryGetValue(index, out var value) ? value : null;
}
public IEnumerable<IFileCollectionFile> Enumerate()
{
return _files.Values;
}
public void ConcurrentTemporaryTruncate(uint index, uint offset)
{
// Nothing to do
}
public void Dispose()
{
}
internal void SimulateCorruptionBySetSize(int size)
{
_files[1].SimulateCorruptionBySetSize(size);
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id$")]
namespace Elmah
{
#region Imports
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Collections.Generic;
#endregion
internal sealed class ErrorLogDownloadHandler : IHttpAsyncHandler
{
private static readonly TimeSpan _beatPollInterval = TimeSpan.FromSeconds(3);
private const int _pageSize = 100;
private Format _format;
private int _pageIndex;
private int _downloadCount;
private int _maxDownloadCount = -1;
private AsyncResult _result;
private ErrorLog _log;
private DateTime _lastBeatTime;
private List<ErrorLogEntry> _errorEntryList;
private HttpContext _context;
private AsyncCallback _callback;
public void ProcessRequest(HttpContext context)
{
EndProcessRequest(BeginProcessRequest(context, null, null));
}
public bool IsReusable
{
get { return false; }
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
if (context == null)
throw new ArgumentNullException("context");
if (_result != null)
throw new InvalidOperationException("An asynchronous operation is already pending.");
HttpRequest request = context.Request;
NameValueCollection query = request.QueryString;
//
// Limit the download by some maximum # of records?
//
_maxDownloadCount = Math.Max(0, Convert.ToInt32(query["limit"], CultureInfo.InvariantCulture));
//
// Determine the desired output format.
//
string format = Mask.EmptyString(query["format"], "csv").ToLower(CultureInfo.InvariantCulture);
switch (format)
{
case "csv": _format = new CsvFormat(context); break;
case "jsonp": _format = new JsonPaddingFormat(context); break;
case "html-jsonp": _format = new JsonPaddingFormat(context, /* wrapped */ true); break;
default:
throw new Exception("Request log format is not supported.");
}
Debug.Assert(_format != null);
//
// Emit format header, initialize and then fetch results.
//
context.Response.BufferOutput = false;
_format.Header();
AsyncResult result = _result = new AsyncResult(extraData);
_log = ErrorLog.GetDefault(context);
_pageIndex = 0;
_lastBeatTime = DateTime.Now;
_context = context;
_callback = cb;
_errorEntryList = new List<ErrorLogEntry>(_pageSize);
_log.BeginGetErrors(_pageIndex, _pageSize, _errorEntryList,
new AsyncCallback(GetErrorsCallback), null);
return result;
}
public void EndProcessRequest(IAsyncResult result)
{
if (result == null)
throw new ArgumentNullException("result");
if (result != _result)
throw new ArgumentException(null, "result");
_result = null;
_log = null;
_context = null;
_callback = null;
_errorEntryList = null;
((AsyncResult) result).End();
}
private void GetErrorsCallback(IAsyncResult result)
{
Debug.Assert(result != null);
try
{
TryGetErrorsCallback(result);
}
catch (Exception e)
{
//
// If anything goes wrong during callback processing then
// the exception needs to be captured and the raising
// delayed until EndProcessRequest.Meanwhile, the
// BeginProcessRequest called is notified immediately of
// completion.
//
_result.Complete(_callback, e);
}
}
private void TryGetErrorsCallback(IAsyncResult result)
{
Debug.Assert(result != null);
int total = _log.EndGetErrors(result);
int count = _errorEntryList.Count;
if (_maxDownloadCount > 0)
{
int remaining = _maxDownloadCount - (_downloadCount + count);
if (remaining < 0)
count += remaining;
}
_format.Entries(_errorEntryList, 0, count, total);
_downloadCount += count;
HttpResponse response = _context.Response;
response.Flush();
//
// Done if either the end of the list (no more errors found) or
// the requested limit has been reached.
//
if (count == 0 || _downloadCount == _maxDownloadCount)
{
if (count > 0)
_format.Entries(new ErrorLogEntry[0], total); // Terminator
_result.Complete(false, _callback);
return;
}
//
// Poll whether the client is still connected so data is not
// unnecessarily sent to an abandoned connection. This check is
// only performed at certain intervals.
//
if (DateTime.Now - _lastBeatTime > _beatPollInterval)
{
if (!response.IsClientConnected)
{
_result.Complete(true, _callback);
return;
}
_lastBeatTime = DateTime.Now;
}
//
// Fetch next page of results.
//
_errorEntryList.Clear();
_log.BeginGetErrors(++_pageIndex, _pageSize, _errorEntryList,
new AsyncCallback(GetErrorsCallback), null);
}
private abstract class Format
{
private readonly HttpContext _context;
protected Format(HttpContext context)
{
Debug.Assert(context != null);
_context = context;
}
protected HttpContext Context { get { return _context; } }
public virtual void Header() {}
public void Entries(IList<ErrorLogEntry> entries, int total)
{
Entries(entries, 0, entries.Count, total);
}
public abstract void Entries(IList<ErrorLogEntry> entries, int index, int count, int total);
}
private sealed class CsvFormat : Format
{
public CsvFormat(HttpContext context) :
base(context) {}
public override void Header()
{
HttpResponse response = Context.Response;
response.AppendHeader("Content-Type", "text/csv; header=present");
response.AppendHeader("Content-Disposition", "attachment; filename=errorlog.csv");
response.Output.Write("Application,Host,Time,Unix Time,Type,Source,User,Status Code,Message,URL,XMLREF,JSONREF\r\n");
}
public override void Entries(IList<ErrorLogEntry> entries, int index, int count, int total)
{
Debug.Assert(entries != null);
Debug.Assert(index >= 0);
Debug.Assert(index + count <= entries.Count);
if (count == 0)
return;
//
// Setup to emit CSV records.
//
StringWriter writer = new StringWriter();
writer.NewLine = "\r\n";
CsvWriter csv = new CsvWriter(writer);
CultureInfo culture = CultureInfo.InvariantCulture;
DateTime epoch = new DateTime(1970, 1, 1);
//
// For each error, emit a CSV record.
//
for (int i = index; i < count; i++)
{
ErrorLogEntry entry = entries[i];
Error error = entry.Error;
DateTime time = error.Time.ToUniversalTime();
string query = "?id=" + HttpUtility.UrlEncode(entry.Id);
Uri requestUrl = Context.Request.Url;
csv.Field(error.ApplicationName)
.Field(error.HostName)
.Field(time.ToString("yyyy-MM-dd HH:mm:ss", culture))
.Field(time.Subtract(epoch).TotalSeconds.ToString("0.0000", culture))
.Field(error.Type)
.Field(error.Source)
.Field(error.User)
.Field(error.StatusCode.ToString(culture))
.Field(error.Message)
.Field(new Uri(requestUrl, "detail" + query).ToString())
.Field(new Uri(requestUrl, "xml" + query).ToString())
.Field(new Uri(requestUrl, "json" + query).ToString())
.Record();
}
Context.Response.Output.Write(writer.ToString());
}
}
private sealed class JsonPaddingFormat : Format
{
private static readonly Regex _callbackExpression = new Regex(@"^
[a-z_] [a-z0-9_]+ ( \[ [0-9]+ \] )?
( \. [a-z_] [a-z0-9_]+ ( \[ [0-9]+ \] )? )* $",
RegexOptions.IgnoreCase
| RegexOptions.Singleline
| RegexOptions.ExplicitCapture
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.CultureInvariant);
private string _callback;
private readonly bool _wrapped;
public JsonPaddingFormat(HttpContext context) :
this(context, false) {}
public JsonPaddingFormat(HttpContext context, bool wrapped) :
base(context)
{
_wrapped = wrapped;
}
public override void Header()
{
string callback = Context.Request.QueryString[Mask.EmptyString(null, "callback")]
?? string.Empty;
if (callback.Length == 0)
throw new Exception("The JSONP callback parameter is missing.");
if (!_callbackExpression.IsMatch(callback))
throw new Exception("The JSONP callback parameter is not in an acceptable format.");
_callback = callback;
HttpResponse response = Context.Response;
if (!_wrapped)
{
response.AppendHeader("Content-Type", "text/javascript");
response.AppendHeader("Content-Disposition", "attachment; filename=errorlog.js");
}
else
{
response.AppendHeader("Content-Type", "text/html");
TextWriter output = response.Output;
output.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
output.WriteLine(@"
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Error Log in HTML-Wrapped JSONP Format</title>
</head>
<body>
<p>This page is primarily designed to be used in an IFRAME of a parent HTML document.</p>");
}
}
public override void Entries(IList<ErrorLogEntry> entries, int index, int count, int total)
{
Debug.Assert(entries != null);
Debug.Assert(index >= 0);
Debug.Assert(index + count <= entries.Count);
StringWriter writer = new StringWriter();
writer.NewLine = "\n";
if (_wrapped)
{
writer.WriteLine("<script type='text/javascript' language='javascript'>");
writer.WriteLine("//<[!CDATA[");
}
writer.Write(_callback);
writer.Write('(');
JsonTextWriter json = new JsonTextWriter(writer);
json.Object()
.Member("total").Number(total)
.Member("errors").Array();
Uri requestUrl = Context.Request.Url;
for (int i = index; i < count; i++)
{
ErrorLogEntry entry = entries[i];
writer.WriteLine();
if (i == 0) writer.Write(' ');
writer.Write(" ");
string urlTemplate = new Uri(requestUrl, "{0}?id=" + HttpUtility.UrlEncode(entry.Id)).ToString();
json.Object();
ErrorJson.Encode(entry.Error, json);
json.Member("hrefs")
.Array()
.Object()
.Member("type").String("text/html")
.Member("href").String(string.Format(urlTemplate, "detail")).Pop()
.Object()
.Member("type").String("aplication/json")
.Member("href").String(string.Format(urlTemplate, "json")).Pop()
.Object()
.Member("type").String("application/xml")
.Member("href").String(string.Format(urlTemplate, "xml")).Pop()
.Pop()
.Pop();
}
json.Pop();
json.Pop();
if (count > 0)
writer.WriteLine();
writer.WriteLine(");");
if (_wrapped)
{
writer.WriteLine("//]]>");
writer.WriteLine("</script>");
if (count == 0)
writer.WriteLine(@"</body></html>");
}
Context.Response.Output.Write(writer);
}
}
private sealed class AsyncResult : IAsyncResult
{
private readonly object _lock = new object();
private ManualResetEvent _event;
private readonly object _userState;
private bool _completed;
private Exception _exception;
private bool _ended;
private bool _aborted;
internal event EventHandler Completed;
public AsyncResult(object userState)
{
_userState = userState;
}
public bool IsCompleted
{
get { return _completed; }
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_event == null)
{
lock (_lock)
{
if (_event == null)
_event = new ManualResetEvent(_completed);
}
}
return _event;
}
}
public object AsyncState
{
get { return _userState; }
}
public bool CompletedSynchronously
{
get { return false; }
}
internal void Complete(bool aborted, AsyncCallback callback)
{
if (_completed)
throw new InvalidOperationException();
_aborted = aborted;
try
{
lock (_lock)
{
_completed = true;
if (_event != null)
_event.Set();
}
if (callback != null)
callback(this);
}
finally
{
OnCompleted();
}
}
internal void Complete(AsyncCallback callback, Exception e)
{
_exception = e;
Complete(false, callback);
}
internal bool End()
{
if (_ended)
throw new InvalidOperationException();
_ended = true;
if (!IsCompleted)
AsyncWaitHandle.WaitOne();
if (_event != null)
_event.Close();
if (_exception != null)
throw _exception;
return _aborted;
}
private void OnCompleted()
{
EventHandler handler = Completed;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
private sealed class CsvWriter
{
private readonly TextWriter _writer;
private int _column;
private static readonly char[] _reserved = new char[] { '\"', ',', '\r', '\n' };
public CsvWriter(TextWriter writer)
{
Debug.Assert(writer != null);
_writer = writer;
}
public CsvWriter Record()
{
_writer.WriteLine();
_column = 0;
return this;
}
public CsvWriter Field(string value)
{
if (_column > 0)
_writer.Write(',');
//
// Fields containing line breaks (CRLF), double quotes, and commas
// need to be enclosed in double-quotes.
//
int index = value.IndexOfAny(_reserved);
if (index < 0)
{
_writer.Write(value);
}
else
{
//
// As double-quotes are used to enclose fields, then a
// double-quote appearing inside a field must be escaped by
// preceding it with another double quote.
//
const string quote = "\"";
_writer.Write(quote);
_writer.Write(value.Replace(quote, quote + quote));
_writer.Write(quote);
}
_column++;
return this;
}
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2020 Microting A/S
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.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microting.eForm.Infrastructure.Constants;
using Microting.eForm.Infrastructure.Data.Entities;
using NUnit.Framework;
namespace eFormSDK.Base.Tests
{
[TestFixture]
public class SiteWorkersUTest : DbTestFixture
{
[Test]
public async Task SiteWorkers_Create_DoesCreate()
{
// Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Worker worker = new Worker
{
Email = Guid.NewGuid().ToString(),
FirstName = Guid.NewGuid().ToString(),
LastName = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await worker.Create(DbContext).ConfigureAwait(false);
SiteWorker siteWorker = new SiteWorker
{
MicrotingUid = rnd.Next(1, 255),
SiteId = site.Id,
WorkerId = worker.Id
};
//Act
await siteWorker.Create(DbContext).ConfigureAwait(false);
List<SiteWorker> siteWorkers = DbContext.SiteWorkers.AsNoTracking().ToList();
List<SiteWorkerVersion> siteWorkerVersions = DbContext.SiteWorkerVersions.AsNoTracking().ToList();
Assert.NotNull(siteWorkers);
Assert.NotNull(siteWorkerVersions);
Assert.AreEqual(1,siteWorkers.Count());
Assert.AreEqual(1,siteWorkerVersions.Count());
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkers[0].CreatedAt.ToString());
Assert.AreEqual(siteWorker.Version, siteWorkers[0].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkers[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkers[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkers[0].Id);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkers[0].MicrotingUid);
Assert.AreEqual(siteWorker.SiteId, site.Id);
Assert.AreEqual(siteWorker.WorkerId, worker.Id);
//Versions
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkerVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, siteWorkerVersions[0].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkerVersions[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkerVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkerVersions[0].SiteWorkerId);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkerVersions[0].MicrotingUid);
Assert.AreEqual(site.Id, siteWorkerVersions[0].SiteId);
Assert.AreEqual(worker.Id, siteWorkerVersions[0].WorkerId);
}
[Test]
public async Task SiteWorkers_Update_DoesUpdate()
{
// Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Worker worker = new Worker
{
Email = Guid.NewGuid().ToString(),
FirstName = Guid.NewGuid().ToString(),
LastName = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await worker.Create(DbContext).ConfigureAwait(false);
SiteWorker siteWorker = new SiteWorker
{
MicrotingUid = rnd.Next(1, 255),
SiteId = site.Id,
WorkerId = worker.Id
};
await siteWorker.Create(DbContext).ConfigureAwait(false);
//Act
DateTime? oldUpdatedAt = siteWorker.UpdatedAt;
int? oldMicroTingUid = siteWorker.MicrotingUid;
siteWorker.MicrotingUid = rnd.Next(1, 255);
await siteWorker.Update(DbContext).ConfigureAwait(false);
List<SiteWorker> siteWorkers = DbContext.SiteWorkers.AsNoTracking().ToList();
List<SiteWorkerVersion> siteWorkerVersions = DbContext.SiteWorkerVersions.AsNoTracking().ToList();
Assert.NotNull(siteWorkers);
Assert.NotNull(siteWorkerVersions);
Assert.AreEqual(1,siteWorkers.Count());
Assert.AreEqual(2,siteWorkerVersions.Count());
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkers[0].CreatedAt.ToString());
Assert.AreEqual(siteWorker.Version, siteWorkers[0].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkers[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkers[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkers[0].Id);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkers[0].MicrotingUid);
Assert.AreEqual(siteWorker.SiteId, site.Id);
Assert.AreEqual(siteWorker.WorkerId, worker.Id);
//Old Version
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkerVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, siteWorkerVersions[0].Version);
// Assert.AreEqual(oldUpdatedAt.ToString(), siteWorkerVersions[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkerVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkerVersions[0].SiteWorkerId);
Assert.AreEqual(oldMicroTingUid, siteWorkerVersions[0].MicrotingUid);
Assert.AreEqual(site.Id, siteWorkerVersions[0].SiteId);
Assert.AreEqual(worker.Id, siteWorkerVersions[0].WorkerId);
//New Version
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkerVersions[1].CreatedAt.ToString());
Assert.AreEqual(2, siteWorkerVersions[1].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkerVersions[1].UpdatedAt.ToString());
Assert.AreEqual(siteWorkerVersions[1].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkerVersions[1].SiteWorkerId);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkerVersions[1].MicrotingUid);
Assert.AreEqual(site.Id, siteWorkerVersions[1].SiteId);
Assert.AreEqual(worker.Id, siteWorkerVersions[1].WorkerId);
}
[Test]
public async Task SiteWorkers_Delete_DoesSetWorkflowStateToRemoved()
{
// Arrange
Random rnd = new Random();
Site site = new Site
{
Name = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await site.Create(DbContext).ConfigureAwait(false);
Worker worker = new Worker
{
Email = Guid.NewGuid().ToString(),
FirstName = Guid.NewGuid().ToString(),
LastName = Guid.NewGuid().ToString(),
MicrotingUid = rnd.Next(1, 255)
};
await worker.Create(DbContext).ConfigureAwait(false);
SiteWorker siteWorker = new SiteWorker
{
MicrotingUid = rnd.Next(1, 255),
SiteId = site.Id,
WorkerId = worker.Id
};
await siteWorker.Create(DbContext).ConfigureAwait(false);
//Act
DateTime? oldUpdatedAt = siteWorker.UpdatedAt;
await siteWorker.Delete(DbContext);
List<SiteWorker> siteWorkers = DbContext.SiteWorkers.AsNoTracking().ToList();
List<SiteWorkerVersion> siteWorkerVersions = DbContext.SiteWorkerVersions.AsNoTracking().ToList();
Assert.NotNull(siteWorkers);
Assert.NotNull(siteWorkerVersions);
Assert.AreEqual(1,siteWorkers.Count());
Assert.AreEqual(2,siteWorkerVersions.Count());
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkers[0].CreatedAt.ToString());
Assert.AreEqual(siteWorker.Version, siteWorkers[0].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkers[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkers[0].WorkflowState, Constants.WorkflowStates.Removed);
Assert.AreEqual(siteWorker.Id, siteWorkers[0].Id);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkers[0].MicrotingUid);
Assert.AreEqual(siteWorker.SiteId, site.Id);
Assert.AreEqual(siteWorker.WorkerId, worker.Id);
//Old Version
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkerVersions[0].CreatedAt.ToString());
Assert.AreEqual(1, siteWorkerVersions[0].Version);
// Assert.AreEqual(oldUpdatedAt.ToString(), siteWorkerVersions[0].UpdatedAt.ToString());
Assert.AreEqual(siteWorkerVersions[0].WorkflowState, Constants.WorkflowStates.Created);
Assert.AreEqual(siteWorker.Id, siteWorkerVersions[0].SiteWorkerId);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkerVersions[0].MicrotingUid);
Assert.AreEqual(site.Id, siteWorkerVersions[0].SiteId);
Assert.AreEqual(worker.Id, siteWorkerVersions[0].WorkerId);
//New Version
Assert.AreEqual(siteWorker.CreatedAt.ToString(), siteWorkerVersions[1].CreatedAt.ToString());
Assert.AreEqual(2, siteWorkerVersions[1].Version);
// Assert.AreEqual(siteWorker.UpdatedAt.ToString(), siteWorkerVersions[1].UpdatedAt.ToString());
Assert.AreEqual(siteWorkerVersions[1].WorkflowState, Constants.WorkflowStates.Removed);
Assert.AreEqual(siteWorker.Id, siteWorkerVersions[1].SiteWorkerId);
Assert.AreEqual(siteWorker.MicrotingUid, siteWorkerVersions[1].MicrotingUid);
Assert.AreEqual(site.Id, siteWorkerVersions[1].SiteId);
Assert.AreEqual(worker.Id, siteWorkerVersions[1].WorkerId);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using ShellTools.Utility;
using System.Xml.Serialization;
using System.Xml;
namespace ShellTools
{
public partial class FileRenameForm : Form
{
private BindingList<FileRenameResult> _renamedResult = new BindingList<FileRenameResult>();
public FileRenameForm()
{
InitializeComponent();
if (Properties.Settings.Default["FileRenameSize"] != null)
this.Size = Properties.Settings.Default.FileRenameSize;
}
public FileRenameForm(string startPath)
: this()
{
folderTextBox.Text = startPath;
}
private void FileRenameForm_Load(object sender, EventArgs e)
{
resultBindingSource.DataSource = _renamedResult;
matchRegexTextBox.Text = Properties.Settings.Default.RenameSearchPattern;
replaceTextBox.Text = Properties.Settings.Default.RenameReplacePattern;
if (string.IsNullOrEmpty(folderTextBox.Text))
folderTextBox.Text = Properties.Settings.Default.SourceFolder;
ignoreCaseToolStripMenuItem.Checked = Properties.Settings.Default.RenameIgnoreCase;
includeSubfoldersToolStripMenuItem.Checked = Properties.Settings.Default.RenameIncludeSubfolders;
}
private void browseFolderButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(folderTextBox.Text))
folderBrowserDialog.SelectedPath = folderTextBox.Text;
folderBrowserDialog.Description = "Select the folder to rename file(s) in.";
DialogResult result = folderBrowserDialog.ShowDialog(this);
if (result != DialogResult.OK)
return;
folderTextBox.Text = folderBrowserDialog.SelectedPath;
}
private void renameButton_Click(object sender, EventArgs e)
{
FileRenameArguments args = CreateArguments();
args.IsPreview = false;
RunRename(args);
}
private void previewButton_Click(object sender, EventArgs e)
{
FileRenameArguments args = CreateArguments();
args.IsPreview = true;
RunRename(args);
}
private FileRenameArguments CreateArguments()
{
FileRenameArguments args = new FileRenameArguments();
args.ReplacePattern = replaceTextBox.Text;
args.SearchPattern = matchRegexTextBox.Text;
args.SourceFolder = folderTextBox.Text;
args.IgnoreCase = ignoreCaseToolStripMenuItem.Checked;
args.IncludeSubfolders = includeSubfoldersToolStripMenuItem.Checked;
return args;
}
private void cancelButton_Click(object sender, EventArgs e)
{
if (renameBackgroundWorker.IsBusy)
renameBackgroundWorker.CancelAsync();
else
this.Close();
}
private void RunRename(FileRenameArguments renameArguments)
{
renameButton.Enabled = false;
previewButton.Enabled = false;
_renamedResult.Clear();
renameBackgroundWorker.RunWorkerAsync(renameArguments);
}
private void renameBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
FileRenameArguments args = e.Argument as FileRenameArguments;
if (args == null || string.IsNullOrEmpty(args.SourceFolder))
return;
DirectoryInfo sourceDirectory = new DirectoryInfo(args.SourceFolder);
if (!sourceDirectory.Exists)
return;
SearchOption so = args.IncludeSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
FileInfo[] files = sourceDirectory.GetFiles("*.*", so);
if (files == null || files.Length == 0)
return;
RegexOptions ro = args.IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Regex searchRegex = new Regex(args.SearchPattern, ro);
int fileIndex = 0;
foreach (FileInfo file in files)
{
if (e.Cancel)
break;
fileIndex++;
string renamedFile = searchRegex.Replace(file.Name, args.ReplacePattern);
FileRenameResult fileResult = new FileRenameResult(file.Name, renamedFile, file.DirectoryName);
int precent = (fileIndex * 100) / files.Length;
renameBackgroundWorker.ReportProgress(precent, fileResult);
if (file.Name.Equals(renamedFile))
continue;
if (!args.IsPreview)
File.Move(file.FullName, Path.Combine(file.DirectoryName, renamedFile));
}
}
private void renameBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar.Value = e.ProgressPercentage;
FileRenameResult fileResult = e.UserState as FileRenameResult;
if (fileResult == null)
return;
toolStripStatusLabel.Text = fileResult.OriginalName;
if (!fileResult.OriginalName.Equals(fileResult.NewName))
{
fileResult.Folder = PathHelper.RelativePathTo(folderTextBox.Text, fileResult.Folder);
_renamedResult.Add(fileResult);
}
renameTabControl.SelectTab("resultTabPage");
}
private void renameBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
toolStripStatusLabel.Text = "Complete";
renameButton.Enabled = true;
previewButton.Enabled = true;
}
private void FileRenameForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.RenameSearchPattern = matchRegexTextBox.Text;
Properties.Settings.Default.RenameReplacePattern = replaceTextBox.Text;
Properties.Settings.Default.SourceFolder = folderTextBox.Text;
Properties.Settings.Default.FileRenameSize = this.Size;
Properties.Settings.Default.RenameIgnoreCase = ignoreCaseToolStripMenuItem.Checked;
Properties.Settings.Default.RenameIncludeSubfolders = includeSubfoldersToolStripMenuItem.Checked;
Properties.Settings.Default.Save();
}
private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is TextBoxBase)
((TextBoxBase)this.ActiveControl).Undo();
}
private void redoToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is RichTextBox)
((RichTextBox)this.ActiveControl).Redo();
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is TextBoxBase)
((TextBoxBase)this.ActiveControl).Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is TextBoxBase)
((TextBoxBase)this.ActiveControl).Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is TextBoxBase)
((TextBoxBase)this.ActiveControl).Paste();
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveControl is TextBoxBase)
((TextBoxBase)this.ActiveControl).SelectAll();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
matchRegexTextBox.Text = string.Empty;
replaceTextBox.Text = string.Empty;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog.ShowDialog(this);
if (result != DialogResult.OK)
return;
FileRenameArguments args;
XmlSerializer serializer = new XmlSerializer(typeof(FileRenameArguments));
using (XmlReader r = XmlReader.Create(openFileDialog.FileName))
{
args = serializer.Deserialize(r) as FileRenameArguments;
}
if (args == null)
return;
folderTextBox.Text = args.SourceFolder;
matchRegexTextBox.Text = args.SearchPattern;
replaceTextBox.Text = args.ReplacePattern;
ignoreCaseToolStripMenuItem.Checked = args.IgnoreCase;
includeSubfoldersToolStripMenuItem.Checked = args.IncludeSubfolders;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog.ShowDialog(this);
if (result != DialogResult.OK)
return;
FileRenameArguments args = CreateArguments();
XmlWriterSettings s = new XmlWriterSettings();
s.Indent = true;
XmlSerializer serializer = new XmlSerializer(typeof(FileRenameArguments));
using (XmlWriter w = XmlWriter.Create(saveFileDialog.FileName, s))
{
serializer.Serialize(w, args);
w.Flush();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| |
namespace GiveCRM.Web.Controllers
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using GiveCRM.BusinessLogic;
using GiveCRM.LoggingService;
using GiveCRM.Models;
using GiveCRM.Models.Search;
using GiveCRM.Web.Attributes;
using GiveCRM.Web.Infrastructure;
using GiveCRM.Web.Models.Campaigns;
using GiveCRM.Web.Models.Search;
using GiveCRM.Web.Properties;
[HandleErrorWithElmah]
public class CampaignController : Controller
{
private readonly IMailingListService mailingListService;
private readonly ISearchService searchService;
private readonly ICampaignService campaignService;
private readonly IMemberSearchFilterService memberSearchFilterService;
private readonly IMemberService memberService;
private readonly ILogService logService;
public CampaignController(
IMailingListService mailingListService,
ISearchService searchService,
ICampaignService campaignService,
IMemberSearchFilterService memberSearchFilterService,
IMemberService memberService,
ILogService logService)
{
this.mailingListService = mailingListService;
this.searchService = searchService;
this.campaignService = campaignService;
this.memberSearchFilterService = memberSearchFilterService;
this.memberService = memberService;
this.logService = logService;
}
[HttpGet]
public ActionResult Index(bool showClosed = false)
{
IEnumerable<Campaign> campaigns = showClosed ? this.campaignService.GetAllClosed() : this.campaignService.GetAllOpen();
string title, linkText;
if (showClosed)
{
title = Resources.Literal_Closed;
linkText = Resources.Literal_Open;
}
else
{
title = Resources.Literal_Open;
linkText = Resources.Literal_Closed;
}
title = string.Format("{0} {1}", title, Resources.Literal_Campaigns);
linkText = string.Format(Resources.Show_Campaigns_Text, linkText);
var model = new CampaignIndexViewModel(title)
{
ShowCampaignsLinkText = linkText,
CreateCampaignLinkText = Resources.Literal_CreateCampaign,
ShowClosed = showClosed,
Campaigns = campaigns
};
return View(model);
}
[HttpGet]
public ActionResult Create()
{
var model = new CampaignShowViewModel(Resources.Literal_CreateCampaign)
{
Campaign = new Campaign
{
Name = "New Campaign"
}
};
return View("Show", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Campaign campaign)
{
var newId = this.InsertCampaign(campaign);
return RedirectToAction("Show", new { id = newId });
}
private int InsertCampaign(Campaign campaign)
{
var savedCampaign = this.campaignService.Insert(campaign);
return savedCampaign.Id;
}
[HttpGet]
public ActionResult Show(int id)
{
var campaign = this.campaignService.Get(id);
var applicableMembers = this.memberService.SearchByCampaignId(id).ToList();
var searchFilters = this.memberSearchFilterService.ForCampaign(id)
.Select(m =>
{
var criteriaDisplayText = SearchCriteria.Create(m.InternalName,
m.DisplayName,
(SearchFieldType) m.FilterType,
(SearchOperator) m.SearchOperator,
m.Value
).ToFriendlyDisplayString();
return new MemberSearchFilterViewModel
{
MemberSearchFilterId = m.Id,
CampaignId = campaign.Id,
CriteriaDisplayText = criteriaDisplayText
};
}).ToList();
var model = new CampaignShowViewModel(Resources.Literal_ShowCampaign)
{
Campaign = campaign,
SearchFilters = searchFilters,
NoSearchFiltersText = Resources.Literal_NoSearchFiltersText,
NoMatchingMembersText = Resources.Literal_NoMatchingMembersText,
ApplicableMembers = applicableMembers,
IsReadonly = campaign.IsReadonly
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Show(CampaignShowViewModel campaignViewModel)
{
var campaign = campaignViewModel.Campaign;
this.campaignService.Update(campaign);
return RedirectToAction("Show", new { id = campaign.Id });
}
[HttpGet]
public ActionResult AddMembershipSearchFilter(int campaignId)
{
var emptySearchCriteria = this.searchService.GetEmptySearchCriteria();
var criteriaNames = emptySearchCriteria.Select(c => c.DisplayName);
var searchOperators = (SearchOperator[])Enum.GetValues(typeof(SearchOperator));
var model = new AddSearchFilterViewModel(Resources.Literal_AddSearchFilter)
{
CampaignId = campaignId,
CriteriaNames = criteriaNames.Select(s => new SelectListItem { Value = s, Text = s }),
SearchOperators = searchOperators.Select(o => new SelectListItem { Value = o.ToString(), Text = o.ToFriendlyDisplayString() })
};
return View("AddSearchFilter", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddMembershipSearchFilter(AddSearchFilterViewModel viewModel)
{
var searchCriteria = this.searchService.GetEmptySearchCriteria();
// we have to find one
var searchCriterion = searchCriteria.First(c => c.DisplayName == viewModel.CriteriaName);
var memberSearchFilter = new MemberSearchFilter
{
CampaignId = viewModel.CampaignId,
InternalName = searchCriterion.InternalName,
FilterType = (int)searchCriterion.Type,
DisplayName = viewModel.CriteriaName,
SearchOperator = (int)viewModel.SearchOperator,
Value = viewModel.Value
};
this.memberSearchFilterService.Insert(memberSearchFilter);
return RedirectToAction("Show", new { id = viewModel.CampaignId });
}
[HttpGet]
public ActionResult DeleteMemberSearchFilter(int campaignId, int memberSearchFilterId)
{
this.memberSearchFilterService.Delete(memberSearchFilterId);
return RedirectToAction("Show", new { id = campaignId });
}
[HttpGet]
public ActionResult CloseCampaign(int campaignId)
{
var campaign = this.campaignService.Get(campaignId);
var viewModel = new SimpleCampaignViewModel(Resources.Literal_CloseCampaign)
{
CampaignId = campaignId,
CampaignName = campaign.Name
};
return View("Close", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CloseCampaign(SimpleCampaignViewModel viewModel)
{
var campaign = this.campaignService.Get(viewModel.CampaignId);
campaign.IsClosed = "Y";
this.campaignService.Update(campaign);
return RedirectToAction("Index", new { showClosed = true });
}
[HttpGet]
public ActionResult CommitCampaign(int campaignId)
{
var campaign = this.campaignService.Get(campaignId);
var viewModel = new SimpleCampaignViewModel(Resources.Literal_CommitCampaign)
{
CampaignId = campaignId,
CampaignName = campaign.Name
};
return View("Commit", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CommitCampaign(SimpleCampaignViewModel viewModel)
{
try
{
this.campaignService.Commit(viewModel.CampaignId);
}
catch (DomainException e)
{
ViewBag.Message = e.Message;
ViewBag.ReturnActionName = "Show";
ViewBag.ReturnRouteValues = new { id = viewModel.CampaignId };
return View("Fail");
}
return RedirectToAction("Show", new { id = viewModel.CampaignId });
}
[HttpGet]
public FileResult DownloadMailingList(int id)
{
var members = this.memberService.FromCampaignRun(id);
byte[] filecontent;
using (var stream = new MemoryStream())
{
this.mailingListService.WriteToStream(members, stream, OutputFormat.XLS);
filecontent = stream.ToArray();
}
return File(filecontent, "application/vnd.ms-excel");
}
[HttpGet]
public ActionResult Clone(int id)
{
var campaign = this.campaignService.Get(id);
var campaignClone = new Campaign
{
Id = 0,
Description = campaign.Description,
IsClosed = "N",
Name = campaign.Name + " (" + Resources.Literal_Cloned + ")",
RunOn = null
};
campaignClone = this.campaignService.Insert(campaignClone);
IEnumerable<MemberSearchFilter> memberSearchFilters = this.memberSearchFilterService.ForCampaign(id);
foreach (MemberSearchFilter memberSearchFilter in memberSearchFilters)
{
this.memberSearchFilterService.Insert(new MemberSearchFilter
{
CampaignId = campaignClone.Id,
DisplayName = memberSearchFilter.DisplayName,
FilterType = memberSearchFilter.FilterType,
InternalName = memberSearchFilter.InternalName,
SearchOperator = memberSearchFilter.SearchOperator,
Value = memberSearchFilter.Value
});
}
return RedirectToAction("Show", new { id = campaignClone.Id });
}
}
}
| |
using System;
namespace Server.Items
{
[FlipableAttribute( 0x13c6, 0x13ce )]
public class LeatherGlovesOfMining : BaseGlovesOfMining
{
public override int BasePhysicalResistance{ get{ return 2; } }
public override int BaseFireResistance{ get{ return 4; } }
public override int BaseColdResistance{ get{ return 3; } }
public override int BasePoisonResistance{ get{ return 3; } }
public override int BaseEnergyResistance{ get{ return 3; } }
public override int InitMinHits{ get{ return 30; } }
public override int InitMaxHits{ get{ return 40; } }
public override int AosStrReq{ get{ return 20; } }
public override int OldStrReq{ get{ return 10; } }
public override int ArmorBase{ get{ return 13; } }
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Leather; } }
public override CraftResource DefaultResource{ get{ return CraftResource.RegularLeather; } }
public override ArmorMeditationAllowance DefMedAllowance{ get{ return ArmorMeditationAllowance.All; } }
public override int LabelNumber{ get{ return 1045122; } } // leather blacksmith gloves of mining
[Constructable]
public LeatherGlovesOfMining( int bonus ) : base( bonus, 0x13C6 )
{
Weight = 1;
}
public LeatherGlovesOfMining( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x13d5, 0x13dd )]
public class StuddedGlovesOfMining : BaseGlovesOfMining
{
public override int BasePhysicalResistance{ get{ return 2; } }
public override int BaseFireResistance{ get{ return 4; } }
public override int BaseColdResistance{ get{ return 3; } }
public override int BasePoisonResistance{ get{ return 3; } }
public override int BaseEnergyResistance{ get{ return 4; } }
public override int InitMinHits{ get{ return 35; } }
public override int InitMaxHits{ get{ return 45; } }
public override int AosStrReq{ get{ return 25; } }
public override int OldStrReq{ get{ return 25; } }
public override int ArmorBase{ get{ return 16; } }
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Studded; } }
public override CraftResource DefaultResource{ get{ return CraftResource.RegularLeather; } }
public override int LabelNumber{ get{ return 1045123; } } // studded leather blacksmith gloves of mining
[Constructable]
public StuddedGlovesOfMining( int bonus ) : base( bonus, 0x13D5 )
{
Weight = 2;
}
public StuddedGlovesOfMining( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
[FlipableAttribute( 0x13eb, 0x13f2 )]
public class RingmailGlovesOfMining : BaseGlovesOfMining
{
public override int BasePhysicalResistance{ get{ return 3; } }
public override int BaseFireResistance{ get{ return 3; } }
public override int BaseColdResistance{ get{ return 1; } }
public override int BasePoisonResistance{ get{ return 5; } }
public override int BaseEnergyResistance{ get{ return 3; } }
public override int InitMinHits{ get{ return 40; } }
public override int InitMaxHits{ get{ return 50; } }
public override int AosStrReq{ get{ return 40; } }
public override int OldStrReq{ get{ return 20; } }
public override int OldDexBonus{ get{ return -1; } }
public override int ArmorBase{ get{ return 22; } }
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Ringmail; } }
public override int LabelNumber{ get{ return 1045124; } } // ringmail blacksmith gloves of mining
[Constructable]
public RingmailGlovesOfMining( int bonus ) : base( bonus, 0x13EB )
{
Weight = 1;
}
public RingmailGlovesOfMining( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
public abstract class BaseGlovesOfMining : BaseArmor
{
private int m_Bonus;
private SkillMod m_SkillMod;
[CommandProperty( AccessLevel.GameMaster )]
public int Bonus
{
get
{
return m_Bonus;
}
set
{
m_Bonus = value;
InvalidateProperties();
if ( m_Bonus == 0 )
{
if ( m_SkillMod != null )
m_SkillMod.Remove();
m_SkillMod = null;
}
else if ( m_SkillMod == null && Parent is Mobile )
{
m_SkillMod = new DefaultSkillMod( SkillName.Mining, true, m_Bonus );
((Mobile)Parent).AddSkillMod( m_SkillMod );
}
else if ( m_SkillMod != null )
{
m_SkillMod.Value = m_Bonus;
}
}
}
public override void OnAdded( object parent )
{
base.OnAdded( parent );
if ( m_Bonus != 0 && parent is Mobile )
{
if ( m_SkillMod != null )
m_SkillMod.Remove();
m_SkillMod = new DefaultSkillMod( SkillName.Mining, true, m_Bonus );
((Mobile)parent).AddSkillMod( m_SkillMod );
}
}
public override void OnRemoved( object parent )
{
base.OnRemoved( parent );
if ( m_SkillMod != null )
m_SkillMod.Remove();
m_SkillMod = null;
}
public BaseGlovesOfMining( int bonus, int itemID ) : base( itemID )
{
m_Bonus = bonus;
this.Hue = CraftResources.GetHue( (CraftResource)Utility.RandomMinMax( (int)CraftResource.MBronze, (int)CraftResource.MSteel ) );
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
if ( m_Bonus != 0 )
list.Add( 1062005, m_Bonus.ToString() ); // mining bonus +~1_val~
}
public BaseGlovesOfMining( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( (int) m_Bonus );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Bonus = reader.ReadInt();
break;
}
}
if ( m_Bonus != 0 && Parent is Mobile )
{
if ( m_SkillMod != null )
m_SkillMod.Remove();
m_SkillMod = new DefaultSkillMod( SkillName.Mining, true, m_Bonus );
((Mobile)Parent).AddSkillMod( m_SkillMod );
}
}
}
}
| |
using RSG.Promises;
using System;
using System.Collections.Generic;
using System.Linq;
using RSG.Exceptions;
using UnityEngine;
namespace RSG
{
/// <summary>
/// Implements a C# promise.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public interface IPromise<PromisedT>
{
/// <summary>
/// Gets the id of the promise, useful for referencing the promise during runtime.
/// </summary>
int Id { get; }
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
IPromise<PromisedT> WithName(string name);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
void Done(Action<PromisedT> onResolved, Action<Exception> onRejected);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
void Done(Action<PromisedT> onResolved);
/// <summary>
/// Complete the promise. Adds a default error handler.
/// </summary>
void Done();
/// <summary>
/// Handle errors for the promise.
/// </summary>
IPromise Catch(Action<Exception> onRejected);
/// <summary>
/// Handle errors for the promise.
/// </summary>
IPromise<PromisedT> Catch(Func<Exception, PromisedT> onRejected);
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved);
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
IPromise Then(Func<PromisedT, IPromise> onResolved);
/// <summary>
/// Add a resolved callback.
/// </summary>
IPromise Then(Action<PromisedT> onResolved);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(
Func<PromisedT, IPromise<ConvertedT>> onResolved,
Func<Exception, IPromise<ConvertedT>> onRejected
);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
IPromise Then(Action<PromisedT> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(
Func<PromisedT, IPromise<ConvertedT>> onResolved,
Func<Exception, IPromise<ConvertedT>> onRejected,
Action<float> onProgress
);
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// The resolved callback chains a non-value promise.
/// </summary>
IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected, Action<float> onProgress);
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// </summary>
IPromise Then(Action<PromisedT> onResolved, Action<Exception> onRejected, Action<float> onProgress);
/// <summary>
/// Return a new promise with a different value.
/// May also change the type of the value.
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, ConvertedT> transform);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Returns a promise for a collection of the resolved results.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise ThenAll(Func<PromisedT, IEnumerable<IPromise>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
IPromise<ConvertedT> ThenRace<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a non-value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
IPromise ThenRace(Func<PromisedT, IEnumerable<IPromise>> chain);
/// <summary>
/// Add a finally callback.
/// Finally callbacks will always be called, even if any preceding promise is rejected, or encounters an error.
/// The returned promise will be resolved or rejected, as per the preceding promise.
/// </summary>
IPromise<PromisedT> Finally(Action onComplete);
/// <summary>
/// Add a callback that chains a non-value promise.
/// ContinueWith callbacks will always be called, even if any preceding promise is rejected, or encounters an error.
/// The state of the returning promise will be based on the new non-value promise, not the preceding (rejected or resolved) promise.
/// </summary>
IPromise ContinueWith(Func<IPromise> onResolved);
/// <summary>
/// Add a callback that chains a value promise (optionally converting to a different value type).
/// ContinueWith callbacks will always be called, even if any preceding promise is rejected, or encounters an error.
/// The state of the returning promise will be based on the new value promise, not the preceding (rejected or resolved) promise.
/// </summary>
IPromise<ConvertedT> ContinueWith<ConvertedT>(Func<IPromise<ConvertedT>> onComplete);
/// <summary>
/// Add a progress callback.
/// Progress callbacks will be called whenever the promise owner reports progress towards the resolution
/// of the promise.
/// </summary>
IPromise<PromisedT> Progress(Action<float> onProgress);
}
/// <summary>
/// Interface for a promise that can be rejected.
/// </summary>
public interface IRejectable
{
/// <summary>
/// Reject the promise with an exception.
/// </summary>
void Reject(Exception ex);
}
/// <summary>
/// Interface for a promise that can be rejected or resolved.
/// </summary>
public interface IPendingPromise<PromisedT> : IRejectable
{
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
int Id { get; }
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
void Resolve(PromisedT value);
/// <summary>
/// Report progress in a promise.
/// </summary>
void ReportProgress(float progress);
}
/// <summary>
/// Specifies the state of a promise.
/// </summary>
public enum PromiseState
{
Pending, // The promise is in-flight.
Rejected, // The promise has been rejected.
Resolved // The promise has been resolved.
};
/// <summary>
/// Implements a C# promise.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public class Promise<PromisedT> : IPromise<PromisedT>, IPendingPromise<PromisedT>, IPromiseInfo
{
/// <summary>
/// The exception when the promise is rejected.
/// </summary>
private Exception rejectionException;
/// <summary>
/// The value when the promises is resolved.
/// </summary>
private PromisedT resolveValue;
/// <summary>
/// Error handler.
/// </summary>
private List<RejectHandler> rejectHandlers;
/// <summary>
/// Progress handlers.
/// </summary>
private List<ProgressHandler> progressHandlers;
/// <summary>
/// Completed handlers that accept a value.
/// </summary>
private List<Action<PromisedT>> resolveCallbacks;
private List<IRejectable> resolveRejectables;
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
public int Id { get { return id; } }
private readonly int id;
/// <summary>
/// Name of the promise, when set, useful for debugging.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Tracks the current state of the promise.
/// </summary>
public PromiseState CurState { get; private set; }
public Promise()
{
this.CurState = PromiseState.Pending;
this.id = Promise.NextId();
if (Promise.EnablePromiseTracking)
{
Promise.PendingPromises.Add(this);
}
}
public Promise(Action<Action<PromisedT>, Action<Exception>> resolver)
{
this.CurState = PromiseState.Pending;
this.id = Promise.NextId();
if (Promise.EnablePromiseTracking)
{
Promise.PendingPromises.Add(this);
}
try
{
resolver(Resolve, Reject);
}
catch (Exception ex)
{
Reject(ex);
}
}
/// <summary>
/// Add a rejection handler for this promise.
/// </summary>
private void AddRejectHandler(Action<Exception> onRejected, IRejectable rejectable)
{
if (rejectHandlers == null)
{
rejectHandlers = new List<RejectHandler>();
}
rejectHandlers.Add(new RejectHandler { callback = onRejected, rejectable = rejectable });
}
/// <summary>
/// Add a resolve handler for this promise.
/// </summary>
private void AddResolveHandler(Action<PromisedT> onResolved, IRejectable rejectable)
{
if (resolveCallbacks == null)
{
resolveCallbacks = new List<Action<PromisedT>>();
}
if (resolveRejectables == null)
{
resolveRejectables = new List<IRejectable>();
}
resolveCallbacks.Add(onResolved);
resolveRejectables.Add(rejectable);
}
/// <summary>
/// Add a progress handler for this promise.
/// </summary>
private void AddProgressHandler(Action<float> onProgress, IRejectable rejectable)
{
if (progressHandlers == null)
{
progressHandlers = new List<ProgressHandler>();
}
progressHandlers.Add(new ProgressHandler { callback = onProgress, rejectable = rejectable });
}
/// <summary>
/// Invoke a single handler.
/// </summary>
private void InvokeHandler<T>(Action<T> callback, IRejectable rejectable, T value)
{
// Argument.NotNull(() => callback);
// Argument.NotNull(() => rejectable);
try
{
callback(value);
}
catch (Exception ex)
{
rejectable.Reject(ex);
}
}
/// <summary>
/// Helper function clear out all handlers after resolution or rejection.
/// </summary>
private void ClearHandlers()
{
rejectHandlers = null;
resolveCallbacks = null;
resolveRejectables = null;
progressHandlers = null;
}
/// <summary>
/// Invoke all reject handlers.
/// </summary>
private void InvokeRejectHandlers(Exception ex)
{
// Argument.NotNull(() => ex);
if (rejectHandlers != null)
{
rejectHandlers.Each(handler => InvokeHandler(handler.callback, handler.rejectable, ex));
}
ClearHandlers();
}
/// <summary>
/// Invoke all resolve handlers.
/// </summary>
private void InvokeResolveHandlers(PromisedT value)
{
if (resolveCallbacks != null)
{
for (int i = 0, maxI = resolveCallbacks.Count; i < maxI; i++) {
InvokeHandler(resolveCallbacks[i], resolveRejectables[i], value);
}
}
ClearHandlers();
}
/// <summary>
/// Invoke all progress handlers.
/// </summary>
private void InvokeProgressHandlers(float progress)
{
if (progressHandlers != null)
{
progressHandlers.Each(handler => InvokeHandler(handler.callback, handler.rejectable, progress));
}
}
/// <summary>
/// Reject the promise with an exception.
/// </summary>
public void Reject(Exception ex)
{
// Argument.NotNull(() => ex);
if (CurState != PromiseState.Pending)
{
throw new PromiseStateException(
"Attempt to reject a promise that is already in state: " + CurState
+ ", a promise can only be rejected when it is still in state: "
+ PromiseState.Pending
);
}
rejectionException = ex;
CurState = PromiseState.Rejected;
if (Promise.EnablePromiseTracking)
{
Promise.PendingPromises.Remove(this);
}
InvokeRejectHandlers(ex);
}
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
public void Resolve(PromisedT value)
{
if (CurState != PromiseState.Pending)
{
throw new PromiseStateException(
"Attempt to resolve a promise that is already in state: " + CurState
+ ", a promise can only be resolved when it is still in state: "
+ PromiseState.Pending
);
}
resolveValue = value;
CurState = PromiseState.Resolved;
if (Promise.EnablePromiseTracking)
{
Promise.PendingPromises.Remove(this);
}
InvokeResolveHandlers(value);
}
/// <summary>
/// Report progress on the promise.
/// </summary>
public void ReportProgress(float progress)
{
if (CurState != PromiseState.Pending)
{
throw new PromiseStateException(
"Attempt to report progress on a promise that is already in state: "
+ CurState + ", a promise can only report progress when it is still in state: "
+ PromiseState.Pending
);
}
InvokeProgressHandlers(progress);
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
public void Done(Action<PromisedT> onResolved, Action<Exception> onRejected)
{
Then(onResolved, onRejected)
.Catch(ex =>
Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
public void Done(Action<PromisedT> onResolved)
{
Then(onResolved)
.Catch(ex =>
Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Complete the promise. Adds a default error handler.
/// </summary>
public void Done()
{
Catch(ex =>
Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
public IPromise<PromisedT> WithName(string name)
{
this.Name = name;
return this;
}
/// <summary>
/// Handle errors for the promise.
/// </summary>
public IPromise Catch(Action<Exception> onRejected)
{
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = _ => resultPromise.Resolve();
Action<Exception> rejectHandler = ex =>
{
try
{
onRejected(ex);
resultPromise.Resolve();
}
catch(Exception cbEx)
{
resultPromise.Reject(cbEx);
}
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
ProgressHandlers(resultPromise, v => resultPromise.ReportProgress(v));
return resultPromise;
}
/// <summary>
/// Handle errors for the promise.
/// </summary>
public IPromise<PromisedT> Catch(Func<Exception, PromisedT> onRejected)
{
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => resultPromise.Resolve(v);
Action<Exception> rejectHandler = ex =>
{
try
{
resultPromise.Resolve(onRejected(ex));
}
catch (Exception cbEx)
{
resultPromise.Reject(cbEx);
}
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
ProgressHandlers(resultPromise, v => resultPromise.ReportProgress(v));
return resultPromise;
}
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved)
{
return Then(onResolved, null, null);
}
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
public IPromise Then(Func<PromisedT, IPromise> onResolved)
{
return Then(onResolved, null, null);
}
/// <summary>
/// Add a resolved callback.
/// </summary>
public IPromise Then(Action<PromisedT> onResolved)
{
return Then(onResolved, null, null);
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(
Func<PromisedT, IPromise<ConvertedT>> onResolved,
Func<Exception, IPromise<ConvertedT>> onRejected
)
{
return Then(onResolved, onRejected, null);
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
public IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected)
{
return Then(onResolved, onRejected, null);
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
public IPromise Then(Action<PromisedT> onResolved, Action<Exception> onRejected)
{
return Then(onResolved, onRejected, null);
}
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(
Func<PromisedT, IPromise<ConvertedT>> onResolved,
Func<Exception, IPromise<ConvertedT>> onRejected,
Action<float> onProgress
)
{
// This version of the function must supply an onResolved.
// Otherwise there is now way to get the converted value to pass to the resulting promise.
// Argument.NotNull(() => onResolved);
var resultPromise = new Promise<ConvertedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v =>
{
onResolved(v)
.Progress(progress => resultPromise.ReportProgress(progress))
.Then(
// Should not be necessary to specify the arg type on the next line, but Unity (mono) has an internal compiler error otherwise.
chainedValue => resultPromise.Resolve(chainedValue),
ex => resultPromise.Reject(ex)
);
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected == null)
{
resultPromise.Reject(ex);
return;
}
try
{
onRejected(ex)
.Then(
chainedValue => resultPromise.Resolve(chainedValue),
callbackEx => resultPromise.Reject(callbackEx)
);
}
catch (Exception callbackEx)
{
resultPromise.Reject(callbackEx);
}
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
if (onProgress != null)
{
ProgressHandlers(this, onProgress);
}
return resultPromise;
}
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// The resolved callback chains a non-value promise.
/// </summary>
public IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected, Action<float> onProgress)
{
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v =>
{
if (onResolved != null)
{
onResolved(v)
.Progress(progress => resultPromise.ReportProgress(progress))
.Then(
() => resultPromise.Resolve(),
ex => resultPromise.Reject(ex)
);
}
else
{
resultPromise.Resolve();
}
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected != null)
{
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
if (onProgress != null)
{
ProgressHandlers(this, onProgress);
}
return resultPromise;
}
/// <summary>
/// Add a resolved callback, a rejected callback and a progress callback.
/// </summary>
public IPromise Then(Action<PromisedT> onResolved, Action<Exception> onRejected, Action<float> onProgress)
{
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v =>
{
if (onResolved != null)
{
onResolved(v);
}
resultPromise.Resolve();
};
Action<Exception> rejectHandler = ex =>
{
if (onRejected != null)
{
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
if (onProgress != null)
{
ProgressHandlers(this, onProgress);
}
return resultPromise;
}
/// <summary>
/// Return a new promise with a different value.
/// May also change the type of the value.
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, ConvertedT> transform)
{
// Argument.NotNull(() => transform);
return Then(value => Promise<ConvertedT>.Resolved(transform(value)));
}
/// <summary>
/// Helper function to invoke or register resolve/reject handlers.
/// </summary>
private void ActionHandlers(IRejectable resultPromise, Action<PromisedT> resolveHandler, Action<Exception> rejectHandler)
{
if (CurState == PromiseState.Resolved)
{
InvokeHandler(resolveHandler, resultPromise, resolveValue);
}
else if (CurState == PromiseState.Rejected)
{
InvokeHandler(rejectHandler, resultPromise, rejectionException);
}
else
{
AddResolveHandler(resolveHandler, resultPromise);
AddRejectHandler(rejectHandler, resultPromise);
}
}
/// <summary>
/// Helper function to invoke or register progress handlers.
/// </summary>
private void ProgressHandlers(IRejectable resultPromise, Action<float> progressHandler)
{
if (CurState == PromiseState.Pending)
{
AddProgressHandler(progressHandler, resultPromise);
}
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Returns a promise for a collection of the resolved results.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain)
{
return Then(value => Promise<ConvertedT>.All(chain(value)));
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise ThenAll(Func<PromisedT, IEnumerable<IPromise>> chain)
{
return Then(value => Promise.All(chain(value)));
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise<IEnumerable<PromisedT>> All(params IPromise<PromisedT>[] promises)
{
return All((IEnumerable<IPromise<PromisedT>>)promises); // Cast is required to force use of the other All function.
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise<IEnumerable<PromisedT>> All(IEnumerable<IPromise<PromisedT>> promises)
{
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0)
{
return Promise<IEnumerable<PromisedT>>.Resolved(Enumerable.Empty<PromisedT>());
}
var remainingCount = promisesArray.Length;
var results = new PromisedT[remainingCount];
var progress = new float[remainingCount];
var resultPromise = new Promise<IEnumerable<PromisedT>>();
resultPromise.WithName("All");
promisesArray.Each((promise, index) =>
{
promise
.Progress(v =>
{
progress[index] = v;
if (resultPromise.CurState == PromiseState.Pending)
{
resultPromise.ReportProgress(progress.Average());
}
})
.Then(result =>
{
progress[index] = 1f;
results[index] = result;
--remainingCount;
if (remainingCount <= 0 && resultPromise.CurState == PromiseState.Pending)
{
// This will never happen if any of the promises errorred.
resultPromise.Resolve(results);
}
})
.Catch(ex =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Done();
});
return resultPromise;
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
public IPromise<ConvertedT> ThenRace<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain)
{
return Then(value => Promise<ConvertedT>.Race(chain(value)));
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a non-value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
public IPromise ThenRace(Func<PromisedT, IEnumerable<IPromise>> chain)
{
return Then(value => Promise.Race(chain(value)));
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise<PromisedT> Race(params IPromise<PromisedT>[] promises)
{
return Race((IEnumerable<IPromise<PromisedT>>)promises); // Cast is required to force use of the other function.
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise<PromisedT> Race(IEnumerable<IPromise<PromisedT>> promises)
{
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0)
{
throw new InvalidOperationException(
"At least 1 input promise must be provided for Race"
);
}
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName("Race");
var progress = new float[promisesArray.Length];
promisesArray.Each((promise, index) =>
{
promise
.Progress(v =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
progress[index] = v;
resultPromise.ReportProgress(progress.Max());
}
})
.Then(result =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
resultPromise.Resolve(result);
}
})
.Catch(ex =>
{
if (resultPromise.CurState == PromiseState.Pending)
{
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Done();
});
return resultPromise;
}
/// <summary>
/// Convert a simple value directly into a resolved promise.
/// </summary>
public static IPromise<PromisedT> Resolved(PromisedT promisedValue)
{
var promise = new Promise<PromisedT>();
promise.Resolve(promisedValue);
return promise;
}
/// <summary>
/// Convert an exception directly into a rejected promise.
/// </summary>
public static IPromise<PromisedT> Rejected(Exception ex)
{
// Argument.NotNull(() => ex);
var promise = new Promise<PromisedT>();
promise.Reject(ex);
return promise;
}
public IPromise<PromisedT> Finally(Action onComplete)
{
var promise = new Promise<PromisedT>();
promise.WithName(Name);
this.Then(x => promise.Resolve(x));
this.Catch(e => {
try {
onComplete();
promise.Reject(e);
} catch (Exception ne) {
promise.Reject(ne);
}
});
return promise.Then(v =>
{
onComplete();
return v;
});
}
public IPromise ContinueWith(Func<IPromise> onComplete)
{
var promise = new Promise();
promise.WithName(Name);
this.Then(x => promise.Resolve());
this.Catch(e => promise.Resolve());
return promise.Then(onComplete);
}
public IPromise<ConvertedT> ContinueWith<ConvertedT>(Func<IPromise<ConvertedT>> onComplete)
{
var promise = new Promise();
promise.WithName(Name);
this.Then(x => promise.Resolve());
this.Catch(e => promise.Resolve());
return promise.Then(onComplete);
}
public IPromise<PromisedT> Progress(Action<float> onProgress)
{
if (onProgress != null)
{
ProgressHandlers(this, onProgress);
}
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using Windows.UI.Core;
using System.Threading.Tasks;
using rhoruntime;
using rhodes;
<% $cur_module.parents.each do |parent| %>
namespace <%= parent.downcase() %> {<%
end %>
<%
dynamic_constants = ''
static_constants = ''
dynamic_methods = ''
static_methods = ''
has_getProperty = false
has_getProperties = false
has_getAllProperties = false
has_setProperty = false
has_setProperties = false
$cur_module.constants.each do |module_constant|
if module_constant.name && module_constant.name.length() > 0
if module_constant.type == RhogenCore::TYPE_STRING
constant = "\n public const string #{module_constant.name} = \"#{module_constant.value}\";"
else
constant = "\n public const #{api_generator_cs_makeNativeTypeArg(module_constant.type)} #{module_constant.name} = #{module_constant.value};"
end
if $cur_module.properties_access == ModuleMethod::ACCESS_INSTANCE
dynamic_constants += constant
else # if $cur_module.properties_access == ModuleMethod::ACCESS_STATIC
static_constants += constant
end
end
end
dynamic_constants += "\n" if dynamic_constants.length() > 0
static_constants += "\n" if static_constants.length() > 0
$cur_module.methods.each do |module_method|
next if !module_method.generateNativeAPI
params = module_method.cached_data["cs_params"]
method_def = "\n abstract public void #{module_method.native_name}(#{params});"
if module_method.access == ModuleMethod::ACCESS_STATIC
static_methods += method_def
else
if module_method.native_name == 'getProperty'
has_getProperty = true
elsif module_method.native_name == 'getProperties'
has_getProperties = true
elsif module_method.native_name == 'getAllProperties'
has_getAllProperties = true
elsif module_method.native_name == 'setProperty'
has_setProperty = true
elsif module_method.native_name == 'setProperties'
has_setProperties = true
else
dynamic_methods += method_def
end
end
end
%>
namespace <%= $cur_module.name %>Impl
{
abstract public class <%= $cur_module.name %>Base : I<%= $cur_module.name %>Impl
{
protected string _strID = "1";
protected long _nativeImpl = 0;
protected CoreDispatcher dispatcher = null;
protected <%= $cur_module.name %>RuntimeComponent _runtime;
<%= dynamic_constants %>
public <%= $cur_module.name %>Base(string id)
{
_strID = id;
_runtime = new <%= $cur_module.name %>RuntimeComponent(this);
try{dispatcher = MainPage.getDispatcher();
}catch(Exception e){deb("Can't get access to dispatcher");}
}
public static void deb(String s, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
if (memberName.Length != 0) {memberName = memberName + " : ";}
System.Diagnostics.Debug.WriteLine(memberName + s);
}
public long getNativeImpl()
{
return _nativeImpl;
}
public virtual void setNativeImpl(string strID, long native)
{
_strID = strID;
_nativeImpl = native;
}
public void dispatchInvoke(Action a)
{
if (dispatcher != null) {
var ignore = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{try{a();} catch (Exception ex) {System.Diagnostics.Debug.WriteLine("Invoke in UI Thread exception");} });
}else{a();}
}
<% if has_getProperty
%>
public void getProperty(string propertyName, IMethodResult oResult)
{
_runtime.getProperty(propertyName, oResult);
}
<% end
if has_getProperties
%>
public void getProperties(IReadOnlyList<string> arrayofNames, IMethodResult oResult)
{
_runtime.getProperties(arrayofNames, oResult);
}
<% end
if has_getAllProperties
%>
public void getAllProperties(IMethodResult oResult)
{
_runtime.getAllProperties(oResult);
}
<% end
if has_setProperty
%>
public void setProperty(string propertyName, string propertyValue, IMethodResult oResult)
{
_runtime.setProperty(propertyName, propertyValue, oResult);
}
<% end
if has_setProperties
%>
public void setProperties(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult)
{
_runtime.setProperties(propertyMap, oResult);
}
<% end
%><%= dynamic_methods%>
}
abstract public class <%= $cur_module.name %>SingletonBase : I<%= $cur_module.name %>SingletonImpl
{
protected SortedDictionary<string, <%= $cur_module.name %>Base> keeper = new SortedDictionary<string, <%= $cur_module.name %>Base>();
public I<%= $cur_module.name %>Impl get<%= $cur_module.name %>ByID(string id)
{
if (keeper.ContainsKey(id))
{
return keeper[id];
}
else
{
<%= $cur_module.name %>Base impl = new <%= $cur_module.name %>(id);
keeper.Add(id, impl);
return impl;
}
}
protected <%= $cur_module.name %>SingletonComponent _runtime;
<%= static_constants %>
public <%= $cur_module.name %>SingletonBase()
{
try{dispatcher = MainPage.getDispatcher();
}catch(Exception e){deb("Can't get access to dispatcher");}
_runtime = new <%= $cur_module.name %>SingletonComponent(this);
}
public static void deb(String s, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
if (memberName.Length != 0) {memberName = memberName + " : ";}
System.Diagnostics.Debug.WriteLine(memberName + s);
}
public void dispatchInvoke(Action a)
{
if (dispatcher != null) {
var ignore = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{try{a();} catch (Exception ex) {System.Diagnostics.Debug.WriteLine("Invoke in UI Thread exception");} });
}else{a();}
}
protected CoreDispatcher dispatcher = null;
<%= static_methods%>
}
public class <%= $cur_module.name %>FactoryBase : I<%= $cur_module.name %>FactoryImpl
{
protected static <%= $cur_module.name %>Singleton instance = null;
public virtual I<%= $cur_module.name %>Impl getImpl(string id) {
getSingletonImpl();
return instance.get<%= $cur_module.name %>ByID(id);
}
public I<%= $cur_module.name %>SingletonImpl getSingletonImpl() {
if (instance == null){instance = new <%= $cur_module.name %>Singleton();}
return instance;
}
}
}
<% $cur_module.parents.each do |parent| %>
}<%
end %>
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Google.ProtocolBuffers;
using Google.ProtocolBuffers.Serialization.Http;
using Google.ProtocolBuffers.TestProtos;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using Google.ProtocolBuffers.Serialization;
using System.Text;
namespace Google.ProtocolBuffers
{
/// <summary>
/// This class verifies the correct code is generated from unittest_rpc_interop.proto and provides a small demonstration
/// of using the new IRpcDispatch to write a client/server
/// </summary>
[TestClass]
public class TestRpcForMimeTypes
{
/// <summary>
/// A sample implementation of the ISearchService for testing
/// </summary>
private class ExampleSearchImpl : ISearchService
{
SearchResponse ISearchService.Search(SearchRequest searchRequest)
{
if (searchRequest.CriteriaCount == 0)
{
throw new ArgumentException("No criteria specified.", new InvalidOperationException());
}
SearchResponse.Builder resp = SearchResponse.CreateBuilder();
foreach (string criteria in searchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://search.com").
Build());
}
return resp.Build();
}
SearchResponse ISearchService.RefineSearch(RefineSearchRequest refineSearchRequest)
{
SearchResponse.Builder resp = refineSearchRequest.PreviousResults.ToBuilder();
foreach (string criteria in refineSearchRequest.CriteriaList)
{
resp.AddResults(
SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://refine.com").
Build());
}
return resp.Build();
}
}
/// <summary>
/// An example extraction of the wire protocol
/// </summary>
private interface IHttpTransfer
{
void Execute(string method, string contentType, Stream input, string acceptType, Stream output);
}
/// <summary>
/// An example of a server responding to a web/http request
/// </summary>
private class ExampleHttpServer : IHttpTransfer
{
public readonly MessageFormatOptions Options =
new MessageFormatOptions
{
ExtensionRegistry = ExtensionRegistry.Empty,
FormattedOutput = true,
XmlReaderOptions = XmlReaderOptions.ReadNestedArrays,
XmlReaderRootElementName = "request",
XmlWriterOptions = XmlWriterOptions.OutputNestedArrays,
XmlWriterRootElementName = "response"
};
private readonly IRpcServerStub _stub;
public ExampleHttpServer(ISearchService implementation)
{
//on the server, we create a dispatch to call the appropriate method by name
IRpcDispatch dispatch = new SearchService.Dispatch(implementation);
//we then wrap that dispatch in a server stub which will deserialize the wire bytes to the message
//type appropriate for the method name being invoked.
_stub = new SearchService.ServerStub(dispatch);
}
void IHttpTransfer.Execute(string method, string contentType, Stream input, string acceptType, Stream output)
{
//3.5: _stub.HttpCallMethod(
Extensions.HttpCallMethod(_stub,
method, Options,
contentType, input,
acceptType, output
);
}
}
/// <summary>
/// An example of a client sending a wire request
/// </summary>
private class ExampleClient : IRpcDispatch
{
public readonly MessageFormatOptions Options =
new MessageFormatOptions
{
ExtensionRegistry = ExtensionRegistry.Empty,
FormattedOutput = true,
XmlReaderOptions = XmlReaderOptions.ReadNestedArrays,
XmlReaderRootElementName = "response",
XmlWriterOptions = XmlWriterOptions.OutputNestedArrays,
XmlWriterRootElementName = "request"
};
private readonly IHttpTransfer _wire;
private readonly string _mimeType;
public ExampleClient(IHttpTransfer wire, string mimeType)
{
_wire = wire;
_mimeType = mimeType;
}
TMessage IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, IMessageLite request,
IBuilderLite<TMessage, TBuilder> response)
{
MemoryStream input = new MemoryStream();
MemoryStream output = new MemoryStream();
//Write to _mimeType format
Extensions.WriteTo(request, Options, _mimeType, input);
input.Position = 0;
_wire.Execute(method, _mimeType, input, _mimeType, output);
//Read from _mimeType format
output.Position = 0;
Extensions.MergeFrom(response, Options, _mimeType, output);
return response.Build();
}
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestClientServerWithJsonFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "text/json"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestClientServerWithXmlFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "text/xml"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestClientServerWithProtoFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ISearchService client = new SearchService(new ExampleClient(wire, "application/x-protobuf"));
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestClientServerWithCustomFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//Setup our custom mime-type format as the only format supported:
server.Options.MimeInputTypes.Clear();
server.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance);
server.Options.MimeOutputTypes.Clear();
server.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance);
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
ExampleClient exclient = new ExampleClient(wire, "foo/bar");
//Add our custom mime-type format
exclient.Options.MimeInputTypes.Add("foo/bar", CodedInputStream.CreateInstance);
exclient.Options.MimeOutputTypes.Add("foo/bar", CodedOutputStream.CreateInstance);
ISearchService client = new SearchService(exclient);
//now the client has a real, typed, interface to work with:
SearchResponse result = client.Search(SearchRequest.CreateBuilder().AddCriteria("Test").Build());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
//The test part of this, call the only other method
result =
client.RefineSearch(
RefineSearchRequest.CreateBuilder().SetPreviousResults(result).AddCriteria("Refine").Build());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Refine", result.ResultsList[1].Name);
Assert.AreEqual("http://refine.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestServerWithUriFormat()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes("?Criteria=Test&Criteria=Test+of%20URI"));
MemoryStream output = new MemoryStream();
//Call the server
wire.Execute("Search",
MessageFormatOptions.ContentFormUrlEncoded, input,
MessageFormatOptions.ContentTypeProtoBuffer, output
);
SearchResponse result = SearchResponse.ParseFrom(output.ToArray());
Assert.AreEqual(2, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
Assert.AreEqual("Test of URI", result.ResultsList[1].Name);
Assert.AreEqual("http://search.com", result.ResultsList[1].Url);
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestInvalidMimeType()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream();
MemoryStream output = new MemoryStream();
//Call the server
wire.Execute("Search",
"bad/mime", input,
MessageFormatOptions.ContentTypeProtoBuffer, output
);
Assert.Fail();
}
/// <summary>
/// Test sending and recieving messages via text/json
/// </summary>
[TestMethod]
public void TestDefaultMimeType()
{
ExampleHttpServer server = new ExampleHttpServer(new ExampleSearchImpl());
//obviously if this was a 'real' transport we would not use the server, rather the server would be listening, the client transmitting
IHttpTransfer wire = server;
MemoryStream input = new MemoryStream(new SearchRequest.Builder().AddCriteria("Test").Build().ToByteArray());
MemoryStream output = new MemoryStream();
//With this default set, any invalid/unknown mime-type will be mapped to use that format
server.Options.DefaultContentType = MessageFormatOptions.ContentTypeProtoBuffer;
wire.Execute("Search",
"foo", input,
"bar", output
);
SearchResponse result = SearchResponse.ParseFrom(output.ToArray());
Assert.AreEqual(1, result.ResultsCount);
Assert.AreEqual("Test", result.ResultsList[0].Name);
Assert.AreEqual("http://search.com", result.ResultsList[0].Url);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
using System.Numerics;
#endif
using System.Text;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenWriterTest : TestFixtureBase
{
[Test]
public void ValueFormatting()
{
byte[] data = Encoding.UTF8.GetBytes("Hello world.");
JToken root;
using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteValue(data);
jsonWriter.WriteEndArray();
root = jsonWriter.Token;
}
CustomAssert.IsInstanceOfType(typeof(JArray), root);
Assert.AreEqual(13, root.Children().Count());
Assert.AreEqual("@", (string)root[0]);
Assert.AreEqual("\r\n\t\f\b?{\\r\\n\"\'", (string)root[1]);
Assert.AreEqual(true, (bool)root[2]);
Assert.AreEqual(10, (int)root[3]);
Assert.AreEqual(10.99, (double)root[4]);
Assert.AreEqual(0.99, (double)root[5]);
Assert.AreEqual(0.000000000000000001d, (double)root[6]);
Assert.AreEqual(0.000000000000000001m, (decimal)root[7]);
Assert.AreEqual(null, (string)root[8]);
Assert.AreEqual("This is a string.", (string)root[9]);
Assert.AreEqual(null, ((JValue)root[10]).Value);
Assert.AreEqual(null, ((JValue)root[11]).Value);
Assert.AreEqual(data, (byte[])root[12]);
}
[Test]
public void State()
{
using (JsonWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
}
}
[Test]
public void CurrentToken()
{
using (JTokenWriter jsonWriter = new JTokenWriter())
{
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(null, jsonWriter.CurrentToken);
jsonWriter.WriteStartObject();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(jsonWriter.Token, jsonWriter.CurrentToken);
JObject o = (JObject)jsonWriter.Token;
jsonWriter.WritePropertyName("CPU");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("CPU"), jsonWriter.CurrentToken);
jsonWriter.WriteValue("Intel");
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(o["CPU"], jsonWriter.CurrentToken);
jsonWriter.WritePropertyName("Drives");
Assert.AreEqual(WriteState.Property, jsonWriter.WriteState);
Assert.AreEqual(o.Property("Drives"), jsonWriter.CurrentToken);
jsonWriter.WriteStartArray();
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(o["Drives"], jsonWriter.CurrentToken);
JArray a = (JArray)jsonWriter.CurrentToken;
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#endif
jsonWriter.WriteValue(new byte[0]);
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
jsonWriter.WriteEnd();
Assert.AreEqual(WriteState.Object, jsonWriter.WriteState);
Assert.AreEqual(a, jsonWriter.CurrentToken);
jsonWriter.WriteEndObject();
Assert.AreEqual(WriteState.Start, jsonWriter.WriteState);
Assert.AreEqual(o, jsonWriter.CurrentToken);
}
}
[Test]
public void WriteComment()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteComment("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
/*fail*/]", writer.Token.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
[Test]
public void WriteBigInteger()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteValue(new BigInteger(123));
writer.WriteEndArray();
JValue i = (JValue)writer.Token[0];
Assert.AreEqual(new BigInteger(123), i.Value);
Assert.AreEqual(JTokenType.Integer, i.Type);
StringAssert.AreEqual(@"[
123
]", writer.Token.ToString());
}
#endif
[Test]
public void WriteRaw()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRaw("fail");
writer.WriteRaw("fail");
writer.WriteEndArray();
// this is a bug. write raw shouldn't be autocompleting like this
// hard to fix without introducing Raw and RawValue token types
// meh
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteRawValue()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartArray();
writer.WriteRawValue("fail");
writer.WriteRawValue("fail");
writer.WriteEndArray();
StringAssert.AreEqual(@"[
fail,
fail
]", writer.Token.ToString());
}
[Test]
public void WriteDuplicatePropertyName()
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("prop1");
writer.WriteStartObject();
writer.WriteEndObject();
writer.WritePropertyName("prop1");
writer.WriteStartArray();
writer.WriteEndArray();
writer.WriteEndObject();
StringAssert.AreEqual(@"{
""prop1"": []
}", writer.Token.ToString());
}
[Test]
public void DateTimeZoneHandling()
{
JTokenWriter writer = new JTokenWriter
{
DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc
};
writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified));
JValue value = (JValue)writer.Token;
DateTime dt = (DateTime)value.Value;
Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion
{
/// <summary>
/// csharp automatic line ender command handler
/// </summary>
[ExportCommandHandler(PredefinedCommandHandlerNames.AutomaticLineEnder, ContentTypeNames.CSharpContentType)]
[Order(After = PredefinedCommandHandlerNames.Completion)]
internal class AutomaticLineEnderCommandHandler : AbstractAutomaticLineEnderCommandHandler
{
[ImportingConstructor]
public AutomaticLineEnderCommandHandler(
IWaitIndicator waitIndicator,
ITextUndoHistoryRegistry undoRegistry,
IEditorOperationsFactoryService editorOperations)
: base(waitIndicator, undoRegistry, editorOperations)
{
}
protected override void NextAction(IEditorOperations editorOperation, Action nextAction)
{
editorOperation.InsertNewLine();
}
protected override bool TreatAsReturn(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var endToken = root.FindToken(position);
if (endToken.IsMissing)
{
return false;
}
var tokenToLeft = root.FindTokenOnLeftOfPosition(position);
var startToken = endToken.GetPreviousToken();
// case 1:
// Consider code like so: try {|}
// With auto brace completion on, user types `{` and `Return` in a hurry.
// During typing, it is possible that shift was still down and not released after typing `{`.
// So we've got an unintentional `shift + enter` and also we have nothing to complete this,
// so we put in a newline,
// which generates code like so : try { }
// |
// which is not useful as : try {
// |
// }
// To support this, we treat `shift + enter` like `enter` here.
var afterOpenBrace = startToken.Kind() == SyntaxKind.OpenBraceToken
&& endToken.Kind() == SyntaxKind.CloseBraceToken
&& tokenToLeft == startToken
&& endToken.Parent.IsKind(SyntaxKind.Block)
&& FormattingRangeHelper.AreTwoTokensOnSameLine(startToken, endToken);
return afterOpenBrace;
}
protected override void FormatAndApply(Document document, int position, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var endToken = root.FindToken(position);
if (endToken.IsMissing)
{
return;
}
var ranges = FormattingRangeHelper.FindAppropriateRange(endToken, useDefaultRange: false);
if (ranges == null)
{
return;
}
var startToken = ranges.Value.Item1;
if (startToken.IsMissing || startToken.Kind() == SyntaxKind.None)
{
return;
}
var changes = Formatter.GetFormattedTextChanges(root, new TextSpan[] { TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) }, document.Project.Solution.Workspace, options: null, // use default
rules: null, // use default
cancellationToken: cancellationToken);
document.ApplyTextChanges(changes.ToArray(), cancellationToken);
}
protected override string GetEndingString(Document document, int position, CancellationToken cancellationToken)
{
// prepare expansive information from document
var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var root = tree.GetRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var text = tree.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var semicolon = SyntaxFacts.GetText(SyntaxKind.SemicolonToken);
// Go through the set of owning nodes in leaf to root chain.
foreach (var owningNode in GetOwningNodes(root, position))
{
SyntaxToken lastToken;
if (!TryGetLastToken(text, position, owningNode, out lastToken))
{
// If we can't get last token, there is nothing more to do, just skip
// the other owning nodes and return.
return null;
}
if (!CheckLocation(text, position, owningNode, lastToken))
{
// If we failed this check, we indeed got the intended owner node and
// inserting line ender here would introduce errors.
return null;
}
// so far so good. we only add semi-colon if it makes statement syntax error free
var textToParse = owningNode.NormalizeWhitespace().ToFullString() + semicolon;
// currently, Parsing a field is not supported. as a workaround, wrap the field in a type and parse
var node = owningNode.TypeSwitch(
(BaseFieldDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(BaseMethodDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(BasePropertyDeclarationSyntax n) => SyntaxFactory.ParseCompilationUnit(WrapInType(textToParse), options: (CSharpParseOptions)tree.Options),
(StatementSyntax n) => SyntaxFactory.ParseStatement(textToParse, options: (CSharpParseOptions)tree.Options),
(UsingDirectiveSyntax n) => (SyntaxNode)SyntaxFactory.ParseCompilationUnit(textToParse, options: (CSharpParseOptions)tree.Options));
// Insert line ender if we didn't introduce any diagnostics, if not try the next owning node.
if (node != null && !node.ContainsDiagnostics)
{
return semicolon;
}
}
return null;
}
/// <summary>
/// wrap field in type
/// </summary>
private string WrapInType(string textToParse)
{
return "class C { " + textToParse + " }";
}
/// <summary>
/// make sure current location is okay to put semicolon
/// </summary>
private static bool CheckLocation(SourceText text, int position, SyntaxNode owningNode, SyntaxToken lastToken)
{
var line = text.Lines.GetLineFromPosition(position);
// if caret is at the end of the line and containing statement is expression statement
// don't do anything
if (position == line.End && owningNode is ExpressionStatementSyntax)
{
return false;
}
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
// make sure that there is no trailing text after last token on the line if it is not at the end of the line
if (!locatedAtTheEndOfLine)
{
var endingString = text.ToString(TextSpan.FromBounds(lastToken.Span.End, line.End));
if (!string.IsNullOrWhiteSpace(endingString))
{
return false;
}
}
// check whether using has contents
if (owningNode.TypeSwitch((UsingDirectiveSyntax u) => u.Name == null || u.Name.IsMissing))
{
return false;
}
// make sure there is no open string literals
var previousToken = lastToken.GetPreviousToken();
if (previousToken.Kind() == SyntaxKind.StringLiteralToken && previousToken.ToString().Last() != '"')
{
return false;
}
if (previousToken.Kind() == SyntaxKind.CharacterLiteralToken && previousToken.ToString().Last() != '\'')
{
return false;
}
// now, check embedded statement case
if (owningNode.IsEmbeddedStatementOwner())
{
var embeddedStatement = owningNode.GetEmbeddedStatement();
if (embeddedStatement == null || embeddedStatement.Span.IsEmpty)
{
return false;
}
}
return true;
}
/// <summary>
/// get last token of the given using/field/statement/expression bodied member if one exists
/// </summary>
private static bool TryGetLastToken(SourceText text, int position, SyntaxNode owningNode, out SyntaxToken lastToken)
{
lastToken = owningNode.GetLastToken(includeZeroWidth: true);
// last token must be on the same line as the caret
var line = text.Lines.GetLineFromPosition(position);
var locatedAtTheEndOfLine = LocatedAtTheEndOfLine(line, lastToken);
if (!locatedAtTheEndOfLine && text.Lines.IndexOf(lastToken.Span.End) != line.LineNumber)
{
return false;
}
// if we already have last semicolon, we don't need to do anything
if (!lastToken.IsMissing && lastToken.Kind() == SyntaxKind.SemicolonToken)
{
return false;
}
return true;
}
/// <summary>
/// check whether the line is located at the end of the line
/// </summary>
private static bool LocatedAtTheEndOfLine(TextLine line, SyntaxToken lastToken)
{
return lastToken.IsMissing && lastToken.Span.End == line.EndIncludingLineBreak;
}
/// <summary>
/// find owning usings/field/statement/expression-bodied member of the given position
/// </summary>
private static IEnumerable<SyntaxNode> GetOwningNodes(SyntaxNode root, int position)
{
// make sure caret position is somewhere we can find a token
var token = root.FindTokenFromEnd(position);
if (token.Kind() == SyntaxKind.None)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return token.GetAncestors<SyntaxNode>()
.Where(AllowedConstructs)
.Select(OwningNode);
}
private static bool AllowedConstructs(SyntaxNode n)
{
return n is StatementSyntax ||
n is BaseFieldDeclarationSyntax ||
n is UsingDirectiveSyntax ||
n is ArrowExpressionClauseSyntax;
}
private static SyntaxNode OwningNode(SyntaxNode n)
{
return n is ArrowExpressionClauseSyntax ? n.Parent : n;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace System.Management.Automation
{
/// <summary>
/// Defines a data structure used to represent informational context destined for the host or user.
/// </summary>
/// <remarks>
/// InformationRecords are passed to <see cref="System.Management.Automation.Cmdlet.WriteInformation(object, string[])"/>,
/// which, according to host or user preference, forwards that information on to the host for rendering to the user.
/// </remarks>
/// <seealso cref="System.Management.Automation.Cmdlet.WriteInformation(object, string[])"/>
[DataContract()]
public class InformationRecord
{
/// <summary>
/// Initializes a new instance of the InformationRecord class.
/// </summary>
/// <param name="messageData">The object to be transmitted to the host.</param>
/// <param name="source">The source of the message (i.e.: script path, function name, etc.).</param>
public InformationRecord(object messageData, string source)
{
this.MessageData = messageData;
this.Source = source;
this.TimeGenerated = DateTime.Now;
this.NativeThreadId = PsUtils.GetNativeThreadId();
this.ManagedThreadId = (uint)Environment.CurrentManagedThreadId;
}
private InformationRecord() { }
/// <summary>
/// Copy constructor.
/// </summary>
internal InformationRecord(InformationRecord baseRecord)
{
this.MessageData = baseRecord.MessageData;
this.Source = baseRecord.Source;
this.TimeGenerated = baseRecord.TimeGenerated;
this.Tags = baseRecord.Tags;
this.User = baseRecord.User;
this.Computer = baseRecord.Computer;
this.ProcessId = baseRecord.ProcessId;
this.NativeThreadId = baseRecord.NativeThreadId;
this.ManagedThreadId = baseRecord.ManagedThreadId;
}
// Some of these setters are internal, while others are public.
// The ones that are public are left that way because systems that proxy
// the events may need to alter them (i.e.: workflow). The ones that remain internal
// are that way because they are fundamental properties of the record itself.
/// <summary>
/// The message data for this informational record.
/// </summary>
[DataMember]
public object MessageData { get; internal set; }
/// <summary>
/// The source of this informational record (script path, function name, etc.)
/// </summary>
[DataMember]
public string Source { get; set; }
/// <summary>
/// The time this informational record was generated.
/// </summary>
[DataMember]
public DateTime TimeGenerated { get; set; }
/// <summary>
/// The tags associated with this informational record (if any)
/// </summary>
[DataMember]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public List<string> Tags
{
get { return _tags ??= new List<string>(); }
internal set { _tags = value; }
}
private List<string> _tags;
/// <summary>
/// The user that generated this informational record.
/// </summary>
[DataMember]
public string User
{
get
{
if (this._user == null)
{
// domain\user on Windows, just user on Unix
#if UNIX
this._user = Environment.UserName;
#else
this._user = Environment.UserDomainName + "\\" + Environment.UserName;
#endif
}
return _user;
}
set
{
_user = value;
}
}
private string _user;
/// <summary>
/// The computer that generated this informational record.
/// </summary>
[DataMember]
public string Computer
{
get { return this._computerName ??= PsUtils.GetHostName(); }
set { this._computerName = value; }
}
private string _computerName;
/// <summary>
/// The process that generated this informational record.
/// </summary>
[DataMember]
public uint ProcessId
{
get
{
if (!this._processId.HasValue)
{
this._processId = (uint)Environment.ProcessId;
}
return this._processId.Value;
}
set
{
_processId = value;
}
}
private uint? _processId;
/// <summary>
/// The native thread that generated this informational record.
/// </summary>
public uint NativeThreadId { get; set; }
/// <summary>
/// The managed thread that generated this informational record.
/// </summary>
[DataMember]
public uint ManagedThreadId { get; set; }
/// <summary>
/// Converts an InformationRecord to a string-based representation.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (MessageData != null)
{
return MessageData.ToString();
}
else
{
return base.ToString();
}
}
internal static InformationRecord FromPSObjectForRemoting(PSObject inputObject)
{
InformationRecord informationRecord = new InformationRecord();
informationRecord.MessageData = RemotingDecoder.GetPropertyValue<object>(inputObject, "MessageData");
informationRecord.Source = RemotingDecoder.GetPropertyValue<string>(inputObject, "Source");
informationRecord.TimeGenerated = RemotingDecoder.GetPropertyValue<DateTime>(inputObject, "TimeGenerated");
informationRecord.Tags = new List<string>();
System.Collections.ArrayList tagsArrayList = RemotingDecoder.GetPropertyValue<System.Collections.ArrayList>(inputObject, "Tags");
foreach (string tag in tagsArrayList)
{
informationRecord.Tags.Add(tag);
}
informationRecord.User = RemotingDecoder.GetPropertyValue<string>(inputObject, "User");
informationRecord.Computer = RemotingDecoder.GetPropertyValue<string>(inputObject, "Computer");
informationRecord.ProcessId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "ProcessId");
informationRecord.NativeThreadId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "NativeThreadId");
informationRecord.ManagedThreadId = RemotingDecoder.GetPropertyValue<uint>(inputObject, "ManagedThreadId");
return informationRecord;
}
/// <summary>
/// Returns this object as a PSObject property bag
/// that can be used in a remoting protocol data object.
/// </summary>
/// <returns>This object as a PSObject property bag.</returns>
internal PSObject ToPSObjectForRemoting()
{
PSObject informationAsPSObject = RemotingEncoder.CreateEmptyPSObject();
informationAsPSObject.Properties.Add(new PSNoteProperty("MessageData", this.MessageData));
informationAsPSObject.Properties.Add(new PSNoteProperty("Source", this.Source));
informationAsPSObject.Properties.Add(new PSNoteProperty("TimeGenerated", this.TimeGenerated));
informationAsPSObject.Properties.Add(new PSNoteProperty("Tags", this.Tags));
informationAsPSObject.Properties.Add(new PSNoteProperty("User", this.User));
informationAsPSObject.Properties.Add(new PSNoteProperty("Computer", this.Computer));
informationAsPSObject.Properties.Add(new PSNoteProperty("ProcessId", this.ProcessId));
informationAsPSObject.Properties.Add(new PSNoteProperty("NativeThreadId", this.NativeThreadId));
informationAsPSObject.Properties.Add(new PSNoteProperty("ManagedThreadId", this.ManagedThreadId));
return informationAsPSObject;
}
}
/// <summary>
/// Class that holds informational messages to represent output created by the
/// Write-Host cmdlet.
/// </summary>
public class HostInformationMessage
{
/// <summary>
/// The message being output by the host.
/// </summary>
public string Message { get; set; }
/// <summary>
/// 'True' if the host should not append a NewLine to the message output.
/// </summary>
public bool? NoNewLine { get; set; }
/// <summary>
/// The foreground color of the message.
/// </summary>
public ConsoleColor? ForegroundColor { get; set; }
/// <summary>
/// The background color of the message.
/// </summary>
public ConsoleColor? BackgroundColor { get; set; }
/// <summary>
/// Returns a string-based representation of the host information message.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Message;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License Is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HWPF.SPRM
{
using System;
using System.Collections;
using NPOI.HWPF.UserModel;
using NPOI.Util;
public class CharacterSprmCompressor
{
public CharacterSprmCompressor()
{
}
public static byte[] CompressCharacterProperty(CharacterProperties newCHP, CharacterProperties oldCHP)
{
ArrayList sprmList = new ArrayList();
int size = 0;
if (newCHP.IsFRMarkDel() != oldCHP.IsFRMarkDel())
{
int value = 0;
if (newCHP.IsFRMarkDel())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0800, value, null, sprmList);
}
if (newCHP.IsFRMark() != oldCHP.IsFRMark())
{
int value = 0;
if (newCHP.IsFRMark())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0801, value, null, sprmList);
}
if (newCHP.IsFFldVanish() != oldCHP.IsFFldVanish())
{
int value = 0;
if (newCHP.IsFFldVanish())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0802, value, null, sprmList);
}
if (newCHP.IsFSpec() != oldCHP.IsFSpec() || newCHP.GetFcPic() != oldCHP.GetFcPic())
{
size += SprmUtils.AddSprm((short)0x6a03, newCHP.GetFcPic(), null, sprmList);
}
if (newCHP.GetIbstRMark() != oldCHP.GetIbstRMark())
{
size += SprmUtils.AddSprm((short)0x4804, newCHP.GetIbstRMark(), null, sprmList);
}
if (!newCHP.GetDttmRMark().Equals(oldCHP.GetDttmRMark()))
{
byte[] buf = new byte[4];
newCHP.GetDttmRMark().Serialize(buf, 0);
size += SprmUtils.AddSprm((short)0x6805, LittleEndian.GetInt(buf), null, sprmList);
}
if (newCHP.IsFData() != oldCHP.IsFData())
{
int value = 0;
if (newCHP.IsFData())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0806, value, null, sprmList);
}
if (newCHP.IsFSpec() && newCHP.GetFtcSym() != 0)
{
byte[] varParam = new byte[4];
LittleEndian.PutShort(varParam, 0, (short)newCHP.GetFtcSym());
LittleEndian.PutShort(varParam, 2, (short)newCHP.GetXchSym());
size += SprmUtils.AddSprm((short)0x6a09, 0, varParam, sprmList);
}
if (newCHP.IsFOle2() != newCHP.IsFOle2())
{
int value = 0;
if (newCHP.IsFOle2())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x080a, value, null, sprmList);
}
if (newCHP.GetIcoHighlight() != oldCHP.GetIcoHighlight())
{
size += SprmUtils.AddSprm((short)0x2a0c, newCHP.GetIcoHighlight(), null, sprmList);
}
if (newCHP.GetFcObj() != oldCHP.GetFcObj())
{
size += SprmUtils.AddSprm((short)0x680e, newCHP.GetFcObj(), null, sprmList);
}
if (newCHP.GetIstd() != oldCHP.GetIstd())
{
size += SprmUtils.AddSprm((short)0x4a30, newCHP.GetIstd(), null, sprmList);
}
if (newCHP.IsFBold() != oldCHP.IsFBold())
{
int value = 0;
if (newCHP.IsFBold())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0835, value, null, sprmList);
}
if (newCHP.IsFItalic() != oldCHP.IsFItalic())
{
int value = 0;
if (newCHP.IsFItalic())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0836, value, null, sprmList);
}
if (newCHP.IsFStrike() != oldCHP.IsFStrike())
{
int value = 0;
if (newCHP.IsFStrike())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0837, value, null, sprmList);
}
if (newCHP.IsFOutline() != oldCHP.IsFOutline())
{
int value = 0;
if (newCHP.IsFOutline())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0838, value, null, sprmList);
}
if (newCHP.IsFShadow() != oldCHP.IsFShadow())
{
int value = 0;
if (newCHP.IsFShadow())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0839, value, null, sprmList);
}
if (newCHP.IsFSmallCaps() != oldCHP.IsFSmallCaps())
{
int value = 0;
if (newCHP.IsFSmallCaps())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x083a, value, null, sprmList);
}
if (newCHP.IsFCaps() != oldCHP.IsFCaps())
{
int value = 0;
if (newCHP.IsFCaps())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x083b, value, null, sprmList);
}
if (newCHP.IsFVanish() != oldCHP.IsFVanish())
{
int value = 0;
if (newCHP.IsFVanish())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x083c, value, null, sprmList);
}
if (newCHP.GetKul() != oldCHP.GetKul())
{
size += SprmUtils.AddSprm((short)0x2a3e, newCHP.GetKul(), null, sprmList);
}
if (newCHP.GetDxaSpace() != oldCHP.GetDxaSpace())
{
size += SprmUtils.AddSprm(unchecked((short)0x8840), newCHP.GetDxaSpace(), null, sprmList);
}
if (newCHP.GetIco() != oldCHP.GetIco())
{
size += SprmUtils.AddSprm((short)0x2a42, newCHP.GetIco(), null, sprmList);
}
if (newCHP.GetHps() != oldCHP.GetHps())
{
size += SprmUtils.AddSprm((short)0x4a43, newCHP.GetHps(), null, sprmList);
}
if (newCHP.GetHpsPos() != oldCHP.GetHpsPos())
{
size += SprmUtils.AddSprm((short)0x4845, newCHP.GetHpsPos(), null, sprmList);
}
if (newCHP.GetHpsKern() != oldCHP.GetHpsKern())
{
size += SprmUtils.AddSprm((short)0x484b, newCHP.GetHpsKern(), null, sprmList);
}
if (newCHP.GetYsr() != oldCHP.GetYsr())
{
size += SprmUtils.AddSprm((short)0x484e, newCHP.GetYsr(), null, sprmList);
}
if (newCHP.GetFtcAscii() != oldCHP.GetFtcAscii())
{
size += SprmUtils.AddSprm((short)0x4a4f, newCHP.GetFtcAscii(), null, sprmList);
}
if (newCHP.GetFtcFE() != oldCHP.GetFtcFE())
{
size += SprmUtils.AddSprm((short)0x4a50, newCHP.GetFtcFE(), null, sprmList);
}
if (newCHP.GetFtcOther() != oldCHP.GetFtcOther())
{
size += SprmUtils.AddSprm((short)0x4a51, newCHP.GetFtcOther(), null, sprmList);
}
if (newCHP.IsFDStrike() != oldCHP.IsFDStrike())
{
int value = 0;
if (newCHP.IsFDStrike())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x2a53, value, null, sprmList);
}
if (newCHP.IsFImprint() != oldCHP.IsFImprint())
{
int value = 0;
if (newCHP.IsFImprint())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0854, value, null, sprmList);
}
if (newCHP.IsFSpec() != oldCHP.IsFSpec())
{
int value = 0;
if (newCHP.IsFSpec())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0855, value, null, sprmList);
}
if (newCHP.IsFObj() != oldCHP.IsFObj())
{
int value = 0;
if (newCHP.IsFObj())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0856, value, null, sprmList);
}
if (newCHP.IsFEmboss() != oldCHP.IsFEmboss())
{
int value = 0;
if (newCHP.IsFEmboss())
{
value = 0x01;
}
size += SprmUtils.AddSprm((short)0x0858, value, null, sprmList);
}
if (newCHP.GetSfxtText() != oldCHP.GetSfxtText())
{
size += SprmUtils.AddSprm((short)0x2859, newCHP.GetSfxtText(), null, sprmList);
}
if (newCHP.GetIco24() != oldCHP.GetIco24())
{
if (newCHP.GetIco24() != -1) // don't Add a sprm if we're looking at an ico = Auto
size += SprmUtils.AddSprm((short)0x6870, newCHP.GetIco24(), null, sprmList);
}
return SprmUtils.GetGrpprl(sprmList, size);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Process
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Defines forked Ignite node.
/// </summary>
public class IgniteProcess
{
/** Executable file name. */
private static readonly string ExeName = "Apache.Ignite.exe";
/** Executable process name. */
private static readonly string ExeProcName = ExeName.Substring(0, ExeName.LastIndexOf('.'));
/** Executable configuration file name. */
private static readonly string ExeCfgName = ExeName + ".config";
/** Executable backup configuration file name. */
private static readonly string ExeCfgBakName = ExeCfgName + ".bak";
/** Directory where binaries are stored. */
private static readonly string ExeDir;
/** Full path to executable. */
private static readonly string ExePath;
/** Full path to executable configuration file. */
private static readonly string ExeCfgPath;
/** Full path to executable configuration file backup. */
private static readonly string ExeCfgBakPath;
/** Default process output reader. */
private static readonly IIgniteProcessOutputReader DfltOutReader = new IgniteProcessConsoleOutputReader();
/** Process. */
private readonly Process _proc;
/// <summary>
/// Static initializer.
/// </summary>
static IgniteProcess()
{
// 1. Locate executable file and related stuff.
DirectoryInfo dir = new FileInfo(new Uri(typeof(IgniteProcess).Assembly.CodeBase).LocalPath).Directory;
// ReSharper disable once PossibleNullReferenceException
ExeDir = dir.FullName;
var exe = dir.GetFiles(ExeName);
if (exe.Length == 0)
throw new Exception(ExeName + " is not found in test output directory: " + dir.FullName);
ExePath = exe[0].FullName;
var exeCfg = dir.GetFiles(ExeCfgName);
if (exeCfg.Length == 0)
throw new Exception(ExeCfgName + " is not found in test output directory: " + dir.FullName);
ExeCfgPath = exeCfg[0].FullName;
ExeCfgBakPath = Path.Combine(ExeDir, ExeCfgBakName);
File.Delete(ExeCfgBakPath);
}
/// <summary>
/// Save current configuration to backup.
/// </summary>
public static void SaveConfigurationBackup()
{
File.Copy(ExeCfgPath, ExeCfgBakPath, true);
}
/// <summary>
/// Restore configuration from backup.
/// </summary>
public static void RestoreConfigurationBackup()
{
File.Copy(ExeCfgBakPath, ExeCfgPath, true);
}
/// <summary>
/// Replace application configuration with another one.
/// </summary>
/// <param name="relPath">Path to config relative to executable directory.</param>
public static void ReplaceConfiguration(string relPath)
{
File.Copy(Path.Combine(ExeDir, relPath), ExeCfgPath, true);
}
/// <summary>
/// Kill all Ignite processes.
/// </summary>
public static void KillAll()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(ExeProcName))
{
proc.Kill();
proc.WaitForExit();
}
}
}
/// <summary>
/// Construector.
/// </summary>
/// <param name="args">Arguments</param>
public IgniteProcess(params string[] args) : this(DfltOutReader, args) { }
/// <summary>
/// Construector.
/// </summary>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
public IgniteProcess(IIgniteProcessOutputReader outReader, params string[] args)
{
// Add test dll path
args = args.Concat(new[] {"-assembly=" + GetType().Assembly.Location}).ToArray();
_proc = Start(ExePath, IgniteHome.Resolve(null), outReader, args);
}
/// <summary>
/// Starts a grid process.
/// </summary>
/// <param name="exePath">Exe path.</param>
/// <param name="ggHome">Ignite home.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
/// <returns>Started process.</returns>
public static Process Start(string exePath, string ggHome, IIgniteProcessOutputReader outReader = null,
params string[] args)
{
Debug.Assert(!string.IsNullOrEmpty(exePath));
Debug.Assert(!string.IsNullOrEmpty(ggHome));
// 1. Define process start configuration.
var sb = new StringBuilder();
foreach (string arg in args)
sb.Append('\"').Append(arg).Append("\" ");
var procStart = new ProcessStartInfo
{
FileName = exePath,
Arguments = sb.ToString()
};
if (!string.IsNullOrEmpty(ggHome))
procStart.EnvironmentVariables[IgniteHome.EnvIgniteHome] = ggHome;
procStart.EnvironmentVariables[Classpath.EnvIgniteNativeTestClasspath] = "true";
procStart.CreateNoWindow = true;
procStart.UseShellExecute = false;
procStart.RedirectStandardOutput = true;
procStart.RedirectStandardError = true;
var workDir = Path.GetDirectoryName(exePath);
if (workDir != null)
procStart.WorkingDirectory = workDir;
Console.WriteLine("About to run Apache.Ignite.exe process [exePath=" + exePath + ", arguments=" + sb + ']');
// 2. Start.
var proc = Process.Start(procStart);
Debug.Assert(proc != null);
// 3. Attach output readers to avoid hangs.
outReader = outReader ?? DfltOutReader;
Attach(proc, proc.StandardOutput, outReader, false);
Attach(proc, proc.StandardError, outReader, true);
return proc;
}
/// <summary>
/// Whether the process is still alive.
/// </summary>
public bool Alive
{
get { return !_proc.HasExited; }
}
/// <summary>
/// Kill process.
/// </summary>
public void Kill()
{
_proc.Kill();
}
/// <summary>
/// Join process.
/// </summary>
/// <returns>Exit code.</returns>
public int Join()
{
_proc.WaitForExit();
return _proc.ExitCode;
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout)
{
return _proc.WaitForExit(timeout);
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <param name="exitCode">Exit code.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout, out int exitCode)
{
if (_proc.WaitForExit(timeout))
{
exitCode = _proc.ExitCode;
return true;
}
exitCode = 0;
return false;
}
/// <summary>
/// Attach output reader to the process.
/// </summary>
/// <param name="proc">Process.</param>
/// <param name="reader">Process stream reader.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="err">Whether this is error stream.</param>
private static void Attach(Process proc, StreamReader reader, IIgniteProcessOutputReader outReader, bool err)
{
new Thread(() =>
{
while (!proc.HasExited)
outReader.OnOutput(proc, reader.ReadLine(), err);
}) {IsBackground = true}.Start();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function EWCreatorWindow::init( %this )
{
// Just so we can recall this method for testing changes
// without restarting.
if ( isObject( %this.array ) )
%this.array.delete();
%this.array = new ArrayObject();
%this.array.caseSensitive = true;
%this.setListView( true );
%this.beginGroup( "Environment" );
// Removed Prefab as there doesn't really seem to be a point in creating a blank one
//%this.registerMissionObject( "Prefab", "Prefab" );
%this.registerMissionObject( "SkyBox", "Sky Box" );
%this.registerMissionObject( "CloudLayer", "Cloud Layer" );
%this.registerMissionObject( "BasicClouds", "Basic Clouds" );
%this.registerMissionObject( "ScatterSky", "Scatter Sky" );
%this.registerMissionObject( "Sun", "Basic Sun" );
%this.registerMissionObject( "Lightning" );
%this.registerMissionObject( "WaterBlock", "Water Block" );
%this.registerMissionObject( "SFXEmitter", "Sound Emitter" );
%this.registerMissionObject( "Precipitation" );
%this.registerMissionObject( "ParticleEmitterNode", "Particle Emitter" );
%this.registerMissionObject( "VolumetricFog", "Volumetric Fog" );
%this.registerMissionObject( "RibbonNode", "Ribbon" );
// Legacy features. Users should use Ground Cover and the Forest Editor.
//%this.registerMissionObject( "fxShapeReplicator", "Shape Replicator" );
//%this.registerMissionObject( "fxFoliageReplicator", "Foliage Replicator" );
%this.registerMissionObject( "PointLight", "Point Light" );
%this.registerMissionObject( "SpotLight", "Spot Light" );
%this.registerMissionObject( "GroundCover", "Ground Cover" );
%this.registerMissionObject( "TerrainBlock", "Terrain Block" );
%this.registerMissionObject( "GroundPlane", "Ground Plane" );
%this.registerMissionObject( "WaterPlane", "Water Plane" );
%this.registerMissionObject( "PxCloth", "Cloth" );
%this.registerMissionObject( "ForestWindEmitter", "Wind Emitter" );
%this.registerMissionObject( "DustEmitter", "Dust Emitter" );
%this.registerMissionObject( "DustSimulation", "Dust Simulation" );
%this.registerMissionObject( "DustEffecter", "Dust Effecter" );
%this.endGroup();
%this.beginGroup( "Level" );
%this.registerMissionObject( "MissionArea", "Mission Area" );
%this.registerMissionObject( "Path" );
%this.registerMissionObject( "Marker", "Path Node" );
%this.registerMissionObject( "Trigger" );
%this.registerMissionObject( "PhysicalZone", "Physical Zone" );
%this.registerMissionObject( "Camera" );
%this.registerMissionObject( "LevelInfo", "Level Info" );
%this.registerMissionObject( "TimeOfDay", "Time of Day" );
%this.registerMissionObject( "Zone", "Zone" );
%this.registerMissionObject( "Portal", "Zone Portal" );
%this.registerMissionObject( "SpawnSphere", "Player Spawn Sphere", "PlayerDropPoint" );
%this.registerMissionObject( "SpawnSphere", "Observer Spawn Sphere", "ObserverDropPoint" );
%this.registerMissionObject( "SFXSpace", "Sound Space" );
%this.registerMissionObject( "OcclusionVolume", "Occlusion Volume" );
%this.registerMissionObject( "AccumulationVolume", "Accumulation Volume" );
%this.registerMissionObject( "Entity", "Entity" );
%this.endGroup();
%this.beginGroup( "System" );
%this.registerMissionObject( "SimGroup" );
%this.endGroup();
%this.beginGroup( "ExampleObjects" );
%this.registerMissionObject( "RenderObjectExample" );
%this.registerMissionObject( "RenderMeshExample" );
%this.registerMissionObject( "RenderShapeExample" );
%this.endGroup();
}
function EWCreatorWindow::onWake( %this )
{
CreatorTabBook.selectPage( 0 );
CreatorTabBook.onTabSelected( "Scripted" );
}
function EWCreatorWindow::beginGroup( %this, %group )
{
%this.currentGroup = %group;
}
function EWCreatorWindow::endGroup( %this, %group )
{
%this.currentGroup = "";
}
function EWCreatorWindow::getCreateObjectPosition()
{
%focusPoint = LocalClientConnection.getControlObject().getLookAtPoint();
if( %focusPoint $= "" )
return "0 0 0";
else
return getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 );
}
function EWCreatorWindow::registerMissionObject( %this, %class, %name, %buildfunc, %group )
{
if( !isClass(%class) )
return;
if ( %name $= "" )
%name = %class;
if ( %this.currentGroup !$= "" && %group $= "" )
%group = %this.currentGroup;
if ( %class $= "" || %group $= "" )
{
warn( "EWCreatorWindow::registerMissionObject, invalid parameters!" );
return;
}
%args = new ScriptObject();
%args.val[0] = %class;
%args.val[1] = %name;
%args.val[2] = %buildfunc;
%this.array.push_back( %group, %args );
}
function EWCreatorWindow::getNewObjectGroup( %this )
{
return %this.objectGroup;
}
function EWCreatorWindow::setNewObjectGroup( %this, %group )
{
if( %this.objectGroup )
{
%oldItemId = EditorTree.findItemByObjectId( %this.objectGroup );
if( %oldItemId > 0 )
EditorTree.markItem( %oldItemId, false );
}
%group = %group.getID();
%this.objectGroup = %group;
%itemId = EditorTree.findItemByObjectId( %group );
EditorTree.markItem( %itemId );
}
function EWCreatorWindow::createStatic( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getRootScene() );
%objId = new TSStatic()
{
shapeName = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createPrefab( %this, %file )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getRootScene() );
%objId = new Prefab()
{
filename = %file;
position = %this.getCreateObjectPosition();
parentGroup = %this.objectGroup;
};
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::createObject( %this, %cmd )
{
if ( !$missionRunning )
return;
if( !isObject(%this.objectGroup) )
%this.setNewObjectGroup( getRootScene() );
pushInstantGroup();
%objId = eval(%cmd);
popInstantGroup();
if( isObject( %objId ) )
%this.onFinishCreateObject( %objId );
return %objId;
}
function EWCreatorWindow::onFinishCreateObject( %this, %objId )
{
%this.objectGroup.add( %objId );
if( %objId.isMemberOfClass( "SceneObject" ) )
{
%objId.position = %this.getCreateObjectPosition();
//flush new position
%objId.setTransform( %objId.getTransform() );
}
%this.onObjectCreated( %objId );
}
function EWCreatorWindow::onObjectCreated( %this, %objId )
{
// Can we submit an undo action?
if ( isObject( %objId ) )
MECreateUndoAction::submit( %objId );
EditorTree.clearSelection();
EWorldEditor.clearSelection();
EWorldEditor.selectObject( %objId );
// When we drop the selection don't store undo
// state for it... the creation deals with it.
EWorldEditor.dropSelection( true );
}
function CreatorTabBook::onTabSelected( %this, %text, %idx )
{
if ( %this.isAwake() )
{
EWCreatorWindow.tab = %text;
EWCreatorWindow.navigate( "" );
}
}
function EWCreatorWindow::navigate( %this, %address )
{
CreatorIconArray.frozen = true;
CreatorIconArray.clear();
CreatorPopupMenu.clear();
if ( %this.tab $= "Scripted" )
{
%category = getWord( %address, 1 );
%dataGroup = "DataBlockGroup";
for ( %i = 0; %i < %dataGroup.getCount(); %i++ )
{
%obj = %dataGroup.getObject(%i);
// echo ("Obj: " @ %obj.getName() @ " - " @ %obj.category );
if ( %obj.category $= "" && %obj.category == 0 )
continue;
// Add category to popup menu if not there already
if ( CreatorPopupMenu.findText( %obj.category ) == -1 )
CreatorPopupMenu.add( %obj.category );
if ( %address $= "" )
{
%ctrl = %this.findIconCtrl( %obj.category );
if ( %ctrl == -1 )
{
%this.addFolderIcon( %obj.category );
}
}
else if ( %address $= %obj.category )
{
%ctrl = %this.findIconCtrl( %obj.getName() );
if ( %ctrl == -1 )
%this.addShapeIcon( %obj );
}
}
}
if ( %this.tab $= "Meshes" )
{
%fullPath = findFirstFileMultiExpr( getFormatExtensions() );
while ( %fullPath !$= "" )
{
if (strstr(%fullPath, "cached.dts") != -1)
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( stricmp( %pathFolders, %address ) == 0 )
{
%this.addStaticIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFileMultiExpr( getFormatExtensions() );
}
}
if ( %this.tab $= "Level" )
{
// Add groups to popup menu
%array = %this.array;
%array.sortk();
%count = %array.count();
if ( %count > 0 )
{
%lastGroup = "";
for ( %i = 0; %i < %count; %i++ )
{
%group = %array.getKey( %i );
if ( %group !$= %lastGroup )
{
CreatorPopupMenu.add( %group );
if ( %address $= "" )
%this.addFolderIcon( %group );
}
if ( %address $= %group )
{
%args = %array.getValue( %i );
%class = %args.val[0];
%name = %args.val[1];
%func = %args.val[2];
%this.addMissionObjectIcon( %class, %name, %func );
}
%lastGroup = %group;
}
}
}
if ( %this.tab $= "Prefabs" )
{
%expr = "*.prefab";
%fullPath = findFirstFile( %expr );
while ( %fullPath !$= "" )
{
%fullPath = makeRelativePath( %fullPath, getMainDotCSDir() );
%splitPath = strreplace( %fullPath, " ", "_" );
%splitPath = strreplace( %splitPath, "/", " " );
if( getWord(%splitPath, 0) $= "tools" )
{
%fullPath = findNextFile( %expr );
continue;
}
%dirCount = getWordCount( %splitPath ) - 1;
%pathFolders = getWords( %splitPath, 0, %dirCount - 1 );
// Add this file's path (parent folders) to the
// popup menu if it isn't there yet.
%temp = strreplace( %pathFolders, " ", "/" );
%temp = strreplace( %temp, "_", " " );
%r = CreatorPopupMenu.findText( %temp );
if ( %r == -1 )
{
CreatorPopupMenu.add( %temp );
}
// Is this file in the current folder?
if ( (%dirCount == 0 && %address $= "") || stricmp( %pathFolders, %address ) == 0 )
{
%this.addPrefabIcon( %fullPath );
}
// Then is this file in a subfolder we need to add
// a folder icon for?
else
{
%wordIdx = 0;
%add = false;
if ( %address $= "" )
{
%add = true;
%wordIdx = 0;
}
else
{
for ( ; %wordIdx < %dirCount; %wordIdx++ )
{
%temp = getWords( %splitPath, 0, %wordIdx );
if ( stricmp( %temp, %address ) == 0 )
{
%add = true;
%wordIdx++;
break;
}
}
}
if ( %add == true )
{
%folder = getWord( %splitPath, %wordIdx );
%ctrl = %this.findIconCtrl( %folder );
if ( %ctrl == -1 )
%this.addFolderIcon( %folder );
}
}
%fullPath = findNextFile( %expr );
}
}
CreatorIconArray.sort( "alphaIconCompare" );
for ( %i = 0; %i < CreatorIconArray.getCount(); %i++ )
{
CreatorIconArray.getObject(%i).autoSize = false;
}
CreatorIconArray.frozen = false;
CreatorIconArray.refresh();
// Recalculate the array for the parent guiScrollCtrl
CreatorIconArray.getParent().computeSizes();
%this.address = %address;
CreatorPopupMenu.sort();
%str = strreplace( %address, " ", "/" );
%r = CreatorPopupMenu.findText( %str );
if ( %r != -1 )
CreatorPopupMenu.setSelected( %r, false );
else
CreatorPopupMenu.setText( %str );
CreatorPopupMenu.tooltip = %str;
}
function EWCreatorWindow::navigateDown( %this, %folder )
{
if ( %this.address $= "" )
%address = %folder;
else
%address = %this.address SPC %folder;
// Because this is called from an IconButton::onClick command
// we have to wait a tick before actually calling navigate, else
// we would delete the button out from under itself.
%this.schedule( 1, "navigate", %address );
}
function EWCreatorWindow::navigateUp( %this )
{
%count = getWordCount( %this.address );
if ( %count == 0 )
return;
if ( %count == 1 )
%address = "";
else
%address = getWords( %this.address, 0, %count - 2 );
%this.navigate( %address );
}
function EWCreatorWindow::setListView( %this, %noupdate )
{
//CreatorIconArray.clear();
//CreatorIconArray.setVisible( false );
CreatorIconArray.setVisible( true );
%this.contentCtrl = CreatorIconArray;
%this.isList = true;
if ( %noupdate == true )
%this.navigate( %this.address );
}
//function EWCreatorWindow::setIconView( %this )
//{
//echo( "setIconView" );
//
//CreatorIconStack.clear();
//CreatorIconStack.setVisible( false );
//
//CreatorIconArray.setVisible( true );
//%this.contentCtrl = CreatorIconArray;
//%this.isList = false;
//
//%this.navigate( %this.address );
//}
function EWCreatorWindow::findIconCtrl( %this, %name )
{
for ( %i = 0; %i < %this.contentCtrl.getCount(); %i++ )
{
%ctrl = %this.contentCtrl.getObject( %i );
if ( %ctrl.text $= %name )
return %ctrl;
}
return -1;
}
function EWCreatorWindow::createIcon( %this )
{
%ctrl = new GuiIconButtonCtrl()
{
profile = "GuiCreatorIconButtonProfile";
buttonType = "radioButton";
groupNum = "-1";
};
if ( %this.isList )
{
%ctrl.iconLocation = "Left";
%ctrl.textLocation = "Right";
%ctrl.extent = "348 19";
%ctrl.textMargin = 8;
%ctrl.buttonMargin = "2 2";
%ctrl.autoSize = true;
}
else
{
%ctrl.iconLocation = "Center";
%ctrl.textLocation = "Bottom";
%ctrl.extent = "40 40";
}
return %ctrl;
}
function EWCreatorWindow::addFolderIcon( %this, %text )
{
%ctrl = %this.createIcon();
%ctrl.altCommand = "EWCreatorWindow.navigateDown(\"" @ %text @ "\");";
%ctrl.iconBitmap = "tools/gui/images/folder.png";
%ctrl.text = %text;
%ctrl.tooltip = %text;
%ctrl.class = "CreatorFolderIconBtn";
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addMissionObjectIcon( %this, %class, %name, %buildfunc )
{
%ctrl = %this.createIcon();
// If we don't find a specific function for building an
// object then fall back to the stock one
%method = "build" @ %buildfunc;
if( !ObjectBuilderGui.isMethod( %method ) )
%method = "build" @ %class;
if( !ObjectBuilderGui.isMethod( %method ) )
%cmd = "return new " @ %class @ "();";
else
%cmd = "ObjectBuilderGui." @ %method @ "();";
%ctrl.altCommand = "ObjectBuilderGui.newObjectCallback = \"EWCreatorWindow.onFinishCreateObject\"; EWCreatorWindow.createObject( \"" @ %cmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorMissionObjectIconBtn";
%ctrl.tooltip = %class;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addShapeIcon( %this, %datablock )
{
%ctrl = %this.createIcon();
%name = %datablock.getName();
%class = %datablock.getClassName();
%cmd = %class @ "::create(" @ %name @ ");";
%shapePath = ( %datablock.shapeFile !$= "" ) ? %datablock.shapeFile : %datablock.shapeName;
%createCmd = "EWCreatorWindow.createObject( \\\"" @ %cmd @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %shapePath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class );
%ctrl.text = %name;
%ctrl.class = "CreatorShapeIconBtn";
%ctrl.tooltip = %name;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addStaticIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%createCmd = "EWCreatorWindow.createStatic( \\\"" @ %fullPath @ "\\\" );";
%ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %fullPath @ "\", \"" @ %createCmd @ "\" );";
%ctrl.iconBitmap = ( ( %ext $= ".dts" ) ? EditorIconRegistry::findIconByClassName( "TSStatic" ) : "tools/gui/images/iconCollada" );
%ctrl.text = %file;
%ctrl.class = "CreatorStaticIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function EWCreatorWindow::addPrefabIcon( %this, %fullPath )
{
%ctrl = %this.createIcon();
%ext = fileExt( %fullPath );
%file = fileBase( %fullPath );
%fileLong = %file @ %ext;
%tip = %fileLong NL
"Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL
"Date Created: " @ fileCreatedTime( %fullPath ) NL
"Last Modified: " @ fileModifiedTime( %fullPath );
%ctrl.altCommand = "EWCreatorWindow.createPrefab( \"" @ %fullPath @ "\" );";
%ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" );
%ctrl.text = %file;
%ctrl.class = "CreatorPrefabIconBtn";
%ctrl.tooltip = %tip;
%ctrl.buttonType = "radioButton";
%ctrl.groupNum = "-1";
%this.contentCtrl.addGuiControl( %ctrl );
}
function CreatorPopupMenu::onSelect( %this, %id, %text )
{
%split = strreplace( %text, "/", " " );
EWCreatorWindow.navigate( %split );
}
function alphaIconCompare( %a, %b )
{
if ( %a.class $= "CreatorFolderIconBtn" )
if ( %b.class !$= "CreatorFolderIconBtn" )
return -1;
if ( %b.class $= "CreatorFolderIconBtn" )
if ( %a.class !$= "CreatorFolderIconBtn" )
return 1;
%result = stricmp( %a.text, %b.text );
return %result;
}
// Generic create object helper for use from the console.
function genericCreateObject( %class )
{
if ( !isClass( %class ) )
{
warn( "createObject( " @ %class @ " ) - Was not a valid class." );
return;
}
%cmd = "return new " @ %class @ "();";
%obj = EWCreatorWindow.createObject( %cmd );
// In case the caller wants it.
return %obj;
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class OperatorsIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void and_1()
{
RunCompilerTestCase(@"and-1.boo");
}
[Test]
public void and_2()
{
RunCompilerTestCase(@"and-2.boo");
}
[Test]
public void bitwise_and_1()
{
RunCompilerTestCase(@"bitwise-and-1.boo");
}
[Test]
public void bitwise_and_2()
{
RunCompilerTestCase(@"bitwise-and-2.boo");
}
[Test]
public void bitwise_or_1()
{
RunCompilerTestCase(@"bitwise-or-1.boo");
}
[Test]
public void bitwise_or_2()
{
RunCompilerTestCase(@"bitwise-or-2.boo");
}
[Test]
public void cast_1()
{
RunCompilerTestCase(@"cast-1.boo");
}
[Test]
public void cast_2()
{
RunCompilerTestCase(@"cast-2.boo");
}
[Test]
public void cast_3()
{
RunCompilerTestCase(@"cast-3.boo");
}
[Test]
public void cast_4()
{
RunCompilerTestCase(@"cast-4.boo");
}
[Test]
public void cast_5()
{
RunCompilerTestCase(@"cast-5.boo");
}
[Test]
public void cast_6()
{
RunCompilerTestCase(@"cast-6.boo");
}
[Test]
public void cast_7()
{
RunCompilerTestCase(@"cast-7.boo");
}
[Test]
public void cast_8()
{
RunCompilerTestCase(@"cast-8.boo");
}
[Test]
public void cast_9()
{
RunCompilerTestCase(@"cast-9.boo");
}
[Test]
public void conditional_1()
{
RunCompilerTestCase(@"conditional-1.boo");
}
[Test]
public void explode_1()
{
RunCompilerTestCase(@"explode-1.boo");
}
[Test]
public void explode_2()
{
RunCompilerTestCase(@"explode-2.boo");
}
[Test]
public void explode_3()
{
RunCompilerTestCase(@"explode-3.boo");
}
[Test]
public void exponential_1()
{
RunCompilerTestCase(@"exponential-1.boo");
}
[Test]
public void in_1()
{
RunCompilerTestCase(@"in-1.boo");
}
[Test]
public void is_1()
{
RunCompilerTestCase(@"is-1.boo");
}
[Test]
public void is_2()
{
RunCompilerTestCase(@"is-2.boo");
}
[Test]
public void isa_1()
{
RunCompilerTestCase(@"isa-1.boo");
}
[Test]
public void isa_2()
{
RunCompilerTestCase(@"isa-2.boo");
}
[Test]
public void isa_3()
{
RunCompilerTestCase(@"isa-3.boo");
}
[Test]
public void not_1()
{
RunCompilerTestCase(@"not-1.boo");
}
[Test]
public void ones_complement_1()
{
RunCompilerTestCase(@"ones-complement-1.boo");
}
[Test]
public void operators_1()
{
RunCompilerTestCase(@"operators-1.boo");
}
[Test]
public void or_1()
{
RunCompilerTestCase(@"or-1.boo");
}
[Test]
public void or_2()
{
RunCompilerTestCase(@"or-2.boo");
}
[Test]
public void or_3()
{
RunCompilerTestCase(@"or-3.boo");
}
[Test]
public void or_4()
{
RunCompilerTestCase(@"or-4.boo");
}
[Test]
public void post_incdec_1()
{
RunCompilerTestCase(@"post-incdec-1.boo");
}
[Test]
public void post_incdec_2()
{
RunCompilerTestCase(@"post-incdec-2.boo");
}
[Test]
public void post_incdec_3()
{
RunCompilerTestCase(@"post-incdec-3.boo");
}
[Test]
public void post_incdec_4()
{
RunCompilerTestCase(@"post-incdec-4.boo");
}
[Test]
public void post_incdec_5()
{
RunCompilerTestCase(@"post-incdec-5.boo");
}
[Test]
public void post_incdec_6()
{
RunCompilerTestCase(@"post-incdec-6.boo");
}
[Test]
public void post_incdec_7()
{
RunCompilerTestCase(@"post-incdec-7.boo");
}
[Test]
public void shift_1()
{
RunCompilerTestCase(@"shift-1.boo");
}
[Test]
public void slicing_1()
{
RunCompilerTestCase(@"slicing-1.boo");
}
[Test]
public void slicing_10()
{
RunCompilerTestCase(@"slicing-10.boo");
}
[Test]
public void slicing_11()
{
RunCompilerTestCase(@"slicing-11.boo");
}
[Test]
public void slicing_12()
{
RunCompilerTestCase(@"slicing-12.boo");
}
[Test]
public void slicing_13()
{
RunCompilerTestCase(@"slicing-13.boo");
}
[Test]
public void slicing_2()
{
RunCompilerTestCase(@"slicing-2.boo");
}
[Test]
public void slicing_3()
{
RunCompilerTestCase(@"slicing-3.boo");
}
[Test]
public void slicing_4()
{
RunCompilerTestCase(@"slicing-4.boo");
}
[Test]
public void slicing_5()
{
RunCompilerTestCase(@"slicing-5.boo");
}
[Test]
public void slicing_6()
{
RunCompilerTestCase(@"slicing-6.boo");
}
[Test]
public void slicing_7()
{
RunCompilerTestCase(@"slicing-7.boo");
}
[Test]
public void slicing_8()
{
RunCompilerTestCase(@"slicing-8.boo");
}
[Test]
public void slicing_9()
{
RunCompilerTestCase(@"slicing-9.boo");
}
[Test]
public void slicing_md_1()
{
RunCompilerTestCase(@"slicing-md-1.boo");
}
[Test]
public void slicing_md_2()
{
RunCompilerTestCase(@"slicing-md-2.boo");
}
[Test]
public void slicing_md_3()
{
RunCompilerTestCase(@"slicing-md-3.boo");
}
[Test]
public void slicing_md_4()
{
RunCompilerTestCase(@"slicing-md-4.boo");
}
[Test]
public void unary_1()
{
RunCompilerTestCase(@"unary-1.boo");
}
[Test]
public void unary_2()
{
RunCompilerTestCase(@"unary-2.boo");
}
[Test]
public void unary_3()
{
RunCompilerTestCase(@"unary-3.boo");
}
[Test]
public void xor_1()
{
RunCompilerTestCase(@"xor-1.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/operators";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.RNG.Tests
{
public class RandomNumberGeneratorTests
{
[Fact]
public static void DifferentSequential_10()
{
DifferentSequential(10);
}
[Fact]
public static void DifferentSequential_256()
{
DifferentSequential(256);
}
[Fact]
public static void DifferentSequential_65536()
{
DifferentSequential(65536);
}
[Fact]
public static void DifferentParallel_10()
{
DifferentParallel(10);
}
[Fact]
public static void DifferentParallel_256()
{
DifferentParallel(256);
}
[Fact]
public static void DifferentParallel_65536()
{
DifferentParallel(65536);
}
[Fact]
public static void RandomDistribution()
{
byte[] random = new byte[2048];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(random);
}
RandomDataGenerator.VerifyRandomDistribution(random);
}
[Fact]
public static void IdempotentDispose()
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
for (int i = 0; i < 10; i++)
{
rng.Dispose();
}
}
[Fact]
public static void NullInput()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
Assert.Throws<ArgumentNullException>(() => rng.GetBytes(null));
}
}
[Fact]
public static void ZeroLengthInput()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
// While this will do nothing, it's not something that throws.
rng.GetBytes(Array.Empty<byte>());
}
}
[Fact]
public static void ConcurrentAccess()
{
const int ParallelTasks = 3;
const int PerTaskIterationCount = 20;
const int RandomSize = 1024;
Task[] tasks = new Task[ParallelTasks];
byte[][] taskArrays = new byte[ParallelTasks][];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
using (ManualResetEvent sync = new ManualResetEvent(false))
{
for (int iTask = 0; iTask < ParallelTasks; iTask++)
{
taskArrays[iTask] = new byte[RandomSize];
byte[] taskLocal = taskArrays[iTask];
tasks[iTask] = Task.Run(
() =>
{
sync.WaitOne();
for (int i = 0; i < PerTaskIterationCount; i++)
{
rng.GetBytes(taskLocal);
}
});
}
// Ready? Set() Go!
sync.Set();
Task.WaitAll(tasks);
}
for (int i = 0; i < ParallelTasks; i++)
{
// The Real test would be to ensure independence of data, but that's difficult.
// The other end of the spectrum is to test that they aren't all just new byte[RandomSize].
// Middle ground is to assert that each of the chunks has random data.
RandomDataGenerator.VerifyRandomDistribution(taskArrays[i]);
}
}
[Fact]
public static void GetNonZeroBytes()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
AssertExtensions.Throws<ArgumentNullException>("data", () => rng.GetNonZeroBytes(null));
// Array should not have any zeros
byte[] rand = new byte[65536];
rng.GetNonZeroBytes(rand);
Assert.Equal(-1, Array.IndexOf<byte>(rand, 0));
}
}
[Fact]
public static void GetBytes_Offset()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
byte[] rand = new byte[400];
// Set canary bytes
rand[99] = 77;
rand[399] = 77;
rng.GetBytes(rand, 100, 200);
// Array should not have been touched outside of 100-299
Assert.Equal(99, Array.IndexOf<byte>(rand, 77, 0));
Assert.Equal(399, Array.IndexOf<byte>(rand, 77, 300));
// Ensure 100-300 has random bytes; not likely to ever fail here by chance (256^200)
Assert.True(rand.Skip(100).Take(200).Sum(b => b) > 0);
}
}
[Fact]
public static void GetBytes_Offset_ZeroCount()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
byte[] rand = new byte[1] { 1 };
// A count of 0 should not do anything
rng.GetBytes(rand, 0, 0);
Assert.Equal(1, rand[0]);
// Having an offset of Length is allowed if count is 0
rng.GetBytes(rand, rand.Length, 0);
Assert.Equal(1, rand[0]);
// Zero-length array should not throw
rand = Array.Empty<byte>();
rng.GetBytes(rand, 0, 0);
}
}
private static void DifferentSequential(int arraySize)
{
// Ensure that the RNG doesn't produce a stable set of data.
byte[] first = new byte[arraySize];
byte[] second = new byte[arraySize];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(first);
rng.GetBytes(second);
}
// Random being random, there is a chance that it could produce the same sequence.
// The smallest test case that we have is 10 bytes.
// The probability that they are the same, given a Truly Random Number Generator is:
// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
// = 1/256 * 1/256 * ... * 1/256
// = 1/(256^10)
// = 1/1,208,925,819,614,629,174,706,176
Assert.NotEqual(first, second);
}
private static void DifferentParallel(int arraySize)
{
// Ensure that two RNGs don't produce the same data series (such as being implemented via new Random(1)).
byte[] first = new byte[arraySize];
byte[] second = new byte[arraySize];
using (RandomNumberGenerator rng1 = RandomNumberGenerator.Create())
using (RandomNumberGenerator rng2 = RandomNumberGenerator.Create())
{
rng1.GetBytes(first);
rng2.GetBytes(second);
}
// Random being random, there is a chance that it could produce the same sequence.
// The smallest test case that we have is 10 bytes.
// The probability that they are the same, given a Truly Random Number Generator is:
// Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
// = 1/256 * 1/256 * ... * 1/256
// = 1/(256^10)
// = 1/1,208,925,819,614,629,174,706,176
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_InvalidArgs()
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
AssertExtensions.Throws<ArgumentNullException>("data", () => rng.GetNonZeroBytes(null));
GetBytes_InvalidArgs(rng);
}
}
[Fact]
public static void GetBytes_InvalidArgs_Base()
{
using (var rng = new RandomNumberGeneratorMininal())
{
Assert.Throws<NotImplementedException>(() => rng.GetNonZeroBytes(null));
GetBytes_InvalidArgs(rng);
}
}
private static void GetBytes_InvalidArgs(RandomNumberGenerator rng)
{
AssertExtensions.Throws<ArgumentNullException>("data", () => rng.GetBytes(null, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => rng.GetBytes(Array.Empty<byte>(), -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => rng.GetBytes(Array.Empty<byte>(), 0, -1));
AssertExtensions.Throws<ArgumentException>(null, () => rng.GetBytes(Array.Empty<byte>(), 0, 1));
// GetBytes(null) covered in test NullInput()
}
private class RandomNumberGeneratorMininal : RandomNumberGenerator
{
public override void GetBytes(byte[] data)
{
// Empty; don't throw NotImplementedException
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AutoRest.Core;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.CSharp.Azure.Model;
using AutoRest.CSharp.Model;
using AutoRest.Extensions;
using AutoRest.Extensions.Azure;
using Newtonsoft.Json.Linq;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.CSharp.Azure
{
public class TransformerCsa : TransformerCs, ITransformer<CodeModelCsa>
{
/// <summary>
/// A type-specific method for code model tranformation.
/// Note: This is the method you want to override.
/// </summary>
/// <param name="codeModel"></param>
/// <returns></returns>
public override CodeModelCs TransformCodeModel(CodeModel codeModel)
{
return ((ITransformer<CodeModelCsa>)this).TransformCodeModel(codeModel);
}
CodeModelCsa ITransformer<CodeModelCsa>.TransformCodeModel(CodeModel cs)
{
var codeModel = cs as CodeModelCsa;
// we're guaranteed to be in our language-specific context here.
Settings.Instance.AddCredentials = true;
// add the Credentials
// PopulateAdditionalProperties(codeModel);
// Do parameter transformations
TransformParameters(codeModel);
// todo: these should be turned into individual transformers
AzureExtensions.NormalizeAzureClientModel(codeModel);
NormalizePaginatedMethods(codeModel);
NormalizeODataMethods(codeModel);
foreach (var model in codeModel.ModelTypes)
{
if (model.Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) &&
(bool)model.Extensions[AzureExtensions.AzureResourceExtension])
{
model.BaseModelType = New<ILiteralType>("Microsoft.Rest.Azure.IResource",
new { SerializedName = "Microsoft.Rest.Azure.IResource" }) as CompositeType;
}
}
return codeModel;
}
public virtual void NormalizeODataMethods(CodeModel client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
foreach (var method in client.Methods)
{
if (method.Extensions.ContainsKey(AzureExtensions.ODataExtension))
{
var odataFilter = method.Parameters.FirstOrDefault(p =>
p.SerializedName.EqualsIgnoreCase("$filter") &&
(p.Location == ParameterLocation.Query) &&
p.ModelType is CompositeType);
if (odataFilter == null)
{
continue;
}
// Remove all odata parameters
method.Remove(source =>
(source.SerializedName.EqualsIgnoreCase("$filter") ||
source.SerializedName.EqualsIgnoreCase("$top") ||
source.SerializedName.EqualsIgnoreCase("$orderby") ||
source.SerializedName.EqualsIgnoreCase("$skip") ||
source.SerializedName.EqualsIgnoreCase("$expand"))
&& (source.Location == ParameterLocation.Query));
var odataQuery = New<Parameter>(new
{
SerializedName = "$filter",
Name = "odataQuery",
// ModelType = New<CompositeType>($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"),
// ModelType = New<CompositeType>(new { Name = new Fixable<string>(){FixedValue = $"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"} } ),
ModelType =
New<ILiteralType>($"Microsoft.Rest.Azure.OData.ODataQuery<{odataFilter.ModelType.Name}>"),
Documentation = "OData parameters to apply to the operation.",
Location = ParameterLocation.Query,
odataFilter.IsRequired
});
odataQuery.Extensions[AzureExtensions.ODataExtension] =
method.Extensions[AzureExtensions.ODataExtension];
method.Insert(odataQuery);
}
}
}
/// <summary>
/// Changes paginated method signatures to return Page type.
/// </summary>
/// <param name="codeModel"></param>
/// <param name="pageClasses"></param>
public virtual void NormalizePaginatedMethods(CodeModelCsa codeModel)
{
if (codeModel == null)
{
throw new ArgumentNullException($"serviceClient");
}
var convertedTypes = new Dictionary<IModelType, CompositeType>();
foreach (
var method in
codeModel.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension)))
{
string nextLinkString;
var pageClassName = GetPagingSetting(method.Extensions, codeModel.pageClasses, out nextLinkString);
if (string.IsNullOrEmpty(pageClassName))
{
continue;
}
var pageTypeFormat = "{0}<{1}>";
var ipageTypeFormat = "Microsoft.Rest.Azure.IPage<{0}>";
if (string.IsNullOrWhiteSpace(nextLinkString))
{
ipageTypeFormat = "System.Collections.Generic.IEnumerable<{0}>";
}
foreach (var responseStatus in method.Responses
.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray())
{
var compositType = (CompositeType)method.Responses[responseStatus].Body;
var sequenceType =
compositType.Properties.Select(p => p.ModelType).FirstOrDefault(t => t is SequenceType) as
SequenceTypeCs;
// if the type is a wrapper over page-able response
if (sequenceType != null)
{
var pagableTypeName = string.Format(CultureInfo.InvariantCulture, pageTypeFormat, pageClassName,
sequenceType.ElementType.AsNullableType(!sequenceType.ElementType.IsValueType() || sequenceType.IsNullable));
var ipagableTypeName = string.Format(CultureInfo.InvariantCulture, ipageTypeFormat,
sequenceType.ElementType.AsNullableType(!sequenceType.ElementType.IsValueType() || sequenceType.IsNullable));
var pagedResult = New<ILiteralType>(pagableTypeName) as CompositeType;
pagedResult.Extensions[AzureExtensions.ExternalExtension] = true;
pagedResult.Extensions[AzureExtensions.PageableExtension] = ipagableTypeName;
convertedTypes[method.Responses[responseStatus].Body] = pagedResult;
method.Responses[responseStatus] = new Response(pagedResult,
method.Responses[responseStatus].Headers);
}
}
if (convertedTypes.ContainsKey(method.ReturnType.Body))
{
method.ReturnType = new Response(convertedTypes[method.ReturnType.Body],
method.ReturnType.Headers);
}
}
SwaggerExtensions.RemoveUnreferencedTypes(codeModel,
new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name.Value)));
}
private static string GetPagingSetting(Dictionary<string, object> extensions,
IDictionary<KeyValuePair<string, string>, string> pageClasses, out string nextLinkName)
{
// default value
nextLinkName = null;
var ext = extensions[AzureExtensions.PageableExtension] as JContainer;
if (ext == null)
{
return null;
}
nextLinkName = (string)ext["nextLinkName"];
var itemName = (string)ext["itemName"] ?? "value";
var keypair = new KeyValuePair<string, string>(nextLinkName, itemName);
if (!pageClasses.ContainsKey(keypair))
{
var className = (string)ext["className"];
if (string.IsNullOrEmpty(className))
{
if (pageClasses.Count > 0)
{
className = string.Format(CultureInfo.InvariantCulture, "Page{0}", pageClasses.Count);
}
else
{
className = "Page";
}
}
pageClasses.Add(keypair, className);
}
return pageClasses[keypair];
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Infoplus.Api;
using Infoplus.Model;
using Infoplus.Client;
using System.Reflection;
namespace Infoplus.Test
{
/// <summary>
/// Class for testing BillOfLading
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class BillOfLadingTests
{
// TODO uncomment below to declare an instance variable for BillOfLading
//private BillOfLading instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of BillOfLading
//instance = new BillOfLading();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of BillOfLading
/// </summary>
[Test]
public void BillOfLadingInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" BillOfLading
//Assert.IsInstanceOfType<BillOfLading> (instance, "variable 'instance' is a BillOfLading");
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'CreateDate'
/// </summary>
[Test]
public void CreateDateTest()
{
// TODO unit test for the property 'CreateDate'
}
/// <summary>
/// Test the property 'ModifyDate'
/// </summary>
[Test]
public void ModifyDateTest()
{
// TODO unit test for the property 'ModifyDate'
}
/// <summary>
/// Test the property 'LobId'
/// </summary>
[Test]
public void LobIdTest()
{
// TODO unit test for the property 'LobId'
}
/// <summary>
/// Test the property 'BolNo'
/// </summary>
[Test]
public void BolNoTest()
{
// TODO unit test for the property 'BolNo'
}
/// <summary>
/// Test the property 'BolDate'
/// </summary>
[Test]
public void BolDateTest()
{
// TODO unit test for the property 'BolDate'
}
/// <summary>
/// Test the property 'ShipFromName'
/// </summary>
[Test]
public void ShipFromNameTest()
{
// TODO unit test for the property 'ShipFromName'
}
/// <summary>
/// Test the property 'ShipFromAddress'
/// </summary>
[Test]
public void ShipFromAddressTest()
{
// TODO unit test for the property 'ShipFromAddress'
}
/// <summary>
/// Test the property 'ShipFromCity'
/// </summary>
[Test]
public void ShipFromCityTest()
{
// TODO unit test for the property 'ShipFromCity'
}
/// <summary>
/// Test the property 'ShipFromState'
/// </summary>
[Test]
public void ShipFromStateTest()
{
// TODO unit test for the property 'ShipFromState'
}
/// <summary>
/// Test the property 'ShipFromZip'
/// </summary>
[Test]
public void ShipFromZipTest()
{
// TODO unit test for the property 'ShipFromZip'
}
/// <summary>
/// Test the property 'Sid'
/// </summary>
[Test]
public void SidTest()
{
// TODO unit test for the property 'Sid'
}
/// <summary>
/// Test the property 'IsShipFromFOB'
/// </summary>
[Test]
public void IsShipFromFOBTest()
{
// TODO unit test for the property 'IsShipFromFOB'
}
/// <summary>
/// Test the property 'ShipToName'
/// </summary>
[Test]
public void ShipToNameTest()
{
// TODO unit test for the property 'ShipToName'
}
/// <summary>
/// Test the property 'ShipToAddress'
/// </summary>
[Test]
public void ShipToAddressTest()
{
// TODO unit test for the property 'ShipToAddress'
}
/// <summary>
/// Test the property 'ShipToCity'
/// </summary>
[Test]
public void ShipToCityTest()
{
// TODO unit test for the property 'ShipToCity'
}
/// <summary>
/// Test the property 'ShipToState'
/// </summary>
[Test]
public void ShipToStateTest()
{
// TODO unit test for the property 'ShipToState'
}
/// <summary>
/// Test the property 'ShipToZip'
/// </summary>
[Test]
public void ShipToZipTest()
{
// TODO unit test for the property 'ShipToZip'
}
/// <summary>
/// Test the property 'ShipToLocationNo'
/// </summary>
[Test]
public void ShipToLocationNoTest()
{
// TODO unit test for the property 'ShipToLocationNo'
}
/// <summary>
/// Test the property 'Cid'
/// </summary>
[Test]
public void CidTest()
{
// TODO unit test for the property 'Cid'
}
/// <summary>
/// Test the property 'IsShipToFOB'
/// </summary>
[Test]
public void IsShipToFOBTest()
{
// TODO unit test for the property 'IsShipToFOB'
}
/// <summary>
/// Test the property 'BillToName'
/// </summary>
[Test]
public void BillToNameTest()
{
// TODO unit test for the property 'BillToName'
}
/// <summary>
/// Test the property 'BillToAddress'
/// </summary>
[Test]
public void BillToAddressTest()
{
// TODO unit test for the property 'BillToAddress'
}
/// <summary>
/// Test the property 'BillToCity'
/// </summary>
[Test]
public void BillToCityTest()
{
// TODO unit test for the property 'BillToCity'
}
/// <summary>
/// Test the property 'BillToState'
/// </summary>
[Test]
public void BillToStateTest()
{
// TODO unit test for the property 'BillToState'
}
/// <summary>
/// Test the property 'BillToZip'
/// </summary>
[Test]
public void BillToZipTest()
{
// TODO unit test for the property 'BillToZip'
}
/// <summary>
/// Test the property 'IsTrailerLoadedByShipper'
/// </summary>
[Test]
public void IsTrailerLoadedByShipperTest()
{
// TODO unit test for the property 'IsTrailerLoadedByShipper'
}
/// <summary>
/// Test the property 'ByDriver'
/// </summary>
[Test]
public void ByDriverTest()
{
// TODO unit test for the property 'ByDriver'
}
/// <summary>
/// Test the property 'CodAmount'
/// </summary>
[Test]
public void CodAmountTest()
{
// TODO unit test for the property 'CodAmount'
}
/// <summary>
/// Test the property 'FeeTermsCollect'
/// </summary>
[Test]
public void FeeTermsCollectTest()
{
// TODO unit test for the property 'FeeTermsCollect'
}
/// <summary>
/// Test the property 'FeeTermsPrepaid'
/// </summary>
[Test]
public void FeeTermsPrepaidTest()
{
// TODO unit test for the property 'FeeTermsPrepaid'
}
/// <summary>
/// Test the property 'CustomerCheckAcceptable'
/// </summary>
[Test]
public void CustomerCheckAcceptableTest()
{
// TODO unit test for the property 'CustomerCheckAcceptable'
}
/// <summary>
/// Test the property 'CarrierName'
/// </summary>
[Test]
public void CarrierNameTest()
{
// TODO unit test for the property 'CarrierName'
}
/// <summary>
/// Test the property 'TrailerNo'
/// </summary>
[Test]
public void TrailerNoTest()
{
// TODO unit test for the property 'TrailerNo'
}
/// <summary>
/// Test the property 'SealNo'
/// </summary>
[Test]
public void SealNoTest()
{
// TODO unit test for the property 'SealNo'
}
/// <summary>
/// Test the property 'Scac'
/// </summary>
[Test]
public void ScacTest()
{
// TODO unit test for the property 'Scac'
}
/// <summary>
/// Test the property 'ProNo'
/// </summary>
[Test]
public void ProNoTest()
{
// TODO unit test for the property 'ProNo'
}
/// <summary>
/// Test the property 'Prepaid'
/// </summary>
[Test]
public void PrepaidTest()
{
// TODO unit test for the property 'Prepaid'
}
/// <summary>
/// Test the property 'Collect'
/// </summary>
[Test]
public void CollectTest()
{
// TODO unit test for the property 'Collect'
}
/// <summary>
/// Test the property 'ThirdParty'
/// </summary>
[Test]
public void ThirdPartyTest()
{
// TODO unit test for the property 'ThirdParty'
}
/// <summary>
/// Test the property 'IsThisAMasterBOL'
/// </summary>
[Test]
public void IsThisAMasterBOLTest()
{
// TODO unit test for the property 'IsThisAMasterBOL'
}
/// <summary>
/// Test the property 'MasterBOLId'
/// </summary>
[Test]
public void MasterBOLIdTest()
{
// TODO unit test for the property 'MasterBOLId'
}
/// <summary>
/// Test the property 'IsFreightCountedByShipper'
/// </summary>
[Test]
public void IsFreightCountedByShipperTest()
{
// TODO unit test for the property 'IsFreightCountedByShipper'
}
/// <summary>
/// Test the property 'ByDriverPallets'
/// </summary>
[Test]
public void ByDriverPalletsTest()
{
// TODO unit test for the property 'ByDriverPallets'
}
/// <summary>
/// Test the property 'ByDriverPieces'
/// </summary>
[Test]
public void ByDriverPiecesTest()
{
// TODO unit test for the property 'ByDriverPieces'
}
/// <summary>
/// Test the property 'SpecialInstructions'
/// </summary>
[Test]
public void SpecialInstructionsTest()
{
// TODO unit test for the property 'SpecialInstructions'
}
/// <summary>
/// Test the property 'OrderInfoLines'
/// </summary>
[Test]
public void OrderInfoLinesTest()
{
// TODO unit test for the property 'OrderInfoLines'
}
/// <summary>
/// Test the property 'CarrierInfoLines'
/// </summary>
[Test]
public void CarrierInfoLinesTest()
{
// TODO unit test for the property 'CarrierInfoLines'
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using WinForms = System.Windows.Forms;
using BT = BitTorrent;
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem fileMenuItem;
private System.Windows.Forms.MenuItem openMenuItem;
private System.Windows.Forms.MenuItem exitMenuItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private TorrentListView torrentListView;
private PeerListView peerListView;
private System.Windows.Forms.TextBox debugMessageBox;
private System.Windows.Forms.Splitter splitter2;
private System.Windows.Forms.Splitter splitter1;
private BT.Session btsession;
private volatile bool mThreadRunning = true;
private static MainForm sInstance = null;
public void OnIdle( object sender, EventArgs e )
{
// btsession.ProcessWaitingData();
}
private void Thread()
{
// initialise bittorrent session
this.btsession = new BT.Session();
while ( mThreadRunning )
{
btsession.ProcessWaitingData();
System.Threading.Thread.Sleep( 10 );
}
}
public MainForm()
{
sInstance = this;
//
// Required for Windows Form Designer support
//
InitializeComponent();
BT.Config.DebugMessageEvent += new BT.DebugMessageCallback(Config_DebugMessageEvent);
Application.Idle += new EventHandler( OnIdle );
System.Threading.Thread thread = new System.Threading.Thread( new System.Threading.ThreadStart( Thread ) );
thread.Start();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
mThreadRunning = false;
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if (this.btsession != null)
this.btsession.Dispose();
this.btsession = null;
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu = new System.Windows.Forms.MainMenu();
this.fileMenuItem = new System.Windows.Forms.MenuItem();
this.openMenuItem = new System.Windows.Forms.MenuItem();
this.exitMenuItem = new System.Windows.Forms.MenuItem();
this.torrentListView = new TorrentListView();
this.peerListView = new PeerListView();
this.debugMessageBox = new System.Windows.Forms.TextBox();
this.splitter2 = new System.Windows.Forms.Splitter();
this.splitter1 = new System.Windows.Forms.Splitter();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.fileMenuItem});
//
// fileMenuItem
//
this.fileMenuItem.Index = 0;
this.fileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.openMenuItem,
this.exitMenuItem});
this.fileMenuItem.Text = "&File";
//
// openMenuItem
//
this.openMenuItem.Index = 0;
this.openMenuItem.Text = "&Open";
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
//
// exitMenuItem
//
this.exitMenuItem.Index = 1;
this.exitMenuItem.Text = "E&xit";
this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
//
// torrentListView
//
this.torrentListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.torrentListView.Dock = System.Windows.Forms.DockStyle.Top;
this.torrentListView.FullRowSelect = true;
this.torrentListView.Location = new System.Drawing.Point(0, 0);
this.torrentListView.Name = "torrentListView";
this.torrentListView.Size = new System.Drawing.Size(904, 88);
this.torrentListView.TabIndex = 5;
this.torrentListView.View = System.Windows.Forms.View.Details;
//
// peerListView
//
this.peerListView.AllowColumnReorder = true;
this.peerListView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.peerListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.peerListView.FullRowSelect = true;
this.peerListView.Location = new System.Drawing.Point(0, 88);
this.peerListView.Name = "peerListView";
this.peerListView.Size = new System.Drawing.Size(904, 417);
this.peerListView.TabIndex = 7;
this.peerListView.View = System.Windows.Forms.View.Details;
//
// debugMessageBox
//
this.debugMessageBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.debugMessageBox.Dock = System.Windows.Forms.DockStyle.Bottom;
this.debugMessageBox.Location = new System.Drawing.Point(0, 281);
this.debugMessageBox.Multiline = true;
this.debugMessageBox.Name = "debugMessageBox";
this.debugMessageBox.ReadOnly = true;
this.debugMessageBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.debugMessageBox.Size = new System.Drawing.Size(904, 224);
this.debugMessageBox.TabIndex = 8;
this.debugMessageBox.Text = "";
//
// splitter2
//
this.splitter2.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter2.Location = new System.Drawing.Point(0, 88);
this.splitter2.MinSize = 5;
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(904, 3);
this.splitter2.TabIndex = 10;
this.splitter2.TabStop = false;
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter1.Location = new System.Drawing.Point(0, 278);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(904, 3);
this.splitter1.TabIndex = 11;
this.splitter1.TabStop = false;
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(904, 505);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.splitter2);
this.Controls.Add(this.debugMessageBox);
this.Controls.Add(this.peerListView);
this.Controls.Add(this.torrentListView);
this.Menu = this.mainMenu;
this.Name = "MainForm";
this.Text = "Torrent.NET";
this.ResumeLayout(false);
}
#endregion
private void openMenuItem_Click(object sender, System.EventArgs e)
{
WinForms.OpenFileDialog dialog = new WinForms.OpenFileDialog();
dialog.Title = "Open torrent file";
dialog.Filter = @"Torrent file (*.torrent)|*.torrent|All files (*.*)|*.*";
if (dialog.ShowDialog(this) == WinForms.DialogResult.OK)
{
BT.Torrent torrent = btsession.CreateTorrent( dialog.FileName );
this.torrentListView.Items.Add(new TorrentListViewItem(torrent));
torrent.PeerConnected += new BT.TorrentPeerConnectedCallback(OnPeerConnected);
torrent.CheckFileIntegrity( true );
torrent.Start();
}
}
private delegate void StringDelegate( string text );
public static void LogDebugMessage( string text )
{
if ( sInstance != null )
sInstance.Invoke( new StringDelegate( BT.Config.LogDebugMessage ), new object[] { text } );
}
private delegate ListViewItem AddNewPeerDelegate( PeerListViewItem item );
private delegate void RemovePeerDelegate( BT.Peer peer );
private void RemovePeer( BT.Peer peer )
{
foreach ( PeerListViewItem item in this.peerListView.Items )
{
if ( item.Peer.Equals( peer ) )
{
item.UnhookPeerEvents();
this.peerListView.Items.Remove(item);
this.peerListView.Refresh();
break;
}
}
}
private void OnPeerConnected(BT.Torrent torrent, BT.Peer peer, bool connected)
{
if (connected)
{
this.peerListView.Invoke( new AddNewPeerDelegate( this.peerListView.Items.Add ), new object[] { new PeerListViewItem( peer ) } );
// this.peerListView.Items.Add(new PeerListViewItem(peer));
}
else
{
LogDebugMessage( "Peer disconnected from mainform.cs: " + peer.ToString() );
this.peerListView.Invoke( new RemovePeerDelegate( RemovePeer ), peer );
}
}
private void exitMenuItem_Click(object sender, System.EventArgs e)
{
if (this.btsession != null)
this.btsession.Dispose();
this.btsession = null;
WinForms.Application.Exit();
}
private delegate void Config_DebugMessageDelegate( string message );
private void Config_DebugMessageEventAsync( string message )
{
this.debugMessageBox.Text += message + "\r\n";
NativeMethods.VerticalScrollToBottom( this.debugMessageBox );
}
private void Config_DebugMessageEvent(string message)
{
this.BeginInvoke( new Config_DebugMessageDelegate( Config_DebugMessageEventAsync ), new object[] { message } );
}
}
| |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// 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.IO;
namespace Medusa.Siren.IO
{
/// <summary>
/// Helper methods for encoding and decoding integer values.
/// </summary>
internal static class IntegerHelper
{
public const int MaxBytesVarInt16 = 3;
public const int MaxBytesVarInt32 = 5;
public const int MaxBytesVarInt64 = 10;
public static int EncodeVarUInt16(byte[] data, ushort value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
// byte 2
data[index++] = (byte)value;
return index;
}
public static int EncodeVarUInt32(byte[] data, uint value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 2
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 3
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
}
}
// last byte
data[index++] = (byte)value;
return index;
}
public static int EncodeVarUInt64(byte[] data, ulong value, int index)
{
// byte 0
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 1
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 2
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 3
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 4
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 5
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 6
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 7
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
// byte 8
if (value >= 0x80)
{
data[index++] = (byte)(value | 0x80);
value >>= 7;
}
}
}
}
}
}
}
}
}
// last byte
data[index++] = (byte)value;
return index;
}
public static ushort DecodeVarUInt16(byte[] data, ref int index)
{
var i = index;
// byte 0
uint result = data[i++];
if (0x80u <= result)
{
// byte 1
uint raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= raw << 14;
}
}
index = i;
return (ushort) result;
}
public static uint DecodeVarUInt32(byte[] data, ref int index)
{
var i = index;
// byte 0
uint result = data[i++];
if (0x80u <= result)
{
// byte 1
uint raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = data[i++];
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = data[i++];
result |= raw << 28;
}
}
}
}
index = i;
return result;
}
public static ulong DecodeVarUInt64(byte[] data, ref int index)
{
var i = index;
// byte 0
ulong result = data[i++];
if (0x80u <= result)
{
// byte 1
ulong raw = data[i++];
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = data[i++];
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = data[i++];
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = data[i++];
result |= (raw & 0x7Fu) << 28;
if (0x80u <= raw)
{
// byte 5
raw = data[i++];
result |= (raw & 0x7Fu) << 35;
if (0x80u <= raw)
{
// byte 6
raw = data[i++];
result |= (raw & 0x7Fu) << 42;
if (0x80u <= raw)
{
// byte 7
raw = data[i++];
result |= (raw & 0x7Fu) << 49;
if (0x80u <= raw)
{
// byte 8
raw = data[i++];
result |= raw << 56;
if (0x80u <= raw)
{
// byte 9
i++;
}
}
}
}
}
}
}
}
}
index = i;
return result;
}
public static void EncodeVarUInt16(Stream stream, ushort value)
{
// byte 0
if (value >= 0x80)
{
stream.WriteByte((byte)(value | 0x80));
value >>= 7;
// byte 1
if (value >= 0x80)
{
stream.WriteByte((byte)(value | 0x80));
value >>= 7;
}
}
// byte 2
stream.WriteByte( (byte)value);
}
public static void EncodeVarUInt32(Stream stream, uint value)
{
// byte 0
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 1
if (value >= 0x80)
{
stream.WriteByte((byte)(value | 0x80));
value >>= 7;
// byte 2
if (value >= 0x80)
{
stream.WriteByte((byte)(value | 0x80));
value >>= 7;
// byte 3
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
}
}
}
}
// last byte
stream.WriteByte( (byte)value);
}
public static void EncodeVarUInt64(Stream stream, ulong value)
{
// byte 0
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 1
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 2
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 3
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 4
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 5
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 6
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 7
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
// byte 8
if (value >= 0x80)
{
stream.WriteByte( (byte)(value | 0x80));
value >>= 7;
}
}
}
}
}
}
}
}
}
// last byte
stream.WriteByte((byte)value);
}
public static ushort DecodeVarUInt16(Stream stream)
{
// byte 0
uint result = (uint)stream.ReadByte();
if (0x80u <= result)
{
// byte 1
uint raw = (uint)stream.ReadByte();
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = (uint)stream.ReadByte();
result |= raw << 14;
}
}
return (ushort)result;
}
public static uint DecodeVarUInt32(Stream stream)
{
// byte 0
uint result = (uint)stream.ReadByte();
if (0x80u <= result)
{
// byte 1
uint raw = (uint)stream.ReadByte();
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = (uint)stream.ReadByte();
result |= raw << 28;
}
}
}
}
return result;
}
public static ulong DecodeVarUInt64(Stream stream)
{
// byte 0
ulong result = (uint)stream.ReadByte();
if (0x80u <= result)
{
// byte 1
ulong raw = (uint)stream.ReadByte();
result = (result & 0x7Fu) | ((raw & 0x7Fu) << 7);
if (0x80u <= raw)
{
// byte 2
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 14;
if (0x80u <= raw)
{
// byte 3
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 21;
if (0x80u <= raw)
{
// byte 4
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 28;
if (0x80u <= raw)
{
// byte 5
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 35;
if (0x80u <= raw)
{
// byte 6
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 42;
if (0x80u <= raw)
{
// byte 7
raw = (uint)stream.ReadByte();
result |= (raw & 0x7Fu) << 49;
if (0x80u <= raw)
{
// byte 8
raw = (uint)stream.ReadByte();
result |= raw << 56;
if (0x80u <= raw)
{
// byte 9
}
}
}
}
}
}
}
}
}
return result;
}
public static UInt16 EncodeZigzag(Int16 value)
{
return (UInt16)((value << 1) ^ (value >> (sizeof(Int16) * 8 - 1)));
}
public static UInt32 EncodeZigzag(Int32 value)
{
return (UInt32)((value << 1) ^ (value >> (sizeof(Int32) * 8 - 1)));
}
public static UInt64 EncodeZigzag(Int64 value)
{
return (UInt64)((value << 1) ^ (value >> (sizeof(Int64) * 8 - 1)));
}
public static Int16 DecodeZigzag(UInt16 value)
{
return (Int16)((value >> 1) ^ (-(value & 1)));
}
public static Int32 DecodeZigzag(UInt32 value)
{
return (Int32)((value >> 1) ^ (-(value & 1)));
}
public static Int64 DecodeZigzag(UInt64 value)
{
return (Int64)((value >> 1) ^ (UInt64)(-(Int64)(value & 1)));
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
//Using PCS's namespaces
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComMaterials.ActualCost.DS
{
public class CST_ActCostAllocationDetailDS
{
private const string THIS = ".CST_ActCostAllocationDetailDS";
public CST_ActCostAllocationDetailDS()
{
}
//**************************************************************************
/// <Description>
/// This method uses to add data to CST_ActCostAllocationDetail
/// </Description>
/// <Inputs>
/// CST_ActCostAllocationDetailVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 21, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
CST_ActCostAllocationDetailVO objObject = (CST_ActCostAllocationDetailVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO CST_ActCostAllocationDetail("
+ CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD + ","
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD + ","
+ CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD + ","
+ CST_ActCostAllocationDetailTable.LINE_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD].Value = objObject.AllocationAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD].Value = objObject.ActCostAllocationMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD].Value = objObject.CostElementID;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD, OleDbType.Integer));
if(objObject.DepartmentID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].Value = objObject.DepartmentID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD, OleDbType.Integer));
if(objObject.ProductionLineID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].Value = objObject.ProductionLineID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTID_FLD, OleDbType.Integer));
if(objObject.ProductID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD, OleDbType.Integer));
if(objObject.ProductGroupID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].Value = objObject.ProductGroupID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.LINE_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.LINE_FLD].Value = objObject.Line;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from CST_ActCostAllocationDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + CST_ActCostAllocationDetailTable.TABLE_NAME + " WHERE " + "ActCostAllocationDetailID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from CST_ActCostAllocationDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// CST_ActCostAllocationDetailVO
/// </Outputs>
/// <Returns>
/// CST_ActCostAllocationDetailVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 21, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD + ","
+ CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD + ","
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD + ","
+ CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD + ","
+ CST_ActCostAllocationDetailTable.LINE_FLD
+ " FROM " + CST_ActCostAllocationDetailTable.TABLE_NAME
+" WHERE " + CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
CST_ActCostAllocationDetailVO objObject = new CST_ActCostAllocationDetailVO();
while (odrPCS.Read())
{
objObject.ActCostAllocationDetailID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD].ToString().Trim());
objObject.AllocationAmount = Decimal.Parse(odrPCS[CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD].ToString().Trim());
objObject.ActCostAllocationMasterID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD].ToString().Trim());
objObject.CostElementID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD].ToString().Trim());
if(!odrPCS[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].Equals(DBNull.Value))
{
objObject.DepartmentID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].ToString().Trim());
}
else
{
objObject.DepartmentID = 0;
}
if(!odrPCS[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].Equals(DBNull.Value))
{
objObject.ProductionLineID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].ToString().Trim());
}
else
{
objObject.ProductionLineID = 0;
}
if(!odrPCS[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].Equals(DBNull.Value))
{
objObject.ProductID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].ToString().Trim());
}
else
{
objObject.ProductID = 0;
}
if(!odrPCS[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].Equals(DBNull.Value))
{
objObject.ProductGroupID = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].ToString().Trim());
}
else
{
objObject.ProductGroupID = 0;
}
objObject.Line = int.Parse(odrPCS[CST_ActCostAllocationDetailTable.LINE_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable GetDetailByMaster(int pintMasterID)
{
const string METHOD_NAME = THIS + ".GetDetailByMaster()";
DataTable dtbTable = new DataTable(CST_ActCostAllocationDetailTable.TABLE_NAME);
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = "SELECT cst_ActCostAllocationDetail.Line,";
strSql += " STD_CostElement.Name as STD_CostElementName,";
strSql += " cst_ActCostAllocationDetail.AllocationAmount,";
strSql += " MST_Department.Code AS MST_DepartmentCode,";
strSql += " PRO_ProductionLine.Code AS PRO_ProductionLineCode,";
strSql += " CST_ProductGroup.Code AS CST_ProductGroupCode,";
strSql += " ITM_Product.Code AS ITM_ProductCode,";
strSql += " ITM_Product.Description as ITM_ProductDescription,";
strSql += " ITM_Product.Revision as ITM_ProductRevision,";
strSql += " MST_UnitOfMeasure.Code AS MST_UnitOfMeasureCode,";
strSql += " cst_ActCostAllocationDetail.ActCostAllocationMasterID,";
strSql += " cst_ActCostAllocationDetail.ActCostAllocationDetailID,";
strSql += " cst_ActCostAllocationDetail.CostElementID,";
strSql += " cst_ActCostAllocationDetail.DepartmentID,";
strSql += " cst_ActCostAllocationDetail.ProductionLineID,";
strSql += " cst_ActCostAllocationDetail.ProductID,";
strSql += " cst_ActCostAllocationDetail.ProductGroupID";
strSql += " FROM cst_ActCostAllocationDetail";
strSql += " INNER JOIN STD_CostElement ON cst_ActCostAllocationDetail.CostElementID = STD_CostElement.CostElementID";
strSql += " LEFT JOIN MST_Department ON cst_ActCostAllocationDetail.DepartmentID = MST_Department.DepartmentID";
strSql += " LEFT JOIN CST_ProductGroup ON cst_ActCostAllocationDetail.ProductGroupID = CST_ProductGroup.ProductGroupID";
strSql += " LEFT JOIN ITM_Product ON cst_ActCostAllocationDetail.ProductID = ITM_Product.ProductID";
strSql += " LEFT JOIN PRO_ProductionLine ON cst_ActCostAllocationDetail.ProductionLineID = PRO_ProductionLine.ProductionLineID";
strSql += " LEFT JOIN MST_UnitOfMeasure ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID";
strSql += " WHERE cst_ActCostAllocationDetail.ActCostAllocationMasterID = " + pintMasterID;
strSql += " ORDER BY cst_ActCostAllocationDetail.Line ASC";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dtbTable);
return dtbTable;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to CST_ActCostAllocationDetail
/// </Description>
/// <Inputs>
/// CST_ActCostAllocationDetailVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
CST_ActCostAllocationDetailVO objObject = (CST_ActCostAllocationDetailVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE CST_ActCostAllocationDetail SET "
+ CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.PRODUCTID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD + "= ?" + ","
+ CST_ActCostAllocationDetailTable.LINE_FLD + "= ?"
+" WHERE " + CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD].Value = objObject.AllocationAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD].Value = objObject.ActCostAllocationMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD].Value = objObject.CostElementID;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD, OleDbType.Integer));
if(objObject.DepartmentID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].Value = objObject.DepartmentID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD, OleDbType.Integer));
if(objObject.ProductionLineID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].Value = objObject.ProductionLineID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTID_FLD, OleDbType.Integer));
if(objObject.ProductID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD, OleDbType.Integer));
if(objObject.ProductGroupID > 0)
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].Value = objObject.ProductGroupID;
}
else
{
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD].Value = DBNull.Value;
}
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.LINE_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.LINE_FLD].Value = objObject.Line;
ocmdPCS.Parameters.Add(new OleDbParameter(CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD].Value = objObject.ActCostAllocationDetailID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from CST_ActCostAllocationDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 21, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD + ","
+ CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD + ","
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD + ","
+ CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD + ","
+ CST_ActCostAllocationDetailTable.LINE_FLD
+ " FROM " + CST_ActCostAllocationDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,CST_ActCostAllocationDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 21, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONDETAILID_FLD + ","
+ CST_ActCostAllocationDetailTable.ALLOCATIONAMOUNT_FLD + ","
+ CST_ActCostAllocationDetailTable.ACTCOSTALLOCATIONMASTERID_FLD + ","
+ CST_ActCostAllocationDetailTable.COSTELEMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.DEPARTMENTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTIONLINEID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTID_FLD + ","
+ CST_ActCostAllocationDetailTable.PRODUCTGROUPID_FLD + ","
+ CST_ActCostAllocationDetailTable.LINE_FLD
+ " FROM " + CST_ActCostAllocationDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,CST_ActCostAllocationDetailTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all product used for import actual cost distribution setup
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DuongNA
/// </Authors>
/// <History>
/// Tuesday, March 07, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetAllProducts()
{
const string METHOD_NAME = THIS + ".GetAllProducts()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT ProductID, ITM_Product.Code, ITM_Product.Description, Revision,"
+ " U.Code AS " + MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD
+ " FROM ITM_Product JOIN MST_UnitOfMeasure U ON ITM_Product.StockUMID = U.UnitOfMeasureID";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,CST_ActCostAllocationDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all product used for import actual cost distribution setup
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DuongNA
/// </Authors>
/// <History>
/// Tuesday, March 07, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetAllProductionLine()
{
const string METHOD_NAME = THIS + ".GetAllProductionLine()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT ProductionLineID, Code, Name, DepartmentID, LocationID, BalancePlanning, RoundUpDaysException"
+ " FROM PRO_ProductionLine";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_ProductionLineTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet GetAllGroup()
{
const string METHOD_NAME = THIS + ".GetAllGroup()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT ProductGroupID, Code, Description, ProductionLineID"
+ " FROM CST_ProductGroup";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_ProductionLineTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all product used for import actual cost distribution setup
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DuongNA
/// </Authors>
/// <History>
/// Tuesday, March 07, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetAllCostElements()
{
const string METHOD_NAME = THIS + ".GetAllCostElements()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ STD_CostElementTable.COSTELEMENTID_FLD + ","
+ STD_CostElementTable.NAME_FLD
+ " FROM " + STD_CostElementTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,CST_ActCostAllocationDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
// 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.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ArtifactSourcesOperations operations.
/// </summary>
internal partial class ArtifactSourcesOperations : IServiceOperations<DevTestLabsClient>, IArtifactSourcesOperations
{
/// <summary>
/// Initializes a new instance of the ArtifactSourcesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ArtifactSourcesOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ArtifactSource>>> ListWithHttpMessagesAsync(string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ArtifactSource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ArtifactSource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get artifact source.
/// </summary>
/// <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='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> GetWithHttpMessagesAsync(string labName, string name, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArtifactSource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing artifact source.
/// </summary>
/// <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='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> CreateOrUpdateWithHttpMessagesAsync(string labName, string name, ArtifactSource artifactSource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (artifactSource == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "artifactSource");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("artifactSource", artifactSource);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(artifactSource != null)
{
_requestContent = SafeJsonConvert.SerializeObject(artifactSource, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArtifactSource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete artifact source.
/// </summary>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
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>
/// Modify properties of artifact sources.
/// </summary>
/// <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='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> UpdateWithHttpMessagesAsync(string labName, string name, ArtifactSourceFragment artifactSource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (artifactSource == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "artifactSource");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("artifactSource", artifactSource);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(this.Client.ResourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(artifactSource != null)
{
_requestContent = SafeJsonConvert.SerializeObject(artifactSource, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ArtifactSource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ArtifactSource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ArtifactSource>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<ArtifactSource>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Provides access to configuration variables for a repository.
/// </summary>
public class Configuration : IDisposable,
IEnumerable<ConfigurationEntry<string>>
{
private readonly FilePath repoConfigPath;
private readonly FilePath globalConfigPath;
private readonly FilePath xdgConfigPath;
private readonly FilePath systemConfigPath;
private ConfigurationSafeHandle configHandle;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Configuration()
{ }
internal Configuration(
Repository repository,
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
if (repositoryConfigurationFileLocation != null)
{
repoConfigPath = NormalizeConfigPath(repositoryConfigurationFileLocation);
}
globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global();
xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg();
systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system();
Init(repository);
}
private void Init(Repository repository)
{
configHandle = Proxy.git_config_new();
if (repository != null)
{
//TODO: push back this logic into libgit2.
// As stated by @carlosmn "having a helper function to load the defaults and then allowing you
// to modify it before giving it to git_repository_open_ext() would be a good addition, I think."
// -- Agreed :)
string repoConfigLocation = Path.Combine(repository.Info.Path, "config");
Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local);
Proxy.git_repository_set_config(repository.Handle, configHandle);
}
else if (repoConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, repoConfigPath, ConfigurationLevel.Local);
}
if (globalConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global);
}
if (xdgConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg);
}
if (systemConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System);
}
}
private FilePath NormalizeConfigPath(FilePath path)
{
if (File.Exists(path.Native))
{
return path;
}
if (!Directory.Exists(path.Native))
{
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
var configPath = Path.Combine(path.Native, "config");
if (File.Exists(configPath))
{
return configPath;
}
var gitConfigPath = Path.Combine(path.Native, ".git", "config");
if (File.Exists(gitConfigPath))
{
return gitConfigPath;
}
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(string repositoryConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, null, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a System configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
return new Configuration(null, repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation);
}
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string) instead.")]
public Configuration(string globalConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, null, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string) instead.")]
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a system configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string, string) instead.")]
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation)
{ }
/// <summary>
/// Determines which configuration file has been found.
/// </summary>
public virtual bool HasConfig(ConfigurationLevel level)
{
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
return handle != null;
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Saves any open configuration files.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Unset a configuration variable (key and value) in the local configuration.
/// </summary>
/// <param name="key">The key to unset.</param>
public virtual void Unset(string key)
{
Unset(key, ConfigurationLevel.Local);
}
/// <summary>
/// Unset a configuration variable (key and value).
/// </summary>
/// <param name="key">The key to unset.</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Unset(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete(h, key);
}
}
internal void UnsetMultivar(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete_multivar(h, key);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
configHandle.SafeDispose();
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }).Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="keyParts">The key parts</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string[] keyParts)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return Get<T>(string.Join(".", keyParts));
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="firstKeyPart">The first key part</param>
/// <param name="secondKeyPart">The second key part</param>
/// <param name="thirdKeyPart">The third key part</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "thirdKeyPart");
return Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart });
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
///
/// The first occurence of the key will be returned.
/// </para>
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
{
return Proxy.git_config_get_entry<T>(snapshot, key);
}
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <param name="level">The configuration file into which the key should be searched for</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
if (handle == null)
{
return null;
}
return Proxy.git_config_get_entry<T>(handle, key);
}
}
/// <summary>
/// Get a configuration value for the given key.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/>if not found</returns>
public virtual T GetValueOrDefault<T>(string key)
{
return ValueOrDefault(Get<T>(key), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value</returns>
public virtual T GetValueOrDefault<T>(string key, T defaultValue)
{
return ValueOrDefault(Get<T>(key), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>The configuration value, or the default value for <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level)
{
return ValueOrDefault(Get<T>(key, level), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValue">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, T defaultValue)
{
return ValueOrDefault(Get<T>(key, level), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <returns>The configuration value, or the default value for<see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts)
{
return ValueOrDefault(Get<T>(keyParts), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, T defaultValue)
{
return ValueOrDefault(Get<T>(keyParts), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key, level), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(keyParts), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValueSelector);
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, T defaultValue)
{
return value == null ? defaultValue : value.Value;
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, Func<T> defaultValueSelector)
{
Ensure.ArgumentNotNull(defaultValueSelector, "defaultValueSelector");
return value == null
? defaultValueSelector()
: value.Value;
}
/// <summary>
/// Set a configuration value for a key in the local configuration. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
public virtual void Set<T>(string key, T value)
{
Set(key, value, ConfigurationLevel.Local);
}
/// <summary>
/// Set a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Set<T>(string key, T value, ConfigurationLevel level)
{
Ensure.ArgumentNotNull(value, "value");
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
if (!configurationTypedUpdater.ContainsKey(typeof(T)))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName));
}
configurationTypedUpdater[typeof(T)](key, value, h);
}
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp)
{
return Find(regexp, ConfigurationLevel.Local);
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot))
{
return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList();
}
}
private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle)
{
ConfigurationSafeHandle handle = null;
if (fromHandle != null)
{
handle = Proxy.git_config_open_level(fromHandle, level);
}
if (handle == null && throwIfStoreHasNotBeenFound)
{
throw new LibGit2SharpException("No {0} configuration file has been found.",
Enum.GetName(typeof(ConfigurationLevel), level));
}
return handle;
}
private static Action<string, object, ConfigurationSafeHandle> GetUpdater<T>(Action<ConfigurationSafeHandle, string, T> setter)
{
return (key, val, handle) => setter(handle, key, (T)val);
}
private readonly static IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>>
{
{ typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) },
{ typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) },
{ typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) },
{ typeof(string), GetUpdater<string>(Proxy.git_config_set_string) },
};
/// <summary>
/// Returns an enumerator that iterates through the configuration entries.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns>
public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator()
{
return BuildConfigEntries().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator();
}
private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries()
{
return Proxy.git_config_foreach(configHandle, BuildConfigEntry);
}
private static ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr)
{
var entry = entryPtr.MarshalAs<GitConfigEntry>();
return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry.namePtr),
LaxUtf8Marshaler.FromNative(entry.valuePtr),
(ConfigurationLevel)entry.level);
}
/// <summary>
/// Builds a <see cref="Signature"/> based on current configuration. If it is not found or
/// some configuration is missing, <code>null</code> is returned.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
/// </para>
/// </summary>
/// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param>
/// <returns>The signature or null if no user identity can be found in the configuration.</returns>
public virtual Signature BuildSignature(DateTimeOffset now)
{
var name = this.GetValueOrDefault<string>("user.name");
var email = this.GetValueOrDefault<string>("user.email");
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email))
{
return null;
}
return new Signature(name, email, now);
}
internal Signature BuildSignatureOrThrow(DateTimeOffset now)
{
var signature = BuildSignature(now);
if (signature == null)
{
throw new LibGit2SharpException("This overload requires 'user.name' and 'user.email' to be set. " +
"Use a different overload or set those variables in the configuation");
}
return signature;
}
private ConfigurationSafeHandle Snapshot()
{
return Proxy.git_config_snapshot(configHandle);
}
}
}
| |
using Engine.Assets;
using Engine.Controls;
using Engine.Input;
using Engine.Interface;
using Engine.Lua;
using Language.Lua;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.Direct3D10;
using SharpDX.DirectInput;
using SharpDX.DXGI;
using SharpDX.Windows;
using System;
using System.Threading;
using System.Windows.Forms;
using Device1 = SharpDX.Direct3D10.Device1;
using DKeyboard = SharpDX.DirectInput.Keyboard;
using DMouse = SharpDX.DirectInput.Mouse;
using DriverType = SharpDX.Direct3D10.DriverType;
using Factory2D = SharpDX.Direct2D1.Factory;
using FactoryDXGI = SharpDX.DXGI.Factory;
using Keyboard = Engine.Input.Keyboard;
using Mouse = Engine.Input.Mouse;
namespace Engine {
public enum GameRunType : byte {
Synchronous,
Asynchronous
}
public abstract partial class GameApplication : SharpDX.Component {
#region Fields/Properties
private static GameApplication _singleton;
public static int MainThreadId { get { return _singleton._mainThreadId; } }
public static int UpdateThreadId { get { return _singleton._updateThreadId; } }
public static float FramesPerSecond { get; private set; }
public static float UpdatesPerSecond { get; private set; }
public static DrawingSizeF ScreenSize { get; private set; }
public static ControlManager ControlManager { get { return _singleton._controlManager; } }
private long _timeAcc;
private uint _fpsCount, _upsCount;
private volatile bool _isRunning = false;
private bool _vsync = false, _isClosed = false, _doRender = true, _isLoaded = false;
private readonly int _mainThreadId;
private int _updateThreadId = -1;
private GameTimer _timer = new GameTimer();
private Thread _updateThread;
private ControlManager _controlManager;
private CommandConsole _commandConsole;
private OutputStreams _streams;
private DirectInput _directInput;
private DKeyboard _dKeyboard;
private DMouse _dMouse;
private AssetManager _assetManager;
private Device1 _device;
private SwapChain _swapChain;
private Texture2D _backBuffer;
private RenderTargetView _backBufferRenderTargetView;
private FactoryDXGI _factoryDXGI;
protected readonly string _formTitle;
protected ApplicationConfig _appConfiguration;
protected RenderForm _form;
protected Viewport Viewport;
protected Factory2D Factory2D;
protected RenderTarget RenderTarget2D;
protected LuaEnvironment Lua { get; private set; }
protected Keyboard Keyboard { get; private set; }
protected Mouse Mouse { get; private set; }
protected IntPtr DisplayHandle { get { return _form.Handle; } }
protected System.Drawing.Size RenderingSize { get { return _form.ClientSize; } }
public Device1 Device { get { return _device; } }
public ApplicationConfig Config { get { return _appConfiguration; } }
#endregion
#region Events
// Mouse events
public static event MouseButtonEventHandler OnMousePressed;
public static event MouseButtonEventHandler OnMouseHeld;
public static event MouseButtonEventHandler OnMouseReleased;
public static event MouseVectorEventHandler OnMouseMoved;
public static event MouseVectorEventHandler OnMousePosition;
public static event MouseScrollEventHandler OnMouseScroll;
// Keyboard events
public static event KeyboardEventHandler OnKeyboardPressed;
public static event KeyboardEventHandler OnKeyboardHeld;
public static event KeyboardEventHandler OnKeyboardReleased;
#endregion
#region Initialization/Disposal
public GameApplication(string configPath = "config/config.cfg", string formTitle = "Default Form Title")
: base() {
if(_singleton != null)
_singleton.Exit();
_singleton = this;
_mainThreadId = Thread.CurrentThread.ManagedThreadId;
_streams = ToDispose<OutputStreams>(new OutputStreams());
_formTitle = formTitle;
_appConfiguration = configPath == null ? new ApplicationConfig() : new ApplicationConfig(configPath);
_initializeForm();
_initializeGraphics();
Lua = new LuaEnvironment();
_commandConsole = ToDispose<CommandConsole>(new CommandConsole(Lua, new DrawingSizeF(Viewport.Width, Viewport.Height), _streams));
RegisterEngineComponent(_commandConsole);
_controlManager = ToDispose<ControlManager>(new ControlManager());
RegisterEngineComponent(_controlManager);
OnUpdate += Update;
OnRender += Render;
OnLoadContent += LoadContent;
OnUnloadContent += UnloadContent;
}
protected override void Dispose(bool disposeManagedResources) {
if (_isLoaded)
_unloadContent();
base.Dispose(disposeManagedResources);
}
/// <summary>
/// In a derived class, implements logic to initialize the application.
/// </summary>
protected virtual void Initialize() {
}
private void _initializeInputs() {
Console.Write("Initializing inputs... ");
_directInput = ToDispose<DirectInput>(new DirectInput());
_dKeyboard = ToDispose<DKeyboard>(new DKeyboard(_directInput));
_dKeyboard.Properties.BufferSize = 256;
_dKeyboard.SetCooperativeLevel(_form, CooperativeLevel.Foreground | CooperativeLevel.Exclusive);
Keyboard = new Keyboard(_dKeyboard);
_dMouse = ToDispose<DMouse>(new DMouse(_directInput));
_dMouse.Properties.AxisMode = DeviceAxisMode.Relative;
_dMouse.SetCooperativeLevel(_form, CooperativeLevel.Foreground | CooperativeLevel.NonExclusive);
Mouse = new Mouse(_form, _dMouse);
Console.WriteLine("done.");
}
/// <summary>
/// Create the form.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
private void _initializeForm() {
Console.Write("Initializing form... ");
_form = ToDispose<RenderForm>(new RenderForm(_formTitle) {
ClientSize = new System.Drawing.Size(_appConfiguration.Width, _appConfiguration.Height)
});
_form.FormClosing += _handleFormClosing;
Console.WriteLine("done.");
}
private void _initializeGraphics() {
Console.Write("Initializing graphic device... ");
var desc = new SwapChainDescription() {
BufferCount = 1,
ModeDescription = new ModeDescription(
_appConfiguration.Width,
_appConfiguration.Height,
new Rational(60, 1),
Format.R8G8B8A8_UNorm),
IsWindowed = !_appConfiguration.FullScreen,
OutputHandle = DisplayHandle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};
Device1.CreateWithSwapChain(
DriverType.Hardware,
#if DEBUG
DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug | DeviceCreationFlags.SingleThreaded,
#else
DeviceCreationFlags.BgraSupport,
#endif
desc,
out _device,
out _swapChain);
if (_device == null)
throw new SharpDXException("Failed to initialize graphics device.");
if (_swapChain == null)
throw new SharpDXException("Failed to initialize swap chain.");
ToDispose<Device1>(_device);
ToDispose<SwapChain>(_swapChain);
Factory2D = ToDispose<Factory2D>(new Factory2D());
_factoryDXGI = ToDispose<FactoryDXGI>(_swapChain.GetParent<FactoryDXGI>());
_factoryDXGI.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll);
_backBuffer = ToDispose<Texture2D>(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
_backBufferRenderTargetView = ToDispose<RenderTargetView>(new RenderTargetView(_device, _backBuffer));
Viewport = new Viewport(0, 0, _appConfiguration.Width, _appConfiguration.Height);
using (var surface = _backBuffer.QueryInterface<Surface>()) {
RenderTarget2D = ToDispose<RenderTarget>(
new RenderTarget(Factory2D,
surface,
new RenderTargetProperties(
new PixelFormat(
Format.Unknown,
AlphaMode.Premultiplied))));
}
RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive;
_vsync = Config.VSync;
ScreenSize = new DrawingSizeF(Viewport.Width, Viewport.Height);
Console.WriteLine("done.");
}
private void _disposeGraphics() {
if (_assetManager != null && !_assetManager.IsDisposed)
RemoveAndDispose<AssetManager>(ref _assetManager);
if(RenderTarget2D != null && !RenderTarget2D.IsDisposed)
RemoveAndDispose<RenderTarget>(ref RenderTarget2D);
if (_backBufferRenderTargetView != null && !_backBufferRenderTargetView.IsDisposed)
RemoveAndDispose<RenderTargetView>(ref _backBufferRenderTargetView);
if (_backBuffer != null && !_backBuffer.IsDisposed)
RemoveAndDispose<Texture2D>(ref _backBuffer);
if (_factoryDXGI != null && !_factoryDXGI.IsDisposed)
RemoveAndDispose<FactoryDXGI>(ref _factoryDXGI);
if (Factory2D != null && !Factory2D.IsDisposed)
RemoveAndDispose<Factory2D>(ref Factory2D);
if (_swapChain != null && !_swapChain.IsDisposed)
RemoveAndDispose<SwapChain>(ref _swapChain);
if (_device != null && !_device.IsDisposed)
RemoveAndDispose<Device1>(ref _device);
}
private void _loadContent() {
Console.Write("Loading content... ");
_assetManager = ToDispose<AssetManager>(new AssetManager(RenderTarget2D));
//_controlManager.LoadContent(_assetManager);
//_commandConsole.LoadContent(_assetManager);
OnLoadContent(_assetManager);
_isLoaded = true;
Console.WriteLine("finished.");
}
private void _unloadContent() {
Console.WriteLine("Unloading content...");
//_controlManager.UnloadContent();
//_commandConsole.UnloadContent();
OnUnloadContent();
_isLoaded = false;
RemoveAndDispose<AssetManager>(ref _assetManager);
}
protected virtual void LoadContent(IAssetManager assetManager) {
}
protected virtual void UnloadContent() {
}
#endregion
#region Main execution
/// <summary>
/// In a derived class, implements logic to update running systems.
/// </summary>
protected virtual void Update() {
}
/// <summary>
/// In a derived class, implements logic to render content
/// </summary>
protected virtual void Render(RenderTarget renderTarget) {
}
/// <summary>
/// In a derived class, implements logic to perform at the start of execution
/// </summary>
protected virtual void BeginRun() {
}
/// <summary>
/// In a derived class, implements logic to perform at the end of execution
/// </summary>
protected virtual void EndRun() {
}
/// <summary>
/// In a derived class, implements logic that should occur before all
/// other rendering.
/// </summary>
protected virtual void BeginDraw() {
}
/// <summary>
/// In a derived class, implements logic that should occur after all
/// other rendering.
/// </summary>
protected virtual void EndDraw() {
}
private void _beginRun() {
BeginRun();
}
/// <summary>
/// Runs the application.
/// </summary>
public void Run(GameRunType runType = GameRunType.Synchronous) {
_initializeInputs();
Initialize();
_isRunning = true;
_beginRun();
_loadContent();
_timer.Start();
switch (runType) {
case GameRunType.Synchronous:
RenderLoop.Run(_form, () => {
if (!_isRunning)
return;
_update();
if (_doRender)
_render();
});
break;
case GameRunType.Asynchronous:
throw new NotImplementedException("Multiple game loops not working");
_updateThread = new Thread(() => {
var offThread = ToDispose<RenderForm>(new RenderForm());
offThread.Visible = false;
offThread.SuspendLayout();
offThread.ClientSize = new System.Drawing.Size();
RenderLoop.Run(_form, () => {
if (!_isRunning)
return;
_update();
});
offThread.Close();
RemoveAndDispose<RenderForm>(ref offThread);
});
_updateThread.Start();
_updateThreadId = _updateThread.ManagedThreadId;
RenderLoop.Run(_form, () => {
if (!_isRunning)
return;
if (_doRender)
_render();
});
_updateThread.Join(5000);
break;
}
_unloadContent();
_endRun();
// Dispose explicity
Dispose();
}
private void _endRun() {
EndRun();
_dMouse.Unacquire();
_dKeyboard.Unacquire();
_singleton = null;
}
/// <summary>
/// Quits the application.
/// </summary>
public void Exit() {
_isRunning = false;
_doRender = false;
if(!_isClosed)
_form.Close();
}
private void _update() {
if (_form.Focused) {
Mouse.Update();
Keyboard.Update();
}
//_commandConsole.ProcessKeyboard(Keyboard);
//_commandConsole.ProcessMouse(Mouse);
//_commandConsole.Update();
// Fire input events
if (OnMousePressed != null) {
foreach (var button in Mouse.State.Pressed)
OnMousePressed(this, new MouseButtonEventArgs(button, Mouse.State.Position));
}
if (OnMouseHeld != null) {
foreach (var button in Mouse.State.Held)
OnMouseHeld(this, new MouseButtonEventArgs(button, Mouse.State.Position));
}
if (OnMouseReleased != null) {
foreach (var button in Mouse.State.Released)
OnMouseReleased(this, new MouseButtonEventArgs(button, Mouse.State.Position));
}
if (OnMouseMoved != null && Mouse.State.Moved)
OnMouseMoved(this, new MouseVectorEventArgs(Mouse.State.Motion));
if (OnMousePosition != null)
OnMousePosition(this, new MouseVectorEventArgs(Mouse.State.Position));
if (OnMouseScroll != null && Mouse.State.ScrollWheel != 0)
OnMouseScroll(this, new MouseScrollEventArgs(Mouse.State.ScrollWheel));
// Keyboard events
if (OnKeyboardPressed != null) {
foreach (var key in Keyboard.State.Pressed)
OnKeyboardPressed(this, new KeyboardEventArgs(key, Keyboard.State.Shift, Keyboard.State.Ctrl, Keyboard.State.Alt));
}
if (OnKeyboardHeld != null) {
foreach (var key in Keyboard.State.Held)
OnKeyboardHeld(this, new KeyboardEventArgs(key, Keyboard.State.Shift, Keyboard.State.Ctrl, Keyboard.State.Alt));
}
if (OnKeyboardReleased != null) {
foreach (var key in Keyboard.State.Released)
OnKeyboardReleased(this, new KeyboardEventArgs(key, Keyboard.State.Shift, Keyboard.State.Ctrl, Keyboard.State.Alt));
}
//_controlManager.ProcessMouse(Mouse);
//_controlManager.ProcessKeyboard(Keyboard);
//_controlManager.Update();
OnUpdate();
_upsCount++;
if ((_timeAcc += _timer.UpdateTicks()) > 1000L * 10000L) {
UpdatesPerSecond = _upsCount / (_timeAcc / (1000L * 10000L)); ;
_upsCount = 0;
FramesPerSecond = _fpsCount / (_timeAcc / (1000L * 10000L));
_fpsCount = 0;
_timeAcc -= 1000L * 10000L;
}
}
private void _render() {
_device.Rasterizer.SetViewports(Viewport);
_device.OutputMerger.SetTargets(_backBufferRenderTargetView);
_device.ClearRenderTargetView(_backBufferRenderTargetView, Color.CornflowerBlue);
BeginDraw();
OnRender(RenderTarget2D);
EndDraw();
_controlManager.Render(RenderTarget2D);
_commandConsole.Render(RenderTarget2D);
_swapChain.Present(_vsync ? 1 : 0, PresentFlags.None);
_fpsCount++;
}
#endregion
#region System event handlers
private void _handleResize(object sender, EventArgs e) {
if (_form.WindowState == FormWindowState.Minimized) {
return;
}
if(_isLoaded)
_unloadContent();
_disposeGraphics();
_initializeGraphics();
if (!_isLoaded)
_loadContent();
}
private void _handleFormClosing(object sender, EventArgs e) {
_isClosed = true;
Exit();
}
#endregion
#region IEngineComponent management
private Action OnUpdate;
private Action<RenderTarget> OnRender;
private Action<IAssetManager> OnLoadContent;
private Action OnUnloadContent;
public void RegisterEngineComponent(IEngineComponent component) {
if (component is IUpdateable)
OnUpdate += (component as IUpdateable).Update;
if (component is IRenderable)
OnRender += (component as IRenderable).Render;
if (component is ILoadable) {
OnLoadContent += (component as ILoadable).LoadContent;
OnUnloadContent += (component as ILoadable).UnloadContent;
}
if (component is IHandleMouseButtonPressed)
OnMousePressed += (component as IHandleMouseButtonPressed).OnMousePressed;
if (component is IHandleMouseButtonHeld)
OnMouseHeld += (component as IHandleMouseButtonHeld).OnMouseHeld;
if (component is IHandleMouseButtonReleased)
OnMouseReleased += (component as IHandleMouseButtonReleased).OnMouseReleased;
if (component is IHandleMouseMotion)
OnMouseMoved += (component as IHandleMouseMotion).OnMotion;
if (component is IHandleMousePosition)
OnMousePosition += (component as IHandleMousePosition).OnPosition;
if (component is IHandleMouseScrollWheel)
OnMouseScroll += (component as IHandleMouseScrollWheel).OnScrolled;
if (component is IHandleKeyboardPressed)
OnKeyboardPressed += (component as IHandleKeyboardPressed).OnKeyboardPressed;
if (component is IHandleKeyboardHeld)
OnKeyboardHeld += (component as IHandleKeyboardHeld).OnKeyboardHeld;
if (component is IHandleKeyboardReleased)
OnKeyboardReleased += (component as IHandleKeyboardReleased).OnKeyboardReleased;
}
public void UnregisterEngineComponent(IEngineComponent component) {
if (component is IUpdateable)
OnUpdate -= (component as IUpdateable).Update;
if (component is IRenderable)
OnRender -= (component as IRenderable).Render;
if (component is ILoadable) {
OnLoadContent -= (component as ILoadable).LoadContent;
OnUnloadContent -= (component as ILoadable).UnloadContent;
}
if(component is IHandleMouseButtonPressed)
OnMousePressed -= (component as IHandleMouseButtonPressed).OnMousePressed;
if(component is IHandleMouseButtonHeld)
OnMouseHeld -= (component as IHandleMouseButtonHeld).OnMouseHeld;
if(component is IHandleMouseButtonReleased)
OnMouseReleased -= (component as IHandleMouseButtonReleased).OnMouseReleased;
if (component is IHandleMouseMotion)
OnMouseMoved -= (component as IHandleMouseMotion).OnMotion;
if (component is IHandleMousePosition)
OnMousePosition -= (component as IHandleMousePosition).OnPosition;
if (component is IHandleMouseScrollWheel)
OnMouseScroll -= (component as IHandleMouseScrollWheel).OnScrolled;
if (component is IHandleKeyboardPressed)
OnKeyboardPressed -= (component as IHandleKeyboardPressed).OnKeyboardPressed;
if (component is IHandleKeyboardHeld)
OnKeyboardHeld -= (component as IHandleKeyboardHeld).OnKeyboardHeld;
if (component is IHandleKeyboardReleased)
OnKeyboardReleased -= (component as IHandleKeyboardReleased).OnKeyboardReleased;
}
#endregion
#region Lua commands
[LuaCommand("Exits the game")]
public static LuaValue exit(LuaValue[] arg) {
_singleton.Exit();
return LuaNil.Nil;
}
#endregion
}
}
| |
// Cloner - An example of use of procedural instancing.
// https://github.com/keijiro/Cloner
using UnityEngine;
using Klak.Chromatics;
namespace Cloner
{
public sealed class ClonerRenderer : MonoBehaviour
{
#region Point source properties
[SerializeField] PointCloud _pointSource;
public PointCloud pointSource {
get { return _pointSource; }
}
#endregion
#region Template properties
[SerializeField] Mesh _template;
public Mesh template {
get { return _template; }
}
[SerializeField] float _templateScale = 0.05f;
public float templateScale {
get { return _templateScale; }
set { _templateScale = value; }
}
[SerializeField] float _scaleByNoise = 0.1f;
public float scaleByNoise {
get { return _scaleByNoise; }
set { _scaleByNoise = value; }
}
[SerializeField] float _scaleByPulse = 0.1f;
public float scaleByPulse {
get { return _scaleByPulse; }
set { _scaleByPulse = value; }
}
#endregion
#region Noise field properties
[SerializeField] float _noiseFrequency = 1;
public float noiseFrequency {
get { return _noiseFrequency; }
set { _noiseFrequency = value; }
}
[SerializeField] Vector3 _noiseMotion = Vector3.up * 0.25f;
public Vector3 noiseMotion {
get { return _noiseMotion; }
set { _noiseMotion = value; }
}
[SerializeField, Range(0, 1)] float _normalModifier = 0.125f;
public float normalModifier {
get { return _normalModifier; }
set { _normalModifier = value; }
}
#endregion
#region Pulse noise properties
[SerializeField, Range(0, 0.1f)] float _pulseProbability = 0;
public float pulseProbability {
get { return _pulseProbability; }
set { _pulseProbability = value; }
}
[SerializeField] float _pulseFrequency = 2;
public float pulseFrequency {
get { return _pulseFrequency; }
set { _pulseFrequency = value; }
}
#endregion
#region Material properties
[SerializeField] Material _material;
public Material material {
get { return _material; }
}
[SerializeField] CosineGradient _gradient;
public CosineGradient gradient {
get { return _gradient; }
set { _gradient = value; }
}
#endregion
#region Misc properties
[SerializeField] Bounds _bounds =
new Bounds(Vector3.zero, Vector3.one * 10);
public Bounds bounds {
get { return _bounds; }
set { _bounds = value; }
}
[SerializeField] int _randomSeed;
public int randomSeed {
get { return _randomSeed; }
}
#endregion
#region Hidden attributes
[SerializeField, HideInInspector] ComputeShader _compute;
#endregion
#region Private fields
ComputeBuffer _drawArgsBuffer;
ComputeBuffer _positionBuffer;
ComputeBuffer _normalBuffer;
ComputeBuffer _tangentBuffer;
ComputeBuffer _transformBuffer;
bool _materialCloned;
MaterialPropertyBlock _props;
Vector3 _noiseOffset;
float _pulseTimer;
Bounds TransformedBounds {
get {
return new Bounds(
transform.TransformPoint(_bounds.center),
Vector3.Scale(transform.lossyScale, _bounds.size)
);
}
}
#endregion
#region Compute configurations
const int kThreadCount = 64;
int ThreadGroupCount {
get { return Mathf.Max(1, _pointSource.pointCount / kThreadCount); }
}
int InstanceCount {
get { return ThreadGroupCount * kThreadCount; }
}
#endregion
#region MonoBehaviour functions
void OnValidate()
{
_noiseFrequency = Mathf.Max(0, _noiseFrequency);
_pulseFrequency = Mathf.Max(0, _pulseFrequency);
_bounds.size = Vector3.Max(Vector3.zero, _bounds.size);
}
void Start()
{
// Initialize the indirect draw args buffer.
_drawArgsBuffer = new ComputeBuffer(
1, 5 * sizeof(uint), ComputeBufferType.IndirectArguments
);
_drawArgsBuffer.SetData(new uint[5] {
_template.GetIndexCount(0), (uint)InstanceCount, 0, 0, 0
});
// Allocate compute buffers.
_positionBuffer = _pointSource.CreatePositionBuffer();
_normalBuffer = _pointSource.CreateNormalBuffer();
_tangentBuffer = _pointSource.CreateTangentBuffer();
_transformBuffer = new ComputeBuffer(InstanceCount * 3, 4 * 4);
// This property block is used only for avoiding an instancing bug.
_props = new MaterialPropertyBlock();
_props.SetFloat("_UniqueID", Random.value);
// Initial noise offset/pulse timer = random seed
_noiseOffset = Vector3.one * _randomSeed;
_pulseTimer = _pulseFrequency * _randomSeed;
// Clone the given material before using.
_material = new Material(_material);
_material.name += " (cloned)";
_materialCloned = true;
}
void OnDestroy()
{
if (_drawArgsBuffer != null) _drawArgsBuffer.Release();
if (_positionBuffer != null) _positionBuffer.Release();
if (_normalBuffer != null) _normalBuffer.Release();
if (_tangentBuffer != null) _tangentBuffer.Release();
if (_transformBuffer != null) _transformBuffer.Release();
if (_materialCloned) Destroy(_material);
}
void Update()
{
// Invoke the update compute kernel.
var kernel = _compute.FindKernel("ClonerUpdate");
_compute.SetInt("InstanceCount", InstanceCount);
_compute.SetFloat("RcpInstanceCount", 1.0f / InstanceCount);
_compute.SetFloat("BaseScale", _templateScale);
_compute.SetFloat("ScaleNoise", _scaleByNoise);
_compute.SetFloat("ScalePulse", _scaleByPulse);
_compute.SetFloat("NoiseFrequency", _noiseFrequency);
_compute.SetVector("NoiseOffset", _noiseOffset);
_compute.SetFloat("NormalModifier", _normalModifier);
_compute.SetFloat("PulseProbability", _pulseProbability);
_compute.SetFloat("PulseTime", _pulseTimer);
_compute.SetBuffer(kernel, "PositionBuffer", _positionBuffer);
_compute.SetBuffer(kernel, "NormalBuffer", _normalBuffer);
_compute.SetBuffer(kernel, "TangentBuffer", _tangentBuffer);
_compute.SetBuffer(kernel, "TransformBuffer", _transformBuffer);
_compute.Dispatch(kernel, ThreadGroupCount, 1, 1);
// Draw the template mesh with instancing.
_material.SetVector("_GradientA", _gradient.coeffsA);
_material.SetVector("_GradientB", _gradient.coeffsB);
_material.SetVector("_GradientC", _gradient.coeffsC2);
_material.SetVector("_GradientD", _gradient.coeffsD2);
_material.SetMatrix("_LocalToWorld", transform.localToWorldMatrix);
_material.SetMatrix("_WorldToLocal", transform.worldToLocalMatrix);
_material.SetBuffer("_TransformBuffer", _transformBuffer);
_material.SetInt("_InstanceCount", InstanceCount);
Graphics.DrawMeshInstancedIndirect(
_template, 0, _material, TransformedBounds,
_drawArgsBuffer, 0, _props
);
// Update the internal state.
_noiseOffset += _noiseMotion * Time.deltaTime;
_pulseTimer += _pulseFrequency * Time.deltaTime;
}
void OnDrawGizmos()
{
Gizmos.color = new Color(0, 1, 1, 0.3f);
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(_bounds.center, _bounds.size);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(_bounds.center, _bounds.size);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using System.Linq;
using Microsoft.Build.Construction;
using System.Text;
using System.Xml;
namespace Microsoft.DotNet.Build.Tasks
{
public class UpdateVSConfigurations : BuildTask
{
public ITaskItem[] ProjectsToUpdate { get; set; }
public ITaskItem[] SolutionsToUpdate { get; set; }
private const string ConfigurationPropsFilename = "Configurations.props";
private static Regex s_configurationConditionRegex = new Regex(@"'\$\(Configuration\)\|\$\(Platform\)' ?== ?'(?<config>.*)'");
private static string[] s_configurationSuffixes = new [] { "Debug|AnyCPU", "Release|AnyCPU" };
public override bool Execute()
{
if (ProjectsToUpdate == null) ProjectsToUpdate = new ITaskItem[0];
if (SolutionsToUpdate == null) SolutionsToUpdate = new ITaskItem[0];
foreach (var item in ProjectsToUpdate)
{
string projectFile = item.ItemSpec;
string projectConfigurationPropsFile = Path.Combine(Path.GetDirectoryName(projectFile), ConfigurationPropsFilename);
string[] expectedConfigurations = s_configurationSuffixes;
if (File.Exists(projectConfigurationPropsFile))
{
expectedConfigurations = GetConfigurationStrings(projectConfigurationPropsFile);
}
Log.LogMessage($"Updating {projectFile}");
var project = ProjectRootElement.Open(projectFile);
ICollection<ProjectPropertyGroupElement> propertyGroups;
var actualConfigurations = GetConfigurationFromPropertyGroups(project, out propertyGroups);
bool addedGuid = EnsureProjectGuid(project);
if (!actualConfigurations.SequenceEqual(expectedConfigurations))
{
ReplaceConfigurationPropertyGroups(project, propertyGroups, expectedConfigurations);
}
if (addedGuid || !actualConfigurations.SequenceEqual(expectedConfigurations))
{
project.Save();
}
}
foreach (var solutionRoot in SolutionsToUpdate)
{
UpdateSolution(solutionRoot);
}
return !Log.HasLoggedErrors;
}
/// <summary>
/// Gets a sorted list of configuration strings from a Configurations.props file
/// </summary>
/// <param name="configurationProjectFile">Path to Configuration.props file</param>
/// <returns>Sorted list of configuration strings</returns>
private static string[] GetConfigurationStrings(string configurationProjectFile, bool addSuffixes = true)
{
var configurationProject = new Project(configurationProjectFile);
var buildConfigurations = configurationProject.GetPropertyValue("BuildConfigurations");
ProjectCollection.GlobalProjectCollection.UnloadProject(configurationProject);
// if starts with _ it is a placeholder configuration and we should ignore it.
var configurations = buildConfigurations.Trim()
.Split(';')
.Select(c => c.Trim())
.Where(c => !String.IsNullOrEmpty(c) && !c.StartsWith("_"));
if (addSuffixes)
{
configurations = configurations.SelectMany(c => s_configurationSuffixes.Select(s => c + "-" + s));
}
return configurations.OrderBy(c => c, StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>
/// Gets a sorted list of configuration strings from a project file's PropertyGroups
/// </summary>
/// <param name="project">Project</param>
/// <param name="propertyGroups">collection that accepts the list of property groups representing configuration strings</param>
/// <returns>Sorted list of configuration strings</returns>
private static string[] GetConfigurationFromPropertyGroups(ProjectRootElement project, out ICollection<ProjectPropertyGroupElement> propertyGroups)
{
propertyGroups = new List<ProjectPropertyGroupElement>();
var configurations = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var propertyGroup in project.PropertyGroups)
{
var match = s_configurationConditionRegex.Match(propertyGroup.Condition);
if (match.Success)
{
configurations.Add(match.Groups["config"].Value);
propertyGroups.Add(propertyGroup);
}
}
return configurations.ToArray();
}
/// <summary>
/// Replaces all configuration propertygroups with empty property groups corresponding to the expected configurations.
/// Doesn't attempt to preserve any content since it can all be regenerated.
/// Does attempt to preserve the ordering in the project file.
/// </summary>
/// <param name="project">Project</param>
/// <param name="oldPropertyGroups">PropertyGroups to remove</param>
/// <param name="newConfigurations"></param>
private static void ReplaceConfigurationPropertyGroups(ProjectRootElement project, IEnumerable<ProjectPropertyGroupElement> oldPropertyGroups, IEnumerable<string> newConfigurations)
{
ProjectElement insertAfter = null, insertBefore = null;
foreach (var oldPropertyGroup in oldPropertyGroups)
{
insertBefore = oldPropertyGroup.NextSibling;
project.RemoveChild(oldPropertyGroup);
}
if (insertBefore == null)
{
// find first itemgroup after imports
var insertAt = project.Imports.FirstOrDefault()?.NextSibling;
while (insertAt != null)
{
if (insertAt is ProjectItemGroupElement)
{
insertBefore = insertAt;
break;
}
insertAt = insertAt.NextSibling;
}
}
if (insertBefore == null)
{
// find last propertygroup after imports, defaulting to after imports
insertAfter = project.Imports.FirstOrDefault();
while (insertAfter?.NextSibling != null && insertAfter.NextSibling is ProjectPropertyGroupElement)
{
insertAfter = insertAfter.NextSibling;
}
}
foreach (var newConfiguration in newConfigurations)
{
var newPropertyGroup = project.CreatePropertyGroupElement();
newPropertyGroup.Condition = $"'$(Configuration)|$(Platform)' == '{newConfiguration}'";
if (insertBefore != null)
{
project.InsertBeforeChild(newPropertyGroup, insertBefore);
}
else if (insertAfter != null)
{
project.InsertAfterChild(newPropertyGroup, insertAfter);
}
else
{
project.AppendChild(newPropertyGroup);
}
insertBefore = null;
insertAfter = newPropertyGroup;
}
}
private static Dictionary<string, string> _guidMap = new Dictionary<string, string>();
private bool EnsureProjectGuid(ProjectRootElement project)
{
ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
string guid = string.Empty;
if (projectGuid != null)
{
guid = projectGuid.Value;
string projectName;
if (_guidMap.TryGetValue(guid, out projectName))
{
Log.LogMessage($"The ProjectGuid='{guid}' is duplicated across projects '{projectName}' and '{project.FullPath}', so creating a new one for project '{project.FullPath}'");
guid = Guid.NewGuid().ToString("B").ToUpper();
_guidMap.Add(guid, project.FullPath);
projectGuid.Value = guid;
return true;
}
else
{
_guidMap.Add(guid, project.FullPath);
}
}
if (projectGuid == null)
{
guid = Guid.NewGuid().ToString("B").ToUpper();
var propertyGroup = project.Imports.FirstOrDefault()?.NextSibling as ProjectPropertyGroupElement;
if (propertyGroup == null || !string.IsNullOrEmpty(propertyGroup.Condition))
{
propertyGroup = project.CreatePropertyGroupElement();
ProjectElement insertAfter = project.Imports.FirstOrDefault();
if (insertAfter == null)
{
insertAfter = project.Children.FirstOrDefault();
}
if (insertAfter != null)
{
project.InsertAfterChild(propertyGroup, insertAfter);
}
else
{
project.AppendChild(propertyGroup);
}
}
propertyGroup.AddProperty("ProjectGuid", guid);
return true;
}
return false;
}
private void UpdateSolution(ITaskItem solutionRootItem)
{
string solutionRootPath = Path.GetFullPath(solutionRootItem.ItemSpec);
string projectExclude = solutionRootItem.GetMetadata("ExcludePattern");
List<ProjectFolder> projectFolders = new List<ProjectFolder>();
if (!solutionRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
solutionRootPath += Path.DirectorySeparatorChar;
}
ProjectFolder testFolder = new ProjectFolder(solutionRootPath, "tests", "{1A2F9F4A-A032-433E-B914-ADD5992BB178}", projectExclude, true);
if (testFolder.FolderExists)
{
projectFolders.Add(testFolder);
}
ProjectFolder srcFolder = new ProjectFolder(solutionRootPath, "src", "{E107E9C1-E893-4E87-987E-04EF0DCEAEFD}", projectExclude);
if (srcFolder.FolderExists)
{
testFolder.DependsOn.Add(srcFolder);
projectFolders.Add(srcFolder);
};
ProjectFolder refFolder = new ProjectFolder(solutionRootPath, "ref", "{2E666815-2EDB-464B-9DF6-380BF4789AD4}", projectExclude);
if (refFolder.FolderExists)
{
srcFolder.DependsOn.Add(refFolder);
projectFolders.Add(refFolder);
}
if (projectFolders.Count == 0)
{
Log.LogMessage($"Directory '{solutionRootPath}' does not contain a 'src', 'tests', or 'ref' directory so skipping solution generation.");
return;
}
Log.LogMessage($"Generating solution for '{solutionRootPath}'...");
StringBuilder slnBuilder = new StringBuilder();
slnBuilder.AppendLine("Microsoft Visual Studio Solution File, Format Version 12.00");
slnBuilder.AppendLine("# Visual Studio 14");
slnBuilder.AppendLine("VisualStudioVersion = 14.0.25420.1");
slnBuilder.AppendLine("MinimumVisualStudioVersion = 10.0.40219.1");
// Output project items
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
string projectName = Path.GetFileNameWithoutExtension(slnProject.ProjectPath);
// Normalize the directory separators to the windows version given these are projects for VS and only work on windows.
string relativePathFromCurrentDirectory = slnProject.ProjectPath.Replace(solutionRootPath, "").Replace("/", "\\");
slnBuilder.AppendLine($"Project(\"{slnProject.SolutionGuid}\") = \"{projectName}\", \"{relativePathFromCurrentDirectory}\", \"{slnProject.ProjectGuid}\"");
bool writeEndProjectSection = false;
foreach (var dependentFolder in projectFolder.DependsOn)
{
foreach (var depProject in dependentFolder.Projects)
{
string depProjectId = depProject.ProjectGuid;
slnBuilder.AppendLine(
$"\tProjectSection(ProjectDependencies) = postProject\r\n\t\t{depProjectId} = {depProjectId}");
writeEndProjectSection = true;
}
}
if (writeEndProjectSection)
{
slnBuilder.AppendLine("\tEndProjectSection");
}
slnBuilder.AppendLine("EndProject");
}
}
// Output the solution folder items
foreach (var projectFolder in projectFolders)
{
slnBuilder.AppendLine($"Project(\"{projectFolder.SolutionGuid}\") = \"{projectFolder.Name}\", \"{projectFolder.Name}\", \"{projectFolder.ProjectGuid}\"\r\nEndProject");
}
string anyCPU = "Any CPU";
string slnDebug = "Debug|" + anyCPU;
string slnRelease = "Release|" + anyCPU;
// Output the solution configurations
slnBuilder.AppendLine("Global");
slnBuilder.AppendLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
slnBuilder.AppendLine($"\t\t{slnDebug} = {slnDebug}");
slnBuilder.AppendLine($"\t\t{slnRelease} = {slnRelease}");
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
// Output the solution to project configuration mappings
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
string projectConfig = slnProject.GetBestConfiguration("netcoreapp-Windows_NT");
if (!string.IsNullOrEmpty(projectConfig))
{
projectConfig += "-";
}
string[] slnConfigs = new string[] { slnDebug, slnRelease };
string[] markers = new string[] { "ActiveCfg", "Build.0" };
foreach (string slnConfig in slnConfigs)
{
foreach (string marker in markers)
{
slnBuilder.AppendLine($"\t\t{slnProject.ProjectGuid}.{slnConfig}.{marker} = {projectConfig}{slnConfig}");
}
}
}
}
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("\tGlobalSection(SolutionProperties) = preSolution");
slnBuilder.AppendLine("\t\tHideSolutionNode = FALSE");
slnBuilder.AppendLine("\tEndGlobalSection");
// Output the project to solution folder mappings
slnBuilder.AppendLine("\tGlobalSection(NestedProjects) = preSolution");
foreach (var projectFolder in projectFolders)
{
foreach (var slnProject in projectFolder.Projects)
{
slnBuilder.AppendLine($"\t\t{slnProject.ProjectGuid} = {projectFolder.ProjectGuid}");
}
}
slnBuilder.AppendLine("\tEndGlobalSection");
slnBuilder.AppendLine("EndGlobal");
string solutionName = GetNameForSolution(solutionRootPath);
string slnFile = Path.Combine(solutionRootPath, solutionName + ".sln");
File.WriteAllText(slnFile, slnBuilder.ToString());
}
private static string GetNameForSolution(string path)
{
if (path.Length < 0)
throw new ArgumentException("Invalid base bath for solution", nameof(path));
if (path[path.Length - 1] == Path.DirectorySeparatorChar || path[path.Length - 1] == Path.AltDirectorySeparatorChar)
{
return GetNameForSolution(path.Substring(0, path.Length - 1));
}
return Path.GetFileName(path);
}
internal class ProjectFolder
{
public string Name { get; }
public string ProjectGuid { get; }
public string SolutionGuid { get { return "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"; } }
public string ProjectFolderPath { get; }
public bool InUse { get; set; }
public List<ProjectFolder> DependsOn { get; set; } = new List<ProjectFolder>();
public bool FolderExists { get; }
public List<SolutionProject> Projects { get; }
public ProjectFolder(string basePath, string relPath, string projectId, string projectExcludePattern, bool searchRecursively = false)
{
Name = relPath;
ProjectGuid = projectId;
ProjectFolderPath = Path.Combine(basePath, relPath);
FolderExists = Directory.Exists(ProjectFolderPath);
Projects = new List<SolutionProject>();
if (FolderExists)
{
SearchOption searchOption = searchRecursively ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
Regex excludePattern = string.IsNullOrEmpty(projectExcludePattern) ? null : new Regex(projectExcludePattern);
string primaryProjectPrefix = Path.Combine(ProjectFolderPath, GetNameForSolution(basePath) + "." + relPath);
foreach (string proj in Directory.EnumerateFiles(ProjectFolderPath, "*proj", searchOption).OrderBy(p => p))
{
if (excludePattern == null || !excludePattern.IsMatch(proj))
{
if (proj.StartsWith(primaryProjectPrefix, StringComparison.OrdinalIgnoreCase))
{
// Always put the primary project first in the list
Projects.Insert(0, new SolutionProject(proj));
}
else
{
Projects.Add(new SolutionProject(proj));
}
}
}
}
}
}
internal class SolutionProject
{
public string ProjectPath { get; }
public string ProjectGuid { get; }
public string[] Configurations { get; set; }
public SolutionProject(string projectPath)
{
ProjectPath = projectPath;
ProjectGuid = ReadProjectGuid(projectPath);
string configurationProps = Path.Combine(Path.GetDirectoryName(projectPath), "Configurations.props");
if (File.Exists(configurationProps))
{
Configurations = GetConfigurationStrings(configurationProps, addSuffixes:false);
}
else
{
Configurations = new string[0];
}
}
public string GetBestConfiguration(string buildConfiguration)
{
//TODO: We should use the FindBestConfigutation logic from the build tasks
var match = Configurations.FirstOrDefault(c => c == buildConfiguration);
if (match != null)
return match;
match = Configurations.FirstOrDefault(c => buildConfiguration.StartsWith(c));
if (match != null)
return match;
// Try again with netstandard if we didn't find the specific build match.
buildConfiguration = "netstandard-Windows_NT";
match = Configurations.FirstOrDefault(c => c == buildConfiguration);
if (match != null)
return match;
match = Configurations.FirstOrDefault(c => buildConfiguration.StartsWith(c));
if (match != null)
return match;
if (Configurations.Length > 0)
return Configurations[0];
return string.Empty;
}
private static string ReadProjectGuid(string projectFile)
{
var project = ProjectRootElement.Open(projectFile);
ProjectPropertyElement projectGuid = project.Properties.FirstOrDefault(p => p.Name == "ProjectGuid");
if (projectGuid == null)
{
return Guid.NewGuid().ToString("B").ToUpper();
}
return projectGuid.Value;
}
public string SolutionGuid
{
get
{
//ProjectTypeGuids for different projects, pulled from the Visual Studio regkeys
//TODO: Clean up or map these to actual projects, this is fragile
string slnGuid = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"; // Windows (C#)
if (ProjectPath.Contains("VisualBasic.vbproj"))
{
slnGuid = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}"; //Windows (VB.NET)
}
if (ProjectPath.Contains("TestNativeService")) //Windows (Visual C++)
{
slnGuid = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
}
if (ProjectPath.Contains("WebServer.csproj")) //Web Application
{
slnGuid = "{349C5851-65DF-11DA-9384-00065B846F21}";
}
return slnGuid;
}
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
namespace Microsoft.Azure.CognitiveServices.Language.TextAnalytics
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for TextAnalyticsClient.
/// </summary>
public static partial class TextAnalyticsClientExtensions
{
/// <summary>
/// The API returns the detected language and a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate 100% certainty that the identified language is
/// true. A total of 120 languages are supported.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='languageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LanguageBatchResult> DetectLanguageBatchAsync(this ITextAnalyticsClient operations, LanguageBatchInput languageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(showStats, languageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The API returns a list of recognized entities in a given document.
/// </summary>
/// <remarks>
/// To get even more information on each recognized entity we recommend using
/// the Bing Entity Search API by querying for the recognized entities names.
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
/// languages in Text Analytics API</a> for the list of enabled
/// languages.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EntitiesBatchResult> EntitiesBatchAsync(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
using (var _result = await operations.EntitiesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The API returns a list of strings denoting the key talking points in the
/// input text.
/// </summary>
/// <remarks>
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by key phrase extraction.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze. Documents can now contain a language
/// field to indicate the text language
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<KeyPhraseBatchResult> KeyPhrasesBatchAsync(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
using (var _result = await operations.KeyPhrasesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The API returns a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate positive sentiment, while scores close to 0
/// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
/// (e.g. a factoid statement). See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by sentiment analysis.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SentimentBatchResult> SentimentBatchAsync(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
using (var _result = await operations.SentimentWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The API returns the detected language and a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate 100% certainty that the identified language is
/// true. A total of 120 languages are supported.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='countryHint'>
/// Contry hint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<LanguageResult> DetectLanguageAsync(
this ITextAnalyticsClient operations,
string inputText = default,
string countryHint = "US",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var languageBatchInput = new LanguageBatchInput(new List<LanguageInput> { new LanguageInput("1", inputText, countryHint) });
using (var _result = await operations.DetectLanguageWithHttpMessagesAsync(showStats, languageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
IList<DetectedLanguage> languages = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].DetectedLanguages : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new LanguageResult(languages, errorMessage, stats);
}
}
/// <summary>
/// The API returns a list of recognized entities in a given document.
/// </summary>
/// <remarks>
/// To get even more information on each recognized entity we recommend using
/// the Bing Entity Search API by querying for the recognized entities names.
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
/// languages in Text Analytics API</a> for the list of enabled
/// languages.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EntitiesResult> EntitiesAsync(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
using (var _result = await operations.EntitiesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
IList<EntityRecord> entities = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].Entities : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new EntitiesResult(entities, errorMessage, stats);
}
}
/// <summary>
/// The API returns a list of strings denoting the key talking points in the
/// input text.
/// </summary>
/// <remarks>
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by key phrase extraction.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<KeyPhraseResult> KeyPhrasesAsync(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
using (var _result = await operations.KeyPhrasesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
IList<string> keyPhrases = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].KeyPhrases : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new KeyPhraseResult(keyPhrases, errorMessage, stats);
}
}
/// <summary>
/// The API returns a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate positive sentiment, while scores close to 0
/// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
/// (e.g. a factoid statement). See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by sentiment analysis.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SentimentResult> SentimentAsync(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
using (var _result = await operations.SentimentWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false))
{
double? score = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].Score : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new SentimentResult(score, errorMessage, stats);
}
}
/// <summary>
/// The API returns the detected language and a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate 100% certainty that the identified language is
/// true. A total of 120 languages are supported.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='languageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static LanguageBatchResult DetectLanguageBatch(this ITextAnalyticsClient operations, LanguageBatchInput languageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
var _result = operations.DetectLanguageWithHttpMessagesAsync(showStats, languageBatchInput, null, cancellationToken).GetAwaiter().GetResult();
return _result.Body;
}
/// <summary>
/// The API returns a list of recognized entities in a given document.
/// </summary>
/// <remarks>
/// To get even more information on each recognized entity we recommend using
/// the Bing Entity Search API by querying for the recognized entities names.
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
/// languages in Text Analytics API</a> for the list of enabled
/// languages.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static EntitiesBatchResult EntitiesBatch(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
var _result = operations.EntitiesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
return _result.Body;
}
/// <summary>
/// The API returns a list of strings denoting the key talking points in the
/// input text.
/// </summary>
/// <remarks>
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by key phrase extraction.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze. Documents can now contain a language
/// field to indicate the text language
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static KeyPhraseBatchResult KeyPhrasesBatch(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
var _result = operations.KeyPhrasesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
return _result.Body;
}
/// <summary>
/// The API returns a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate positive sentiment, while scores close to 0
/// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
/// (e.g. a factoid statement). See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by sentiment analysis.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='multiLanguageBatchInput'>
/// Collection of documents to analyze.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static SentimentBatchResult SentimentBatch(this ITextAnalyticsClient operations, MultiLanguageBatchInput multiLanguageBatchInput = default, bool? showStats = default, CancellationToken cancellationToken = default)
{
var _result = operations.SentimentWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
return _result.Body;
}
/// <summary>
/// The API returns the detected language and a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate 100% certainty that the identified language is
/// true. A total of 120 languages are supported.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='countryHint'>
/// Contry hint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static LanguageResult DetectLanguage(
this ITextAnalyticsClient operations,
string inputText = default,
string countryHint = "US",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var languageBatchInput = new LanguageBatchInput(new List<LanguageInput> { new LanguageInput("1", inputText, countryHint) });
var _result = operations.DetectLanguageWithHttpMessagesAsync(showStats, languageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
IList<DetectedLanguage> languages = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].DetectedLanguages : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new LanguageResult(languages, errorMessage, stats);
}
/// <summary>
/// The API returns a list of recognized entities in a given document.
/// </summary>
/// <remarks>
/// To get even more information on each recognized entity we recommend using
/// the Bing Entity Search API by querying for the recognized entities names.
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/text-analytics-supported-languages">Supported
/// languages in Text Analytics API</a> for the list of enabled
/// languages.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static EntitiesResult Entities(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
var _result = operations.EntitiesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
IList<EntityRecord> entities = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].Entities : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new EntitiesResult(entities, errorMessage, stats);
}
/// <summary>
/// The API returns a list of strings denoting the key talking points in the
/// input text.
/// </summary>
/// <remarks>
/// See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by key phrase extraction.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static KeyPhraseResult KeyPhrases(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
var _result = operations.KeyPhrasesWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
IList<string> keyPhrases = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].KeyPhrases : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new KeyPhraseResult(keyPhrases, errorMessage, stats);
}
/// <summary>
/// The API returns a numeric score between 0 and 1.
/// </summary>
/// <remarks>
/// Scores close to 1 indicate positive sentiment, while scores close to 0
/// indicate negative sentiment. A score of 0.5 indicates the lack of sentiment
/// (e.g. a factoid statement). See the <a
/// href="https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#supported-languages">Text
/// Analytics Documentation</a> for details about the languages that are
/// supported by sentiment analysis.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='showStats'>
/// (optional) if set to true, response will contain input and document level
/// statistics.
/// </param>
/// <param name='inputText'>
/// Input text of one document.
/// </param>
/// <param name='language'>
/// Language code.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static SentimentResult Sentiment(
this ITextAnalyticsClient operations,
string inputText = default,
string language = "en",
bool? showStats = default,
CancellationToken cancellationToken = default)
{
var multiLanguageBatchInput = new MultiLanguageBatchInput(new List<MultiLanguageInput> { new MultiLanguageInput("1", inputText, language) });
var _result = operations.SentimentWithHttpMessagesAsync(showStats, multiLanguageBatchInput, null, cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult();
double? score = _result.Body.Documents.Count > 0 ? _result.Body.Documents[0].Score : null;
string errorMessage = _result.Body.Errors.Count > 0 ? _result.Body.Errors[0].Message : null;
RequestStatistics stats = _result.Body.Statistics;
return new SentimentResult(score, errorMessage, stats);
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Collections.Generic;
namespace Hydra.Framework.Conversions
{
//
// **********************************************************************
/// <summary>
/// Class for load data from text file into DataTable.
/// </summary>
// **********************************************************************
//
public class ConvertTextFileLoader
{
#region Member Variables
//
// **********************************************************************
/// <summary>
/// Data File StateName
/// </summary>
// **********************************************************************
//
protected string m_DataFileName = null;
//
// **********************************************************************
/// <summary>
/// File Format
/// </summary>
// **********************************************************************
//
protected NxFileFormat m_FileFormat = NxFileFormat.Delimited;
//
// **********************************************************************
/// <summary>
/// Separator
/// </summary>
// **********************************************************************
//
protected string m_Separator = ",";
//
// **********************************************************************
/// <summary>
/// Text Qualifier
/// </summary>
// **********************************************************************
//
protected char m_TextQualifier = '\"';
//
// **********************************************************************
/// <summary>
/// First Row has Column Names
/// </summary>
// **********************************************************************
//
protected bool m_IsFirstRowHasColumnNames = false;
/// <summary>
/// Decimal Separator
/// </summary>
protected char m_DecimalSeparator = '.';
//
// **********************************************************************
/// <summary>
/// List of Source Columns
/// </summary>
// **********************************************************************
//
protected ArrayList m_SourceColumnList = new ArrayList();
//
// **********************************************************************
/// <summary>
/// Source Column Hashmap
/// </summary>
// **********************************************************************
//
protected Hashtable m_SourceColumnMap = new Hashtable();
//
// **********************************************************************
/// <summary>
/// Target Column List
/// </summary>
// **********************************************************************
//
protected ArrayList m_TargetColumnList = new ArrayList();
//
// **********************************************************************
/// <summary>
/// Target Column Hashmap
/// </summary>
// **********************************************************************
//
protected Hashtable m_TargetColumnMap = new Hashtable();
//
// **********************************************************************
/// <summary>
/// Source Table
/// </summary>
// **********************************************************************
//
protected DataTable m_SourceTable = new DataTable();
//
// **********************************************************************
/// <summary>
/// Target Table
/// </summary>
// **********************************************************************
//
protected DataTable m_TargetTable = new DataTable();
//
// **********************************************************************
/// <summary>
/// CSV Content
/// </summary>
// **********************************************************************
//
private string m_CsvContent;
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="ConvertTextFileLoader"/> class.
/// </summary>
/// <param name="dataFileName">StateName of the data file.</param>
/// <param name="xmlDescFileName">StateName of the XML desc file.</param>
// **********************************************************************
//
public ConvertTextFileLoader(string dataFileName, string xmlDescFileName)
{
m_DataFileName = dataFileName;
LoadXmlDescription(ConvertXml.LoadDocument(xmlDescFileName));
}
//
// **********************************************************************
/// <summary>
/// Constructor.
/// </summary>
/// <param name="dataFileName">StateName of the data file.</param>
/// <param name="xmlDoc">The XML doc.</param>
// **********************************************************************
//
public ConvertTextFileLoader(string dataFileName, XmlDocument xmlDoc)
{
m_DataFileName = dataFileName;
LoadXmlDescription(xmlDoc);
}
//
// **********************************************************************
/// <summary>
/// Constructor.
/// </summary>
/// <param name="xmlDoc">The XML doc.</param>
// **********************************************************************
//
public ConvertTextFileLoader(XmlDocument xmlDoc)
{
LoadXmlDescription(xmlDoc);
}
#endregion
#region Properties
//
// **********************************************************************
/// <summary>
/// Gets the content of the CSV.
/// </summary>
/// <value>The content of the CSV.</value>
// **********************************************************************
//
public string CsvContent
{
get
{
return m_CsvContent;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets data file name.
/// </summary>
/// <value>The name of the data file.</value>
// **********************************************************************
//
public string DataFileName
{
get
{
return m_DataFileName;
}
set
{
m_DataFileName = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets data file format.
/// </summary>
/// <value>The file format.</value>
// **********************************************************************
//
public NxFileFormat FileFormat
{
get
{
return m_FileFormat;
}
set
{
m_FileFormat = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets field separator.
/// </summary>
/// <value>The separator.</value>
// **********************************************************************
//
public string Separator
{
get
{
return m_Separator;
}
set
{
m_Separator = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets field text qualifier.
/// </summary>
/// <value>The text qualifier.</value>
// **********************************************************************
//
public char TextQualifier
{
get
{
return m_TextQualifier;
}
set
{
m_TextQualifier = value;
}
}
//
// **********************************************************************
/// <summary>
/// True if first row should contain column names.
/// </summary>
/// <value>
/// <c>true</c> if this instance is first row has column names; otherwise, <c>false</c>.
/// </value>
// **********************************************************************
//
public bool IsFirstRowHasColumnNames
{
get
{
return m_IsFirstRowHasColumnNames;
}
set
{
m_IsFirstRowHasColumnNames = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets decimal separator.
/// </summary>
/// <value>The decimal separator.</value>
// **********************************************************************
//
public char DecimalSeparator
{
get
{
return m_DecimalSeparator;
}
set
{
m_DecimalSeparator = value;
}
}
#endregion
#region Protected / Internal Methods
//
// **********************************************************************
/// <summary>
/// Loads file description from the XML document.
/// </summary>
/// <param name="xmlDoc">The XML doc.</param>
// **********************************************************************
//
protected void LoadXmlDescription(XmlDocument xmlDoc)
{
if (xmlDoc != null &&
xmlDoc.DocumentElement != null)
{
XmlElement rootElement = xmlDoc.DocumentElement;
m_FileFormat = ConvertEnum.Parse<NxFileFormat>(ConvertXml.GetAttr(rootElement, "format"), NxFileFormat.Delimited);
m_Separator = ConvertXml.GetAttr(rootElement, "separator");
string textQualifier = ConvertXml.GetAttr(rootElement, "text_qualifier");
m_TextQualifier = ConvertUtils.NotEmpty(textQualifier) ? textQualifier[0] : '\x0';
m_IsFirstRowHasColumnNames = ConvertBool.Parse(ConvertXml.GetAttr(rootElement, "first_row_has_column_names"));
string decimalSeparator = ConvertXml.GetAttr(rootElement, "decimal_separator");
m_DecimalSeparator = ConvertUtils.NotEmpty(decimalSeparator) ? decimalSeparator[0] : '.';
XmlElement columnsElement = (XmlElement)rootElement.SelectSingleNode("columns");
if (columnsElement != null)
{
foreach (XmlElement element in columnsElement.SelectNodes("column"))
{
ColumnDescription columnDesc = new ColumnDescription(element);
m_SourceColumnList.Add(columnDesc);
m_SourceColumnMap.Add(columnDesc.Name, columnDesc);
}
}
XmlElement targetColumnsElement = (XmlElement)rootElement.SelectSingleNode("target_columns");
if (targetColumnsElement != null)
{
foreach (XmlElement element in targetColumnsElement.SelectNodes("column"))
{
ColumnDescription columnDesc = new ColumnDescription(element);
m_TargetColumnList.Add(columnDesc);
m_TargetColumnMap.Add(columnDesc.Name, columnDesc);
}
}
}
}
//
// **********************************************************************
/// <summary>
/// Returns line data splitted to text values of columns.
/// </summary>
/// <param name="line">The line.</param>
/// <returns></returns>
// **********************************************************************
//
protected string[] GetSplittedLineData(string line)
{
if (ConvertUtils.NotEmpty(line))
{
IList<string> list = null;
if (m_FileFormat == NxFileFormat.Delimited)
{
list = ConvertText.DecomposeWithSeparator(line, m_Separator, m_TextQualifier);
}
else if (m_FileFormat == NxFileFormat.Fixed)
{
list = new List<string>();
int currentIndex = 0;
foreach (ColumnDescription columnDesc in m_SourceColumnList)
{
string s = null;
if (columnDesc.FixedSize > 0 &&
currentIndex + columnDesc.FixedSize <= line.Length)
s = line.Substring(currentIndex, columnDesc.FixedSize);
if (s != null)
list.Add(s.Trim());
currentIndex += columnDesc.FixedSize;
}
}
if (list != null)
{
string[] array = new string[list.Count];
list.CopyTo(array, 0);
return array;
}
}
return null;
}
//
// **********************************************************************
/// <summary>
/// Returns pre-processed line value.
/// Strips special characters from the line.
/// </summary>
/// <param name="line">The line.</param>
/// <returns></returns>
// **********************************************************************
//
protected string GetPreProcessedLine(string line)
{
if (ConvertUtils.NotEmpty(line))
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < line.Length; i++)
{
char ch = line[i];
if (ch >= 32 ||
char.IsWhiteSpace(ch))
sb.Append(line[i]);
}
return sb.ToString().Trim();
}
return null;
}
//
// **********************************************************************
/// <summary>
/// Returns pre-processed text value.
/// </summary>
/// <param name="columnDesc">The column desc.</param>
/// <param name="textValue">The text value.</param>
/// <returns></returns>
// **********************************************************************
//
protected string GetPreProcessedTextValue(ColumnDescription columnDesc, string textValue)
{
if (ConvertUtils.NotEmpty(textValue))
{
if (ConvertType.IsNumber(columnDesc.DataType))
return textValue.Replace(new String(m_DecimalSeparator, 1), NumberFormatInfo.InvariantInfo.CurrencyDecimalSeparator);
}
return textValue;
}
#endregion
#region Public Methods
//
// **********************************************************************
/// <summary>
/// Reads the full CSV line from the reader, taking into account any possible
/// caret returns inside it.
/// </summary>
/// <param name="reader">the reader to read by</param>
/// <returns>the full line read</returns>
// **********************************************************************
//
public string ReadFullLine(StreamReader reader)
{
string line = reader.ReadLine();
while (ConvertText.CalcEntriesAmount(line, "\"") % 2 == 1)
line += Environment.NewLine + reader.ReadLine();
return line;
}
//
// **********************************************************************
/// <summary>
/// Loads data from text file into the data table.
/// </summary>
/// <param name="csvContent">Content of the CSV.</param>
/// <returns></returns>
// **********************************************************************
//
public DataTable LoadData(string csvContent)
{
m_CsvContent = csvContent;
return LoadData();
}
//
// **********************************************************************
/// <summary>
/// Loads data from text file into the data table.
/// </summary>
/// <returns></returns>
// **********************************************************************
//
public DataTable LoadData()
{
m_SourceTable.Clear();
m_SourceTable.Columns.Clear();
m_TargetTable.Clear();
m_TargetTable.Columns.Clear();
foreach (ColumnDescription columnDesc in m_SourceColumnList)
m_SourceTable.Columns.Add(columnDesc.Name, columnDesc.DataType);
foreach (ColumnDescription columnDesc in m_TargetColumnList)
m_TargetTable.Columns.Add(columnDesc.Name, columnDesc.DataType);
//
// Read source file into the source data table.
//
StreamReader reader;
if (CsvContent == null)
reader = File.OpenText(m_DataFileName);
else
{
MemoryStream ms = new MemoryStream();
byte[] csvBytes = Encoding.UTF8.GetBytes(CsvContent);
ms.Write(csvBytes, 0, csvBytes.Length);
ms.Position = 0;
reader = new StreamReader(ms);
}
try
{
Hashtable columnNameMap = null;
int lineIndex = 0;
string line = ReadFullLine(reader);
while (line != null)
{
line = GetPreProcessedLine(line);
if (lineIndex == 0 && m_IsFirstRowHasColumnNames)
{
//
// Get column names map from the first line
//
string[] names = GetSplittedLineData(line);
if (names != null && names.Length > 0)
{
columnNameMap = new Hashtable();
for (int i = 0; i < names.Length; i++)
columnNameMap[names[i]] = i;
}
}
else
{
//
// Read values from the text line
//
string[] values = GetSplittedLineData(line);
if (values != null && values.Length > 0)
{
DataRow dr = m_SourceTable.NewRow();
for (int i = 0; i < m_SourceTable.Columns.Count; i++)
{
DataColumn dc = m_SourceTable.Columns[i];
int valueIndex = i;
if (columnNameMap != null)
valueIndex = ConvertInt.Parse(columnNameMap[dc.ColumnName], -1);
if (valueIndex >= 0 && valueIndex < values.Length)
{
ColumnDescription columnDesc = (ColumnDescription)m_SourceColumnMap[dc.ColumnName];
if (columnDesc != null)
{
string textValue = GetPreProcessedTextValue(columnDesc, values[valueIndex]);
dr[dc] = columnDesc.GetDataValue(textValue);
}
}
}
m_SourceTable.Rows.Add(dr);
}
}
lineIndex++;
line = ReadFullLine(reader);
}
}
finally
{
reader.Close();
}
if (m_SourceTable.Columns.Count > 0)
{
if (m_TargetTable.Columns.Count > 0)
{
//
// Map from source data table to the target data table
//
foreach (DataRow sourceRow in m_SourceTable.Rows)
{
DataRow targetRow = m_TargetTable.NewRow();
foreach (DataColumn targetColumn in m_TargetTable.Columns)
{
ColumnDescription columnDesc = (ColumnDescription)m_TargetColumnMap[targetColumn.ColumnName];
if (columnDesc != null && ConvertUtils.NotEmpty(columnDesc.SourceColumnName))
{
int sourceIndex = m_SourceTable.Columns.IndexOf(columnDesc.SourceColumnName);
if (sourceIndex >= 0)
targetRow[targetColumn] = sourceRow[sourceIndex];
}
}
m_TargetTable.Rows.Add(targetRow);
}
return m_TargetTable;
}
else
{
return m_SourceTable;
}
}
return null;
}
#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.DataLake.Store
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
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>
/// TrustedIdProvidersOperations operations.
/// </summary>
internal partial class TrustedIdProvidersOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, ITrustedIdProvidersOperations
{
/// <summary>
/// Initializes a new instance of the TrustedIdProvidersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TrustedIdProvidersOperations(DataLakeStoreAccountManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DataLakeStoreAccountManagementClient
/// </summary>
public DataLakeStoreAccountManagementClient Client { get; private set; }
/// <summary>
/// Creates or updates the specified trusted identity provider. During update,
/// the trusted identity provider with the specified name will be replaced with
/// this new provider
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to add or replace the trusted
/// identity provider.
/// </param>
/// <param name='trustedIdProviderName'>
/// The name of the trusted identity provider. This is used for differentiation
/// of providers in the account.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or replace the trusted identity provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TrustedIdProvider>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (trustedIdProviderName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("trustedIdProviderName", trustedIdProviderName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TrustedIdProvider>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_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>
/// Updates the specified trusted identity provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to which to update the trusted
/// identity provider.
/// </param>
/// <param name='trustedIdProviderName'>
/// The name of the trusted identity provider. This is used for differentiation
/// of providers in the account.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the trusted identity provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TrustedIdProvider>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, UpdateTrustedIdProviderParameters parameters = default(UpdateTrustedIdProviderParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (trustedIdProviderName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("trustedIdProviderName", trustedIdProviderName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_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(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TrustedIdProvider>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_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>
/// Deletes the specified trusted identity provider from the specified Data
/// Lake Store account
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to delete the trusted
/// identity provider.
/// </param>
/// <param name='trustedIdProviderName'>
/// The name of the trusted identity provider to delete.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (trustedIdProviderName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("trustedIdProviderName", trustedIdProviderName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_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 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the specified Data Lake Store trusted identity provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to get the trusted
/// identity provider.
/// </param>
/// <param name='trustedIdProviderName'>
/// The name of the trusted identity provider to retrieve.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<TrustedIdProvider>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (trustedIdProviderName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("trustedIdProviderName", trustedIdProviderName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<TrustedIdProvider>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_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>
/// Lists the Data Lake Store trusted identity providers within the specified
/// Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake Store
/// account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account from which to get the trusted
/// identity providers.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<TrustedIdProvider>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/trustedIdProviders").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<TrustedIdProvider>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_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>
/// Lists the Data Lake Store trusted identity providers within the specified
/// Data Lake Store account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<TrustedIdProvider>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAccountNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<TrustedIdProvider>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_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;
}
}
}
| |
// 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 414
using System;
public class A{
//////////////////////////////
// Instance Fields
public int FldAPubInst;
private int FldAPrivInst;
protected int FldAFamInst; //Translates to "family"
internal int FldAAsmInst; //Translates to "assembly"
protected internal int FldAFoaInst; //Translates to "famorassem"
//////////////////////////////
// Static Fields
public static int FldAPubStat;
private static int FldAPrivStat;
protected static int FldAFamStat; //family
internal static int FldAAsmStat; //assembly
protected internal static int FldAFoaStat; //famorassem
//////////////////////////////////////
// Instance fields for nested classes
public ClsA ClsAPubInst = new ClsA();
private ClsA ClsAPrivInst = new ClsA();
protected ClsA ClsAFamInst = new ClsA();
internal ClsA ClsAAsmInst = new ClsA();
protected internal ClsA ClsAFoaInst = new ClsA();
/////////////////////////////////////
// Static fields of nested classes
public static ClsA ClsAPubStat = new ClsA();
private static ClsA ClsAPrivStat = new ClsA();
//////////////////////////////
// Instance Methods
public int MethAPubInst(){
Console.WriteLine("A::MethAPubInst()");
return 100;
}
private int MethAPrivInst(){
Console.WriteLine("A::MethAPrivInst()");
return 100;
}
protected int MethAFamInst(){
Console.WriteLine("A::MethAFamInst()");
return 100;
}
internal int MethAAsmInst(){
Console.WriteLine("A::MethAAsmInst()");
return 100;
}
protected internal int MethAFoaInst(){
Console.WriteLine("A::MethAFoaInst()");
return 100;
}
//////////////////////////////
// Static Methods
public static int MethAPubStat(){
Console.WriteLine("A::MethAPubStat()");
return 100;
}
private static int MethAPrivStat(){
Console.WriteLine("A::MethAPrivStat()");
return 100;
}
protected static int MethAFamStat(){
Console.WriteLine("A::MethAFamStat()");
return 100;
}
internal static int MethAAsmStat(){
Console.WriteLine("A::MethAAsmStat()");
return 100;
}
protected internal static int MethAFoaStat(){
Console.WriteLine("A::MethAFoaStat()");
return 100;
}
//////////////////////////////
// Virtual Instance Methods
public virtual int MethAPubVirt(){
Console.WriteLine("A::MethAPubVirt()");
return 100;
}
//@csharp - Note that C# won't compile an illegal private virtual function
//So there is no negative testing MethAPrivVirt() here.
protected virtual int MethAFamVirt(){
Console.WriteLine("A::MethAFamVirt()");
return 100;
}
internal virtual int MethAAsmVirt(){
Console.WriteLine("A::MethAAsmVirt()");
return 100;
}
protected internal virtual int MethAFoaVirt(){
Console.WriteLine("A::MethAFoaVirt()");
return 100;
}
public class ClsA{
public int Test(){
int mi_RetCode = 100;
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// ACCESS ENCLOSING FIELDS/MEMBERS
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
//@csharp - C# will not allow nested classes to access non-static members of their enclosing classes
/////////////////////////////////
// Test static field access
FldAPubStat = 100;
if(FldAPubStat != 100)
mi_RetCode = 0;
FldAFamStat = 100;
if(FldAFamStat != 100)
mi_RetCode = 0;
FldAAsmStat = 100;
if(FldAAsmStat != 100)
mi_RetCode = 0;
FldAFoaStat = 100;
if(FldAFoaStat != 100)
mi_RetCode = 0;
/////////////////////////////////
// Test static method access
if(MethAPubStat() != 100)
mi_RetCode = 0;
if(MethAFamStat() != 100)
mi_RetCode = 0;
if(MethAAsmStat() != 100)
mi_RetCode = 0;
if(MethAFoaStat() != 100)
mi_RetCode = 0;
return mi_RetCode;
}
//////////////////////////////
// Instance Fields
public int NestFldAPubInst;
private int NestFldAPrivInst;
protected int NestFldAFamInst; //Translates to "family"
internal int NestFldAAsmInst; //Translates to "assembly"
protected internal int NestFldAFoaInst; //Translates to "famorassem"
//////////////////////////////
// Static Fields
public static int NestFldAPubStat;
private static int NestFldAPrivStat;
protected static int NestFldAFamStat; //family
internal static int NestFldAAsmStat; //assembly
protected internal static int NestFldAFoaStat; //famorassem
//////////////////////////////
// Instance NestMethAods
public int NestMethAPubInst(){
Console.WriteLine("A::NestMethAPubInst()");
return 100;
}
private int NestMethAPrivInst(){
Console.WriteLine("A::NestMethAPrivInst()");
return 100;
}
protected int NestMethAFamInst(){
Console.WriteLine("A::NestMethAFamInst()");
return 100;
}
internal int NestMethAAsmInst(){
Console.WriteLine("A::NestMethAAsmInst()");
return 100;
}
protected internal int NestMethAFoaInst(){
Console.WriteLine("A::NestMethAFoaInst()");
return 100;
}
//////////////////////////////
// Static NestMethods
public static int NestMethAPubStat(){
Console.WriteLine("A::NestMethAPubStat()");
return 100;
}
private static int NestMethAPrivStat(){
Console.WriteLine("A::NestMethAPrivStat()");
return 100;
}
protected static int NestMethAFamStat(){
Console.WriteLine("A::NestMethAFamStat()");
return 100;
}
internal static int NestMethAAsmStat(){
Console.WriteLine("A::NestMethAAsmStat()");
return 100;
}
protected internal static int NestMethAFoaStat(){
Console.WriteLine("A::NestMethAFoaStat()");
return 100;
}
//////////////////////////////
// Virtual Instance NestMethods
public virtual int NestMethAPubVirt(){
Console.WriteLine("A::NestMethAPubVirt()");
return 100;
}
//@csharp - Note that C# won't compile an illegal private virtual function
//So there is no negative testing NestMethAPrivVirt() here.
protected virtual int NestMethAFamVirt(){
Console.WriteLine("A::NestMethAFamVirt()");
return 100;
}
internal virtual int NestMethAAsmVirt(){
Console.WriteLine("A::NestMethAAsmVirt()");
return 100;
}
protected internal virtual int NestMethAFoaVirt(){
Console.WriteLine("A::NestMethAFoaVirt()");
return 100;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Stardust.Interstellar.Rest.Annotations;
using Stardust.Interstellar.Rest.Common;
namespace Stardust.Interstellar.Rest.Service
{
class ServiceBuilder
{
private AssemblyBuilder myAssemblyBuilder;
private ModuleBuilder myModuleBuilder;
public ServiceBuilder()
{
var myCurrentDomain = AppDomain.CurrentDomain;
var myAssemblyName = new AssemblyName();
myAssemblyName.Name = Guid.NewGuid().ToString().Replace("-", "") + "_ServiceWrapper";
myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.RunAndSave);
myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule", "service.dll");
}
public Type CreateServiceImplementation<T>()
{
return CreateServiceImplementation(typeof(T));
}
public Type CreateServiceImplementation(Type interfaceType)
{
try
{
ExtensionsFactory.GetService<ILogger>()?.Message("Generating webapi controller for {0}", interfaceType.FullName);
var type = CreateServiceType(interfaceType);
ctor(type, interfaceType);
foreach (var methodInfo in interfaceType.GetMethods().Length == 0 ? interfaceType.GetInterfaces().First().GetMethods() : interfaceType.GetMethods())
{
if (typeof(Task).IsAssignableFrom(methodInfo.ReturnType))
{
if (methodInfo.ReturnType.GetGenericArguments().Length == 0)
{
BuildAsyncVoidMethod(type, methodInfo);
}
else BuildAsyncMethod(type, methodInfo);
}
else
{
if (methodInfo.ReturnType == typeof(void)) BuildVoidMethod(type, methodInfo);
else BuildMethod(type, methodInfo);
}
}
return type.CreateType();
}
catch (Exception ex)
{
ExtensionsFactory.GetService<ILogger>()?.Error(ex);
ExtensionsFactory.GetService<ILogger>()?.Message("Skipping type: {0}", interfaceType.FullName);
return null;
}
}
public MethodBuilder InternalMethodBuilder(TypeBuilder type, MethodInfo implementationMethod, Func<MethodInfo, MethodBuilder, Type[], List<ParameterWrapper>, MethodBuilder> bodyBuilder)
{
List<ParameterWrapper> methodParams;
Type[] pTypes;
var method = DefineMethod(type, implementationMethod, out methodParams, out pTypes);
return bodyBuilder(implementationMethod, method, pTypes, methodParams);
}
public MethodBuilder BuildMethod(TypeBuilder type, MethodInfo implementationMethod)
{
return InternalMethodBuilder(type, implementationMethod, BodyImplementer);
}
private static MethodBuilder BodyImplementer(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List<ParameterWrapper> methodParams)
{
MethodInfo gatherParams = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType)
.GetMethod("GatherParameters", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(String), typeof(Object[]) }, null);
var baseType = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType);
var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation");
MethodInfo getValue = typeof(ParameterWrapper).GetMethod("get_value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
MethodInfo createResponse = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponse", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (implementationMethod.ReturnType == typeof(void)) createResponse = createResponse.MakeGenericMethod(typeof(object));
else createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType);
MethodInfo method9 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType)
.GetMethod("CreateErrorResponse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Exception) }, null);
// Setting return type
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder parameters = gen.DeclareLocal(typeof(Object[]));
LocalBuilder serviceParameters = gen.DeclareLocal(typeof(ParameterWrapper[]));
LocalBuilder result = gen.DeclareLocal(typeof(String));
LocalBuilder message = gen.DeclareLocal(typeof(HttpResponseMessage));
LocalBuilder ex = gen.DeclareLocal(typeof(Exception));
// Preparing labels
Label label97 = gen.DefineLabel();
// Writing body
gen.Emit(OpCodes.Nop);
gen.BeginExceptionBlock();
gen.Emit(OpCodes.Nop);
var ps = pTypes;
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j];
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, implementationMethod.Name);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, gatherParams);
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, implementation);
int iii = 0;
foreach (var parameterWrapper in methodParams)
{
gen.Emit(OpCodes.Ldloc_1);
EmitHelpers.EmitInt32(gen, iii);
gen.Emit(OpCodes.Ldelem_Ref);
gen.Emit(OpCodes.Callvirt, getValue);
if (parameterWrapper.Type.IsValueType) gen.Emit(OpCodes.Unbox_Any, parameterWrapper.Type);
else gen.Emit(OpCodes.Castclass, parameterWrapper.Type);
iii++;
}
gen.Emit(OpCodes.Callvirt, implementationMethod);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4, 200);
if (implementationMethod.ReturnType != typeof(void)) gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Call, createResponse);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Leave_S, label97);
gen.BeginCatchBlock(typeof(Exception));
gen.Emit(OpCodes.Stloc_S, 4);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_S, 4);
gen.Emit(OpCodes.Call, method9);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Leave_S, label97);
gen.EndExceptionBlock();
gen.MarkLabel(label97);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private static MethodBuilder DefineMethod(TypeBuilder type, MethodInfo implementationMethod, out List<ParameterWrapper> methodParams, out Type[] pTypes)
{
// Declaring method builder
// Method attributes
const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot;
var method = type.DefineMethod(implementationMethod.Name, methodAttributes);
// Preparing Reflection instances
var route = typeof(RouteAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);
var httpGet = httpMethodAttribute(implementationMethod);
var uriAttrib = typeof(FromUriAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
var bodyAttrib = typeof(FromBodyAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
method.SetReturnType(typeof(Task).IsAssignableFrom(implementationMethod.ReturnType) ? typeof(Task<HttpResponseMessage>) : typeof(HttpResponseMessage));
// Adding parameters
methodParams = GetMethodParams(implementationMethod);
pTypes = methodParams.Where(p => p.In != InclutionTypes.Header).Select(p => p.Type).ToArray();
method.SetParameters(pTypes.ToArray());
// Parameter id
int pid = 1;
foreach (var parameterWrapper in methodParams.Where(p => p.In != InclutionTypes.Header))
{
try
{
var p = method.DefineParameter(pid, ParameterAttributes.None, parameterWrapper.Name);
if (parameterWrapper.In == InclutionTypes.Path) p.SetCustomAttribute(new CustomAttributeBuilder(uriAttrib, new Type[] { }));
else if (parameterWrapper.In == InclutionTypes.Body) p.SetCustomAttribute(new CustomAttributeBuilder(bodyAttrib, new Type[] { }));
pid++;
}
catch (Exception)
{
throw;
}
}
DefineAuthorizeAttributes(implementationMethod, method);
// Adding custom attributes to method
// [RouteAttribute]
var template = implementationMethod.GetCustomAttribute<RouteAttribute>()?.Template;
if (template == null) template = ExtensionsFactory.GetServiceTemplate(implementationMethod);
method.SetCustomAttribute(new CustomAttributeBuilder(route, new[] { template }));
// [HttpGetAttribute]
method.SetCustomAttribute(new CustomAttributeBuilder(httpGet, new Type[] { }));
ConstructorInfo ctor5 = typeof(ResponseTypeAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Type) }, null);
method.SetCustomAttribute(new CustomAttributeBuilder(ctor5, new object[] { GetReturnType(implementationMethod) }));
return method;
}
private static void DefineAuthorizeAttributes(MethodInfo implementationMethod, MethodBuilder method)
{
var authorizeAttribs = implementationMethod.GetCustomAttributes<AuthorizeWrapperAttribute>().ToList();
var classAuthorizeAttribs = implementationMethod.DeclaringType.GetCustomAttributes<AuthorizeWrapperAttribute>();
var authorizeWrapperAttributes = classAuthorizeAttribs as AuthorizeWrapperAttribute[] ?? classAuthorizeAttribs.ToArray();
if (classAuthorizeAttribs != null && authorizeWrapperAttributes.Any()) authorizeAttribs.AddRange(authorizeWrapperAttributes);
if (authorizeAttribs.Any())
{
foreach (var authorizeWrapperAttribute in authorizeAttribs)
{
var authAtrib = authorizeWrapperAttribute.GetAutorizationAttribute();
var ctorParams = authorizeWrapperAttribute.GetConstructorParameters();
var ctor = authAtrib.GetType().GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, (from p in ctorParams select p.GetType()).ToArray(), null);
var props = authAtrib.GetType().GetProperties().Where(p=>p.SetMethod!=null);
var propVals = props.Select(p => p.GetMethod.Invoke(authAtrib, null));
method.SetCustomAttribute(new CustomAttributeBuilder(ctor, ctorParams,props.ToArray(),propVals.ToArray()));
}
}
}
private static Type GetReturnType(MethodInfo implementationMethod)
{
if (typeof(Task).IsAssignableFrom(implementationMethod.ReturnType))
{
if (implementationMethod.ReturnType.IsGenericType) return implementationMethod.ReturnType.GenericTypeArguments.FirstOrDefault();
else return typeof(void);
}
return implementationMethod.ReturnType;
}
private static List<ParameterWrapper> GetMethodParams(MethodInfo implementationMethod)
{
var resolver = ExtensionsFactory.GetService<IServiceParameterResolver>();
var resolvedParams = resolver?.ResolveParameters(implementationMethod);
if (resolvedParams != null && resolvedParams.Count() == implementationMethod.GetParameters().Length) return resolvedParams.ToList();
var methodParams = new List<ParameterWrapper>();
foreach (var parameterInfo in implementationMethod.GetParameters())
{
var @in = parameterInfo.GetCustomAttribute<InAttribute>(true);
if (@in == null)
{
var fromBody = parameterInfo.GetCustomAttribute<FromBodyAttribute>(true);
if (fromBody != null) @in = new InAttribute(InclutionTypes.Body);
if (@in == null)
{
var fromUri = parameterInfo.GetCustomAttribute<FromUriAttribute>(true);
if (fromUri != null) @in = new InAttribute(InclutionTypes.Path);
}
}
methodParams.Add(new ParameterWrapper { Name = parameterInfo.Name, Type = parameterInfo.ParameterType, In = @in?.InclutionType ?? InclutionTypes.Body });
}
return methodParams;
}
public MethodBuilder BuildVoidMethod(TypeBuilder type, MethodInfo implementationMethod)
{
return InternalMethodBuilder(type, implementationMethod, VoidMethodBuilder);
}
private MethodBuilder VoidMethodBuilder(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List<ParameterWrapper> methodParams)
{
MethodInfo gatherParams = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"GatherParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(String),
typeof(Object[])
},
null
);
var baseType = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType);
var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation");
MethodInfo getValue = typeof(ParameterWrapper).GetMethod(
"get_value",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
},
null
);
MethodInfo createResponse = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponse", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (implementationMethod.ReturnType == typeof(void))
createResponse = createResponse.MakeGenericMethod(typeof(object));
else
createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType);
MethodInfo method9 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"CreateErrorResponse",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(Exception)
},
null
);
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder parameters = gen.DeclareLocal(typeof(Object[]));
LocalBuilder serviceParameters = gen.DeclareLocal(typeof(ParameterWrapper[]));
LocalBuilder message = gen.DeclareLocal(typeof(HttpResponseMessage));
LocalBuilder ex = gen.DeclareLocal(typeof(Exception));
// Writing body
gen.Emit(OpCodes.Nop);
gen.BeginExceptionBlock();
gen.Emit(OpCodes.Nop);
var ps = pTypes;
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j];
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, implementationMethod.Name);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Call, gatherParams);
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, implementation);
int iii = 0;
foreach (var parameterWrapper in methodParams)
{
gen.Emit(OpCodes.Ldloc_1);
EmitHelpers.EmitInt32(gen, iii);//gen.Emit(OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ldelem_Ref);
gen.Emit(OpCodes.Callvirt, getValue);
if (parameterWrapper.Type.IsValueType)
{
gen.Emit(OpCodes.Unbox_Any, parameterWrapper.Type);
}
else
gen.Emit(OpCodes.Castclass, parameterWrapper.Type);
iii++;
}
gen.Emit(OpCodes.Callvirt, implementationMethod);
if (implementationMethod.ReturnType != typeof(void))
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4, 200);
if (implementationMethod.ReturnType != typeof(void))
gen.Emit(OpCodes.Ldloc_2);
else { gen.Emit(OpCodes.Ldnull); }
gen.Emit(OpCodes.Call, createResponse);
gen.Emit(OpCodes.Stloc_2);
gen.BeginCatchBlock(typeof(Exception));
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Call, method9);
gen.Emit(OpCodes.Stloc_2);
gen.EndExceptionBlock();
gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private static ConstructorInfo httpMethodAttribute(MethodInfo implementationMethod)
{
var httpMethod = ExtensionsFactory.GetService<IWebMethodConverter>()?.GetHttpMethods(implementationMethod);
if (httpMethod != null && httpMethod.Any())
{
switch (httpMethod.First().Method.ToUpper())
{
case "GET":
return typeof(HttpGetAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "POST":
return typeof(HttpPostAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "PUT":
return typeof(HttpPutAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "DELETE":
return typeof(HttpDeleteAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "OPTIONS":
return typeof(HttpOptionsAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "HEAD":
return typeof(HttpHeadAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
case "PATCH":
return typeof(HttpPatchAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
}
}
var attribs = implementationMethod.GetCustomAttributes().ToList();
if (attribs.Any(p => p is HttpGetAttribute))
return typeof(HttpGetAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpPostAttribute))
return typeof(HttpPostAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpPutAttribute))
return typeof(HttpPutAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpDeleteAttribute))
return typeof(HttpDeleteAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpOptionsAttribute))
return typeof(HttpOptionsAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpHeadAttribute))
return typeof(HttpHeadAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
if (attribs.Any(p => p is HttpPatchAttribute))
return typeof(HttpPatchAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
return typeof(HttpGetAttribute).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
}
public MethodBuilder BuildAsyncMethod(TypeBuilder type, MethodInfo implementationMethod)
{
return InternalMethodBuilder(type, implementationMethod, (a, b, c, d) => BuildAsyncMethodBody(a, b, c, d, type));
}
private static int typeCounter = 0;
private MethodBuilder BuildAsyncMethodBody(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List<ParameterWrapper> methodParams, TypeBuilder parent)
{
MethodInfo gatherParams = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"GatherParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(string),
typeof(object[])
},
null
);
var delegateType = new DelegateBuilder(myModuleBuilder).CreateDelegate(implementationMethod, parent, methodParams);
var delegateCtor = delegateType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
var baseType = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType);
var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation");
MethodInfo getValue = typeof(ParameterWrapper).GetMethod(
"get_value",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
},
null
);
ConstructorInfo ctor9 = typeof(System.Func<>).MakeGenericType(typeof(Task<>).MakeGenericType(implementationMethod.ReturnType.GenericTypeArguments)).GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(Object),
typeof(IntPtr)
},
null
);
MethodInfo createResponse = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponseAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType.GetGenericArguments());
MethodInfo method9 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"CreateErrorResponse",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(Exception)
},
null
);
var delegateMethod = delegateType.GetMethod(implementationMethod.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);//.MakeGenericMethod(implementationMethod.ReturnType.GenericTypeArguments);
var method10 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType)
.GetMethod("ExecuteMethodAsync", BindingFlags.Instance | BindingFlags.NonPublic);
method10 = method10.MakeGenericMethod(implementationMethod.ReturnType.GenericTypeArguments);
FieldInfo field7 = delegateType.GetField("parameters", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo field5 = delegateType.GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo fromResult = typeof(Task).GetMethod("FromResult").MakeGenericMethod(typeof(HttpResponseMessage));
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder del = gen.DeclareLocal(delegateType);
LocalBuilder serviceParameters = gen.DeclareLocal(typeof(object[]));
LocalBuilder result = gen.DeclareLocal(typeof(Task<>).MakeGenericType(typeof(HttpResponseMessage)));
LocalBuilder ex = gen.DeclareLocal(typeof(Exception));
// Preparing labels
Label label97 = gen.DefineLabel();
// Writing body
gen.Emit(OpCodes.Nop);
gen.BeginExceptionBlock();
gen.Emit(OpCodes.Newobj, delegateCtor);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Stfld, field5);
var ps = pTypes;
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j];
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, implementationMethod.Name);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Call, gatherParams);
gen.Emit(OpCodes.Stfld, field7);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldftn, delegateMethod);
gen.Emit(OpCodes.Newobj, ctor9);
gen.Emit(OpCodes.Call, method10);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Leave_S, label97);
gen.Emit(OpCodes.Leave_S, label97);
gen.BeginCatchBlock(typeof(Exception));
gen.Emit(OpCodes.Stloc_S, 3);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_S, 3);
gen.Emit(OpCodes.Call, method9);
gen.Emit(OpCodes.Call, fromResult);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Leave_S, label97);
gen.EndExceptionBlock();
gen.MarkLabel(label97);
gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
public MethodBuilder BuildAsyncVoidMethod(TypeBuilder type, MethodInfo implementationMethod)
{
return InternalMethodBuilder(type, implementationMethod, (a, b, c, d) => BuildAsyncVoidMethodBody(a, b, c, d, type));
}
private MethodBuilder BuildAsyncVoidMethodBody(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List<ParameterWrapper> methodParams, TypeBuilder parent)
{
MethodInfo gatherParams = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"GatherParameters",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(string),
typeof(object[])
},
null
);
var delegateType = new VoidDelegateBuilder(myModuleBuilder).CreateVoidDelegate(implementationMethod, parent, methodParams);
var delegateCtor = delegateType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
var baseType = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType);
var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation");
MethodInfo getValue = typeof(ParameterWrapper).GetMethod(
"get_value",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
},
null
);
ConstructorInfo ctor9 = typeof(System.Func<>).MakeGenericType(typeof(Task)).GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(Object),
typeof(IntPtr)
},
null
);
MethodInfo createResponse = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponseAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType.GetGenericArguments());
MethodInfo method9 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType).GetMethod(
"CreateErrorResponse",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(Exception)
},
null
);
var delegateMethod = delegateType.GetMethod(implementationMethod.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);//.MakeGenericMethod(implementationMethod.ReturnType.GenericTypeArguments);
var method10 = typeof(ServiceWrapperBase<>).MakeGenericType(implementationMethod.DeclaringType)
.GetMethod("ExecuteMethodVoidAsync", BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo field7 = delegateType.GetField("parameters", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo field5 = delegateType.GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo fromResult = typeof(Task).GetMethod("FromResult").MakeGenericMethod(typeof(HttpResponseMessage));
ILGenerator gen = method.GetILGenerator();
// Preparing locals
LocalBuilder del = gen.DeclareLocal(delegateType);
LocalBuilder serviceParameters = gen.DeclareLocal(typeof(object[]));
LocalBuilder result = gen.DeclareLocal(typeof(Task<>).MakeGenericType(typeof(HttpResponseMessage)));
LocalBuilder ex = gen.DeclareLocal(typeof(Exception));
// Preparing labels
Label label97 = gen.DefineLabel();
// Writing body
gen.Emit(OpCodes.Nop);
gen.BeginExceptionBlock();
gen.Emit(OpCodes.Newobj, delegateCtor);
gen.Emit(OpCodes.Stloc_0);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Stfld, field5);
var ps = pTypes;
EmitHelpers.EmitInt32(gen, ps.Length);
gen.Emit(OpCodes.Newarr, typeof(object));
for (int j = 0; j < ps.Length; j++)
{
gen.Emit(OpCodes.Dup);
EmitHelpers.EmitInt32(gen, j);
EmitHelpers.EmitLdarg(gen, j + 1);
var paramType = ps[j];
if (paramType.IsValueType)
{
gen.Emit(OpCodes.Box, paramType);
}
gen.Emit(OpCodes.Stelem_Ref);
}
gen.Emit(OpCodes.Stloc_1);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldstr, implementationMethod.Name);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Call, gatherParams);
gen.Emit(OpCodes.Stfld, field7);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ldftn, delegateMethod);
gen.Emit(OpCodes.Newobj, ctor9);
gen.Emit(OpCodes.Call, method10);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Leave_S, label97);
gen.Emit(OpCodes.Leave_S, label97);
gen.BeginCatchBlock(typeof(Exception));
gen.Emit(OpCodes.Stloc_S, 3);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldloc_S, 3);
gen.Emit(OpCodes.Call, method9);
gen.Emit(OpCodes.Call, fromResult);
gen.Emit(OpCodes.Stloc_2);
gen.Emit(OpCodes.Leave_S, label97);
gen.EndExceptionBlock();
gen.MarkLabel(label97);
gen.Emit(OpCodes.Ldloc_2);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
public ConstructorBuilder ctor(TypeBuilder type, Type interfaceType)
{
const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig;
var method = type.DefineConstructor(methodAttributes, CallingConventions.Standard | CallingConventions.HasThis, new[] { interfaceType });
var implementation = method.DefineParameter(1, ParameterAttributes.None, "implementation");
var ctor1 = typeof(ServiceWrapperBase<>).MakeGenericType(interfaceType).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { interfaceType }, null);
var gen = method.GetILGenerator();
// Writing body
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Call, ctor1);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ret);
// finished
return method;
}
private TypeBuilder CreateServiceType(Type interfaceType)
{
var routePrefix = interfaceType.GetCustomAttribute<IRoutePrefixAttribute>()
?? interfaceType.GetInterfaces().FirstOrDefault()?.GetCustomAttribute<IRoutePrefixAttribute>();
var type = myModuleBuilder.DefineType("TempModule.Controllers." + interfaceType.Name.Remove(0, 1) + "Controller", TypeAttributes.Public | TypeAttributes.Class, typeof(ServiceWrapperBase<>).MakeGenericType(interfaceType));
if (routePrefix != null)
{
var prefix = routePrefix.Prefix;
if (routePrefix.IncludeTypeName) prefix = prefix + "/" + (interfaceType.GetGenericArguments().Any() ? interfaceType.GetGenericArguments().FirstOrDefault()?.Name.ToLower() : interfaceType.GetInterfaces().FirstOrDefault()?.GetGenericArguments().First().Name.ToLower());
var routePrefixCtor = typeof(RoutePrefixAttribute).GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[]{
typeof(string)
},
null
);
type.SetCustomAttribute(new CustomAttributeBuilder(routePrefixCtor, new object[] { prefix }));
}
return type;
}
public void Save()
{
if (ConfigurationManager.AppSettings["stardust.saveGeneratedAssemblies"] == "true")
myAssemblyBuilder.Save("service.dll");
}
public Assembly GetCustomAssembly()
{
return myModuleBuilder.Assembly;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Collections
{
public class IntervalTreeTests
{
private class TupleIntrospector<T> : IIntervalIntrospector<Tuple<int, int, T>>
{
public int GetStart(Tuple<int, int, T> value)
{
return value.Item1;
}
public int GetLength(Tuple<int, int, T> value)
{
return value.Item2;
}
}
private static IEnumerable<SimpleIntervalTree<Tuple<int, int, string>>> CreateTrees(params Tuple<int, int, string>[] values)
{
return CreateTrees((IEnumerable<Tuple<int, int, string>>)values);
}
private static IEnumerable<SimpleIntervalTree<Tuple<int, int, string>>> CreateTrees(IEnumerable<Tuple<int, int, string>> values)
{
yield return SimpleIntervalTree.Create(new TupleIntrospector<string>(), values);
var tree1 = SimpleIntervalTree.Create(new TupleIntrospector<string>());
foreach (var v in values)
{
tree1 = tree1.AddInterval(v);
}
yield return tree1;
}
[Fact]
public void TestEmpty()
{
foreach (var tree in CreateTrees())
{
var spans = tree.GetOverlappingIntervals(0, 1);
Assert.Empty(spans);
}
}
[Fact]
public void TestBeforeSpan()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(0, 1);
Assert.Empty(spans);
}
}
[Fact]
public void TestAbuttingBeforeSpan()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(0, 5);
Assert.Empty(spans);
}
}
[Fact]
public void TestAfterSpan()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(15, 5);
Assert.Empty(spans);
}
}
[Fact]
public void TestAbuttingAfterSpan()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(10, 5);
Assert.Empty(spans);
}
}
[Fact]
public void TestMatchingSpan()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(5, 5).Select(t => t.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestContainedAbuttingStart()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(5, 2).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestContainedAbuttingEnd()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(8, 2).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestCompletedContained()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(7, 2).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestOverlappingStart()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(4, 2).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestRightRotation()
{
var nodes = new[]
{
Tuple.Create(8, 1, "a"),
Tuple.Create(10, 1, "b"),
Tuple.Create(4, 1, "c"),
Tuple.Create(6, 1, "d"),
Tuple.Create(0, 1, "e"),
Tuple.Create(2, 1, "f")
};
foreach (var tree in CreateTrees(nodes))
{
Assert.True(tree.Select(t => t.Item3).SequenceEqual(
List("c", "e", "f", "a", "d", "b")));
}
}
[Fact]
public void InnerLeftOuterRightRotation()
{
var nodes = new[]
{
Tuple.Create(8, 1, "a"),
Tuple.Create(10, 1, "b"),
Tuple.Create(2, 1, "c"),
Tuple.Create(0, 1, "e"),
Tuple.Create(4, 1, "d"),
Tuple.Create(6, 1, "f")
};
foreach (var tree in CreateTrees(nodes))
{
Assert.True(tree.Select(t => t.Item3).SequenceEqual(
List("d", "c", "e", "a", "f", "b")));
}
}
[Fact]
public void TestOverlappingEnd()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(9, 2).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestOverlappingAll()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A")))
{
var spans = tree.GetOverlappingIntervals(4, 7).Select(i => i.Item3);
Assert.True(Set("A").SetEquals(spans));
}
}
[Fact]
public void TestNonOverlappingSpans()
{
foreach (var tree in CreateTrees(Tuple.Create(5, 5, "A"), Tuple.Create(15, 5, "B")))
{
// Test between the spans
Assert.Empty(tree.GetOverlappingIntervals(2, 2));
Assert.Empty(tree.GetOverlappingIntervals(11, 2));
Assert.Empty(tree.GetOverlappingIntervals(22, 2));
// Test in the spans
Assert.True(Set("A").SetEquals(tree.GetOverlappingIntervals(6, 2).Select(i => i.Item3)));
Assert.True(Set("B").SetEquals(tree.GetOverlappingIntervals(16, 2).Select(i => i.Item3)));
// Test covering both spans
Assert.True(Set("A", "B").SetEquals(tree.GetOverlappingIntervals(2, 20).Select(i => i.Item3)));
Assert.True(Set("A", "B").SetEquals(tree.GetOverlappingIntervals(2, 14).Select(i => i.Item3)));
Assert.True(Set("A", "B").SetEquals(tree.GetOverlappingIntervals(6, 10).Select(i => i.Item3)));
Assert.True(Set("A", "B").SetEquals(tree.GetOverlappingIntervals(6, 20).Select(i => i.Item3)));
}
}
[Fact]
public void TestSubsumedSpans()
{
var spans = List(
Tuple.Create(5, 5, "a"),
Tuple.Create(6, 3, "b"),
Tuple.Create(7, 1, "c"));
TestOverlapsAndIntersects(spans);
}
[Fact]
public void TestOverlappingSpans()
{
var spans = List(
Tuple.Create(5, 5, "a"),
Tuple.Create(7, 5, "b"),
Tuple.Create(9, 5, "c"));
TestOverlapsAndIntersects(spans);
}
[Fact]
public void TestIntersectsWith()
{
var spans = List(
Tuple.Create(0, 2, "a"));
foreach (var tree in CreateTrees(spans))
{
Assert.False(tree.IntersectsWith(-1));
Assert.True(tree.IntersectsWith(0));
Assert.True(tree.IntersectsWith(1));
Assert.True(tree.IntersectsWith(2));
Assert.False(tree.IntersectsWith(3));
}
}
[Fact]
public void LargeTest()
{
var spans = List(
Tuple.Create(0, 3, "a"),
Tuple.Create(5, 3, "b"),
Tuple.Create(6, 4, "c"),
Tuple.Create(8, 1, "d"),
Tuple.Create(15, 8, "e"),
Tuple.Create(16, 5, "f"),
Tuple.Create(17, 2, "g"),
Tuple.Create(19, 1, "h"),
Tuple.Create(25, 5, "i"));
TestOverlapsAndIntersects(spans);
}
[Fact]
public void TestCrash1()
{
foreach (var tree in CreateTrees(Tuple.Create(8, 1, "A"), Tuple.Create(59, 1, "B"), Tuple.Create(52, 1, "C")))
{
}
}
[Fact]
public void TestEmptySpanAtStart()
{
// Make sure creating empty spans works (there was a bug here)
var tree = CreateTrees(Tuple.Create(0, 0, "A")).Last();
Assert.Equal(1, tree.Count());
}
private static void TestOverlapsAndIntersects(IList<Tuple<int, int, string>> spans)
{
foreach (var tree in CreateTrees(spans))
{
var max = spans.Max(t => t.Item1 + t.Item2);
for (int start = 0; start <= max; start++)
{
for (int length = 1; length <= max; length++)
{
var span = new Span(start, length);
var set1 = new HashSet<string>(tree.GetOverlappingIntervals(start, length).Select(i => i.Item3));
var set2 = new HashSet<string>(spans.Where(t =>
{
return span.OverlapsWith(new Span(t.Item1, t.Item2));
}).Select(t => t.Item3));
Assert.True(set1.SetEquals(set2));
var set3 = new HashSet<string>(tree.GetIntersectingIntervals(start, length).Select(i => i.Item3));
var set4 = new HashSet<string>(spans.Where(t =>
{
return span.IntersectsWith(new Span(t.Item1, t.Item2));
}).Select(t => t.Item3));
Assert.True(set3.SetEquals(set4));
}
}
Assert.Equal(spans.Count, tree.Count());
Assert.True(new HashSet<string>(spans.Select(t => t.Item3)).SetEquals(tree.Select(i => i.Item3)));
}
}
private ISet<T> Set<T>(params T[] values)
{
return new HashSet<T>(values);
}
private IList<T> List<T>(params T[] values)
{
return new List<T>(values);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using Epi.Windows.Dialogs;
using Epi.Windows.MakeView.Forms;
namespace Epi.Windows.MakeView.Dialogs
{
/// <summary>
/// Dialog for setting background color and background image
/// </summary>
public partial class PageSetupDialog : DialogBase
{
private enum PaperSizeUnit { Inches, Millimeters, Pixels };
#region Private Variables
private string bgLayout=String.Empty;
private Color bgColor=Color.Empty;
private string bgImagePath=String.Empty;
private Configuration config;
private System.Collections.Generic.Dictionary<string, Size> _sizes;
private MakeViewMainForm mainForm;
private string _useAsDefaultPageSize = string.Empty;
private string _widthText, _heightText;
#endregion
#region Public Variables
public event EventHandler SettingsSaved;
#endregion
#region Public Constructors
/// <summary>
/// Default Constructor - Design mode only
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public PageSetupDialog()
{
InitializeComponent();
config = Configuration.GetNewInstance();
}
/// <summary>
/// Constructor for the class
/// </summary>
public PageSetupDialog(MainForm main) : base(main)
{
InitializeComponent();
mainForm = main as MakeViewMainForm;
_sizes = new System.Collections.Generic.Dictionary<String, Size>();
string displayLabel;
Size size;
/// INCHES
FormatSizeKeyValue("Letter (default)", PaperSizeUnit.Inches, 8.5, 11, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("Legal", PaperSizeUnit.Inches, 8.5, 14, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("Executive", PaperSizeUnit.Inches, 7.25, 10.5, out displayLabel, out size);
_sizes.Add(displayLabel, size);
/// MILLIMETERS
FormatSizeKeyValue("A0", PaperSizeUnit.Millimeters, 841, 1189, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A1", PaperSizeUnit.Millimeters, 594, 841, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A2", PaperSizeUnit.Millimeters, 420, 594, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A3", PaperSizeUnit.Millimeters, 297, 420, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A4", PaperSizeUnit.Millimeters, 210, 297, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A5", PaperSizeUnit.Millimeters, 148, 210, out displayLabel, out size);
_sizes.Add(displayLabel, size);
FormatSizeKeyValue("A6", PaperSizeUnit.Millimeters, 105, 148, out displayLabel, out size);
_sizes.Add(displayLabel, size);
/// ANDROID
FormatSizeKeyValue("Mobile Interview", PaperSizeUnit.Pixels, 549, 780, out displayLabel, out size);
_sizes.Add(displayLabel, size);
displayLabel = "Custom Size";
_sizes.Add(displayLabel, new Size(780, 1016));
_useAsDefaultPageSize = displayLabel;
InitSettings();
}
private void FormatSizeKeyValue(string sizeName, PaperSizeUnit paperSizeUnit, double width, double height, out string displayLabel, out Size size)
{
double ratio = 94.55;
double linearCorrection = 0.25;
string unitAsString = string.Empty;
switch(paperSizeUnit)
{
case PaperSizeUnit.Inches:
unitAsString = "in";
ratio = 94.55;
break;
case PaperSizeUnit.Millimeters:
unitAsString = "mm";
ratio = ratio / 25.4;
break;
case PaperSizeUnit.Pixels:
unitAsString = "px";
ratio = 1;
linearCorrection = 0.0;
break;
}
size = new Size((int)((width - linearCorrection) * ratio), (int)((height - linearCorrection) * ratio));
displayLabel = string.Format("{0} ({1:#####.##}x{2:#####.##}{3})", sizeName, width, height, unitAsString);
}
#endregion
#region Private Methods
private void InitSettings()
{
config = Configuration.GetNewInstance();
View view = mainForm.mediator.ProjectExplorer.SelectedPage.GetView();
DataRow selectedPageSetupDataRow = mainForm.mediator.Project.Metadata.GetPageSetupData(view);
string[] sizeNames = new string[_sizes.Count];
_sizes.Keys.CopyTo(sizeNames, 0);
comboBoxSize.Items.AddRange(sizeNames);
if (((String)selectedPageSetupDataRow[ColumnNames.PAGE_ORIENTATION]).ToLowerInvariant() == "landscape")
{
radioButtonLandscape.Select();
}
else
{
radioButtonPortrait.Select();
}
if (((String)selectedPageSetupDataRow[ColumnNames.PAGE_LABEL_ALIGN]).ToLowerInvariant() == "horizontal")
{
radioButtonLabelAlignHorizontal.Select();
}
else
{
radioButtonLabelAlignVertical.Select();
}
int selectedPageWidth = (int)selectedPageSetupDataRow[ColumnNames.PAGE_WIDTH];
int selectedPageHeight = (int)selectedPageSetupDataRow[ColumnNames.PAGE_HEIGHT];
Size selectedPageSize = new Size(selectedPageWidth, selectedPageHeight);
comboBoxSize.SelectedItem = _useAsDefaultPageSize;
textBoxWidth.Text = selectedPageWidth.ToString();
textBoxHeight.Text = selectedPageHeight.ToString();
_widthText = textBoxWidth.Text;
_heightText = textBoxHeight.Text;
foreach (KeyValuePair<string, Size> kvp in _sizes)
{
if (((Size)kvp.Value).Equals(selectedPageSize))
{
comboBoxSize.SelectedItem = (string)kvp.Key;
break;
}
}
}
/// <summary>
/// Cancel button closes this dialog
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnCancel_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void btnOK_Click(object sender, EventArgs e)
{
int parsedInt;
int.TryParse(textBoxWidth.Text, out parsedInt);
mainForm.CurrentPage.view.PageWidth = parsedInt;
int.TryParse(textBoxHeight.Text, out parsedInt);
mainForm.CurrentPage.view.PageHeight = parsedInt;
mainForm.CurrentPage.view.PageOrientation = radioButtonPortrait.Checked ? "Portrait" : "Landscape";
mainForm.CurrentPage.view.PageLabelAlign = radioButtonLabelAlignVertical.Checked ? "Vertical" : "Horizontal";
View view = mainForm.mediator.Project.Views[mainForm.CurrentPage.view.Name];
view.PageWidth = mainForm.CurrentPage.view.PageWidth;
view.PageHeight = mainForm.CurrentPage.view.PageHeight;
view.PageOrientation = mainForm.CurrentPage.view.PageOrientation;
view.PageLabelAlign = mainForm.CurrentPage.view.PageLabelAlign;
mainForm.CurrentPage.GetMetadata().UpdatePageSetupData
(
mainForm.CurrentPage.view,
mainForm.CurrentPage.view.PageWidth,
mainForm.CurrentPage.view.PageHeight,
mainForm.CurrentPage.view.PageOrientation,
mainForm.CurrentPage.view.PageLabelAlign,
"Paper"
);
if (SettingsSaved != null)
{
SettingsSaved(this, new EventArgs());
}
this.Close();
}
void textBoxWidth_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
{
e.Handled = true;
}
}
void textBoxHeight_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
{
e.Handled = true;
}
}
void textBoxWidth_TextChanged(object sender, System.EventArgs e)
{
int value = 0;
if (Int32.TryParse(((TextBox)sender).Text, out value))
{
if (value > 4425)
{
((TextBox)sender).Text = _widthText;
}
}
}
void textBoxHeight_TextChanged(object sender, System.EventArgs e)
{
int value = 0;
if (Int32.TryParse(((TextBox)sender).Text, out value))
{
if (value > 4425)
{
((TextBox)sender).Text = _heightText;
}
}
}
#endregion
private void pictureBoxLabelAlignVertical_Click(object sender, EventArgs e)
{
this.radioButtonLabelAlignVertical.Select();
}
private void pictureBoxLabelAlignHorizontal_Click(object sender, EventArgs e)
{
this.radioButtonLabelAlignHorizontal.Select();
}
private void comboBoxSize_SelectedIndexChanged(object sender, EventArgs e)
{
string key = ((ComboBox)sender).Text.Trim();
radioButtonPortrait.Checked = true;
if (key.ToLowerInvariant().Contains("mobile interview"))
{
radioButtonLandscape.Checked = true;
}
if (key.ToLowerInvariant().Equals("custom size"))
{
this.textBoxHeight.Enabled = true;
this.textBoxWidth.Enabled = true;
this.textBoxHeight.ReadOnly = false;
this.textBoxWidth.ReadOnly = false;
}
else if (_sizes.ContainsKey(key))
{
Size selectedSize = _sizes[key];
textBoxWidth.Text = selectedSize.Width.ToString();
textBoxHeight.Text = selectedSize.Height.ToString();
this.textBoxHeight.Enabled = false;
this.textBoxWidth.Enabled = false;
this.textBoxHeight.ReadOnly = true;
this.textBoxWidth.ReadOnly = true;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
namespace Microsoft.Zelig.MetaData
{
using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
using System.Text;
public class MetaDataDumper : Normalized.IMetaDataDumper, IDisposable
{
//
// State
//
MetaDataDumper m_sub;
System.IO.TextWriter m_writer;
int m_indent;
GrowOnlySet< Normalized.MetaDataObject > m_processed;
Normalized.MetaDataObject m_context;
//
// Constructor Methods
//
public MetaDataDumper( string name ,
MetaDataVersion ver )
{
name = name.Replace( "<", "" );
name = name.Replace( ">", "" );
name = name.Replace( ":", "" );
m_sub = null;
m_writer = new System.IO.StreamWriter( String.Format( "{0}_{1}.{2}.{3}.{4}.txt", name, ver.MajorVersion, ver.MinorVersion, ver.BuildNumber, ver.RevisionNumber ), false, Encoding.ASCII );
m_indent = 0;
m_processed = SetFactory.NewWithReferenceEquality< Normalized.MetaDataObject >();
m_context = null;
}
private MetaDataDumper( MetaDataDumper sub ,
Normalized.MetaDataObject context )
{
m_sub = sub;
m_writer = sub.m_writer;
m_indent = sub.m_indent;
m_processed = sub.m_processed;
m_context = context;
}
public void IndentPush( string s )
{
WriteLine( s );
m_indent += 1;
}
public void IndentPop( string s )
{
m_indent -= 1;
WriteLine( s );
}
public void WriteLine()
{
WriteIndentation();
m_writer.WriteLine();
}
public void WriteLine( string s )
{
WriteIndentation();
m_writer.WriteLine( s );
}
public void WriteLine( string s ,
object arg1 )
{
WriteIndentedLine( s, arg1 );
}
public void WriteLine( string s ,
object arg1 ,
object arg2 )
{
WriteIndentedLine( s, arg1, arg2 );
}
public void WriteLine( string s ,
object arg1 ,
object arg2 ,
object arg3 )
{
WriteIndentedLine( s, arg1, arg2, arg3 );
}
public void WriteLine( string s ,
params object[] args )
{
WriteIndentedLine( s, args );
}
public void Process( Normalized.MetaDataObject obj ,
bool fOnlyOnce )
{
if(fOnlyOnce == false || m_processed.Contains( obj ) == false)
{
m_processed.Insert( obj );
obj.Dump( this );
}
}
public bool AlreadyProcessed( Normalized.MetaDataObject obj )
{
return m_processed.Contains( obj );
}
public Normalized.MetaDataMethodAbstract GetContextMethodAndPop( out Normalized.IMetaDataDumper context )
{
MetaDataDumper pThis = this;
while(pThis != null)
{
Normalized.MetaDataObject obj = pThis.m_context;
if(obj is Normalized.MetaDataMethodAbstract)
{
Normalized.MetaDataMethodAbstract md = (Normalized.MetaDataMethodAbstract)obj;
context = pThis.m_sub;
if(obj is Normalized.MetaDataMethodGeneric)
{
while(pThis != null)
{
if(pThis.m_context is Normalized.MetaDataMethodGenericInstantiation)
{
Normalized.MetaDataMethodGenericInstantiation inst = (Normalized.MetaDataMethodGenericInstantiation)pThis.m_context;
if(inst.BaseMethod.Equals( md ))
{
context = pThis.m_sub;
md = inst;
break;
}
}
pThis = pThis.m_sub;
}
}
return md;
}
pThis = pThis.m_sub;
}
context = null;
return null;
}
public Normalized.MetaDataTypeDefinitionAbstract GetContextTypeAndPop( out Normalized.IMetaDataDumper context )
{
MetaDataDumper pThis = this;
while(pThis != null)
{
Normalized.MetaDataObject obj = pThis.m_context;
if(obj is Normalized.MetaDataTypeDefinitionAbstract)
{
Normalized.MetaDataTypeDefinitionAbstract td = (Normalized.MetaDataTypeDefinitionAbstract)obj;
context = pThis.m_sub;
if(obj is Normalized.MetaDataTypeDefinitionGeneric)
{
while(pThis != null)
{
if(pThis.m_context is Normalized.MetaDataTypeDefinitionGenericInstantiation)
{
Normalized.MetaDataTypeDefinitionGenericInstantiation inst = (Normalized.MetaDataTypeDefinitionGenericInstantiation)pThis.m_context;
if(inst.GenericType.Equals( td ))
{
context = pThis.m_sub;
td = inst;
break;
}
}
pThis = pThis.m_sub;
}
}
return td;
}
pThis = pThis.m_sub;
}
context = null;
return null;
}
public Normalized.IMetaDataDumper PushContext( Normalized.MetaDataObject obj )
{
return new MetaDataDumper( this, obj );
}
//--//
private void WriteIndentedLine( string s ,
params object[] args )
{
WriteIndentation();
m_writer.WriteLine( s, args );
}
private void WriteIndentation()
{
for(int i = 0; i < m_indent; i++)
{
m_writer.Write( " " );
}
}
#region IDisposable Members
public void Dispose()
{
if(m_writer != null)
{
m_writer.Dispose();
m_writer = null;
}
}
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_IOS
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace MsgPack.Serialization
{
/// <summary>
/// Build serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <typeparam name="TObject">Object to be serialized/deserialized.</typeparam>
internal abstract class SerializerBuilder<TObject> : ISerializerBuilder
{
private readonly SerializationContext _context;
/// <summary>
/// Gets the <see cref="SerializationContext"/>.
/// </summary>
/// <value>
/// The <see cref="SerializationContext"/>.
/// </value>
public SerializationContext Context
{
get
{
Contract.Ensures(Contract.Result<SerializationContext>() != null);
return this._context;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializerBuilder<TObject>"/> class.
/// </summary>
/// <param name="context">The <see cref="SerializationContext"/>.</param>
protected SerializerBuilder(SerializationContext context)
{
Contract.Requires(context != null);
this._context = context;
}
/// <summary>
/// Creates serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
/// </returns>
public MessagePackSerializer<TObject> CreateSerializer()
{
Contract.Ensures(Contract.Result<MessagePackSerializer<TObject>>() != null);
var entries = GetTargetMembers().OrderBy(item => item.Contract.Id).ToArray();
if (entries.Length == 0)
{
throw SerializationExceptions.NewNoSerializableFieldsException(typeof(TObject));
}
if (entries.All(item => item.Contract.Id == DataMemberContract.UnspecifiedId))
{
// Alphabetical order.
return this.CreateSerializer(entries.OrderBy(item => item.Contract.Name).ToArray());
}
else
{
// ID order.
Contract.Assert(entries[0].Contract.Id >= 0);
if (this.Context.CompatibilityOptions.OneBoundDataMemberOrder && entries[0].Contract.Id == 0)
{
throw new NotSupportedException("Cannot specify order value 0 on DataMemberAttribute when SerializationContext.CompatibilityOptions.OneBoundDataMemberOrder is set to true.");
}
var maxId = entries.Max(item => item.Contract.Id);
var result = new List<SerializingMember>(maxId + 1);
for (int source = 0, destination = this.Context.CompatibilityOptions.OneBoundDataMemberOrder ? 1 : 0; source < entries.Length; source++, destination++)
{
Contract.Assert(entries[source].Contract.Id >= 0);
if (entries[source].Contract.Id < destination)
{
throw new SerializationException(String.Format(CultureInfo.CurrentCulture, "The member ID '{0}' is duplicated in the '{1}' type.", entries[source].Contract.Id, typeof(TObject)));
}
while (entries[source].Contract.Id > destination)
{
result.Add(new SerializingMember());
destination++;
}
result.Add(entries[source]);
}
return this.CreateSerializer(result.ToArray());
}
}
private static IEnumerable<SerializingMember> GetTargetMembers()
{
#if !NETFX_CORE
var members =
typeof(TObject).FindMembers(
MemberTypes.Field | MemberTypes.Property,
BindingFlags.Public | BindingFlags.Instance,
(member, criteria) => true,
null
);
var filtered = members.Where(item => Attribute.IsDefined(item, typeof(MessagePackMemberAttribute))).ToArray();
#else
var members =
typeof( TObject ).GetRuntimeFields().Where( f => f.IsPublic && !f.IsStatic ).OfType<MemberInfo>().Concat( typeof( TObject ).GetRuntimeProperties().Where( p => p.GetMethod != null && p.GetMethod.IsPublic && !p.GetMethod.IsStatic ) );
var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();
#endif
if (filtered.Length > 0)
{
return
filtered.Select(member =>
new SerializingMember(
member,
new DataMemberContract(member, member.GetCustomAttribute<MessagePackMemberAttribute>())
)
);
}
if (typeof(TObject).IsDefined(typeof(DataContractAttribute)))
{
return
members.Where(item => item.IsDefined(typeof(DataMemberAttribute)))
.Select(member =>
new SerializingMember(
member,
new DataMemberContract(member, member.GetCustomAttribute<DataMemberAttribute>())
)
);
}
#if SILVERLIGHT || NETFX_CORE
return members.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#else
return
members.Where(item => !Attribute.IsDefined(item, typeof(NonSerializedAttribute)))
.Select(member => new SerializingMember(member, new DataMemberContract(member)));
#endif
}
/// <summary>
/// Creates serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <param name="entries">Serialization target members. This will not be <c>null</c> nor empty.</param>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
/// </returns>
protected abstract MessagePackSerializer<TObject> CreateSerializer(SerializingMember[] entries);
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is array type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateArraySerializer();
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is map type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateMapSerializer();
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is tuple type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateTupleSerializer();
IMessagePackSingleObjectSerializer ISerializerBuilder.CreateArraySerializer()
{
return this.CreateArraySerializer();
}
IMessagePackSingleObjectSerializer ISerializerBuilder.CreateMapSerializer()
{
return this.CreateMapSerializer();
}
IMessagePackSingleObjectSerializer ISerializerBuilder.CreateSerializer()
{
return this.CreateSerializer();
}
}
internal abstract class SerializerBuilderContract<T> : SerializerBuilder<T>
{
protected SerializerBuilderContract() : base(null) { }
protected override MessagePackSerializer<T> CreateSerializer(SerializingMember[] entries)
{
Contract.Requires(entries != null);
Contract.Ensures(Contract.Result<MessagePackSerializer<T>>() != null);
return null;
}
public override MessagePackSerializer<T> CreateArraySerializer()
{
Contract.Ensures(Contract.Result<MessagePackSerializer<T>>() != null);
return null;
}
public override MessagePackSerializer<T> CreateMapSerializer()
{
Contract.Ensures(Contract.Result<MessagePackSerializer<T>>() != null);
return null;
}
public override MessagePackSerializer<T> CreateTupleSerializer()
{
Contract.Ensures(Contract.Result<MessagePackSerializer<T>>() != null);
return null;
}
}
}
#else // UNITY_IOS
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace MsgPack.Serialization
{
/// <summary>
/// Build serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <typeparam name="TObject">Object to be serialized/deserialized.</typeparam>
internal abstract class SerializerBuilder<TObject>
{
private readonly SerializationContext _context;
/// <summary>
/// Gets the <see cref="SerializationContext"/>.
/// </summary>
/// <value>
/// The <see cref="SerializationContext"/>.
/// </value>
public SerializationContext Context
{
get
{
Contract.Ensures( Contract.Result<SerializationContext>() != null );
return this._context;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializerBuilder<TObject>"/> class.
/// </summary>
/// <param name="context">The <see cref="SerializationContext"/>.</param>
protected SerializerBuilder( SerializationContext context )
{
Contract.Requires( context != null );
this._context = context;
}
/// <summary>
/// Creates serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
/// </returns>
public MessagePackSerializer<TObject> CreateSerializer()
{
Contract.Ensures( Contract.Result<MessagePackSerializer<TObject>>() != null );
var entries = GetTargetMembers().OrderBy( item => item.Contract.Id ).ToArray();
//if ( entries.Length == 0 )
//{
// throw SerializationExceptions.NewNoSerializableFieldsException( typeof( TObject ) );
//}
if ( entries.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
{
// Alphabetical order.
return this.CreateSerializer( entries.OrderBy( item => item.Contract.Name ).ToArray() );
}
else
{
// ID order.
Contract.Assert( entries[ 0 ].Contract.Id >= 0 );
if ( this.Context.CompatibilityOptions.OneBoundDataMemberOrder && entries[ 0 ].Contract.Id == 0 )
{
throw new NotSupportedException( "Cannot specify order value 0 on DataMemberAttribute when SerializationContext.CompatibilityOptions.OneBoundDataMemberOrder is set to true." );
}
var maxId = entries.Max( item => item.Contract.Id );
var result = new List<SerializingMember>( maxId + 1 );
for ( int source = 0, destination = this.Context.CompatibilityOptions.OneBoundDataMemberOrder ? 1 : 0; source < entries.Length; source++, destination++ )
{
Contract.Assert( entries[ source ].Contract.Id >= 0 );
if ( entries[ source ].Contract.Id < destination )
{
throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "The member ID '{0}' is duplicated in the '{1}' type.", entries[ source ].Contract.Id, typeof( TObject ) ) );
}
while ( entries[ source ].Contract.Id > destination )
{
result.Add( new SerializingMember() );
destination++;
}
result.Add( entries[ source ] );
}
return this.CreateSerializer( result.ToArray() );
}
}
private static IEnumerable<SerializingMember> GetTargetMembers()
{
#if !NETFX_CORE
var members =
typeof( TObject ).FindMembers(
MemberTypes.Field | MemberTypes.Property,
BindingFlags.Public | BindingFlags.Instance,
( member, criteria ) => true,
null
);
var filtered = members.Where( item => Attribute.IsDefined( item, typeof( MessagePackMemberAttribute ) ) ).ToArray();
#else
var members =
typeof( TObject ).GetRuntimeFields().Where( f => f.IsPublic && !f.IsStatic ).OfType<MemberInfo>().Concat( typeof( TObject ).GetRuntimeProperties().Where( p => p.GetMethod != null && p.GetMethod.IsPublic && !p.GetMethod.IsStatic ) );
var filtered = members.Where( item => item.IsDefined( typeof( MessagePackMemberAttribute ) ) ).ToArray();
#endif
if ( filtered.Length > 0 )
{
return
filtered.Select( member =>
new SerializingMember(
member,
new DataMemberContract( member, member.GetCustomAttribute<MessagePackMemberAttribute>() )
)
);
}
if ( typeof( TObject ).IsDefined( typeof( DataContractAttribute ) ) )
{
return
members.Where( item => item.IsDefined( typeof( DataMemberAttribute ) ) )
.Select( member =>
new SerializingMember(
member,
new DataMemberContract( member, member.GetCustomAttribute<DataMemberAttribute>() )
)
);
}
#if SILVERLIGHT || NETFX_CORE
return members.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#else
return
members.Where( item => !Attribute.IsDefined( item, typeof( NonSerializedAttribute ) ) )
.Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
#endif
}
/// <summary>
/// Creates serializer for <typeparamref name="TObject"/>.
/// </summary>
/// <param name="entries">Serialization target members. This will not be <c>null</c> nor empty.</param>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>. This value will not be <c>null</c>.
/// </returns>
protected abstract MessagePackSerializer<TObject> CreateSerializer( SerializingMember[] entries );
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is array type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateArraySerializer();
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is map type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateMapSerializer();
/// <summary>
/// Creates serializer as <typeparamref name="TObject"/> is tuple type.
/// </summary>
/// <returns>
/// <see cref="MessagePackSerializer{T}"/>.
/// This value will not be <c>null</c>.
/// </returns>
public abstract MessagePackSerializer<TObject> CreateTupleSerializer();
}
internal abstract class SerializerBuilderContract<T> : SerializerBuilder<T>
{
protected SerializerBuilderContract() : base( null ) { }
protected override MessagePackSerializer<T> CreateSerializer( SerializingMember[] entries )
{
Contract.Requires( entries != null );
Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
return null;
}
public override MessagePackSerializer<T> CreateArraySerializer()
{
Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
return null;
}
public override MessagePackSerializer<T> CreateMapSerializer()
{
Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
return null;
}
public override MessagePackSerializer<T> CreateTupleSerializer()
{
Contract.Ensures( Contract.Result<MessagePackSerializer<T>>() != null );
return 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.
using System;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/*
* Define the different access levels that symbols can have.
*/
internal enum ACCESS
{
ACC_UNKNOWN, // Not yet determined.
ACC_PRIVATE,
ACC_INTERNAL,
ACC_PROTECTED,
ACC_INTERNALPROTECTED, // internal OR protected
ACC_PUBLIC
}
// The kinds of aggregates.
internal enum AggKindEnum
{
Unknown,
Class,
Delegate,
Interface,
Struct,
Enum,
Lim
}
/////////////////////////////////////////////////////////////////////////////////
// Special constraints.
[Flags]
internal enum SpecCons
{
None = 0x00,
New = 0x01,
Ref = 0x02,
Val = 0x04
}
// ----------------------------------------------------------------------------
//
// Symbol - the base symbol.
//
// ----------------------------------------------------------------------------
internal abstract class Symbol
{
private SYMKIND _kind; // the symbol kind
private ACCESS _access; // access level
// If this is true, then we had an error the first time so do not give an error the second time.
public Name name; // name of the symbol
public ParentSymbol parent; // parent of the symbol
public Symbol nextChild; // next child of this parent
public Symbol nextSameName; // next child of this parent with same name.
public ACCESS GetAccess()
{
Debug.Assert(_access != ACCESS.ACC_UNKNOWN);
return _access;
}
public void SetAccess(ACCESS access)
{
_access = access;
}
public SYMKIND getKind()
{
return _kind;
}
public void setKind(SYMKIND kind)
{
_kind = kind;
}
public symbmask_t mask()
{
return (symbmask_t)(1 << (int)_kind);
}
public CType getType()
{
if (this is MethodOrPropertySymbol methProp)
{
return methProp.RetType;
}
if (this is FieldSymbol field)
{
return field.GetType();
}
if (this is EventSymbol ev)
{
return ev.type;
}
return null;
}
public bool isStatic
{
get
{
if (this is FieldSymbol field)
{
return field.isStatic;
}
if (this is EventSymbol ev)
{
return ev.isStatic;
}
if (this is MethodOrPropertySymbol methProp)
{
return methProp.isStatic;
}
return this is AggregateSymbol;
}
}
private Assembly GetAssembly()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return ((AggregateSymbol)parent).AssociatedAssembly;
case SYMKIND.SK_AggregateDeclaration:
return ((AggregateDeclaration)this).GetAssembly();
case SYMKIND.SK_AggregateSymbol:
return ((AggregateSymbol)this).AssociatedAssembly;
default:
// Should never call this with any other kind.
Debug.Assert(false, "GetAssemblyID called on bad sym kind");
return null;
}
}
/*
* returns the assembly id for the declaration of this symbol
*/
private bool InternalsVisibleTo(Assembly assembly)
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return ((AggregateSymbol)parent).InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateDeclaration:
return ((AggregateDeclaration)this).Agg().InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateSymbol:
return ((AggregateSymbol)this).InternalsVisibleTo(assembly);
default:
// Should never call this with any other kind.
Debug.Assert(false, "InternalsVisibleTo called on bad sym kind");
return false;
}
}
public bool SameAssemOrFriend(Symbol sym)
{
Assembly assem = GetAssembly();
return assem == sym.GetAssembly() || sym.InternalsVisibleTo(assem);
}
/* Returns if the symbol is virtual. */
public bool IsVirtual()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
return ((MethodSymbol)this).isVirtual;
case SYMKIND.SK_EventSymbol:
MethodSymbol methAdd = ((EventSymbol)this).methAdd;
return methAdd != null && methAdd.isVirtual;
case SYMKIND.SK_PropertySymbol:
PropertySymbol prop = ((PropertySymbol)this);
MethodSymbol meth = prop.GetterMethod ?? prop.SetterMethod;
return meth != null && meth.isVirtual;
default:
return false;
}
}
public bool IsOverride()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return ((MethodOrPropertySymbol)this).isOverride;
case SYMKIND.SK_EventSymbol:
return ((EventSymbol)this).isOverride;
default:
return false;
}
}
public bool IsHideByName()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return ((MethodOrPropertySymbol)this).isHideByName;
case SYMKIND.SK_EventSymbol:
MethodSymbol methAdd = ((EventSymbol)this).methAdd;
return methAdd != null && methAdd.isHideByName;
default:
return true;
}
}
/*
* returns true if this symbol is a normal symbol visible to the user
*/
public bool isUserCallable()
{
return !(this is MethodSymbol methSym) || methSym.isUserCallable();
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using Moq.Language.Flow;
using Xunit;
namespace Moq.Tests
{
public class ReturnsValidationFixture
{
private Mock<IType> mock;
private ISetup<IType, IType> setup;
private ISetup<IType, IType> setupNoArgs;
public ReturnsValidationFixture()
{
this.mock = new Mock<IType>();
this.setup = this.mock.Setup(m => m.Method(It.IsAny<object>(), It.IsAny<object>()));
this.setupNoArgs = this.mock.Setup(m => m.MethodNoArgs());
}
[Fact]
public void Returns_does_not_accept_delegate_without_return_value()
{
Action<object> delegateWithoutReturnValue = (arg) => { };
var ex = Record.Exception(() =>
{
this.setup.Returns(delegateWithoutReturnValue);
});
Assert.IsType<ArgumentException>(ex);
}
[Fact]
public void Returns_does_not_accept_delegate_with_wrong_return_type()
{
Func<string> delegateWithWrongReturnType = () => "42";
var ex = Record.Exception(() =>
{
this.setup.Returns(delegateWithWrongReturnType);
});
Assert.IsType<ArgumentException>(ex);
}
[Fact]
public void Returns_accepts_parameterless_delegate_for_method_without_parameters()
{
Func<IType> delegateWithoutParameters = () => default(IType);
this.setupNoArgs.Returns(delegateWithoutParameters);
var ex = Record.Exception(() =>
{
this.mock.Object.MethodNoArgs();
});
Assert.Null(ex);
}
[Fact]
public void Returns_accepts_parameterless_delegate_even_for_method_having_parameters()
{
Func<IType> delegateWithoutParameters = () => default(IType);
this.setup.Returns(delegateWithoutParameters);
var ex = Record.Exception(() =>
{
this.mock.Object.Method(42, 3);
});
Assert.Null(ex);
}
[Fact]
public void Returns_does_not_accept_delegate_with_wrong_parameter_count()
{
Func<object, object, object, IType> delegateWithWrongParameterCount = (arg1, arg2, arg3) => default(IType);
var ex = Record.Exception(() =>
{
this.setup.Returns(delegateWithWrongParameterCount);
});
Assert.IsType<ArgumentException>(ex);
}
[Fact]
public void Returns_accepts_delegate_with_wrong_parameter_types_but_setup_invocation_will_fail()
{
Func<string, string, IType> delegateWithWrongParameterType = (arg1, arg2) => default(IType);
this.setup.Returns(delegateWithWrongParameterType);
var ex = Record.Exception(() =>
{
mock.Object.Method(42, 7);
});
Assert.IsType<ArgumentException>(ex);
// In case you're wondering why this use case isn't "fixed" by properly validating delegates
// passed to `Returns`... it's entirely possible that some people might do this:
//
// mock.Setup(m => m.Method(It.IsAny<int>()).Returns<int>(obj => ...);
// mock.Setup(m => m.Method(It.IsAny<string>()).Returns<string>(obj => ...);
//
// where `Method` has a parameter of type `object`. That is, people might rely on a matcher
// to ensure that the return callback delegate invocation (and the cast to `object` that has to
// happen) will always succeed. See also the next test, as well as old Google Code issue 267
// in `IssueReportsFixture.cs`.
//
// While not the cleanest of techniques, it might be useful to some people and probably
// shouldn't be broken by eagerly validating everything.
}
[Fact]
public void Returns_accepts_delegate_with_wrong_parameter_types_and_setup_invocation_will_succeed_if_args_convertible()
{
Func<string, string, IType> delegateWithWrongParameterType = (arg1, arg2) => default(IType);
this.setup.Returns(delegateWithWrongParameterType);
var ex = Record.Exception(() =>
{
mock.Object.Method(null, null);
});
Assert.Null(ex);
}
[Fact]
public void Returns_accepts_parameterless_extension_method_for_method_without_parameters()
{
Func<IType> delegateWithoutParameters = new ReturnsValidationFixture().ExtensionMethodNoArgs;
this.setupNoArgs.Returns(delegateWithoutParameters);
var ex = Record.Exception(() =>
{
this.mock.Object.MethodNoArgs();
});
Assert.Null(ex);
}
[Fact]
public void Returns_accepts_parameterless_extension_method_even_for_method_having_parameters()
{
Func<IType> delegateWithoutParameters = new ReturnsValidationFixture().ExtensionMethodNoArgs;
this.setup.Returns(delegateWithoutParameters);
var ex = Record.Exception(() =>
{
this.mock.Object.Method(42, 5);
});
Assert.Null(ex);
}
[Fact]
public void Returns_does_not_accept_extension_method_with_wrong_parameter_count()
{
Func<object, object, IType> delegateWithWrongParameterCount = new ReturnsValidationFixture().ExtensionMethod;
var ex = Record.Exception(() =>
{
this.setupNoArgs.Returns(delegateWithWrongParameterCount);
});
Assert.IsType<ArgumentException>(ex);
}
[Fact]
public void Returns_accepts_extension_method_with_correct_parameter_count()
{
Func<object, object, IType> delegateWithCorrectParameterCount = new ReturnsValidationFixture().ExtensionMethod;
this.setup.Returns(delegateWithCorrectParameterCount);
var ex = Record.Exception(() =>
{
this.mock.Object.Method(42, 5);
});
Assert.Null(ex);
}
public interface IType
{
IType Method(object arg1, object arg2);
IType MethodNoArgs();
}
}
static class ReturnsValidationFixtureExtensions
{
internal static ReturnsValidationFixture.IType ExtensionMethod(this ReturnsValidationFixture fixture, object arg1, object arg2)
{
return default(ReturnsValidationFixture.IType);
}
internal static ReturnsValidationFixture.IType ExtensionMethodNoArgs(this ReturnsValidationFixture fixture)
{
return default(ReturnsValidationFixture.IType);
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using WebSharpJs.NodeJS;
using WebSharpJs.DOM;
using WebSharpJs.DOM.Events;
using WebSharpJs.Script;
using WebSharpJs.Electron;
using System.Collections.Generic;
#if !DEV
namespace ConvertUI
{
#endif
public class Startup
{
static WebSharpJs.NodeJS.Console console;
HtmlElement btnSubmit;
HtmlElement btnSource;
HtmlElement btnDestination;
HtmlElement source;
HtmlElement destination;
HtmlElement name;
HtmlDocument document;
IpcRenderer ipcRenderer;
static readonly WebSharpJs.DOM.Events.Event changeEvent = new WebSharpJs.DOM.Events.Event(HtmlEventNames.Change);
/// <summary>
/// Default entry into managed code.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<object> Invoke(object input)
{
if (console == null)
console = await WebSharpJs.NodeJS.Console.Instance();
try
{
ipcRenderer = await IpcRenderer.Create();
document = await HtmlPage.GetDocument();
var form = await document.QuerySelector("form");
// Input fields
source = await form.QuerySelector("input[name=\"source\"]");
destination = await form.QuerySelector("input[name=\"destination\"]");
name = await form.QuerySelector("input[name=\"name\"]");
// Buttons
btnSource = await document.GetElementById("chooseSource");
btnDestination = await document.GetElementById("chooseDestination");
btnSubmit = await form.QuerySelector("button[type=\"submit\"]");
// Handle input fields
await source.AttachEvent(HtmlEventNames.Input, updateUI);
await source.AttachEvent(HtmlEventNames.Change, updateUI);
await destination.AttachEvent(HtmlEventNames.Input, updateUI);
await destination.AttachEvent(HtmlEventNames.Change, updateUI);
await name.AttachEvent(HtmlEventNames.Input, updateUI);
// Handle buttons
await btnSource.AttachEvent(HtmlEventNames.Click, handleSource);
await btnDestination.AttachEvent(HtmlEventNames.Click, handleDestination);
// Handle form Submit
await form.AttachEvent(HtmlEventNames.Submit,
async (s,e) => {
e.PreventDefault();
await ToggleUI(true);
// Send off the convert request
await ipcRenderer.Send("submitform",
await source.GetProperty<string>("value"),
await destination.GetProperty<string>("value"),
await name.GetProperty<string>("value")
);
}
);
await ipcRenderer.AddListener("gotMetaData",
new IpcRendererEventListener(
async (result) =>
{
var state = result.CallbackState as object[];
var ipcMainEvent = (IpcRendererEvent)state[0];
var parms = state[1] as object[];
var audio = ScriptObjectHelper.AnonymousObjectToScriptableType<Audio>(parms[0]);
var video = ScriptObjectHelper.AnonymousObjectToScriptableType<Video>(parms[1]);
var duration = TimeSpan.Parse(parms[2].ToString());
await updateInfo(audio, video, duration);
}
)
);
await ipcRenderer.AddListener("completed",
new IpcRendererEventListener(
async (result) =>
{
await ToggleUI(false);
}
)
);
await console.Log($"Hello: {input}");
}
catch (Exception exc) { await console.Log($"extension exception: {exc.Message}"); }
return null;
}
async void handleSource (object sender, EventArgs args)
{
var dialog = await Dialog.Instance();
// Create an OpenDialogOptions reference with custom FileFilters
var openOptions = new OpenDialogOptions()
{
Filters = new FileFilter[]
{
//new FileFilter() { Name = "All Files", Extensions = new string[] {"*"} },
new FileFilter() { Name = "Movies", Extensions = new string[] {"mkv", "avi"}},
}
};
// Now show the open dialog passing in the options created previously
// and a call back function when a file is selected.
// If a call back function is not specified then the ShowOpenDialog function
// will return an array of the selected file(s) or an empty array if no
// files are selected.
var sourceFile = await dialog.ShowOpenDialog(await BrowserWindow.GetFocusedWindow(),
openOptions
);
if (sourceFile != null && sourceFile.Length > 0)
{
await source.SetProperty("value", sourceFile[0]);
await name.SetProperty("value", Path.GetFileNameWithoutExtension(sourceFile[0]) + ".m4v");
await source.DispatchEvent(changeEvent);
await ipcRenderer.Send("getMetaData", sourceFile[0]);
}
}
async void handleDestination (object sender, EventArgs args)
{
var dialog = await Dialog.Instance();
// Create an OpenDialogOptions reference with custom Properties
var openOptions = new OpenDialogOptions()
{
PropertyFlags = OpenDialogProperties.OpenDirectory | OpenDialogProperties.CreateDirectory
};
// Now show the open dialog passing in the options created previously
// and a call back function when a file is selected.
// If a call back function is not specified then the ShowOpenDialog function
// will return an array of the selected file(s) or an empty array if no
// files are selected.
var destDirectory = await dialog.ShowOpenDialog(await BrowserWindow.GetFocusedWindow(),
openOptions
);
if (destDirectory != null && destDirectory.Length > 0)
{
await destination.SetProperty("value", destDirectory[0]);
await destination.DispatchEvent(changeEvent);
}
}
async Task ToggleUI(bool protect)
{
if (protect)
{
await btnSource.SetAttribute("disabled", "");
await btnDestination.SetAttribute("disabled", "");
await destination.SetAttribute("readonly", "");
await name.SetAttribute("readonly", "");
// update our submit button to loading and disabled
await btnSubmit.SetProperty("innerHTML", "<i class='fa fa-circle-o-notch fa-spin'></i> Converting ...");
await btnSubmit.SetAttribute("disabled", "");
}
else
{
await btnSource.RemoveAttribute("disabled");
await btnDestination.RemoveAttribute("disabled");
await destination.RemoveAttribute("readonly");
await name.RemoveAttribute("readonly");
// update our submit button to loading and disabled
await btnSubmit.SetProperty("innerText", "Convert");
await btnSubmit.RemoveAttribute("disabled");
}
}
async void updateUI (object sender, EventArgs args)
{
var srcValue = (await source.GetProperty<string>("value")).Trim();
var destValue = (await destination.GetProperty<string>("value")).Trim();
var nameValue = (await name.GetProperty<string>("value")).Trim();
if (!string.IsNullOrEmpty(srcValue)
&& !string.IsNullOrEmpty(destValue)
&& !string.IsNullOrEmpty(nameValue))
{
await btnSubmit.RemoveAttribute("disabled");
await removeClass(btnSubmit, "btn-outline-primary");
await addClass(btnSubmit, "btn-primary");
}
else
{
await btnSubmit.SetAttribute("disabled", "");
await removeClass(btnSubmit, "btn-primary");
await addClass(btnSubmit, "btn-outline-primary");
}
}
async Task updateInfo(Audio audio, Video video, TimeSpan duration)
{
var durInfo = await document.GetElementById("duration");
await durInfo.SetProperty("innerText", duration.ToString());
var videoFormat = await document.GetElementById("videoFormat");
var vidString = $"<b>Format:</b> {video.Format}<br/><b>Fps:</b> {video.Fps}";
await videoFormat.SetProperty("innerHTML", vidString);
var audioFormat = await document.GetElementById("audioFormat");
var audString = $"<b>Format:</b>{audio.Format}<br/><b>BitRate:</b> {audio.BitRateKbs}";
await audioFormat.SetProperty("innerHTML", audString);
}
# region CSS Class minipulation
static readonly char[] rnothtmlwhite = new char[] {' ','\r','\n','\t','\f' };
bool IsHasClass(string elementClass, string className)
{
if (string.IsNullOrEmpty(elementClass) || string.IsNullOrEmpty(className))
return false;
return elementClass.Split(rnothtmlwhite, StringSplitOptions.RemoveEmptyEntries).Contains(className);
}
async Task<string> addClass(HtmlElement element, string klass, string elementClass = null)
{
if (string.IsNullOrEmpty(elementClass))
{
elementClass = await element.GetCssClass();
}
if (!IsHasClass(elementClass, klass))
{
elementClass += $" {klass} ";
await element.SetCssClass(elementClass);
}
return elementClass;
}
async Task<bool> removeClass(HtmlElement element, string klass, string elementClass = null)
{
if (string.IsNullOrEmpty(elementClass))
{
elementClass = await element.GetCssClass();
}
if (IsHasClass(elementClass, klass))
{
var classList = elementClass.Split(rnothtmlwhite, StringSplitOptions.RemoveEmptyEntries).ToList();
classList.Remove(klass);
await element.SetCssClass(string.Join(" ",classList));
return true;
}
return false;
}
#endregion
}
[ScriptableType]
public class Video
{
public string Format { get; internal set; }
public string ColorModel { get; internal set; }
public string FrameSize { get; internal set; }
public int? BitRateKbs { get; internal set; }
public double Fps { get; internal set; }
}
[ScriptableType]
public class Audio
{
public string Format { get; internal set; }
public string SampleRate { get; internal set; }
public string ChannelOutput { get; internal set; }
public int BitRateKbs { get; internal set; }
}
#if !DEV
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
public abstract class NameVisitorCreator
{
private static readonly CSharpNameVisitorCreator[] _csCreators =
(from x in Enumerable.Range(0, (int)NameOptions.All + 1)
select new CSharpNameVisitorCreator((NameOptions)x)).ToArray();
private static readonly VBNameVisitorCreator[] _vbCreators =
(from x in Enumerable.Range(0, (int)NameOptions.All + 1)
select new VBNameVisitorCreator((NameOptions)x)).ToArray();
protected NameVisitorCreator()
{
}
public string GetName(ISymbol symbol)
{
var visitor = Create();
symbol.Accept(visitor);
return visitor.GetTypeName();
}
protected abstract NameVisitor Create();
public static NameVisitorCreator GetCSharp(NameOptions option)
{
if (option < NameOptions.None || option > NameOptions.All)
{
throw new ArgumentOutOfRangeException("option");
}
return _csCreators[(int)option];
}
public static NameVisitorCreator GetVB(NameOptions option)
{
if (option < NameOptions.None || option > NameOptions.All)
{
throw new ArgumentOutOfRangeException("option");
}
return _vbCreators[(int)option];
}
}
public abstract class NameVisitor : SymbolVisitor
{
private readonly StringBuilder sb;
protected NameVisitor()
{
sb = new StringBuilder();
}
protected void Append(string text)
{
sb.Append(text);
}
internal string GetTypeName()
{
return sb.ToString();
}
}
[Flags]
public enum NameOptions
{
None = 0,
UseAlias = 1,
WithNamespace = 2,
WithTypeGenericParameter = 4,
WithParameter = 8,
WithType = 16,
WithMethodGenericParameter = 32,
WithGenericParameter = WithTypeGenericParameter | WithMethodGenericParameter,
Qualified = WithNamespace | WithType,
All = UseAlias | WithNamespace | WithTypeGenericParameter | WithParameter | WithType | WithMethodGenericParameter,
}
public class CSharpNameVisitorCreator : NameVisitorCreator
{
private readonly NameOptions _options;
public CSharpNameVisitorCreator(NameOptions options)
{
_options = options;
}
protected override NameVisitor Create()
{
return new CSharpNameVisitor(_options);
}
}
internal sealed class CSharpNameVisitor : NameVisitor
{
private readonly NameOptions Options;
public CSharpNameVisitor(NameOptions options)
{
Options = options;
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if ((Options & NameOptions.UseAlias) == NameOptions.UseAlias &&
TrySpecialType(symbol))
{
return;
}
if (symbol.ContainingType != null)
{
symbol.ContainingType.Accept(this);
Append(".");
}
else if ((Options & NameOptions.WithNamespace) == NameOptions.WithNamespace)
{
if (!symbol.ContainingNamespace.IsGlobalNamespace)
{
symbol.ContainingNamespace.Accept(this);
Append(".");
}
}
Append(symbol.Name);
if ((Options & NameOptions.WithTypeGenericParameter) == NameOptions.WithTypeGenericParameter &&
symbol.TypeParameters.Length > 0)
{
if (symbol.TypeArguments != null && symbol.TypeArguments.Length > 0)
{
if (symbol.IsUnboundGenericType)
{
WriteGeneric(symbol.TypeArguments.Length);
}
else
{
WriteGeneric(symbol.TypeArguments);
}
}
else
{
WriteGeneric(symbol.TypeParameters);
}
}
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
Append(VisitorHelper.GlobalNamespaceId);
return;
}
if (!symbol.ContainingNamespace.IsGlobalNamespace)
{
symbol.ContainingNamespace.Accept(this);
Append(".");
}
Append(symbol.Name);
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
symbol.ElementType.Accept(this);
if (symbol.Rank == 1)
{
Append("[]");
}
else
{
Append("[");
for (int i = 1; i < symbol.Rank; i++)
{
Append(",");
}
Append("]");
}
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this);
Append("*");
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
Append(symbol.Name);
}
public override void VisitMethod(IMethodSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
switch (symbol.MethodKind)
{
case MethodKind.Constructor:
Append(symbol.ContainingType.Name);
break;
case MethodKind.Conversion:
if (symbol.Name == "op_Explicit")
{
Append("Explicit");
}
else if (symbol.Name == "op_Implicit")
{
Append("Implicit");
}
else
{
Debug.Fail("Unexpected conversion name.");
Append(symbol.Name);
}
break;
case MethodKind.UserDefinedOperator:
if (symbol.Name.StartsWith("op_"))
{
Append(symbol.Name.Substring(3));
}
else
{
Debug.Fail("Operator should start with 'op_'");
Append(symbol.Name);
}
break;
default:
if (symbol.ExplicitInterfaceImplementations.Length == 0)
{
Append(symbol.Name);
}
else
{
var interfaceMethod = symbol.ExplicitInterfaceImplementations[0];
if ((Options & NameOptions.WithType) == NameOptions.None)
{
interfaceMethod.ContainingType.Accept(this);
Append(".");
}
interfaceMethod.Accept(this);
return;
}
break;
}
if (symbol.IsGenericMethod &&
(Options & NameOptions.WithMethodGenericParameter) == NameOptions.WithMethodGenericParameter)
{
Append("<");
var typeParams = symbol.TypeArguments.Length > 0 ? symbol.TypeArguments.CastArray<ISymbol>() : symbol.TypeParameters.CastArray<ISymbol>();
for (int i = 0; i < typeParams.Length; i++)
{
if (i > 0)
{
Append(", ");
}
typeParams[i].Accept(this);
}
Append(">");
}
if ((Options & NameOptions.WithParameter) == NameOptions.WithParameter)
{
Append("(");
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
Append(", ");
}
symbol.Parameters[i].Accept(this);
if (symbol.MethodKind == MethodKind.Conversion && !symbol.ReturnsVoid)
{
Append(" to ");
symbol.ReturnType.Accept(this);
}
}
Append(")");
}
}
public override void VisitProperty(IPropertySymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
if (symbol.ExplicitInterfaceImplementations.Length > 0)
{
var interfaceProperty = symbol.ExplicitInterfaceImplementations[0];
if ((Options & NameOptions.WithType) == NameOptions.None)
{
interfaceProperty.ContainingType.Accept(this);
Append(".");
}
interfaceProperty.Accept(this);
return;
}
if (symbol.Parameters.Length > 0)
{
if ((Options & NameOptions.UseAlias) == NameOptions.UseAlias)
{
Append("this");
}
else
{
Append(symbol.MetadataName);
}
if ((Options & NameOptions.WithParameter) == NameOptions.WithParameter)
{
Append("[");
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
Append(", ");
}
symbol.Parameters[i].Accept(this);
}
Append("]");
}
}
else
{
Append(symbol.Name);
}
}
public override void VisitEvent(IEventSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
if (symbol.ExplicitInterfaceImplementations.Length > 0)
{
var interfaceEvent = symbol.ExplicitInterfaceImplementations[0];
if ((Options & NameOptions.WithType) == NameOptions.None)
{
interfaceEvent.ContainingType.Accept(this);
Append(".");
}
interfaceEvent.Accept(this);
}
else
{
Append(symbol.Name);
}
}
public override void VisitField(IFieldSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
Append(symbol.Name);
}
public override void VisitParameter(IParameterSymbol symbol)
{
if (symbol.RefKind == RefKind.Ref)
{
Append("ref ");
}
else if (symbol.RefKind == RefKind.Out)
{
Append("out ");
}
symbol.Type.Accept(this);
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
if ((Options & NameOptions.UseAlias) == NameOptions.UseAlias)
{
Append("dynamic");
}
else if ((Options & NameOptions.WithNamespace) == NameOptions.WithNamespace)
{
Append(typeof(object).FullName);
}
else
{
Append(typeof(object).Name);
}
}
private bool TrySpecialType(INamedTypeSymbol symbol)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Object:
Append("object");
return true;
case SpecialType.System_Void:
Append("void");
return true;
case SpecialType.System_Boolean:
Append("bool");
return true;
case SpecialType.System_Char:
Append("char");
return true;
case SpecialType.System_SByte:
Append("sbyte");
return true;
case SpecialType.System_Byte:
Append("byte");
return true;
case SpecialType.System_Int16:
Append("short");
return true;
case SpecialType.System_UInt16:
Append("ushort");
return true;
case SpecialType.System_Int32:
Append("int");
return true;
case SpecialType.System_UInt32:
Append("uint");
return true;
case SpecialType.System_Int64:
Append("long");
return true;
case SpecialType.System_UInt64:
Append("ulong");
return true;
case SpecialType.System_Decimal:
Append("decimal");
return true;
case SpecialType.System_Single:
Append("float");
return true;
case SpecialType.System_Double:
Append("double");
return true;
case SpecialType.System_String:
Append("string");
return true;
default:
if (symbol.IsGenericType && !symbol.IsDefinition && symbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
symbol.TypeArguments[0].Accept(this);
Append("?");
return true;
}
return false;
}
}
private void WriteGeneric(int typeParameterCount)
{
Append("<");
for (int i = 1; i < typeParameterCount; i++)
{
Append(",");
}
Append(">");
}
private void WriteGeneric(IReadOnlyList<ITypeSymbol> types)
{
Append("<");
for (int i = 0; i < types.Count; i++)
{
if (i > 0)
{
Append(", ");
}
types[i].Accept(this);
}
Append(">");
}
}
public class VBNameVisitorCreator : NameVisitorCreator
{
private readonly NameOptions _options;
public VBNameVisitorCreator(NameOptions options)
{
_options = options;
}
protected override NameVisitor Create()
{
return new VBNameVisitor(_options);
}
}
internal sealed class VBNameVisitor : NameVisitor
{
private readonly NameOptions Options;
public VBNameVisitor(NameOptions options)
{
Options = options;
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if ((Options & NameOptions.UseAlias) == NameOptions.UseAlias &&
TrySpecialType(symbol))
{
return;
}
if (symbol.ContainingType != null)
{
symbol.ContainingType.Accept(this);
Append(".");
}
else if ((Options & NameOptions.WithNamespace) == NameOptions.WithNamespace)
{
if (!symbol.ContainingNamespace.IsGlobalNamespace)
{
symbol.ContainingNamespace.Accept(this);
Append(".");
}
}
Append(symbol.Name);
if ((Options & NameOptions.WithTypeGenericParameter) == NameOptions.WithTypeGenericParameter &&
symbol.TypeParameters.Length > 0)
{
if (symbol.TypeArguments != null && symbol.TypeArguments.Length > 0)
{
if (symbol.IsUnboundGenericType)
{
WriteGeneric(symbol.TypeArguments.Length);
}
else
{
WriteGeneric(symbol.TypeArguments);
}
}
else
{
WriteGeneric(symbol.TypeParameters);
}
}
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
return;
}
if (!symbol.ContainingNamespace.IsGlobalNamespace)
{
symbol.ContainingNamespace.Accept(this);
Append(".");
}
Append(symbol.Name);
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
symbol.ElementType.Accept(this);
if (symbol.Rank == 1)
{
Append("()");
}
else
{
Append("(");
for (int i = 1; i < symbol.Rank; i++)
{
Append(",");
}
Append(")");
}
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
symbol.PointedAtType.Accept(this);
Append("*");
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
Append(symbol.Name);
}
public override void VisitMethod(IMethodSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
switch (symbol.MethodKind)
{
case MethodKind.Constructor:
Append(symbol.ContainingType.Name);
break;
case MethodKind.Conversion:
if (symbol.Name == "op_Explicit")
{
Append("Narrowing");
}
else if (symbol.Name == "op_Implicit")
{
Append("Widening");
}
else
{
Debug.Fail("Unexpected conversion name.");
Append(symbol.Name);
}
break;
case MethodKind.UserDefinedOperator:
if (symbol.Name.StartsWith("op_"))
{
Append(symbol.Name.Substring(3));
}
else
{
Debug.Fail("Operator should start with 'op_'");
Append(symbol.Name);
}
break;
default:
Append(symbol.Name);
break;
}
if (symbol.IsGenericMethod &&
(Options & NameOptions.WithMethodGenericParameter) == NameOptions.WithMethodGenericParameter)
{
Append("(Of ");
var typeParams = symbol.TypeArguments.Length > 0 ? symbol.TypeArguments.CastArray<ISymbol>() : symbol.TypeParameters.CastArray<ISymbol>();
for (int i = 0; i < typeParams.Length; i++)
{
if (i > 0)
{
Append(", ");
}
typeParams[i].Accept(this);
}
Append(")");
}
if ((Options & NameOptions.WithParameter) == NameOptions.WithParameter)
{
Append("(");
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
Append(", ");
}
symbol.Parameters[i].Accept(this);
if (symbol.MethodKind == MethodKind.Conversion && !symbol.ReturnsVoid)
{
Append(" to ");
symbol.ReturnType.Accept(this);
}
}
Append(")");
}
}
public override void VisitProperty(IPropertySymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
Append(symbol.MetadataName);
if ((Options & NameOptions.WithParameter) == NameOptions.WithParameter)
{
if (symbol.Parameters.Length > 0)
{
Append("(");
for (int i = 0; i < symbol.Parameters.Length; i++)
{
if (i > 0)
{
Append(", ");
}
symbol.Parameters[i].Accept(this);
}
Append(")");
}
}
}
public override void VisitEvent(IEventSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
Append(symbol.Name);
}
public override void VisitField(IFieldSymbol symbol)
{
if ((Options & NameOptions.WithType) == NameOptions.WithType)
{
symbol.ContainingType.Accept(this);
Append(".");
}
Append(symbol.Name);
}
public override void VisitParameter(IParameterSymbol symbol)
{
if (symbol.RefKind != RefKind.None)
{
Append("ByRef ");
}
symbol.Type.Accept(this);
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
if ((Options & NameOptions.WithNamespace) == NameOptions.WithNamespace)
{
Append(typeof(object).FullName);
}
else
{
Append(typeof(object).Name);
}
}
private bool TrySpecialType(INamedTypeSymbol symbol)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Object:
Append("Object");
return true;
case SpecialType.System_Void:
return true;
case SpecialType.System_Boolean:
Append("Boolean");
return true;
case SpecialType.System_Char:
Append("Char");
return true;
case SpecialType.System_SByte:
Append("SByte");
return true;
case SpecialType.System_Byte:
Append("Byte");
return true;
case SpecialType.System_Int16:
Append("Short");
return true;
case SpecialType.System_UInt16:
Append("UShort");
return true;
case SpecialType.System_Int32:
Append("Integer");
return true;
case SpecialType.System_UInt32:
Append("UInteger");
return true;
case SpecialType.System_Int64:
Append("Long");
return true;
case SpecialType.System_UInt64:
Append("ULong");
return true;
case SpecialType.System_DateTime:
Append("Date");
return true;
case SpecialType.System_Decimal:
Append("Decimal");
return true;
case SpecialType.System_Single:
Append("Single");
return true;
case SpecialType.System_Double:
Append("Double");
return true;
case SpecialType.System_String:
Append("String");
return true;
default:
if (symbol.IsGenericType && !symbol.IsDefinition && symbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
symbol.TypeArguments[0].Accept(this);
Append("?");
return true;
}
return false;
}
}
private void WriteGeneric(int typeParameterCount)
{
Append("(Of ");
for (int i = 1; i < typeParameterCount; i++)
{
Append(",");
}
Append(")");
}
private void WriteGeneric(IReadOnlyList<ITypeSymbol> types)
{
Append("(Of ");
for (int i = 0; i < types.Count; i++)
{
if (i > 0)
{
Append(", ");
}
types[i].Accept(this);
}
Append(")");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Security;
using System.Runtime.CompilerServices;
namespace System.Text
{
// DBCSCodePageEncoding
//
internal class DBCSCodePageEncoding : BaseCodePageEncoding
{
// Pointers to our memory section parts
protected unsafe char* mapBytesToUnicode = null; // char 65536
protected unsafe ushort* mapUnicodeToBytes = null; // byte 65536
protected const char UNKNOWN_CHAR_FLAG = (char)0x0;
protected const char UNICODE_REPLACEMENT_CHAR = (char)0xFFFD;
protected const char LEAD_BYTE_CHAR = (char)0xFFFE; // For lead bytes
// Note that even though we provide bytesUnknown and byteCountUnknown,
// They aren't actually used because of the fallback mechanism. (char is though)
private ushort _bytesUnknown;
private int _byteCountUnknown;
protected char charUnknown = (char)0;
public DBCSCodePageEncoding(int codePage) : this(codePage, codePage)
{
}
internal DBCSCodePageEncoding(int codePage, int dataCodePage) : base(codePage, dataCodePage)
{
}
internal DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codePage, dataCodePage, enc, dec)
{
}
// MBCS data section:
//
// We treat each multibyte pattern as 2 bytes in our table. If it's a single byte, then the high byte
// for that position will be 0. When the table is loaded, leading bytes are flagged with 0xFFFE, so
// when reading the table look up with each byte. If the result is 0xFFFE, then use 2 bytes to read
// further data. FFFF is a special value indicating that the Unicode code is the same as the
// character code (this helps us support code points < 0x20). FFFD is used as replacement character.
//
// Normal table:
// WCHAR* - Starting with MB code point 0.
// FFFF indicates we are to use the multibyte value for our code point.
// FFFE is the lead byte mark. (This should only appear in positions < 0x100)
// FFFD is the replacement (unknown character) mark.
// 2-20 means to advance the pointer 2-0x20 characters.
// 1 means to advance to the multibyte position contained in the next char.
// 0 has no specific meaning (May not be possible.)
//
// Table ends when multibyte position has advanced to 0xFFFF.
//
// Bytes->Unicode Best Fit table:
// WCHAR* - Same as normal table, except first wchar is byte position to start at.
//
// Unicode->Bytes Best Fit Table:
// WCHAR* - Same as normal table, except first wchar is char position to start at and
// we loop through unicode code points and the table has the byte points that
// correspond to those unicode code points.
// We have a managed code page entry, so load our tables
//
protected override unsafe void LoadManagedCodePage()
{
Debug.Assert(m_codePageHeader?.Length > 0);
fixed (byte* pBytes = &m_codePageHeader![0])
{
CodePageHeader* pCodePage = (CodePageHeader*)pBytes;
// Should be loading OUR code page
Debug.Assert(pCodePage->CodePage == dataTableCodePage,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page");
// Make sure we're really a 1-byte code page
if (pCodePage->ByteCount != 2)
throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage));
// Remember our unknown bytes & chars
_bytesUnknown = pCodePage->ByteReplace;
charUnknown = pCodePage->UnicodeReplace;
// Need to make sure the fallback buffer's fallback char is correct
if (DecoderFallback is InternalDecoderBestFitFallback)
{
((InternalDecoderBestFitFallback)(DecoderFallback)).cReplacement = charUnknown;
}
// Is our replacement bytesUnknown a single or double byte character?
_byteCountUnknown = 1;
if (_bytesUnknown > 0xff)
_byteCountUnknown++;
// We use fallback encoder, which uses ?, which so far all of our tables do as well
Debug.Assert(_bytesUnknown == 0x3f,
"[DBCSCodePageEncoding.LoadManagedCodePage]Expected 0x3f (?) as unknown byte character");
// Get our mapped section (bytes to allocate = 2 bytes per 65536 Unicode chars + 2 bytes per 65536 DBCS chars)
// Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment)
int sizeToAllocate = 65536 * 2 * 2 + 4 + iExtraBytes;
byte* pNativeMemory = GetNativeMemory(sizeToAllocate);
Unsafe.InitBlockUnaligned(pNativeMemory, 0, (uint)sizeToAllocate);
mapBytesToUnicode = (char*)pNativeMemory;
mapUnicodeToBytes = (ushort*)(pNativeMemory + 65536 * 2);
// Need to read our data file and fill in our section.
// WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide)
// so be careful here. Only stick legal values in here, don't stick temporary values.
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytePosition = 0;
int useBytes = 0;
while (bytePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytePosition = (int)(*pData);
pData++;
continue;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytePosition += input;
continue;
}
else if (input == 0xFFFF)
{
// Same as our bytePosition
useBytes = bytePosition;
input = unchecked((char)bytePosition);
}
else if (input == LEAD_BYTE_CHAR) // 0xfffe
{
// Lead byte mark
Debug.Assert(bytePosition < 0x100, "[DBCSCodePageEncoding.LoadManagedCodePage]expected lead byte to be < 0x100");
useBytes = bytePosition;
// input stays 0xFFFE
}
else if (input == UNICODE_REPLACEMENT_CHAR)
{
// Replacement char is already done
bytePosition++;
continue;
}
else
{
// Use this character
useBytes = bytePosition;
// input == input;
}
// We may need to clean up the selected character & position
if (CleanUpBytes(ref useBytes))
{
// Use this selected character at the selected position, don't do this if not supposed to.
if (input != LEAD_BYTE_CHAR)
{
// Don't do this for lead byte marks.
mapUnicodeToBytes[input] = unchecked((ushort)useBytes);
}
mapBytesToUnicode[useBytes] = input;
}
bytePosition++;
}
}
// See if we have any clean up to do
CleanUpEndBytes(mapBytesToUnicode);
}
}
// Any special processing for this code page
protected virtual bool CleanUpBytes(ref int bytes)
{
return true;
}
// Any special processing for this code page
protected virtual unsafe void CleanUpEndBytes(char* chars)
{
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static object? s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Read in our best fit table
protected unsafe override void ReadBestFitTable()
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// If we got a best fit array already then don't do this
if (arrayUnicodeBestFit == null)
{
//
// Read in Best Fit table.
//
// First we have to advance past original character mapping table
// Move to the beginning of the data section
byte[] buffer = new byte[m_dataSize];
lock (s_streamLock)
{
s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
s_codePagesEncodingDataStream.Read(buffer, 0, m_dataSize);
}
fixed (byte* pBuffer = buffer)
{
char* pData = (char*)pBuffer;
// We start at bytes position 0
int bytesPosition = 0;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// All other cases add 1 to bytes position
bytesPosition++;
}
}
// Now bytesPosition is at start of bytes->unicode best fit table
char* pBytes2Unicode = pData;
// Now pData should be pointing to first word of bytes -> unicode best fit table
// (which we're also not using at the moment)
int iBestFitCount = 0;
bytesPosition = *pData;
pData++;
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless it's unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them the same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
iBestFitCount++;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// Now we know how big the best fit table has to be
char[] arrayTemp = new char[iBestFitCount * 2];
// Now we know how many best fits we have, so go back & read them in
iBestFitCount = 0;
pData = pBytes2Unicode;
bytesPosition = *pData;
pData++;
bool bOutOfOrder = false;
// Read it all in again
while (bytesPosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
bytesPosition = (int)(*pData);
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
bytesPosition += input;
}
else
{
// Use this character (unless its unknown, unk just skips 1)
if (input != UNICODE_REPLACEMENT_CHAR)
{
int correctedChar = bytesPosition;
if (CleanUpBytes(ref correctedChar))
{
// Sometimes correction makes them same as no best fit, skip those.
if (mapBytesToUnicode[correctedChar] != input)
{
if (correctedChar != bytesPosition)
bOutOfOrder = true;
arrayTemp[iBestFitCount++] = unchecked((char)correctedChar);
arrayTemp[iBestFitCount++] = input;
}
}
}
// Position gets incremented in any case.
bytesPosition++;
}
}
// If they're out of order we need to sort them.
if (bOutOfOrder)
{
Debug.Assert((arrayTemp.Length / 2) < 20,
"[DBCSCodePageEncoding.ReadBestFitTable]Expected small best fit table < 20 for code page " + CodePage + ", not " + arrayTemp.Length / 2);
for (int i = 0; i < arrayTemp.Length - 2; i += 2)
{
int iSmallest = i;
char cSmallest = arrayTemp[i];
for (int j = i + 2; j < arrayTemp.Length; j += 2)
{
// Find smallest one for front
if (cSmallest > arrayTemp[j])
{
cSmallest = arrayTemp[j];
iSmallest = j;
}
}
// If smallest one is something else, switch them
if (iSmallest != i)
{
char temp = arrayTemp[iSmallest];
arrayTemp[iSmallest] = arrayTemp[i];
arrayTemp[i] = temp;
temp = arrayTemp[iSmallest + 1];
arrayTemp[iSmallest + 1] = arrayTemp[i + 1];
arrayTemp[i + 1] = temp;
}
}
}
// Remember our array
arrayBytesBestFit = arrayTemp;
// Now were at beginning of Unicode -> Bytes best fit table, need to count them
char* pUnicode2Bytes = pData;
int unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
// Same as our unicodePosition or use this character
if (input > 0)
iBestFitCount++;
unicodePosition++;
}
}
// Allocate our table
arrayTemp = new char[iBestFitCount * 2];
// Now do it again to fill the array with real values
pData = pUnicode2Bytes;
unicodePosition = *(pData++);
iBestFitCount = 0;
while (unicodePosition < 0x10000)
{
// Get the next byte
char input = *pData;
pData++;
// build our table:
if (input == 1)
{
// Use next data as our byte position
unicodePosition = (int)*pData;
pData++;
}
else if (input < 0x20 && input > 0)
{
// Advance input characters
unicodePosition += input;
}
else
{
if (input > 0)
{
// Use this character, may need to clean it up
int correctedChar = (int)input;
if (CleanUpBytes(ref correctedChar))
{
arrayTemp[iBestFitCount++] = unchecked((char)unicodePosition);
// Have to map it to Unicode because best fit will need Unicode value of best fit char.
arrayTemp[iBestFitCount++] = mapBytesToUnicode[correctedChar];
}
}
unicodePosition++;
}
}
// Remember our array
arrayUnicodeBestFit = arrayTemp;
}
}
}
}
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
public override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetByteCount]Attempting to use null fallback");
CheckMemorySection();
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
// Only count if encoder.m_throwOnOverflow
if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
}
// prepare our end
int byteCount = 0;
char* charEnd = chars + count;
// For fallback we will need a fallback buffer
EncoderFallbackBuffer? fallbackBuffer = null;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(char.IsHighSurrogate(charLeftOver), "[DBCSCodePageEncoding.GetByteCount]leftover character should be high surrogate");
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetByteCount]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder!.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already (from the encoder)
// We have to use fallback method.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = EncoderFallback!.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - count, charEnd, encoder, false);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
if (sTemp >= 0x100)
byteCount++;
}
return (int)byteCount;
}
public override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS? encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetBytes]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetBytes]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetBytes]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(EncoderFallback != null, "[DBCSCodePageEncoding.GetBytes]Attempting to use null encoder fallback");
CheckMemorySection();
// For fallback we will need a fallback buffer
EncoderFallbackBuffer? fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
char* charStart = chars;
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
EncoderFallbackBufferHelper fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
// Get any left over characters
char charLeftOver = (char)0;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver),
"[DBCSCodePageEncoding.GetBytes]leftover character should be high surrogate");
// Go ahead and get the fallback buffer (need leftover fallback if converting)
fallbackBuffer = encoder.FallbackBuffer;
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(chars, charEnd, encoder, true);
// If we're not converting we must not have a fallback buffer
if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(encoder != null,
"[DBCSCodePageEncoding.GetBytes]Expect to have encoder if we have a charLeftOver");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackHelper.InternalFallback(charLeftOver, ref chars);
}
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackHelper.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// get byte for this char
ushort sTemp = mapUnicodeToBytes[ch];
// Check for fallback, this'll catch surrogate pairs too.
if (sTemp == 0 && ch != (char)0)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
Debug.Assert(encoder == null,
"[DBCSCodePageEncoding.GetBytes]Expected delayed create fallback only if no encoder.");
fallbackBuffer = EncoderFallback!.CreateFallbackBuffer();
fallbackHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackHelper.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one (or two)
// Bounds check
// Go ahead and add it, lead byte 1st if necessary
if (sTemp >= 0x100)
{
if (bytes + 1 >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (double byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp >> 8));
bytes++;
}
// Single byte
else if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackHelper.bFallingBack == false)
{
Debug.Assert(chars > charStart,
"[DBCSCodePageEncoding.GetBytes]Expected chars to have advanced (single byte case)");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious(); // don't use last fallback
ThrowBytesOverflow(encoder, chars == charStart); // throw ?
break; // don't throw, stop
}
*bytes = unchecked((byte)(sTemp & 0xff));
bytes++;
}
// encoder stuff if we have one
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackHelper.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
public override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[DBCSCodePageEncoding.GetCharCount]byteCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder? decoder = (DBCSDecoder?)baseDecoder;
// Get our fallback
DecoderFallbackBuffer? fallbackBuffer = null;
// We'll need to know where the end is
byte* byteEnd = bytes + count;
int charCount = count; // Assume 1 char / byte
// Shouldn't have anything in fallback buffer for GetCharCount
// (don't have to check m_throwOnOverflow for count)
Debug.Assert(decoder == null ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (count == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, null);
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
return fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// This is either 1 known char or fallback
// Already counted 1 char
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == 0 && iBytes != 0)
{
// Deallocate preallocated one
charCount--;
// We'll need a fallback
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer for unknown pair");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
// Do fallback, we know there are 2 bytes
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
// else we already reserved space for this one.
}
// Loop, watch out for fallbacks
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// It's a lead byte
charCount--; // deallocate preallocated lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
charCount++; // reallocate deallocated lead byte
c = UNKNOWN_CHAR_FLAG;
}
else
{
// We'll stick it in decoder
break;
}
}
}
// See if it was unknown.
// Unknown and known chars already allocated, but fallbacks aren't
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - count, null);
}
// Do fallback
charCount--; // Get rid of preallocated extra char
byte[] byteBuffer = iBytes < 0x100 ?
new byte[] { unchecked((byte)iBytes) } :
new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
charCount += fallbackHelper.InternalFallback(byteBuffer, bytes);
}
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetCharCount]Expected empty fallback buffer at end");
// Return our count
return charCount;
}
public override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS? baseDecoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[DBCSCodePageEncoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[DBCSCodePageEncoding.GetChars]byteCount is negative");
Debug.Assert(chars != null, "[DBCSCodePageEncoding.GetChars]chars is null");
Debug.Assert(charCount >= 0, "[DBCSCodePageEncoding.GetChars]charCount is negative");
CheckMemorySection();
// Fix our decoder
DBCSDecoder? decoder = (DBCSDecoder?)baseDecoder;
// We'll need to know where the end is
byte* byteStart = bytes;
byte* byteEnd = bytes + byteCount;
char* charStart = chars;
char* charEnd = chars + charCount;
bool bUsedDecoder = false;
// Get our fallback
DecoderFallbackBuffer? fallbackBuffer = null;
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at start");
DecoderFallbackBufferHelper fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
// If we have a left over byte, use it
if (decoder != null && decoder.bLeftOver > 0)
{
// We have a left over byte?
if (byteCount == 0)
{
// No input though
if (!decoder.MustFlush)
{
// Don't have to flush
return 0;
}
// Well, we're flushing, so use '?' or fallback
// fallback leftover byte
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(bytes, charEnd);
// If no room, it's hopeless, this was 1st fallback
byte[] byteBuffer = new byte[] { unchecked((byte)decoder.bLeftOver) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
decoder.bLeftOver = 0;
// Done, return it
return (int)(chars - charStart);
}
// Get our full info
int iBytes = decoder.bLeftOver << 8;
iBytes |= (*bytes);
bytes++;
// Look up our bytes
char cDecoder = mapBytesToUnicode[iBytes];
if (cDecoder == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
Debug.Assert(fallbackBuffer == null,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback for two bytes");
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
byte[] byteBuffer = new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
ThrowCharsOverflow(decoder, true);
}
else
{
// Do we have output room?, hopeless if not, this is first char
if (chars >= charEnd)
ThrowCharsOverflow(decoder, true);
*(chars++) = cDecoder;
}
}
// Loop, paying attention to our fallbacks.
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
int iBytes = *bytes;
bytes++;
char c = mapBytesToUnicode[iBytes];
// See if it was a double byte character
if (c == LEAD_BYTE_CHAR)
{
// Its a lead byte
if (bytes < byteEnd)
{
// Have another to use, so use it
iBytes <<= 8;
iBytes |= *bytes;
bytes++;
c = mapBytesToUnicode[iBytes];
}
else
{
// No input left
if (decoder == null || decoder.MustFlush)
{
// have to flush anyway, set to unknown so we use fallback
c = UNKNOWN_CHAR_FLAG;
}
else
{
// Stick it in decoder
bUsedDecoder = true;
decoder.bLeftOver = (byte)iBytes;
break;
}
}
}
// See if it was unknown
if (c == UNKNOWN_CHAR_FLAG && iBytes != 0)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackHelper = new DecoderFallbackBufferHelper(fallbackBuffer);
fallbackHelper.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Do fallback
byte[] byteBuffer = iBytes < 0x100 ?
new byte[] { unchecked((byte)iBytes) } :
new byte[] { unchecked((byte)(iBytes >> 8)), unchecked((byte)iBytes) };
if (!fallbackHelper.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes >= byteStart + byteBuffer.Length,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for fallback");
bytes -= byteBuffer.Length; // didn't use these byte(s)
fallbackHelper.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Do we have buffer room?
if (chars >= charEnd)
{
// May or may not throw, but we didn't get these byte(s)
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for lead byte");
bytes--; // unused byte
if (iBytes >= 0x100)
{
Debug.Assert(bytes > byteStart,
"[DBCSCodePageEncoding.GetChars]Expected bytes to have advanced for trail byte");
bytes--; // 2nd unused byte
}
ThrowCharsOverflow(decoder, bytes == byteStart); // throw?
break; // don't throw, but stop loop
}
*(chars++) = c;
}
}
// We already stuck it in encoder if necessary, but we have to clear cases where nothing new got into decoder
if (decoder != null)
{
// Clear it in case of MustFlush
if (bUsedDecoder == false)
{
decoder.bLeftOver = 0;
}
// Remember our count
decoder.m_bytesUsed = (int)(bytes - byteStart);
}
// Shouldn't have anything in fallback buffer for GetChars
Debug.Assert(decoder == null || !decoder.m_throwOnOverflow ||
!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
"[DBCSCodePageEncoding.GetChars]Expected empty fallback buffer at end");
// Return length of our output
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 2 to 1 is worst case. Already considered surrogate fallback
byteCount *= 2;
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
// DBCS is pretty much the same, but could have hanging high byte making extra ? and fallback for unknown
long charCount = ((long)byteCount + 1);
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
public override Decoder GetDecoder()
{
return new DBCSDecoder(this);
}
internal class DBCSDecoder : DecoderNLS
{
// Need a place for the last left over byte
internal byte bLeftOver = 0;
public DBCSDecoder(DBCSCodePageEncoding encoding) : base(encoding)
{
// Base calls reset
}
public override void Reset()
{
bLeftOver = 0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Anything left in our decoder?
internal override bool HasState
{
get
{
return (bLeftOver != 0);
}
}
}
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap31 : TwMap {
public override int MapIndex => 31;
public override int MapID => 0x0C02;
protected override int RandomEncounterChance => 0;
protected override int RandomEncounterExtraCount => 0;
private const int CASETRAP2 = 1;
private const int FIGHT_ME = 2;
private const int IMHERE = 3;
private const int KEEPER = 4;
private const int LASTBATTLE = 5;
private const int USEDNEPTRI = 6;
private const int USEDGAEAFLAIL = 7;
private const int IHAVETHEFLAIL = 8;
private const int SPRUNGTRAP = 1;
private const int STORMGIANTS = 25;
private const int EOSBATTLE = 26;
private const int NEPTUNEBATTLE = 27;
private const int ARESBATTLE = 28;
private const int GAEABATTLE = 29;
private const int QUEENSGUARDONE = 30;
private const int QUEENSGUARDTWO = 31;
private const int QUEENSGUARDTHREE = 32;
private const int QUEENSGUARDFOUR = 33;
private const int HALLGUARD1 = 34;
private const int HALLGUARD2 = 35;
private const int HALLGUARD3 = 36;
private const int HALLGUARD4 = 37;
private const int HALLGUARD5 = 38;
private const int DRAKSNUMBER = 39;
private const int QUEENSNUMBER = 40;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Each of these four portals offers the passer-by an exotic weapon from a past visitor to this domain.");
if (GetPartyCount(player, type, doMsgs) == 1) {
if (HasItem(player, type, doMsgs, SWORDOFARES) || HasItem(player, type, doMsgs, BOWOFEOS) || HasItem(player, type, doMsgs, GAEASFLAIL) || HasItem(player, type, doMsgs, NEPTUNESTRIDENT)) {
ShowText(player, type, doMsgs, "You cannot enter here, you already have one of the weapons of the Gods.");
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
else {
ShowText(player, type, doMsgs, "Enter, and claim one of the four artifacts for your reward. You may only have one!");
ShowText(player, type, doMsgs, "Arm yourself with whichever artifact you choose before you challenge she who threatens the Gateway's existence.");
WallClear(player, type, doMsgs);
}
}
else {
ShowText(player, type, doMsgs, "Be off!! Only one Hero may enter here at a time!");
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, SWORDOFARES)) {
AssaultTxt(player, type, doMsgs);
TeleportParty(player, type, doMsgs, 12, 2, 68, Direction.North);
}
else {
AdvTxt(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, BOWOFEOS)) {
AssaultTxt(player, type, doMsgs);
TeleportParty(player, type, doMsgs, 12, 2, 64, Direction.North);
}
else {
AdvTxt(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, NEPTUNESTRIDENT)) {
AssaultTxt(player, type, doMsgs);
TeleportParty(player, type, doMsgs, 12, 2, 67, Direction.North);
}
else {
AdvTxt(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, PORTAL, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
WallClear(player, type, doMsgs);
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, GAEASFLAIL)) {
AssaultTxt(player, type, doMsgs);
TeleportParty(player, type, doMsgs, 12, 2, 65, Direction.North);
}
else {
AdvTxt(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
int itemA = 0;
switch (GetTile(player, type, doMsgs)) {
case 252:
itemA = GAEASFLAIL;
GaeasText(player, type, doMsgs);
break;
case 234:
itemA = SWORDOFARES;
AresText(player, type, doMsgs);
break;
case 203:
itemA = BOWOFEOS;
EosText(player, type, doMsgs);
break;
case 221:
itemA = NEPTUNESTRIDENT;
NeptunesTxt(player, type, doMsgs);
break;
}
if ((!HasItem(player, type, doMsgs, itemA))) {
GiveItem(player, type, doMsgs, itemA);
}
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "WARNING: This will only take you back to the Keepers room. You must retrace your steps or take a different path to proceed from there.");
TeleportParty(player, type, doMsgs, 12, 2, 0, Direction.East);
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Pure Dissemination lies through this portal.");
TeleportParty(player, type, doMsgs, 12, 1, 255, Direction.West);
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, LASTBATTLE) == 1) {
ShowText(player, type, doMsgs, "Before you, now mad with power and muttering spells upon spells, hovers Aeowyn. Using the Rings of Fate, she is trying to manipulate the Gateway of Immortality. Shaping its destination and purpose.");
ShowText(player, type, doMsgs, "She scorns you as you approach, 'FOOL! MORTAL! You were so easily subdued; so quick to crave the power I offered; you lost sight of yourself and succumbed to my desires.");
ShowText(player, type, doMsgs, "You shall learn the price of your ignorance! For only now, at the end do you understand. Had you kept the rings, had you breached the seal alone, then you may have had this power. But now, I WILL DESTROY YOU!'");
ShowText(player, type, doMsgs, "Aeowyn conjures four guardsmen to her aid, as well as summoning from their entombment, the five Dralkarians...");
AddEncounter(player, type, doMsgs, 01, QUEENSGUARDONE);
AddEncounter(player, type, doMsgs, 02, QUEENSGUARDTWO);
AddEncounter(player, type, doMsgs, 03, QUEENSGUARDTHREE);
AddEncounter(player, type, doMsgs, 04, QUEENSGUARDFOUR);
AddEncounter(player, type, doMsgs, 05, DRAKSNUMBER);
AddEncounter(player, type, doMsgs, 06, QUEENSNUMBER);
}
else {
ShowText(player, type, doMsgs, "Guardians of the Gateway are summoned to its defense as you attempt to gain access to its secrets.");
AddEncounter(player, type, doMsgs, 01, QUEENSGUARDONE);
AddEncounter(player, type, doMsgs, 02, QUEENSGUARDTWO);
AddEncounter(player, type, doMsgs, 03, QUEENSGUARDTHREE);
AddEncounter(player, type, doMsgs, 04, QUEENSGUARDFOUR);
AddEncounter(player, type, doMsgs, 05, DRAKSNUMBER);
}
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "An illusionary door fades away as you approach.");
ClearWallItem(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
int trap = 0;
trap = GetFlag(player, type, doMsgs, FlagTypeParty, CASETRAP2);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
switch (trap) {
case 1:
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 3);
NoMapsZone(player, type, doMsgs);
NoSpellZone(player, type, doMsgs);
ShowText(player, type, doMsgs, "Evil winds rip through you, mauling you horribly.");
trap++;
break;
case 2:
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) - 2000);
SetDebuff(player, type, doMsgs, POISON, 15, 100);
ShowText(player, type, doMsgs, "Poisoned gas strangles you as it dissipates.");
trap++;
break;
case 3:
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 4);
ShowText(player, type, doMsgs, "A flash of magical light blinds you temporarily; causing you damage.");
trap++;
break;
case 4:
ModifyMana(player, type, doMsgs, - 2000);
while (HasItem(player, type, doMsgs, ZEUSSCROLL))
RemoveItem(player, type, doMsgs, ZEUSSCROLL);
while (HasItem(player, type, doMsgs, SOVEREIGNSCROLL))
RemoveItem(player, type, doMsgs, SOVEREIGNSCROLL);
ShowText(player, type, doMsgs, "Mystical currents from an ancient snare steal from and damage you.");
trap++;
break;
case 5:
ShowText(player, type, doMsgs, "A blast of fire greets you at this next snare.");
ModifyMana(player, type, doMsgs, - 200);
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4);
trap++;
break;
default:
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 3);
DisableHealing(player, type, doMsgs);
trap = 1;
NoSpellZone(player, type, doMsgs);
ShowText(player, type, doMsgs, "Evil laughter echoes off the walls as yet another snare harms you.");
break;
}
SetFlag(player, type, doMsgs, FlagTypeParty, CASETRAP2, trap);
SprungTrap(player, type, doMsgs);
}
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.WONTHISGAME) == 0)) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ENDGAMETELE, 2);
ShowText(player, type, doMsgs, "You've defeated the Queen; preventing the her from threatening all the Portals that interconnect throughout this world and others.");
ShowText(player, type, doMsgs, "Now, take these boosts to your attributes and to your wealths of knowledge and gold. You have restored the system to its rightful balance.");
ShowText(player, type, doMsgs, "In time, when you are ready, the portal will grant you access to new planes of existence! But that, is another story...");
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.WONTHISGAME, 1);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.WINNER, 1);
ModifyExperience(player, type, doMsgs, 7500000);
ModifyGold(player, type, doMsgs, 2000000);
ModAttribute(player, type, doMsgs, STRENGTH, 3);
ModAttribute(player, type, doMsgs, AGILITY, 3);
ModAttribute(player, type, doMsgs, DEFENSE, 3);
ModAttribute(player, type, doMsgs, INITIATIVE, 3);
if (GetGuild(player, type, doMsgs) != WIZARD) {
ShowText(player, type, doMsgs, "You are bestowed with a new spell!");
GiveSpell(player, type, doMsgs, DEATH_DARTS_SPELL, 6);
}
else {
ShowText(player, type, doMsgs, "Mighty sorcerer, gain knowledge to control life from death.");
GiveSpell(player, type, doMsgs, RESUSCITATE_SPELL, 6);
}
}
else {
ShowText(player, type, doMsgs, "The portal glows with power. You may enter it now, but it will not take you to your true destination yet.");
ShowText(player, type, doMsgs, "The future has taken root in the present. All will be explained... with Yserbius III!!%%");
}
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Here you must go, but only after you've retrieved one of the mystic artifacts that travelers of this portal have left as gifts.");
TeleportParty(player, type, doMsgs, 12, 2, 232, Direction.South);
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisablePartyJoining(player, type, doMsgs);
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
FnEvent15(player, type, doMsgs);
if (GetFlag(player, type, doMsgs, FlagTypeParty, STORMGIANT) != GetTile(player, type, doMsgs)) {
if (GetPartyCount(player, type, doMsgs) == 1) {
ShowText(player, type, doMsgs, "An ominous force stands before you!");
if (HasItem(player, type, doMsgs, STATUEOFSTORMGIANT) && GetFlag(player, type, doMsgs, FlagTypeParty, IMHERE) != GetTile(player, type, doMsgs) && (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ONLYONCE) == 0)) {
WallClear(player, type, doMsgs);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ONLYONCE, 1);
ShowText(player, type, doMsgs, "Using one of the mystical statues, you turn into a Storm Giant and kill them all!");
ModifyGold(player, type, doMsgs, 10000);
GiveItem(player, type, doMsgs, PHOSPHORESCENTBLADE);
GiveItem(player, type, doMsgs, HEALAMPHORA);
GiveItem(player, type, doMsgs, ZEUSSCROLL);
SetFlag(player, type, doMsgs, FlagTypeParty, IMHERE, GetTile(player, type, doMsgs));
}
}
else if (GetFlag(player, type, doMsgs, FlagTypeParty, IMHERE) != GetTile(player, type, doMsgs)) {
ShowText(player, type, doMsgs, "Had you been alone and with their talisman, you may have stood a chance!");
for (i = 1; i <= 4; i++) {
AddEncounter(player, type, doMsgs, i, STORMGIANTS);
}
SetFlag(player, type, doMsgs, FlagTypeParty, IMHERE, GetTile(player, type, doMsgs));
}
SetFlag(player, type, doMsgs, FlagTypeParty, STORMGIANT, GetTile(player, type, doMsgs));
}
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
switch (GetFacing(player, type, doMsgs)) {
case Direction.North:
SetFacing(player, type, doMsgs, Direction.West);
SprungTrap(player, type, doMsgs);
break;
case Direction.South:
SetFacing(player, type, doMsgs, Direction.East);
SprungTrap(player, type, doMsgs);
break;
case Direction.East:
SetFacing(player, type, doMsgs, Direction.South);
SprungTrap(player, type, doMsgs);
break;
case Direction.West:
SetFacing(player, type, doMsgs, Direction.East);
SprungTrap(player, type, doMsgs);
break;
}
}
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) {
switch (GetFacing(player, type, doMsgs)) {
case Direction.North:
SetFacing(player, type, doMsgs, Direction.South);
SetFacing(player, type, doMsgs, Direction.West);
SetFacing(player, type, doMsgs, Direction.South);
SprungTrap(player, type, doMsgs);
break;
case Direction.South:
SetFacing(player, type, doMsgs, Direction.West);
SprungTrap(player, type, doMsgs);
break;
case Direction.East:
SetFacing(player, type, doMsgs, Direction.North);
SprungTrap(player, type, doMsgs);
break;
case Direction.West:
SetFacing(player, type, doMsgs, Direction.East);
TeleportParty(player, type, doMsgs, 12, 2, GetTile(player, type, doMsgs), Direction.East);
SprungTrap(player, type, doMsgs);
break;
}
}
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
NoSpellZone(player, type, doMsgs);
DisablePartyJoining(player, type, doMsgs);
if (GetPartyCount(player, type, doMsgs) == 1) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KILLEDQUEEN) == 0)) {
ShowText(player, type, doMsgs, "Those who hath not faced the mad Queen must lead, lest your efforts are futile. You are one that may lead!");
SetFlag(player, type, doMsgs, FlagTypeParty, LASTBATTLE, 1);
TeleportParty(player, type, doMsgs, 12, 2, 104, Direction.East);
}
else {
ShowText(player, type, doMsgs, "You have already defeated the Queen, you cannot face that which is no more.");
SetFlag(player, type, doMsgs, FlagTypeParty, LASTBATTLE, 0);
TeleportParty(player, type, doMsgs, 12, 2, 104, Direction.East);
}
}
else {
ShowText(player, type, doMsgs, "Step forth ALONE!");
TeleportParty(player, type, doMsgs, 12, 2, 119, Direction.North);
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeParty, KEEPER) == 0)) {
ShowText(player, type, doMsgs, "The statue of an ancient guardian greets you here. It writhes to life as you approach: 'Hail to thee! I am Chrysagorn, Keeper of the Portal and Servant to the Fates.");
ShowText(player, type, doMsgs, "I have been imprisoned here in granite by the mad Queen! Her powers are farther reaching than you dare imagine. With the five rings, she is now trying to gain control of the Gateway.");
ShowText(player, type, doMsgs, "I cannot defend the Gate from her powers, you must destroy her or all of time shall fold in upon itself. Our fate will be sealed in oblivion's tomb.'");
ShowText(player, type, doMsgs, "The statue begins to crumble as you watch, 'Go! defeat her! I can no longer protect...' but its too late, the statue explodes into dust flying across the room and damaging you.");
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 5);
SetFlag(player, type, doMsgs, FlagTypeParty, KEEPER, 1);
}
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetTileBlock(player, type, doMsgs, GetTile(player, type, doMsgs));
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
ShowText(player, type, doMsgs, "Eos' servants form from the morning mists which permeate this place.");
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, EOSBATTLE);
}
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
ShowText(player, type, doMsgs, "Descendents of Gaea rise from the earthen floor to challenge you!");
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, GAEABATTLE);
}
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
ShowText(player, type, doMsgs, "Ancient servants of Neptune rise from the waters and bar your way!");
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, NEPTUNEBATTLE);
}
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
ShowText(player, type, doMsgs, "Masters of Warfare, students of Ares, ambush you!");
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, ARESBATTLE);
}
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetTileState(player, type, doMsgs, 0);
}
protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetTileState(player, type, doMsgs) != GetTile(player, type, doMsgs)) {
SetTileState(player, type, doMsgs, GetTile(player, type, doMsgs));
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, HALLGUARD1);
AddEncounter(player, type, doMsgs, 02, HALLGUARD1);
break;
case 2:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD1);
}
break;
default:
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD1);
}
break;
}
}
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HALLOFDOOM) == 0)) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HALLOFDOOM, 1);
}
ShowText(player, type, doMsgs, "This enormous hallway is adorned with precious jewels and artworks in every crevice. Golden statues in the images of greater deities and gods who hath passed this way line either side of the hall.");
ShowText(player, type, doMsgs, "A challenge of outrageous proportions guards this passageway before you. Northward, two rows of beasts and man stand as guardians to the ultimate Gateway.");
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetTileState(player, type, doMsgs) != GetTile(player, type, doMsgs)) {
SetTileState(player, type, doMsgs, GetTile(player, type, doMsgs));
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, HALLGUARD2);
AddEncounter(player, type, doMsgs, 02, HALLGUARD2);
break;
case 2:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD2);
}
break;
default:
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD2);
}
break;
}
}
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, NEPTUNESTRIDENT, NEPTUNESTRIDENT)) {
ShowText(player, type, doMsgs, "The lava before you swirls into a wading pool! Neptune himself has used such power to bypass these foul snares.");
ClearMe(player, type, doMsgs);
}
else if (UsedItem(player, type, ref doMsgs, GAEASFLAIL, GAEASFLAIL)) {
ShowText(player, type, doMsgs, "The lava hardens into solid rock! Gaea herself has used such powers to pass safely by such traps!");
ClearMe(player, type, doMsgs);
}
else if (UsedItem(player, type, ref doMsgs, BOWOFEOS, BOWOFEOS)) {
ShowText(player, type, doMsgs, "Dawn's light shines bright upon the bow forming a golden arch across the lava!");
ClearMe(player, type, doMsgs);
}
else if (UsedItem(player, type, ref doMsgs, SWORDOFARES, SWORDOFARES)) {
ShowText(player, type, doMsgs, "The sword summons a powerful Ice Elemental! The elemental sinks into the lava, quenching the raging war between fire and ice!");
ClearMe(player, type, doMsgs);
}
else if (UsedItem(player, type, ref doMsgs, SHORTSWORD, UNITYRING)) {
ShowText(player, type, doMsgs, "The lava resumes its form.");
SetFlag(player, type, doMsgs, FlagTypeParty, USEDNEPTRI, 0);
}
else {
ShowText(player, type, doMsgs, "A vile pool of molten lava bubbles violently before you. You must find a way to alter this pool of sure death.");
}
}
private void ClearMe(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeParty, USEDNEPTRI, 1);
switch (GetTile(player, type, doMsgs)) {
case 160:
case 192:
ClearTileBlock(player, type, doMsgs, 176);
SetFloorItem(player, type, doMsgs, WATER, 176);
break;
default:
ClearTileBlock(player, type, doMsgs, 85);
SetFloorItem(player, type, doMsgs, WATER, 85);
break;
}
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, USEDNEPTRI) == 1) {
ShowText(player, type, doMsgs, "The magic sustains the pool, allowing you to safely pass.");
}
else {
ShowText(player, type, doMsgs, "The lava scorches and torments your body. The magical fluids then hurl you across the maze...");
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) - 100);
TeleportParty(player, type, doMsgs, 12, 2, 191, Direction.South);
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetTileState(player, type, doMsgs) != GetTile(player, type, doMsgs)) {
SetTileState(player, type, doMsgs, GetTile(player, type, doMsgs));
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, HALLGUARD3);
AddEncounter(player, type, doMsgs, 02, HALLGUARD3);
break;
case 2:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD3);
}
break;
default:
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD3);
}
break;
}
}
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetTileState(player, type, doMsgs) != GetTile(player, type, doMsgs)) {
SetTileState(player, type, doMsgs, GetTile(player, type, doMsgs));
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, HALLGUARD4);
AddEncounter(player, type, doMsgs, 02, HALLGUARD4);
break;
case 2:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD4);
}
break;
default:
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD4);
}
break;
}
}
}
protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) {
int i = 0;
if (GetTileState(player, type, doMsgs) != GetTile(player, type, doMsgs)) {
SetTileState(player, type, doMsgs, GetTile(player, type, doMsgs));
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, HALLGUARD5);
AddEncounter(player, type, doMsgs, 02, HALLGUARD5);
break;
case 2:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD5);
}
break;
default:
for (i = 1; i <= 5; i++) {
AddEncounter(player, type, doMsgs, i, HALLGUARD5);
}
break;
}
}
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeParty, IHAVETHEFLAIL) == 0)) {
if (UsedItem(player, type, ref doMsgs, GAEASFLAIL, GAEASFLAIL)) {
ShowText(player, type, doMsgs, "The pit before you congeals into a solid earthen floor! Gaea's power is obvious concerning the nature of things.");
SetFlag(player, type, doMsgs, FlagTypeParty, USEDGAEAFLAIL, 1);
switch (GetTile(player, type, doMsgs)) {
case 23:
case 55:
ClearTileBlock(player, type, doMsgs, 39);
SetFloorItem(player, type, doMsgs, NO_OBJECT, 39);
break;
}
}
else if (UsedItem(player, type, ref doMsgs, SHORTSWORD, UNITYRING)) {
ShowText(player, type, doMsgs, "The pit remains open.");
SetFlag(player, type, doMsgs, FlagTypeParty, USEDGAEAFLAIL, 0);
}
else {
ShowText(player, type, doMsgs, "An eerie black pit stretches deep into the earth here. Echoes of your every sound are barely audible whispers by the time they return.");
}
}
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeParty, IHAVETHEFLAIL) == 0)) {
if (GetFlag(player, type, doMsgs, FlagTypeParty, USEDGAEAFLAIL) == 1) {
ShowText(player, type, doMsgs, "The flail keeps the earth intact, allowing you to safely pass.");
}
else {
ShowText(player, type, doMsgs, "The pit swallows you whole, this magical snare does not kill you, however, but you are swept away through the maze.");
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) - 100);
TeleportParty(player, type, doMsgs, 12, 2, 222, Direction.East);
}
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((!HasItem(player, type, doMsgs, GAEASFLAIL))) {
SetFlag(player, type, doMsgs, FlagTypeParty, IHAVETHEFLAIL, 1);
}
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "An ancient portal carved of pure magic and wrought with precious gemstones stands guard here.");
if (GetPartyCount(player, type, doMsgs) == 1) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HALLOFDOOM) == 1) && (HasItem(player, type, doMsgs, SWORDOFARES) || HasItem(player, type, doMsgs, BOWOFEOS) || HasItem(player, type, doMsgs, GAEASFLAIL) || HasItem(player, type, doMsgs, NEPTUNESTRIDENT))) {
ShowText(player, type, doMsgs, "The ancient crystals merge into a teleport, allowing you to gain quick access to the Gateway's heart.");
TeleportParty(player, type, doMsgs, 12, 2, 205, Direction.North);
}
else {
ShowText(player, type, doMsgs, "Here you will enter the ancient Gods' treasure room.");
TeleportParty(player, type, doMsgs, 12, 2, 219, Direction.South);
}
}
else {
ShowText(player, type, doMsgs, "Be off!! Only one Hero may enter here at a time!");
SetFacing(player, type, doMsgs, Direction.East);
}
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ONLYONCE, 0);
ShowText(player, type, doMsgs, "From here you enter the heart of The Gateway.");
TeleportParty(player, type, doMsgs, 12, 2, 246, Direction.East);
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((!HasItem(player, type, doMsgs, STATUEOFSTORMGIANT))) {
GiveItem(player, type, doMsgs, STATUEOFSTORMGIANT);
ShowText(player, type, doMsgs, "You pick up an odd statue. Perhaps it will protect you when you are alone.");
}
switch (GetTile(player, type, doMsgs)) {
case 238:
ShowText(player, type, doMsgs, "A jeweled carving depicts a band of travelers journeying through an ancient dungeon in search of some great treasure.");
break;
case 222:
ShowText(player, type, doMsgs, "This carving shows four ancient fragments brought unto themselves, forming some magical piece that allows access into a dark kingdom.");
break;
case 206:
ShowText(player, type, doMsgs, "Here you see a myriad of images strewn across various puzzles and hordes of vile creatures that scorn the travelers as they seek the treasure.");
break;
case 190:
if (IsFlagOn(player, type, doMsgs, FlagTypeDungeon, TwIndexes.KILLEDQUEEN)) {
ShowText(player, type, doMsgs, "Emblazoned in the stones you see your own image slaying the mad Queen and eventually entering the mystical Gateway of Immortality.");
}
else {
ShowText(player, type, doMsgs, "Shadowy, incoherent images flash across the stones as though some part of future history is yet to be completed.");
}
break;
}
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 12, 2, 150, Direction.West);
ShowText(player, type, doMsgs, "To the last pathway of challenge. From there you will ultimately meet your Fate.");
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FINISHEDGAME) == 0)) {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.FINISHEDGAME, 1);
ShowText(player, type, doMsgs, "An eerie, shimmering portal hangs before you. This is the Gateway...the ingress into new adventures and future history.");
ShowText(player, type, doMsgs, "You will come back here in time, when you feel you are ready for new challenges and greater travels. Until then, you must rest and restore your drained powers for that day.");
ShowText(player, type, doMsgs, "There is a place, guarded by Shaddax, the Keeper, you must journey there and unravel the riddles placed in your path by some vile deity that inhabits another dimension.");
ShowText(player, type, doMsgs, "That is your task for now, you may return here when time dictates! Go now, seek Shaddax...you may find the entrance through Dragon's Ire! Go, brave champion!");
TeleportParty(player, type, doMsgs, 1, 1, 3, Direction.South);
}
else {
ShowText(player, type, doMsgs, "The portal is here; but the future is not yours to see...yet.");
TeleportParty(player, type, doMsgs, 1, 1, 3, Direction.South);
}
}
private void AdvTxt(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "This portal will offer you no advancement without the proper artifact.");
}
private void AssaultTxt(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Through here you begin the final assault.");
}
private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void AresText(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Ares had visited this place many moons ago. As his mark, he left behind a legend that clever Night Elf craftsmen emblazoned with ancient runes upon this jeweled blade.");
}
private void NeptunesTxt(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Lord Neptune, Master of the Wind and the Sea, used this Trident to command the waters that now surround Twinion to swirl into fury; crashing down upon his enemies. Its power is now yours to borrow.");
}
private void GaeasText(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Gaea had exhausted herself in many travels, but her pleasures here have always been her favorite. She filled herself with energies and moved on to a new adventure via the Portal.");
ShowText(player, type, doMsgs, "Her flail now remains as her mark, and is offered to you to defend the Portal from abuse.");
}
private void EosText(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Dawn shall come! Eos brings the sun, and the first arch of gold was wrought into this magnificent bow in honor of this goddess.");
ShowText(player, type, doMsgs, "Now the Bow of Eos, shall be your light and guide past the snares that await you along the paths to the Portal.");
}
private void NoMapsZone(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
}
private void NoSpellZone(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableSpells(player, type, doMsgs);
}
private void SprungTrap(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1);
}
}
}
| |
// 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using UIKit;
using Colors = System.Drawing.Color;
namespace ArcGISRuntime.Samples.DisplayGrid
{
[Register("DisplayGrid")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Display grid",
category: "MapView",
description: "Display coordinate system grids including Latitude/Longitude, MGRS, UTM and USNG on a map view. Also, toggle label visibility and change the color of grid lines and grid labels.",
instructions: "Select type of grid from the types (LatLong, MGRS, UTM and USNG) and modify its properties like label visibility, grid line color, and grid label color. Press the button to apply these settings.",
tags: new[] { "MGRS", "USNG", "UTM", "coordinates", "degrees", "graticule", "grid", "latitude", "longitude", "minutes", "seconds" })]
public class DisplayGrid : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UIBarButtonItem _typeButton;
private UIBarButtonItem _lineColorButton;
private UIBarButtonItem _positionButton;
private UIBarButtonItem _labelColorButton;
// Fields for storing the user's grid preferences.
private string _selectedGridType = "LatLong";
private Colors? _selectedGridColor = Colors.Red;
private Colors? _selectedLabelColor = Colors.White;
private GridLabelPosition _selectedLabelPosition = GridLabelPosition.Geographic;
public DisplayGrid()
{
Title = "Display a grid";
}
private void Initialize()
{
// Set a basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISImagery);
// Apply a grid by default.
ApplyCurrentSettings();
// Zoom to a default scale that will show the grid labels if they are enabled.
_myMapView.SetViewpointCenterAsync(
new MapPoint(-7702852.905619, 6217972.345771, SpatialReferences.WebMercator), 23227);
}
private void ApplyCurrentSettings()
{
Grid grid;
// First, update the grid based on the type selected.
switch (_selectedGridType)
{
case "LatLong":
grid = new LatitudeLongitudeGrid();
break;
case "MGRS":
grid = new MgrsGrid();
break;
case "UTM":
grid = new UtmGrid();
break;
case "USNG":
default:
grid = new UsngGrid();
break;
}
// Next, apply the label position setting.
grid.LabelPosition = _selectedLabelPosition;
// Next, apply the grid color and label color settings for each zoom level.
for (long level = 0; level < grid.LevelCount; level++)
{
// Set the grid color if the grid is selected for display.
if (_selectedGridColor != null)
{
// Set the line symbol.
Symbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, _selectedGridColor.Value, 2);
grid.SetLineSymbol(level, lineSymbol);
}
// Set the label color if labels are enabled for display.
if (_selectedLabelColor != null)
{
// Set the text symbol.
Symbol textSymbol = new TextSymbol
{
Color = _selectedLabelColor.Value,
Size = 16,
FontWeight = FontWeight.Bold
};
grid.SetTextSymbol(level, textSymbol);
}
}
// Next, hide the grid if it has been hidden.
if (_selectedGridColor == null)
{
grid.IsVisible = false;
}
// Next, hide the labels if they have been hidden.
if (_selectedLabelColor == null)
{
grid.IsLabelVisible = false;
}
// Apply the updated grid.
_myMapView.Grid = grid;
}
private void LabelPositionButton_Click(object sender, EventArgs e)
{
// Create the view controller that will present the list of label positions.
UIAlertController labelPositionAlert = UIAlertController.Create(null, "Select a label position", UIAlertControllerStyle.ActionSheet);
// Needed to prevent a crash on iPad.
UIPopoverPresentationController presentationPopover = labelPositionAlert.PopoverPresentationController;
if (presentationPopover != null)
{
presentationPopover.BarButtonItem = (UIBarButtonItem)sender;
presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
}
// Add an option for each label position option.
foreach (string item in Enum.GetNames(typeof(GridLabelPosition)))
{
// Record the selection and re-apply all settings.
labelPositionAlert.AddAction(UIAlertAction.Create(item, UIAlertActionStyle.Default, action =>
{
_selectedLabelPosition = (GridLabelPosition)Enum.Parse(typeof(GridLabelPosition), item);
ApplyCurrentSettings();
}));
}
// Show the alert.
PresentViewController(labelPositionAlert, true, null);
}
private void GridTypeButton_Click(object sender, EventArgs e)
{
// Create the view controller that will present the list of grid types.
UIAlertController gridTypeAlert = UIAlertController.Create(null, "Select a grid type", UIAlertControllerStyle.ActionSheet);
// Needed to prevent a crash on iPad.
UIPopoverPresentationController presentationPopover = gridTypeAlert.PopoverPresentationController;
if (presentationPopover != null)
{
presentationPopover.BarButtonItem = (UIBarButtonItem)sender;
presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
}
// Add an option for each grid type.
foreach (string item in new[] { "LatLong", "UTM", "MGRS", "USNG" })
{
// Record the selection and re-apply all settings.
gridTypeAlert.AddAction(UIAlertAction.Create(item, UIAlertActionStyle.Default, action =>
{
_selectedGridType = item;
ApplyCurrentSettings();
}));
}
// Show the alert.
PresentViewController(gridTypeAlert, true, null);
}
private void LabelColorButton_Click(object sender, EventArgs e)
{
// Create the view controller that will present the list of label color options.
UIAlertController labelColorAlert = UIAlertController.Create(null, "Select a label color", UIAlertControllerStyle.ActionSheet);
// Needed to prevent a crash on iPad.
UIPopoverPresentationController presentationPopover = labelColorAlert.PopoverPresentationController;
if (presentationPopover != null)
{
presentationPopover.BarButtonItem = (UIBarButtonItem)sender;
presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
}
// Add an option for each color.
foreach (Colors item in new[] { Colors.Red, Colors.Green, Colors.Blue, Colors.White })
{
// Record the selection and re-apply all settings.
labelColorAlert.AddAction(UIAlertAction.Create(item.Name, UIAlertActionStyle.Default, action =>
{
_selectedLabelColor = item;
ApplyCurrentSettings();
}));
}
// Add an option to hide labels.
labelColorAlert.AddAction(UIAlertAction.Create("Hide labels", UIAlertActionStyle.Default, action =>
{
// Record the selection and re-apply all settings.
_selectedLabelColor = null;
ApplyCurrentSettings();
}));
// Show the alert.
PresentViewController(labelColorAlert, true, null);
}
private void GridColorButton_Click(object sender, EventArgs e)
{
// Create the view controller that will present the list of grid color options.
UIAlertController gridColorAlert = UIAlertController.Create(null, "Select a grid color", UIAlertControllerStyle.ActionSheet);
// Needed to prevent a crash on iPad.
UIPopoverPresentationController presentationPopover = gridColorAlert.PopoverPresentationController;
if (presentationPopover != null)
{
presentationPopover.BarButtonItem = (UIBarButtonItem)sender;
presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down;
}
// Add an option for each color.
foreach (Colors item in new[] { Colors.Red, Colors.Green, Colors.Blue, Colors.White })
{
// Record the selection and re-apply all settings.
gridColorAlert.AddAction(UIAlertAction.Create(item.Name, UIAlertActionStyle.Default, action =>
{
_selectedGridColor = item;
ApplyCurrentSettings();
}));
}
// Add an option to hide the grid.
gridColorAlert.AddAction(UIAlertAction.Create("Hide the grid", UIAlertActionStyle.Default, action =>
{
// Record the selection and re-apply all settings.
_selectedGridColor = null;
ApplyCurrentSettings();
}));
// Show the alert.
PresentViewController(gridColorAlert, true, null);
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_typeButton = new UIBarButtonItem();
_typeButton.Title = "Grid type";
_lineColorButton = new UIBarButtonItem();
_lineColorButton.Title = "Line color";
_positionButton = new UIBarButtonItem();
_positionButton.Title = "Positions";
_labelColorButton = new UIBarButtonItem();
_labelColorButton.Title = "Text color";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
_typeButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_lineColorButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_positionButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_labelColorButton
};
// Add the views.
View.AddSubviews(_myMapView, toolbar);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
});
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_typeButton.Clicked += GridTypeButton_Click;
_lineColorButton.Clicked += GridColorButton_Click;
_positionButton.Clicked += LabelPositionButton_Click;
_labelColorButton.Clicked += LabelColorButton_Click;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_typeButton.Clicked -= GridTypeButton_Click;
_lineColorButton.Clicked -= GridColorButton_Click;
_positionButton.Clicked -= LabelPositionButton_Click;
_labelColorButton.Clicked -= LabelColorButton_Click;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace EditingSampleApp
{
partial class EditingForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditingForm));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.GroupBox1 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.Label7 = new System.Windows.Forms.Label();
this.Label6 = new System.Windows.Forms.Label();
this.Label5 = new System.Windows.Forms.Label();
this.Label4 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.Label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl();
this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axEditorToolbar = new ESRI.ArcGIS.Controls.AxToolbarControl();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.tableLayoutPanel1.SuspendLayout();
this.GroupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axEditorToolbar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.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.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 26.94611F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 73.05389F));
this.tableLayoutPanel1.Controls.Add(this.GroupBox1, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.axMapControl1, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.axToolbarControl1, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.axEditorToolbar, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.axTOCControl1, 0, 2);
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, -4);
this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 4;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 39F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.88717F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 89.21283F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 290F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(1207, 673);
this.tableLayoutPanel1.TabIndex = 1;
//
// GroupBox1
//
this.GroupBox1.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.GroupBox1.Controls.Add(this.label1);
this.GroupBox1.Controls.Add(this.Label7);
this.GroupBox1.Controls.Add(this.Label6);
this.GroupBox1.Controls.Add(this.Label5);
this.GroupBox1.Controls.Add(this.Label4);
this.GroupBox1.Controls.Add(this.Label2);
this.GroupBox1.Controls.Add(this.label16);
this.GroupBox1.Controls.Add(this.Label8);
this.GroupBox1.Controls.Add(this.label9);
this.GroupBox1.Controls.Add(this.label10);
this.GroupBox1.Controls.Add(this.label11);
this.GroupBox1.Controls.Add(this.label12);
this.GroupBox1.Location = new System.Drawing.Point(3, 384);
this.GroupBox1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.GroupBox1.Name = "GroupBox1";
this.GroupBox1.Padding = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.GroupBox1.Size = new System.Drawing.Size(319, 287);
this.GroupBox1.TabIndex = 6;
this.GroupBox1.TabStop = false;
this.GroupBox1.Text = "Steps...";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 117);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(230, 17);
this.label1.TabIndex = 23;
this.label1.Text = "5. Cut polygons with the sketch tool";
//
// Label7
//
this.Label7.AutoSize = true;
this.Label7.Location = new System.Drawing.Point(16, 156);
this.Label7.Name = "Label7";
this.Label7.Size = new System.Drawing.Size(99, 17);
this.Label7.TabIndex = 22;
this.Label7.Text = "7. Stop editing";
//
// Label6
//
this.Label6.AutoSize = true;
this.Label6.Location = new System.Drawing.Point(16, 137);
this.Label6.Name = "Label6";
this.Label6.Size = new System.Drawing.Size(198, 17);
this.Label6.TabIndex = 21;
this.Label6.Text = "6. Finish sketch to perform cut";
//
// Label5
//
this.Label5.AutoSize = true;
this.Label5.Location = new System.Drawing.Point(16, 97);
this.Label5.Name = "Label5";
this.Label5.Size = new System.Drawing.Size(135, 17);
this.Label5.TabIndex = 20;
this.Label5.Text = "4. Select sketch tool";
//
// Label4
//
this.Label4.AutoSize = true;
this.Label4.Location = new System.Drawing.Point(16, 78);
this.Label4.Name = "Label4";
this.Label4.Size = new System.Drawing.Size(287, 17);
this.Label4.TabIndex = 19;
this.Label4.Text = "3. Select Cut Polygon Without Selection task";
//
// Label2
//
this.Label2.AutoSize = true;
this.Label2.Location = new System.Drawing.Point(16, 41);
this.Label2.Name = "Label2";
this.Label2.Size = new System.Drawing.Size(244, 17);
this.Label2.TabIndex = 17;
this.Label2.Text = "1. Zoom in on polygon features to cut";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(16, 60);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(100, 17);
this.label16.TabIndex = 16;
this.label16.Text = "2. Start editing";
//
// Label8
//
this.Label8.AutoSize = true;
this.Label8.Location = new System.Drawing.Point(20, 331);
this.Label8.Name = "Label8";
this.Label8.Size = new System.Drawing.Size(279, 17);
this.Label8.TabIndex = 15;
this.Label8.Text = "6. Digitize line, intersect feature in 2 places";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(20, 370);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(171, 17);
this.label9.TabIndex = 14;
this.label9.Text = "8. Stop editing, save edits";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(20, 351);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(231, 17);
this.label10.TabIndex = 13;
this.label10.Text = "7. Finish sketch to perform reshape";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(20, 311);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(135, 17);
this.label11.TabIndex = 12;
this.label11.Text = "5. Select sketch tool";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(20, 292);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(201, 17);
this.label12.TabIndex = 11;
this.label12.Text = "4. Select reshape polyline task";
//
// axMapControl1
//
this.axMapControl1.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.axMapControl1.Location = new System.Drawing.Point(329, 80);
this.axMapControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.axMapControl1.Name = "axMapControl1";
this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState")));
this.tableLayoutPanel1.SetRowSpan(this.axMapControl1, 2);
this.axMapControl1.Size = new System.Drawing.Size(874, 589);
this.axMapControl1.TabIndex = 1;
this.axMapControl1.OnMouseUp += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseUpEventHandler(this.axMapControl1_OnMouseUp);
//
// axToolbarControl1
//
this.axToolbarControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.SetColumnSpan(this.axToolbarControl1, 2);
this.axToolbarControl1.Location = new System.Drawing.Point(4, 43);
this.axToolbarControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.axToolbarControl1.Name = "axToolbarControl1";
this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState")));
this.axToolbarControl1.Size = new System.Drawing.Size(1199, 28);
this.axToolbarControl1.TabIndex = 4;
//
// axEditorToolbar
//
this.axEditorToolbar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.SetColumnSpan(this.axEditorToolbar, 2);
this.axEditorToolbar.Location = new System.Drawing.Point(4, 4);
this.axEditorToolbar.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.axEditorToolbar.Name = "axEditorToolbar";
this.axEditorToolbar.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axEditorToolbar.OcxState")));
this.axEditorToolbar.Size = new System.Drawing.Size(1199, 28);
this.axEditorToolbar.TabIndex = 5;
//
// axTOCControl1
//
this.axTOCControl1.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.axTOCControl1.Location = new System.Drawing.Point(4, 80);
this.axTOCControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(317, 298);
this.axTOCControl1.TabIndex = 2;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(239, 476);
this.axLicenseControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 2;
//
// EditingForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1215, 676);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.tableLayoutPanel1);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "EditingForm";
this.Text = "Cut Polygon Without Selection EngineEditTask Sample (C#)";
this.Load += new System.EventHandler(this.EngineEditingForm_Load);
this.tableLayoutPanel1.ResumeLayout(false);
this.GroupBox1.ResumeLayout(false);
this.GroupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axEditorToolbar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private ESRI.ArcGIS.Controls.AxMapControl axMapControl1;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1;
private ESRI.ArcGIS.Controls.AxToolbarControl axEditorToolbar;
internal System.Windows.Forms.GroupBox GroupBox1;
internal System.Windows.Forms.Label label1;
internal System.Windows.Forms.Label Label7;
internal System.Windows.Forms.Label Label6;
internal System.Windows.Forms.Label Label5;
internal System.Windows.Forms.Label Label4;
internal System.Windows.Forms.Label Label2;
internal System.Windows.Forms.Label label16;
internal System.Windows.Forms.Label Label8;
internal System.Windows.Forms.Label label9;
internal System.Windows.Forms.Label label10;
internal System.Windows.Forms.Label label11;
internal System.Windows.Forms.Label label12;
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using ASC.Data.Storage;
namespace ASC.Web.Studio.Helpers
{
public class ImageInfo
{
#region Members
private string name;
private int originalWidth;
private int originalHeight;
private int previewWidth;
private int previewHeight;
private int thumbnailWidth;
private int thumbnailHeight;
private string originalPath;
private string previewPath;
private string thumbnailPath;
private string actionDate;
#endregion
#region Properties
public virtual string Name
{
get { return name; }
set { name = value; }
}
public virtual int OriginalWidth
{
get { return originalWidth; }
set { originalWidth = value; }
}
public virtual int OriginalHeight
{
get { return originalHeight; }
set { originalHeight = value; }
}
public virtual int PreviewWidth
{
get { return previewWidth; }
set { previewWidth = value; }
}
public virtual int PreviewHeight
{
get { return previewHeight; }
set { previewHeight = value; }
}
public virtual int ThumbnailWidth
{
get { return thumbnailWidth; }
set { thumbnailWidth = value; }
}
public virtual int ThumbnailHeight
{
get { return thumbnailHeight; }
set { thumbnailHeight = value; }
}
public virtual string OriginalPath
{
get { return originalPath; }
set { originalPath = value; }
}
public virtual string PreviewPath
{
get { return previewPath; }
set { previewPath = value; }
}
public virtual string ThumbnailPath
{
get { return thumbnailPath; }
set { thumbnailPath = value; }
}
public virtual string ActionDate
{
get { return actionDate; }
set { actionDate = value; }
}
#endregion
}
public class ThumbnailGenerator
{
readonly bool _crop = false;
readonly int _width;
readonly int _heigth;
readonly int _widthPreview;
readonly int _heightPreview;
public IDataStore store
{
get;
set;
}
public ThumbnailGenerator(string tmpPath, bool crop, int width, int heigth, int widthPreview, int heightPreview)
{
_crop = crop;
_width = width;
_heigth = heigth;
_widthPreview = widthPreview;
_heightPreview = heightPreview;
}
public void DoThumbnail(string path, string outputPath, ref ImageInfo imageInfo)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
DoThumbnail(fs, outputPath, ref imageInfo);
}
}
public void DoThumbnail(Stream image, string outputPath, ref ImageInfo imageInfo)
{
using (Image img = Image.FromStream(image))
{
DoThumbnail(img, outputPath, ref imageInfo);
}
}
public void DoThumbnail(Image image, string outputPath, ref ImageInfo imageInfo)
{
int realWidth = image.Width;
int realHeight = image.Height;
imageInfo.OriginalWidth = realWidth;
imageInfo.OriginalHeight = realHeight;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)90);
ImageCodecInfo icJPG = getCodecInfo("image/jpeg");
if (!String.IsNullOrEmpty(imageInfo.Name) && imageInfo.Name.Contains("."))
{
int indexDot = imageInfo.Name.ToLower().LastIndexOf(".");
if (imageInfo.Name.ToLower().IndexOf("png", indexDot) > indexDot)
icJPG = getCodecInfo("image/png");
else if (imageInfo.Name.ToLower().IndexOf("gif", indexDot) > indexDot)
icJPG = getCodecInfo("image/png");
}
Bitmap thumbnail;
if (realWidth < _width && realHeight < _heigth)
{
imageInfo.ThumbnailWidth = realWidth;
imageInfo.ThumbnailHeight = realHeight;
if (store == null)
image.Save(outputPath);
else
{
MemoryStream ms = new MemoryStream();
image.Save(ms, icJPG, ep);
ms.Seek(0, SeekOrigin.Begin);
store.Save(outputPath, ms);
ms.Dispose();
}
return;
}
else
{
thumbnail = new Bitmap(_width < realWidth ? _width : realWidth, _heigth < realHeight ? _heigth : realHeight);
int maxSide = realWidth > realHeight ? realWidth : realHeight;
int minSide = realWidth < realHeight ? realWidth : realHeight;
bool alignWidth = true;
if (_crop)
alignWidth = (minSide == realWidth);
else
alignWidth = (maxSide == realWidth);
double scaleFactor = (alignWidth) ? (realWidth / (1.0 * _width)) : (realHeight / (1.0 * _heigth));
if (scaleFactor < 1) scaleFactor = 1;
int locationX, locationY;
int finalWidth, finalHeigth;
finalWidth = (int)(realWidth / scaleFactor);
finalHeigth = (int)(realHeight / scaleFactor);
locationY = (int)(((_heigth < realHeight ? _heigth : realHeight) / 2.0) - (finalHeigth / 2.0));
locationX = (int)(((_width < realWidth ? _width : realWidth) / 2.0) - (finalWidth / 2.0));
Rectangle rect = new Rectangle(locationX, locationY, finalWidth, finalHeigth);
imageInfo.ThumbnailWidth = thumbnail.Width;
imageInfo.ThumbnailHeight = thumbnail.Height;
using (Graphics graphic = Graphics.FromImage(thumbnail))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.DrawImage(image, rect);
}
}
if (store == null)
thumbnail.Save(outputPath, icJPG, ep);
else
{
MemoryStream ms = new MemoryStream();
thumbnail.Save(ms, icJPG, ep);
ms.Seek(0, SeekOrigin.Begin);
store.Save(outputPath, ms);
ms.Dispose();
}
thumbnail.Dispose();
}
public void DoPreviewImage(string path, string outputPath, ref ImageInfo imageInfo)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
DoPreviewImage(fs, outputPath, ref imageInfo);
}
}
public void DoPreviewImage(Stream image, string outputPath, ref ImageInfo imageInfo)
{
using (Image img = Image.FromStream(image))
{
DoPreviewImage(img, outputPath, ref imageInfo);
}
}
public void DoPreviewImage(Image image, string outputPath, ref ImageInfo imageInfo)
{
int realWidth = image.Width;
int realHeight = image.Height;
int heightPreview = realHeight;
int widthPreview = realWidth;
EncoderParameters ep = new EncoderParameters(1);
ImageCodecInfo icJPG = getCodecInfo("image/jpeg");
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)90);
if (realWidth <= _widthPreview && realHeight <= _heightPreview)
{
imageInfo.PreviewWidth = widthPreview;
imageInfo.PreviewHeight = heightPreview;
if (store == null)
image.Save(outputPath);
else
{
MemoryStream ms = new MemoryStream();
image.Save(ms, icJPG, ep);
ms.Seek(0, SeekOrigin.Begin);
store.Save(outputPath, ms);
ms.Dispose();
}
return;
}
else if ((double)realHeight / (double)_heightPreview > (double)realWidth / (double)_widthPreview)
{
if (heightPreview > _heightPreview)
{
widthPreview = (int)(realWidth * _heightPreview * 1.0 / realHeight + 0.5);
heightPreview = _heightPreview;
}
}
else
{
if (widthPreview > _widthPreview)
{
heightPreview = (int)(realHeight * _widthPreview * 1.0 / realWidth + 0.5);
widthPreview = _widthPreview;
}
}
imageInfo.PreviewWidth = widthPreview;
imageInfo.PreviewHeight = heightPreview;
Bitmap preview = new Bitmap(widthPreview, heightPreview);
using (Graphics graphic = Graphics.FromImage(preview))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.DrawImage(image, 0, 0, widthPreview, heightPreview);
}
if (store == null)
preview.Save(outputPath, icJPG, ep);
else
{
MemoryStream ms = new MemoryStream();
preview.Save(ms, icJPG, ep);
ms.Seek(0, SeekOrigin.Begin);
store.Save(outputPath, ms);
ms.Dispose();
}
preview.Dispose();
}
public void RotateImage(string path, string outputPath, bool back)
{
try
{
using (var stream = store.GetReadStream(path))
using (var image = Image.FromStream(stream))
{
if (back)
{
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
}
else
{
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
var ep = new EncoderParameters(1);
var icJPG = getCodecInfo("image/jpeg");
ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);
if (store == null)
{
image.Save(outputPath, icJPG, ep);
}
else
{
using (var ms = new MemoryStream())
{
image.Save(ms, icJPG, ep);
ms.Seek(0, SeekOrigin.Begin);
store.Save(outputPath, ms);
}
}
store.Delete(path);
}
}
catch { }
}
private static ImageCodecInfo getCodecInfo(string mt)
{
ImageCodecInfo[] ici = ImageCodecInfo.GetImageEncoders();
int idx = 0;
for (int ii = 0; ii < ici.Length; ii++)
{
if (ici[ii].MimeType == mt)
{
idx = ii;
break;
}
}
return ici[idx];
}
}
public class ImageHelper
{
public const int maxSize = 200;
public const int maxWidthPreview = 933;
public const int maxHeightPreview = 700;
public static void GenerateThumbnail(string path, string outputPath, ref ImageInfo imageInfo)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.DoThumbnail(path, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(string path, string outputPath, ref ImageInfo imageInfo, int maxWidth, int maxHeight)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxWidth,
maxHeight,
maxWidthPreview,
maxHeightPreview);
_generator.DoThumbnail(path, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(Stream stream, string outputPath, ref ImageInfo imageInfo, int maxWidth, int maxHeight)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxWidth,
maxHeight,
maxWidthPreview,
maxHeightPreview);
_generator.DoThumbnail(stream, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(string path, string outputPath, ref ImageInfo imageInfo, int maxWidth, int maxHeight, IDataStore store)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxWidth,
maxHeight,
maxWidthPreview,
maxHeightPreview);
_generator.store = store;
_generator.DoThumbnail(path, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(Stream stream, string outputPath, ref ImageInfo imageInfo, int maxWidth, int maxHeight, IDataStore store)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxWidth,
maxHeight,
maxWidthPreview,
maxHeightPreview);
_generator.store = store;
_generator.DoThumbnail(stream, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(Stream stream, string outputPath, ref ImageInfo imageInfo)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.DoThumbnail(stream, outputPath, ref imageInfo);
}
public static void GenerateThumbnail(Stream stream, string outputPath, ref ImageInfo imageInfo, IDataStore store)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.store = store;
_generator.DoThumbnail(stream, outputPath, ref imageInfo);
}
public static void GeneratePreview(string path, string outputPath, ref ImageInfo imageInfo)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.DoPreviewImage(path, outputPath, ref imageInfo);
}
public static void GeneratePreview(Stream stream, string outputPath, ref ImageInfo imageInfo)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.DoPreviewImage(stream, outputPath, ref imageInfo);
}
public static void GeneratePreview(Stream stream, string outputPath, ref ImageInfo imageInfo, IDataStore store)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.store = store;
_generator.DoPreviewImage(stream, outputPath, ref imageInfo);
}
public static void RotateImage(string path, string outputPath, bool back, IDataStore store)
{
ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
maxSize,
maxSize,
maxWidthPreview,
maxHeightPreview);
_generator.store = store;
_generator.RotateImage(path, outputPath, back);
}
}
}
| |
namespace PokerTell.DatabaseSetup
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Text;
using log4net;
using NHibernate;
using NHibernate.Cfg;
using PokerTell.DatabaseSetup.Properties;
using PokerTell.Infrastructure;
using PokerTell.Infrastructure.Interfaces.DatabaseSetup;
using Environment = NHibernate.Cfg.Environment;
public class DataProvider : IDataProvider
{
static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
IDbConnection _connection;
DbProviderFactory _providerFactory;
IDataProviderInfo _dataProviderInfo;
Configuration _configuration;
public DataProvider()
{
DatabaseName = Resources.Status_NotConnectedToDatabase;
}
~DataProvider()
{
if (_connection != null)
{
_connection.Close();
}
}
public IDbConnection Connection
{
get { return _connection; }
}
public string DatabaseName { get; set; }
public bool IsConnectedToDatabase
{
get
{
return _connection != null && _connection.State.Equals(ConnectionState.Open) &&
! string.IsNullOrEmpty(_connection.Database);
}
}
public bool IsConnectedToServer
{
get { return _connection != null && _connection.State.Equals(ConnectionState.Open); }
}
public string ParameterPlaceHolder { get; set; }
public Configuration NHibernateConfiguration
{
get { return _configuration; }
}
public void Connect(string connString, IDataProviderInfo dataProviderInfo)
{
_dataProviderInfo = dataProviderInfo;
_providerFactory = DbProviderFactories.GetFactory(dataProviderInfo.FullName);
_connection = _providerFactory.CreateConnection();
_connection.ConnectionString = connString;
_connection.Open();
DatabaseName = IsConnectedToDatabase ? Connection.Database : Resources.Status_NotConnectedToDatabase;
}
public int ExecuteNonQuery(string nonQuery)
{
IDbCommand cmd = _connection.CreateCommand();
cmd.CommandText = nonQuery;
return cmd.ExecuteNonQuery();
}
public IDataReader ExecuteQuery(string query)
{
IDbCommand cmd = _connection.CreateCommand();
cmd.CommandText = query;
return cmd.ExecuteReader();
}
/// <summary>
/// Executes an SqlQuery and adds all values in the specified column to a list
/// </summary>
/// <param name="query">Sql Query to be executed</param>
/// <param name="column">Number of the column to get the results from</param>
/// <returns>List of values found in the specified column</returns>
public IList<T> ExecuteQueryGetColumn<T>(string query, int column)
{
var result = new List<T>();
try
{
using (IDataReader dr = ExecuteQuery(query))
{
while (dr.Read())
{
var value = (T)Convert.ChangeType(dr[column].ToString(), typeof(T));
result.Add(value);
}
}
}
catch (Exception excep)
{
Log.Error("Unexpected", excep);
}
return result;
}
public object ExecuteScalar(string query)
{
IDbCommand cmd = _connection.CreateCommand();
cmd.CommandText = query;
return cmd.ExecuteScalar();
}
public IDbCommand GetCommand()
{
return _connection.CreateCommand();
}
public DataTable GetDataTableFor(string query)
{
var dt = new DataTable();
using (IDataReader dr = ExecuteQuery(query))
{
dt.Load(dr);
}
return dt;
}
public string ListInstalledProviders()
{
var sb = new StringBuilder();
DataTable dt = DbProviderFactories.GetFactoryClasses();
foreach (DataRow row in dt.Rows)
{
sb.AppendLine(row[0].ToString());
}
return sb.ToString();
}
public void Dispose()
{
Connection.Dispose();
}
/// <summary>
/// Builds an NHibernate Session Factory using the Connection String from the current database connection and
/// the NHibernate Dialect, ConnectionDriver specified in the DataProviderInfo.
/// Therefore first InitializeWith(dataProviderInfo) and ConnectToDatabase() before calling this Method.
/// </summary>
/// <returns>Newly created NHibernate SessionFactory or null if DataProvider was not connected.</returns>
public ISessionFactory NewSessionFactory
{
get { return BuildSessionFactory(); }
}
public ISessionFactory BuildSessionFactory()
{
if (IsConnectedToDatabase && _dataProviderInfo != null)
{
_configuration = new Configuration()
.SetProperty(Environment.Dialect, _dataProviderInfo.NHibernateDialect)
.SetProperty(Environment.ConnectionDriver, _dataProviderInfo.NHibernateConnectionDriver)
.SetProperty(Environment.ConnectionString, Connection.ConnectionString)
.AddAssembly(ApplicationProperties.PokerHandMappingAssemblyName)
.AddAssembly(ApplicationProperties.DatabaseSetupMappingAssemblyName);
return NHibernateConfiguration.BuildSessionFactory();
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma warning disable 1634, 1691
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Host;
namespace System.Management.Automation
{
/// <summary>
/// Default implementation of ICommandRuntime for running Cmdlets standalone.
/// </summary>
internal class DefaultCommandRuntime : ICommandRuntime2
{
private List<object> _output;
/// <summary>
/// Constructs an instance of the default ICommandRuntime object
/// that will write objects into the list that was passed.
/// </summary>
public DefaultCommandRuntime(List<object> outputList)
{
if (outputList == null)
throw new System.ArgumentNullException("outputList");
_output = outputList;
}
/// <summary>
/// Return the instance of PSHost - null by default.
/// </summary>
public PSHost Host { set; get; }
#region Write
/// <summary>
/// Implementation of WriteDebug - just discards the input.
/// </summary>
/// <param name="text">Text to write.</param>
public void WriteDebug(string text) {; }
/// <summary>
/// Default implementation of WriteError - if the error record contains
/// an exception then that exception will be thrown. If not, then an
/// InvalidOperationException will be constructed and thrown.
/// </summary>
/// <param name="errorRecord">Error record instance to process.</param>
public void WriteError(ErrorRecord errorRecord)
{
if (errorRecord.Exception != null)
throw errorRecord.Exception;
else
throw new InvalidOperationException(errorRecord.ToString());
}
/// <summary>
/// Default implementation of WriteObject - adds the object to the list
/// passed to the objects constructor.
/// </summary>
/// <param name="sendToPipeline">Object to write.</param>
public void WriteObject(object sendToPipeline)
{
_output.Add(sendToPipeline);
}
/// <summary>
/// Default implementation of the enumerated WriteObject. Either way, the
/// objects are added to the list passed to this object in the constuctor.
/// </summary>
/// <param name="sendToPipeline">Object to write.</param>
/// <param name="enumerateCollection">If true, the collection is enumerated, otherwise
/// it's written as a scalar.
/// </param>
public void WriteObject(object sendToPipeline, bool enumerateCollection)
{
if (enumerateCollection)
{
IEnumerator e = LanguagePrimitives.GetEnumerator(sendToPipeline);
if (e == null)
{
_output.Add(sendToPipeline);
}
else
{
while (e.MoveNext())
{
_output.Add(e.Current);
}
}
}
else
{
_output.Add(sendToPipeline);
}
}
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="progressRecord">Progress record to write.</param>
public void WriteProgress(ProgressRecord progressRecord) {; }
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="sourceId">Source ID to write for.</param>
/// <param name="progressRecord">Record to write.</param>
public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord) {; }
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="text">Text to write.</param>
public void WriteVerbose(string text) {; }
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="text">Text to write.</param>
public void WriteWarning(string text) {; }
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="text">Text to write.</param>
public void WriteCommandDetail(string text) {; }
/// <summary>
/// Default implementation - just discards it's arguments.
/// </summary>
/// <param name="informationRecord">Record to write.</param>
public void WriteInformation(InformationRecord informationRecord) {; }
#endregion Write
#region Should
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="target">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldProcess(string target) { return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="target">Ignored.</param>
/// <param name="action">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldProcess(string target, string action) { return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="verboseDescription">Ignored.</param>
/// <param name="verboseWarning">Ignored.</param>
/// <param name="caption">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) { return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="verboseDescription">Ignored.</param>
/// <param name="verboseWarning">Ignored.</param>
/// <param name="caption">Ignored.</param>
/// <param name="shouldProcessReason">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) { shouldProcessReason = ShouldProcessReason.None; return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="query">Ignored.</param>
/// <param name="caption">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldContinue(string query, string caption) { return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="query">Ignored.</param>
/// <param name="caption">Ignored.</param>
/// <param name="yesToAll">Ignored.</param>
/// <param name="noToAll">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) { return true; }
/// <summary>
/// Default implementation - always returns true.
/// </summary>
/// <param name="query">Ignored.</param>
/// <param name="caption">Ignored.</param>
/// <param name="hasSecurityImpact">Ignored.</param>
/// <param name="yesToAll">Ignored.</param>
/// <param name="noToAll">Ignored.</param>
/// <returns>True.</returns>
public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) { return true; }
#endregion Should
#region Transaction Support
/// <summary>
/// Returns true if a transaction is available and active.
/// </summary>
public bool TransactionAvailable() { return false; }
/// <summary>
/// Gets an object that surfaces the current PowerShell transaction.
/// When this object is disposed, PowerShell resets the active transaction.
/// </summary>
public PSTransactionContext CurrentPSTransaction
{
get
{
string error = TransactionStrings.CmdletRequiresUseTx;
// We want to throw in this situation, and want to use a
// property because it mimics the C# using(TransactionScope ...) syntax
#pragma warning suppress 56503
throw new InvalidOperationException(error);
}
}
#endregion Transaction Support
#region Misc
/// <summary>
/// Implementation of the dummy default ThrowTerminatingError API - it just
/// does what the base implementation does anyway - rethrow the exception
/// if it exists, otherwise throw an invalid operation exception.
/// </summary>
/// <param name="errorRecord">The error record to throw.</param>
public void ThrowTerminatingError(ErrorRecord errorRecord)
{
if (errorRecord.Exception != null)
{
throw errorRecord.Exception;
}
else
{
throw new System.InvalidOperationException(errorRecord.ToString());
}
}
#endregion
}
}
| |
/*
* CodeGroup.cs - Implementation of the
* "System.Security.Policy.CodeGroup" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Security.Policy
{
#if CONFIG_POLICY_OBJECTS
using System.Collections;
[Serializable]
public abstract class CodeGroup
{
// Internal state.
private IMembershipCondition membershipCondition;
private PolicyStatement policy;
private IList children;
private String description;
private String name;
// Constructors.
public CodeGroup(IMembershipCondition membershipCondition,
PolicyStatement policy)
{
if(membershipCondition == null)
{
throw new ArgumentNullException("membershipCondition");
}
this.membershipCondition = membershipCondition;
this.policy = policy;
this.children = new ArrayList();
}
internal CodeGroup()
{
this.children = new ArrayList();
}
// Properties.
public virtual String AttributeString
{
get
{
if(policy != null)
{
return policy.AttributeString;
}
else
{
return null;
}
}
}
public IList Children
{
get
{
return children;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
children = value;
}
}
public String Description
{
get
{
return description;
}
set
{
description = value;
}
}
public IMembershipCondition MembershipCondition
{
get
{
return membershipCondition;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
membershipCondition = value;
}
}
public abstract String MergeLogic { get; }
public String Name
{
get
{
return name;
}
set
{
name = value;
}
}
public virtual String PermissionSetName
{
get
{
if(policy != null)
{
NamedPermissionSet permSet;
permSet = (policy.PermissionSetNoCopy
as NamedPermissionSet);
if(permSet != null)
{
return permSet.Name;
}
}
return null;
}
}
public PolicyStatement PolicyStatement
{
get
{
if(policy != null)
{
return policy.Copy();
}
else
{
return null;
}
}
set
{
if(value != null)
{
policy = value.Copy();
}
else
{
policy = null;
}
}
}
// Add a child to this code group.
public void AddChild(CodeGroup group)
{
if(group == null)
{
throw new ArgumentNullException("group");
}
Children.Add(group);
}
// Make a copy of this code group.
public abstract CodeGroup Copy();
// Create the XML form of this code group.
protected virtual void CreateXml
(SecurityElement element, PolicyLevel level)
{
// Nothing to do in the base class.
}
// Compare two code groups for equality.
public override bool Equals(Object obj)
{
CodeGroup cg = (obj as CodeGroup);
if(cg != null)
{
return Equals(cg, false);
}
else
{
return false;
}
}
public bool Equals(CodeGroup cg, bool compareChildren)
{
if(cg == null)
{
return false;
}
if(Name != cg.Name || Description != cg.Description ||
!MembershipCondition.Equals(cg.MembershipCondition))
{
return false;
}
if(compareChildren)
{
IList list1 = Children;
IList list2 = cg.Children;
if(list1.Count != list2.Count)
{
return false;
}
int posn;
for(posn = 0; posn < list1.Count; ++posn)
{
if(!((CodeGroup)(list1[posn])).Equals
(((CodeGroup)(list2[posn])), true))
{
return false;
}
}
}
return true;
}
// Convert an XML security element into a code group.
public void FromXml(SecurityElement et)
{
FromXml(et, null);
}
public void FromXml(SecurityElement et, PolicyLevel level)
{
SecurityElement child;
String className;
Type type;
ArrayList list;
CodeGroup group;
if(et == null)
{
throw new ArgumentNullException("et");
}
if(et.Tag != "CodeGroup")
{
throw new ArgumentException
(_("Security_CodeGroupName"));
}
if(et.Attribute("version") != "1")
{
throw new ArgumentException
(_("Security_PolicyVersion"));
}
name = et.Attribute("Name");
description = et.Attribute("Description");
// Load the membership condition information for the group.
child = et.SearchForChildByTag("IMembershipCondition");
if(child != null)
{
className = child.Attribute("class");
if(className == null)
{
throw new ArgumentException
(_("Invalid_PermissionXml"));
}
type = Type.GetType(className);
if(type == null && className.IndexOf('.') == -1)
{
// May not have been fully-qualified.
type = Type.GetType
("System.Security.Policy." + className);
}
if(!typeof(IMembershipCondition).IsAssignableFrom(type))
{
throw new ArgumentException
(_("Invalid_PermissionXml"));
}
membershipCondition =
(Activator.CreateInstance(type)
as IMembershipCondition);
if(membershipCondition != null)
{
membershipCondition.FromXml(child, level);
}
}
else
{
throw new ArgumentException
(_("Arg_InvalidMembershipCondition"));
}
// Load the children within this code group.
list = new ArrayList();
foreach(SecurityElement elem in et.Children)
{
if(elem.Tag != "CodeGroup")
{
continue;
}
className = child.Attribute("class");
if(className == null)
{
throw new ArgumentException
(_("Invalid_PermissionXml"));
}
type = Type.GetType(className);
if(type == null && className.IndexOf('.') == -1)
{
// May not have been fully-qualified.
type = Type.GetType
("System.Security.Policy." + className);
}
if(!typeof(CodeGroup).IsAssignableFrom(type))
{
throw new ArgumentException
(_("Invalid_PermissionXml"));
}
group = (Activator.CreateInstance(type) as CodeGroup);
if(group != null)
{
group.FromXml(elem, level);
list.Add(group);
}
}
children = list;
// Parse subclass-specific data from the element.
ParseXml(et, level);
}
// Get the hash code for this instance.
public override int GetHashCode()
{
return membershipCondition.GetHashCode();
}
// Remove a child from this code group.
public void RemoveChild(CodeGroup group)
{
if(group == null)
{
throw new ArgumentNullException("group");
}
if(!(Children.Contains(group)))
{
throw new ArgumentException
(_("Security_NotCodeGroupChild"));
}
}
// Resolve the policy for this code group.
public abstract PolicyStatement Resolve(Evidence evidence);
// Resolve code groups that match specific evidence.
public abstract CodeGroup ResolveMatchingCodeGroups(Evidence evidence);
// Convert a code group into an XML security element
public SecurityElement ToXml()
{
return ToXml(null);
}
public SecurityElement ToXml(PolicyLevel level)
{
SecurityElement element;
element = new SecurityElement("CodeGroup");
element.AddAttribute
("class",
SecurityElement.Escape(GetType().AssemblyQualifiedName));
element.AddAttribute("version", "1");
element.AddChild(membershipCondition.ToXml(level));
if(policy != null)
{
PermissionSet permSet = policy.PermissionSetNoCopy;
if(permSet is NamedPermissionSet && level != null &&
level.GetNamedPermissionSet
(((NamedPermissionSet)permSet).Name) != null)
{
element.AddAttribute
("PermissionSetName",
((NamedPermissionSet)permSet).Name);
}
else if(!permSet.IsEmpty())
{
element.AddChild(permSet.ToXml());
}
if(policy.Attributes != PolicyStatementAttribute.Nothing)
{
element.AddAttribute
("Attributes", policy.Attributes.ToString());
}
foreach(CodeGroup group in Children)
{
element.AddChild(group.ToXml(level));
}
}
if(name != null)
{
element.AddAttribute("Name", SecurityElement.Escape(name));
}
if(description != null)
{
element.AddAttribute
("Description", SecurityElement.Escape(description));
}
CreateXml(element, level);
return element;
}
// Parse the XML form of this code group.
protected virtual void ParseXml
(SecurityElement element, PolicyLevel level)
{
// Nothing to do in the base class.
}
}; // class CodeGroup
#endif // CONFIG_POLICY_OBJECTS
}; // namespace System.Security.Policy
| |
/* ****************************************************************************
*
* 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.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
#if SILVERLIGHT
using System.Core;
#endif
#if CLR2
namespace Microsoft.Scripting.Ast {
#else
namespace System.Linq.Expressions {
#endif
/// <summary>
/// Represents a constructor call.
/// </summary>
#if !SILVERLIGHT
[DebuggerTypeProxy(typeof(Expression.NewExpressionProxy))]
#endif
public class NewExpression : Expression, IArgumentProvider {
private readonly ConstructorInfo _constructor;
private IList<Expression> _arguments;
private readonly ReadOnlyCollection<MemberInfo> _members;
internal NewExpression(ConstructorInfo constructor, IList<Expression> arguments, ReadOnlyCollection<MemberInfo> members) {
_constructor = constructor;
_arguments = arguments;
_members = members;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type {
get { return _constructor.DeclaringType; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType {
get { return ExpressionType.New; }
}
/// <summary>
/// Gets the called constructor.
/// </summary>
public ConstructorInfo Constructor {
get { return _constructor; }
}
/// <summary>
/// Gets the arguments to the constructor.
/// </summary>
public ReadOnlyCollection<Expression> Arguments {
get { return ReturnReadOnly(ref _arguments); }
}
Expression IArgumentProvider.GetArgument(int index) {
return _arguments[index];
}
int IArgumentProvider.ArgumentCount {
get {
return _arguments.Count;
}
}
/// <summary>
/// Gets the members that can retrieve the values of the fields that were initialized with constructor arguments.
/// </summary>
public ReadOnlyCollection<MemberInfo> Members {
get { return _members; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor) {
return visitor.VisitNew(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public NewExpression Update(IEnumerable<Expression> arguments) {
if (arguments == Arguments) {
return this;
}
if (Members != null) {
return Expression.New(Constructor, arguments, Members);
}
return Expression.New(Constructor, arguments);
}
}
internal class NewValueTypeExpression : NewExpression {
private readonly Type _valueType;
internal NewValueTypeExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
: base(null, arguments, members) {
_valueType = type;
}
public sealed override Type Type {
get { return _valueType; }
}
}
public partial class Expression {
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> property set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor) {
return New(constructor, (IEnumerable<Expression>)null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An array of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, params Expression[] arguments) {
return New(constructor, (IEnumerable<Expression>)arguments);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments) {
ContractUtils.RequiresNotNull(constructor, "constructor");
ContractUtils.RequiresNotNull(constructor.DeclaringType, "constructor.DeclaringType");
TypeUtils.ValidateType(constructor.DeclaringType);
var argList = arguments.ToReadOnly();
ValidateArgumentTypes(constructor, ExpressionType.New, ref argList);
return new NewExpression(constructor, argList, null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An <see cref="IEnumerable{T}"/> of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members) {
ContractUtils.RequiresNotNull(constructor, "constructor");
var memberList = members.ToReadOnly();
var argList = arguments.ToReadOnly();
ValidateNewArgs(constructor, ref argList, ref memberList);
return new NewExpression(constructor, argList, memberList);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An Array of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo[] members) {
return New(constructor, arguments, (IEnumerable<MemberInfo>)members);
}
/// <summary>
/// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type.
/// </summary>
/// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments. </param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type.</returns>
public static NewExpression New(Type type) {
ContractUtils.RequiresNotNull(type, "type");
if (type == typeof(void)) {
throw Error.ArgumentCannotBeOfTypeVoid();
}
ConstructorInfo ci = null;
if (!type.IsValueType) {
ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, System.Type.EmptyTypes, null);
if (ci == null) {
throw Error.TypeMissingDefaultConstructor(type);
}
return New(ci);
}
return new NewValueTypeExpression(type, EmptyReadOnlyCollection<Expression>.Instance, null);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCollection<Expression> arguments, ref ReadOnlyCollection<MemberInfo> members) {
ParameterInfo[] pis;
if ((pis = constructor.GetParametersCached()).Length > 0) {
if (arguments.Count != pis.Length) {
throw Error.IncorrectNumberOfConstructorArguments();
}
if (arguments.Count != members.Count) {
throw Error.IncorrectNumberOfArgumentsForMembers();
}
Expression[] newArguments = null;
MemberInfo[] newMembers = null;
for (int i = 0, n = arguments.Count; i < n; i++) {
Expression arg = arguments[i];
RequiresCanRead(arg, "argument");
MemberInfo member = members[i];
ContractUtils.RequiresNotNull(member, "member");
if (!TypeUtils.AreEquivalent(member.DeclaringType, constructor.DeclaringType)) {
throw Error.ArgumentMemberNotDeclOnType(member.Name, constructor.DeclaringType.Name);
}
Type memberType;
ValidateAnonymousTypeMember(ref member, out memberType);
if (!TypeUtils.AreReferenceAssignable(memberType, arg.Type)) {
if (!TryQuote(memberType, ref arg)) {
throw Error.ArgumentTypeDoesNotMatchMember(arg.Type, memberType);
}
}
ParameterInfo pi = pis[i];
Type pType = pi.ParameterType;
if (pType.IsByRef) {
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) {
if (!TryQuote(pType, ref arg)) {
throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
}
}
if (newArguments == null && arg != arguments[i]) {
newArguments = new Expression[arguments.Count];
for (int j = 0; j < i; j++) {
newArguments[j] = arguments[j];
}
}
if (newArguments != null) {
newArguments[i] = arg;
}
if (newMembers == null && member != members[i]) {
newMembers = new MemberInfo[members.Count];
for (int j = 0; j < i; j++) {
newMembers[j] = members[j];
}
}
if (newMembers != null) {
newMembers[i] = member;
}
}
if (newArguments != null) {
arguments = new TrueReadOnlyCollection<Expression>(newArguments);
}
if (newMembers != null) {
members = new TrueReadOnlyCollection<MemberInfo>(newMembers);
}
} else if (arguments != null && arguments.Count > 0) {
throw Error.IncorrectNumberOfConstructorArguments();
} else if (members != null && members.Count > 0) {
throw Error.IncorrectNumberOfMembersForGivenConstructor();
}
}
private static void ValidateAnonymousTypeMember(ref MemberInfo member, out Type memberType) {
switch (member.MemberType) {
case MemberTypes.Field:
FieldInfo field = member as FieldInfo;
if (field.IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
memberType = field.FieldType;
return;
case MemberTypes.Property:
PropertyInfo pi = member as PropertyInfo;
if (!pi.CanRead) {
throw Error.PropertyDoesNotHaveGetter(pi);
}
if (pi.GetGetMethod().IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
memberType = pi.PropertyType;
return;
case MemberTypes.Method:
MethodInfo method = member as MethodInfo;
if (method.IsStatic) {
throw Error.ArgumentMustBeInstanceMember();
}
#if SILVERLIGHT
if (SilverlightQuirks) {
// we used to just store the MethodInfo
memberType = method.ReturnType;
return;
}
#endif
PropertyInfo prop = GetProperty(method);
member = prop;
memberType = prop.PropertyType;
return;
default:
throw Error.ArgumentMustBeFieldInfoOrPropertInfoOrMethod();
}
// don't add code here, we've already returned
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class TextMeshProFloatingText : MonoBehaviour
{
public Font TheFont;
private GameObject m_floatingText;
private TextMeshPro m_textMeshPro;
private TextMesh m_textMesh;
private Transform m_transform;
private Transform m_floatingText_Transform;
private Transform m_cameraTransform;
Vector3 lastPOS = Vector3.zero;
Quaternion lastRotation = Quaternion.identity;
public int SpawnType;
//private int m_frame = 0;
void Awake()
{
m_transform = transform;
m_floatingText = new GameObject(this.name + " floating text");
// Reference to Transform is lost when TMP component is added since it replaces it by a RectTransform.
//m_floatingText_Transform = m_floatingText.transform;
//m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
m_cameraTransform = Camera.main.transform;
}
void Start()
{
if (SpawnType == 0)
{
// TextMesh Pro Implementation
m_textMeshPro = m_floatingText.AddComponent<TextMeshPro>();
m_textMeshPro.rectTransform.sizeDelta = new Vector2(3, 3);
m_floatingText_Transform = m_floatingText.transform;
m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
//m_textMeshPro.fontAsset = Resources.Load("Fonts & Materials/JOKERMAN SDF", typeof(TextMeshProFont)) as TextMeshProFont; // User should only provide a string to the resource.
//m_textMeshPro.fontSharedMaterial = Resources.Load("Fonts & Materials/LiberationSans SDF", typeof(Material)) as Material;
m_textMeshPro.alignment = TextAlignmentOptions.Center;
m_textMeshPro.color = new Color32((byte) Random.Range(0, 255), (byte) Random.Range(0, 255),
(byte) Random.Range(0, 255), 255);
m_textMeshPro.fontSize = 24;
//m_textMeshPro.enableExtraPadding = true;
//m_textMeshPro.enableShadows = false;
m_textMeshPro.text = string.Empty;
StartCoroutine(DisplayTextMeshProFloatingText());
}
else if (SpawnType == 1)
{
//Debug.Log("Spawning TextMesh Objects.");
m_floatingText_Transform = m_floatingText.transform;
m_floatingText_Transform.position = m_transform.position + new Vector3(0, 15f, 0);
m_textMesh = m_floatingText.AddComponent<TextMesh>();
m_textMesh.font = Resources.Load("Fonts/ARIAL", typeof(Font)) as Font;
m_textMesh.GetComponent<Renderer>().sharedMaterial = m_textMesh.font.material;
m_textMesh.color = new Color32((byte) Random.Range(0, 255), (byte) Random.Range(0, 255),
(byte) Random.Range(0, 255), 255);
m_textMesh.anchor = TextAnchor.LowerCenter;
m_textMesh.fontSize = 24;
StartCoroutine(DisplayTextMeshFloatingText());
}
else if (SpawnType == 2)
{
}
}
//void Update()
//{
// if (SpawnType == 0)
// {
// m_textMeshPro.SetText("{0}", m_frame);
// }
// else
// {
// m_textMesh.text = m_frame.ToString();
// }
// m_frame = (m_frame + 1) % 1000;
//}
public IEnumerator DisplayTextMeshProFloatingText()
{
float CountDuration = 2.0f; // How long is the countdown alive.
float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at.
float current_Count = starting_Count;
Vector3 start_pos = m_floatingText_Transform.position;
Color32 start_color = m_textMeshPro.color;
float alpha = 255;
//int int_counter = 0;
float fadeDuration = 3 / starting_Count * CountDuration;
while (current_Count > 0)
{
current_Count -= (Time.deltaTime / CountDuration) * starting_Count;
if (current_Count <= 3)
{
//Debug.Log("Fading Counter ... " + current_Count.ToString("f2"));
alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255);
}
//int_counter = (int)current_Count;
m_textMeshPro.SetText("{0}", (int) current_Count);
m_textMeshPro.color = new Color32(start_color.r, start_color.g, start_color.b, (byte) alpha);
// Move the floating text upward each update
m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0);
// Align floating text perpendicular to Camera.
if (!lastPOS.Compare(m_cameraTransform.position, 1000) ||
!lastRotation.Compare(m_cameraTransform.rotation, 1000))
{
lastPOS = m_cameraTransform.position;
lastRotation = m_cameraTransform.rotation;
m_floatingText_Transform.rotation = lastRotation;
Vector3 dir = m_transform.position - lastPOS;
m_transform.forward = new Vector3(dir.x, 0, dir.z);
}
yield return new WaitForEndOfFrame();
}
//Debug.Log("Done Counting down.");
yield return new WaitForSeconds(Random.Range(0.1f, 1.0f));
m_floatingText_Transform.position = start_pos;
StartCoroutine(DisplayTextMeshProFloatingText());
}
public IEnumerator DisplayTextMeshFloatingText()
{
float CountDuration = 2.0f; // How long is the countdown alive.
float starting_Count = Random.Range(5f, 20f); // At what number is the counter starting at.
float current_Count = starting_Count;
Vector3 start_pos = m_floatingText_Transform.position;
Color32 start_color = m_textMesh.color;
float alpha = 255;
int int_counter = 0;
float fadeDuration = 3 / starting_Count * CountDuration;
while (current_Count > 0)
{
current_Count -= (Time.deltaTime / CountDuration) * starting_Count;
if (current_Count <= 3)
{
//Debug.Log("Fading Counter ... " + current_Count.ToString("f2"));
alpha = Mathf.Clamp(alpha - (Time.deltaTime / fadeDuration) * 255, 0, 255);
}
int_counter = (int) current_Count;
m_textMesh.text = int_counter.ToString();
//Debug.Log("Current Count:" + current_Count.ToString("f2"));
m_textMesh.color = new Color32(start_color.r, start_color.g, start_color.b, (byte) alpha);
// Move the floating text upward each update
m_floatingText_Transform.position += new Vector3(0, starting_Count * Time.deltaTime, 0);
// Align floating text perpendicular to Camera.
if (!lastPOS.Compare(m_cameraTransform.position, 1000) ||
!lastRotation.Compare(m_cameraTransform.rotation, 1000))
{
lastPOS = m_cameraTransform.position;
lastRotation = m_cameraTransform.rotation;
m_floatingText_Transform.rotation = lastRotation;
Vector3 dir = m_transform.position - lastPOS;
m_transform.forward = new Vector3(dir.x, 0, dir.z);
}
yield return new WaitForEndOfFrame();
}
//Debug.Log("Done Counting down.");
yield return new WaitForSeconds(Random.Range(0.1f, 1.0f));
m_floatingText_Transform.position = start_pos;
StartCoroutine(DisplayTextMeshFloatingText());
}
}
}
| |
using System;
using System.ComponentModel;
using Nucleo.EventArguments;
using Nucleo.Windows.UI;
using Nucleo.Windows.Actions;
using Nucleo.Collections;
namespace Nucleo.Windows.Application
{
public class ApplicationModel
{
private DocumentWindowCollection _documentWindows = null;
private MenuItemCollection _menus = null;
private PopupWindowCollection _popupWindows = null;
private StatusLabel _statusLabel = null;
private ToolbarCollection _toolbars = null;
private ToolWindowCollection _toolWindows = null;
private NameRegister _register = null;
#region " Events "
public event ApplicationModelEventHandler ItemAdded;
public event ApplicationModelEventHandler ItemRemoved;
#endregion
#region " Properties "
/// <summary>
/// The collection of documents in the main windows.
/// </summary>
protected internal DocumentWindowCollection DocumentWindows
{
get
{
if (_documentWindows == null)
_documentWindows = new DocumentWindowCollection();
return _documentWindows;
}
}
/// <summary>
/// Gets the collection of top-level menu items registered with the application.
/// </summary>
protected internal MenuItemCollection Menus
{
get
{
if (_menus == null)
_menus = new MenuItemCollection();
return _menus;
}
}
/// <summary>
/// Gets the collection of popup windows registered with the application.
/// </summary>
protected internal PopupWindowCollection PopupWindows
{
get
{
if (_popupWindows == null)
_popupWindows = new PopupWindowCollection();
return _popupWindows;
}
}
/// <summary>
/// The status to display about the application, usually displayed in a status bar.
/// </summary>
public string Status
{
get
{
if (this._statusLabel != null)
return this._statusLabel.Text;
else
return string.Empty;
}
set
{
if (this._statusLabel == null)
throw new NullReferenceException("The Status Label has not been created");
this._statusLabel.Text = value;
}
}
/// <summary>
/// The collection of toolbars that are displayed in the top section of the form.
/// </summary>
protected internal ToolbarCollection Toolbars
{
get
{
if (_toolbars == null)
_toolbars = new ToolbarCollection();
return _toolbars;
}
}
/// <summary>
/// The collection of tool windows that make up the left and right sides of the application.
/// </summary>
protected internal ToolWindowCollection ToolWindows
{
get
{
if (_toolWindows == null)
_toolWindows = new ToolWindowCollection();
return _toolWindows;
}
}
#endregion
#region " Constructors "
protected ApplicationModel()
{
_register = new NameRegister();
}
#endregion
#region " Methods "
/// <summary>
/// Adds a single item to the appropriate repository.
/// </summary>
/// <param name="element">The element to add to the repository.</param>
public void AddItem(UIElement element)
{
this.AddItemToCollection(-1, element);
}
/// <summary>
/// Adds a child to a parent element.
/// </summary>
/// <param name="parent">The parent to add.</param>
/// <param name="child">The child to add to the parent.</param>
public void AddItem(UIElement parent, UIElement child)
{
this.AddItemToCollection(-1, parent, child);
}
/// <summary>
/// Adds an item to the repository at the specified index.
/// </summary>
/// <param name="index">The index value to add an item to.</param>
/// <param name="element">The element to add.</param>
public void AddItem(int index, UIElement element)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index");
this.AddItemToCollection(index, element);
}
/// <summary>
/// Adds a child item to its respective parent. For the parent/child relationship to work, the parent must implement <see cref="UI.IParentElement" /> and the child must implement <see cref="UI.IChildElement" />.
/// </summary>
/// <param name="index">The index to add the item at.</param>
/// <param name="parent">The parent item that can accept children.</param>
/// <param name="child">The child to add to the parent collection.</param>
public void AddItem(int index, UIElement parent, UIElement child)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index");
this.AddItemToCollection(index, parent, child);
}
protected void AddItemToCollection(int index, UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
if (!this.IsValidName(element))
throw new ArgumentException(string.Format("An element with the name '{0}' already exists, or the name is not valid.", element.Name));
//If a child element, which means it has a parent, if the parent isn't null, use the overload
if (element is IChildElement)
{
IChildElement child = (IChildElement)element;
if (child.Parent != null)
{
this.AddItemToCollection(index, child.Parent, element);
return;
}
}
if (!this.IsValidSingleItem(element))
throw new ArgumentException(string.Format("The element of type {0} cannot be added using this overload.", element.GetType().Name));
this.OnItemAdded(new ApplicationModelEventArgs(element, index, this));
if (index > 0)
this.GetCollection(element.GetType()).Insert(index, element);
else
this.GetCollection(element.GetType()).Add(element);
_register.Add(element);
this.CheckForStatusLabel(element);
}
protected void AddItemToCollection(int index, UIElement parent, UIElement child)
{
if (parent == null)
throw new ArgumentNullException("parent");
if (child == null)
throw new ArgumentNullException("child");
if (!this.IsValidChildItem(parent, child))
throw new ArgumentException(string.Format("The element {0} cannot be added as a child of {1}.", child.GetType().Name, parent.GetType().Name));
if (!this.IsValidName(child))
throw new ArgumentException(string.Format("An element with the name '{0}' already exists, or the name is not valid.", child.Name));
if (index > 0)
((IParentElement)parent).Items.Insert(index, child);
else
((IParentElement)parent).Items.Add(child);
this.OnItemAdded(new ApplicationModelEventArgs(parent, child, index, this));
_register.Add(child);
this.CheckForStatusLabel(child);
}
private void CheckForStatusLabel(UIElement element)
{
if (element is StatusLabel)
{
//if the element is a status label, which only one can exist in the application,
//then determine if one already exists, and if so throw an exception. Otherwise,
//assign it to the local variable.
if (_statusLabel != null)
throw new Exception("The status label has already been assigned");
_statusLabel = (StatusLabel)element;
}
}
/// <summary>
/// Whether an item exists in the model with the designated name.
/// </summary>
/// <param name="itemName">The item to determine whether it exists.</param>
/// <returns>Whether the item exists.</returns>
/// <exception cref="ArgumentNullException">Thrown whenever the item name is null.</exception>
public bool ContainsItem(string itemName)
{
if (string.IsNullOrEmpty(itemName))
throw new ArgumentNullException("itemName");
return _register.Contains(itemName);
}
/// <summary>
/// Whether an item exists in the model, by reference.
/// </summary>
/// <param name="element">The item to determine whether it exists.</param>
/// <returns>Whether the item exists.</returns>
/// <exception cref="ArgumentNullException">Thrown whenever the element is null.</exception>
public bool ContainsItem(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
IElementCollection collection = this.GetCollection(element.GetType());
if (collection != null)
return collection.Contains(element);
else
return false;
}
/// <summary>
/// Whether an item exists in the model for a specified type.
/// </summary>
/// <typeparam name="T">The type of item to look in its respective collection.</typeparam>
/// <param name="name">The name of the item to find in the respective collection.</param>
/// <returns>Whether the item was found by name.</returns>
/// <exception cref="ArgumentNullException">Thrown whenever the name is null.</exception>
public bool ContainsItem<T>(string name) where T : UIElement
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
return this.GetCollection<T>().Contains(new ValuePath(name));
}
/// <summary>
/// Uses a value path to traverse the designated item collection to see if the item exists.
/// </summary>
/// <typeparam name="T">The specified item type to look for.</typeparam>
/// <param name="path">The path of values to use to navigate through the list.</param>
/// <returns>Whether the item exists.</returns>
/// <exception cref="ArgumentNullException">Thrown whenever the path is null.</exception>
/// <example>
/// ValuePath path = new ValuePath("File", "New", "C# File");
/// Assert.IsTrue(_model.ContainsItem<MenuItem>(path));
/// </example>
public bool ContainsItem<T>(ValuePath path) where T : UIElement
{
if (path == null)
throw new ArgumentNullException("path");
return this.GetCollection<T>().Contains(path);
}
public bool ContainsItem<T>(T item) where T : UIElement
{
return this.GetCollection<T>().Contains(item);
}
private IElementCollection GetCollection(Type elementType)
{
if (elementType == typeof(DocumentWindow))
return this.DocumentWindows;
if (elementType == typeof(ToolWindow))
return this.ToolWindows;
if (elementType == typeof(MenuItem))
return this.Menus;
if (elementType == typeof(Toolbar) ||
elementType == typeof(ToolbarItem) ||
elementType.IsAssignableFrom(elementType))
return this.Toolbars;
if (elementType == (typeof(PopupWindow)))
return this.PopupWindows;
return null;
}
private IElementCollection GetCollection<T>() where T : UIElement
{
return this.GetCollection(typeof(T));
}
/// <summary>
/// Gets the count from the specified collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public int GetCount<T>() where T:UIElement
{
return this.GetCollection<T>().Count;
}
/// <summary>
/// Gets the item that is in a collection with the specified name.
/// </summary>
/// <typeparam name="T">The type of item to retrieve, which uses the type to get the respective collection of items.</typeparam>
/// <param name="name">The name of the item to find.</param>
/// <returns>The instance of the item, or null if not found.</returns>
public T GetItem<T>(string name) where T : UIElement
{
IElementCollection collection = this.GetCollection<T>();
if (collection == null)
return null;
return (T)collection[name];
}
/// <summary>
/// Gets the item from the specified value path.
/// </summary>
/// <typeparam name="T">The type of item to retrieve, which uses the type to get the respective collection of items.</typeparam>
/// <param name="path">The path to use to navigate through the collection.</param>
/// <returns>The instance of the item, or null if not found.</returns>
public T GetItem<T>(ValuePath path) where T : UIElement
{
IElementCollection collection = this.GetCollection<T>();
if (collection != null)
return (T)collection[path];
else
return null;
}
/// <summary>
/// Instantiates the application model object using the singleton pattern.
/// </summary>
/// <returns>An instance of the application model.</returns>
public static ApplicationModel Instantiate()
{
return new ApplicationModel();
}
/// <summary>
/// Determines whether the parent element, and the child element, are valid parent/child relationship items.
/// </summary>
/// <param name="parent">The parent element to compare.</param>
/// <param name="child">The child element to compare.</param>
/// <returns>Whether the relationship is valid.</returns>
private bool IsValidChildItem(UIElement parent, UIElement child)
{
if (!(parent is IParentElement))
return false;
if (!(child is IChildElement))
return false;
return true;
}
/// <summary>
/// Whether an item is a valid single root item, which means that the item cannot be added at the root level.
/// </summary>
/// <param name="element">The item to determine if it is a valid single-level item.</param>
/// <returns>Whether the item is a single-level item.</returns>
private bool IsValidSingleItem(UIElement element)
{
if (element is ToolbarItem)
return false;
else
return true;
}
/// <summary>
/// Whether the element's name is a valid name, meaning it's not null and it doesn't already exist.
/// </summary>
/// <param name="element">The element to determine validity for.</param>
/// <returns></returns>
private bool IsValidName(UIElement element)
{
if (string.IsNullOrEmpty(element.Name))
return false;
return !_register.Contains(element.Name);
}
/// <summary>
/// Fires the <see cref="ItemAdded" /> event.
/// </summary>
/// <param name="e">The details about the added item.</param>
protected virtual void OnItemAdded(ApplicationModelEventArgs e)
{
if (ItemAdded != null)
ItemAdded(this, e);
}
/// <summary>
/// Fires the <see cref="ItemRemoved" /> event.
/// </summary>
/// <param name="e">The details about the removed item.</param>
protected virtual void OnItemRemoved(ApplicationModelEventArgs e)
{
if (ItemRemoved != null)
ItemRemoved(this, e);
}
/// <summary>
/// Removes an item from its designated collection.
/// </summary>
/// <param name="element">The item to remove.</param>
public void RemoveItem(UIElement element)
{
this.RemoveItemInternal(element);
}
/// <summary>
/// Removes a child from its designated parent.
/// </summary>
/// <param name="parent">The parent item to remove a child from.</param>
/// <param name="child">The child to remove.</param>
public void RemoveItem(UIElement parent, UIElement child)
{
if (parent == null)
throw new ArgumentNullException("parent");
if (child == null)
throw new ArgumentNullException("child");
if (!this.IsValidChildItem(parent, child))
throw new ArgumentException(string.Format("The element {0} cannot be added as a child of {1}.", child.GetType().Name, parent.GetType().Name));
if (!this.IsValidName(child))
throw new ArgumentException(string.Format("An element with the name '{0}' already exists, or the name is not valid.", child.Name));
this.OnItemRemoved(new ApplicationModelEventArgs(parent, child, -1, this));
((IParentElement)parent).Items.Remove(child);
_register.Remove(child);
if (child is StatusLabel)
_statusLabel = null;
}
/// <summary>
/// Removes root-level items that are found in the specified collection by type. Does not work for child menu items or toolbar items.
/// </summary>
/// <typeparam name="T">The type that denotes the collection to look in.</typeparam>
/// <param name="name">The name of the item to find.</param>
public void RemoveItem<T>(string name) where T: UIElement
{
this.RemoveItem<T>(new ValuePath(name));
}
/// <summary>
/// Uses a value path to navigate through a hierarchy of items and remove the last one in the list.
/// </summary>
/// <typeparam name="T">The type of item to remove.</typeparam>
/// <param name="path">The path to navigate through, and find the respective item.</param>
/// <example>
/// ValuePath path = new ValuePath("File", "New");
/// _model.RemoveItem<MenuItem>(path);
/// </example>
public void RemoveItem<T>(ValuePath path) where T : UIElement
{
UIElement item = this.GetCollection<T>()[path];
if (item == null)
throw new ArgumentNullException("path", "The item does not exist at the specified path");
this.RemoveItem(item);
if (item is StatusLabel)
_statusLabel = null;
}
/// <summary>
/// Removes an item from the collection for the specified type.
/// </summary>
/// <typeparam name="T">A type that derives from UIElement.</typeparam>
/// <param name="item">The item to remove from the collection.</param>
public void RemoveItem<T>(T item) where T : UIElement
{
this.RemoveItemInternal(item);
if (item is StatusLabel)
_statusLabel = null;
}
private void RemoveItemInternal(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
if (!this.IsValidSingleItem(element))
throw new ArgumentException(string.Format("The element of type {0} cannot be removed using this overload.", element.GetType().Name));
this.OnItemRemoved(new ApplicationModelEventArgs(element, -1, this));
this.GetCollection(element.GetType()).Remove(element);
_register.Remove(element);
if (element is StatusLabel)
_statusLabel = null;
}
#endregion
}
}
| |
//---------------------------------------------------------------------
// <copyright file="Domain.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common.Utils;
using System.Data.Entity;
using System.Data.Mapping.ViewGeneration.Utils;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Mapping.ViewGeneration.Structures
{
using CellConstantSet = Set<Constant>;
// A set of cell constants -- to keep track of a cell constant's domain
// values. It encapsulates the notions of NULL, NOT NULL and can be
// enhanced in the future with more functionality
// To represent "infinite" domains such as integer, a special constant CellConstant.NotNull is used.
// For example: domain of System.Boolean is {true, false}, domain of
// (nullable) System.Int32 property is {Null, NotNull}.
internal class Domain : InternalBase
{
#region Constructors
// effects: Creates an "fully-done" set with no values -- possibleDiscreteValues are the values
// that this domain can take
internal Domain(Constant value, IEnumerable<Constant> possibleDiscreteValues) :
this(new Constant[] { value }, possibleDiscreteValues)
{
}
// effects: Creates a domain populated using values -- possibleValues
// are all possible values that this can take
internal Domain(IEnumerable<Constant> values,
IEnumerable<Constant> possibleDiscreteValues)
{
// Note that the values can contain both null and not null
Debug.Assert(values != null);
Debug.Assert(possibleDiscreteValues != null);
// Determine the possibleValues first and then create the negatedConstant
m_possibleValues = DeterminePossibleValues(values, possibleDiscreteValues);
// Now we need to make sure that m_domain is correct. if "values" (v) already has
// the negated stuff, we need to make sure it is in conformance
// with what m_possibleValues (p) has
// For NOT --> Add all constants into d that are present in p but
// not in the NOT
// v = 1, NOT(1, 2); p = 1, 2, 3 => d = 1, NOT(1, 2, 3), 3
// v = 1, 2, NOT(1); p = 1, 2, 4 => d = 1, 2, 4, NOT(1, 2, 4)
// v = 1, 2, NOT(1, 2, 4), NOT(1, 2, 4, 5); p = 1, 2, 4, 5, 6 => d = 1, 2, 5, 6, NOT(1, 2, 4, 5, 6)
// NotNull works naturally now. If possibleValues has (1, 2, NULL) and values has NOT(NULL), add 1, 2 to m_domain
m_domain = ExpandNegationsInDomain(values, m_possibleValues);
AssertInvariant();
}
// effects: Creates a copy of the set "domain"
internal Domain(Domain domain)
{
m_domain = new Set<Constant>(domain.m_domain, Constant.EqualityComparer);
m_possibleValues = new Set<Constant>(domain.m_possibleValues, Constant.EqualityComparer);
AssertInvariant();
}
#endregion
#region Fields
// The set of values in the cell constant domain
private CellConstantSet m_domain; // e.g., 1, 2, NULL, NOT(1, 2, NULL)
private CellConstantSet m_possibleValues; // e.g., 1, 2, NULL, Undefined
// Invariant: m_domain is a subset of m_possibleValues except for a
// negated constant
#endregion
#region Properties
// effects: Returns all the possible values that this can contain (including the negated constants)
internal IEnumerable<Constant> AllPossibleValues
{
get { return AllPossibleValuesInternal; }
}
// effects: Returns all the possible values that this can contain (including the negated constants)
private Set<Constant> AllPossibleValuesInternal
{
get
{
NegatedConstant negatedPossibleValue = new NegatedConstant(m_possibleValues);
return m_possibleValues.Union(new Constant[] { negatedPossibleValue });
}
}
// effects: Returns the number of constants in this (including a negated constant)
internal int Count
{
get { return m_domain.Count; }
}
/// <summary>
/// Yields the set of all values in the domain.
/// </summary>
internal IEnumerable<Constant> Values
{
get { return m_domain; }
}
#endregion
#region Static Helper Methods to create cell constant sets from metadata
// effects: Given a member, determines all possible values that can be created from Metadata
internal static CellConstantSet DeriveDomainFromMemberPath(MemberPath memberPath, EdmItemCollection edmItemCollection, bool leaveDomainUnbounded)
{
CellConstantSet domain = DeriveDomainFromType(memberPath.EdmType, edmItemCollection, leaveDomainUnbounded);
if (memberPath.IsNullable)
{
domain.Add(Constant.Null);
}
return domain;
}
// effects: Given a type, determines all possible values that can be created from Metadata
private static CellConstantSet DeriveDomainFromType(EdmType type, EdmItemCollection edmItemCollection, bool leaveDomainUnbounded)
{
CellConstantSet domain = null;
if (Helper.IsScalarType(type))
{
// Get the domain for scalars -- for booleans, we special case.
if (MetadataHelper.HasDiscreteDomain(type))
{
Debug.Assert(Helper.AsPrimitive(type).PrimitiveTypeKind == PrimitiveTypeKind.Boolean, "Only boolean type has discrete domain.");
// Closed domain
domain = new Set<Constant>(CreateList(true, false), Constant.EqualityComparer);
}
else
{
// Unbounded domain
domain = new Set<Constant>(Constant.EqualityComparer);
if (leaveDomainUnbounded)
{
domain.Add(Constant.NotNull);
}
}
}
else //Type Constants - Domain is all possible concrete subtypes
{
Debug.Assert(Helper.IsEntityType(type) || Helper.IsComplexType(type) || Helper.IsRefType(type) || Helper.IsAssociationType(type));
// Treat ref types as their referenced entity types
if (Helper.IsRefType(type))
{
type = ((RefType)type).ElementType;
}
List<Constant> types = new List<Constant>();
foreach (EdmType derivedType in MetadataHelper.GetTypeAndSubtypesOf(type, edmItemCollection, false /*includeAbstractTypes*/))
{
TypeConstant derivedTypeConstant = new TypeConstant(derivedType);
types.Add(derivedTypeConstant);
}
domain = new Set<Constant>(types, Constant.EqualityComparer);
}
Debug.Assert(domain != null, "Domain not set up for some type");
return domain;
}
// effect: returns the default value for the member
// if the member is nullable and has no default, changes default value to CellConstant.NULL and returns true
// if the mebmer is not nullable and has no default, returns false
// CHANGE_[....]_FEATURE_DEFAULT_VALUES: return the right default once metadata supports it
internal static bool TryGetDefaultValueForMemberPath(MemberPath memberPath, out Constant defaultConstant)
{
object defaultValue = memberPath.DefaultValue;
defaultConstant = Constant.Null;
if (defaultValue != null)
{
defaultConstant = new ScalarConstant(defaultValue);
return true;
}
else if (memberPath.IsNullable || memberPath.IsComputed)
{
return true;
}
return false;
}
internal static Constant GetDefaultValueForMemberPath(MemberPath memberPath, IEnumerable<LeftCellWrapper> wrappersForErrorReporting,
ConfigViewGenerator config)
{
Constant defaultValue = null;
if (!Domain.TryGetDefaultValueForMemberPath(memberPath, out defaultValue))
{
string message = Strings.ViewGen_No_Default_Value(memberPath.Extent.Name, memberPath.PathToString(false));
ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.NoDefaultValue, message, wrappersForErrorReporting, String.Empty);
ExceptionHelpers.ThrowMappingException(record, config);
}
return defaultValue;
}
#endregion
#region External methods
internal int GetHash()
{
int result = 0;
foreach (Constant constant in m_domain)
{
result ^= Constant.EqualityComparer.GetHashCode(constant);
}
return result;
}
// effects: Returns true iff this domain has the same values as
// second. Note that this method performs a semantic check not just
// an element by element check
internal bool IsEqualTo(Domain second)
{
return m_domain.SetEquals(second.m_domain);
}
// requires: this is complete
// effects: Returns true iff this contains NOT(NULL OR ....)
internal bool ContainsNotNull()
{
NegatedConstant negated = GetNegatedConstant(m_domain);
return negated != null && negated.Contains(Constant.Null);
}
/// <summary>
/// Returns true if the domain contains the given Cell Constant
/// </summary>
internal bool Contains(Constant constant)
{
return m_domain.Contains(constant);
}
// effects: Given a set of values in domain, "normalizes" it, i.e.,
// all positive constants are seperated out and any negative constant
// is changed s.t. it is the negative of all positive values
// extraValues indicates more constants that domain could take, e.g.,
// domain could be "1, 2, NOT(1, 2)", extraValues could be "3". In
// this case, we return "1, 2, 3, NOT(1, 2, 3)"
internal static CellConstantSet ExpandNegationsInDomain(IEnumerable<Constant> domain, IEnumerable<Constant> otherPossibleValues)
{
//Finds all constants referenced in (domain UNION extraValues) e.g: 1, NOT(2) => 1, 2
CellConstantSet possibleValues = DeterminePossibleValues(domain, otherPossibleValues);
// For NOT --> Add all constants into d that are present in p but
// not in the NOT
// v = 1, NOT(1, 2); p = 1, 2, 3 => d = 1, NOT(1, 2, 3), 3
// v = 1, 2, NOT(1); p = 1, 2, 4 => d = 1, 2, 4, NOT(1, 2, 4)
// v = 1, 2, NOT(1, 2, 4), NOT(1, 2, 4, 5); p = 1, 2, 4, 5, 6 => d = 1, 2, 5, 6, NOT(1, 2, 4, 5, 6)
// NotNull works naturally now. If possibleValues has (1, 2, NULL)
// and values has NOT(NULL), add 1, 2 to m_domain
CellConstantSet result = new Set<Constant>(Constant.EqualityComparer);
foreach (Constant constant in domain)
{
NegatedConstant negated = constant as NegatedConstant;
if (negated != null)
{
result.Add(new NegatedConstant(possibleValues));
// Compute all elements in possibleValues that are not present in negated. E.g., if
// negated is NOT(1, 2, 3) and possibleValues is 1, 2, 3,
// 4, we need to add 4 to result
CellConstantSet remainingElements = possibleValues.Difference(negated.Elements);
result.AddRange(remainingElements);
}
else
{
result.Add(constant);
}
}
return result;
}
internal static CellConstantSet ExpandNegationsInDomain(IEnumerable<Constant> domain)
{
return ExpandNegationsInDomain(domain, domain);
}
// effects: Given a set of values in domain
// Returns all possible values that are present in domain.
static CellConstantSet DeterminePossibleValues(IEnumerable<Constant> domain)
{
// E.g., if we have 1, 2, NOT(1) --> Result = 1, 2
// 1, NOT(1, 2) --> Result = 1, 2
// 1, 2, NOT(NULL) --> Result = 1, 2, NULL
// 1, 2, NOT(2), NOT(3, 4) --> Result = 1, 2, 3, 4
CellConstantSet result = new CellConstantSet(Constant.EqualityComparer);
foreach (Constant constant in domain)
{
NegatedConstant negated = constant as NegatedConstant;
if (negated != null)
{
// Go through all the constants in negated and add them to domain
// We add them to possible values also even if (say) Null is not allowed because we want the complete
// partitioning of the space, e.g., if the values specified by the caller are 1, NotNull -> we want 1, Null
foreach (Constant constElement in negated.Elements)
{
Debug.Assert(constElement as NegatedConstant == null, "Negated cell constant inside NegatedCellConstant");
result.Add(constElement);
}
}
else
{
result.Add(constant);
}
}
return result;
}
#endregion
#region Helper methods for determining domains from cells
// effects: Given a set of cells, returns all the different values
// that each memberPath in cells can take
internal static Dictionary<MemberPath, CellConstantSet>
ComputeConstantDomainSetsForSlotsInQueryViews(IEnumerable<Cell> cells, EdmItemCollection edmItemCollection, bool isValidationEnabled)
{
Dictionary<MemberPath, CellConstantSet> cDomainMap =
new Dictionary<MemberPath, CellConstantSet>(MemberPath.EqualityComparer);
foreach (Cell cell in cells)
{
CellQuery cQuery = cell.CQuery;
// Go through the conjuncts to get the constants (e.g., we
// just don't want to NULL, NOT(NULL). We want to say that
// the possible values are NULL, 4, NOT(NULL, 4)
foreach (MemberRestriction restriction in cQuery.GetConjunctsFromWhereClause())
{
MemberProjectedSlot slot = restriction.RestrictedMemberSlot;
CellConstantSet cDomain = DeriveDomainFromMemberPath(slot.MemberPath, edmItemCollection, isValidationEnabled);
// Now we add the domain of oneConst into this
//Isnull=true and Isnull=false conditions should not contribute to a member's domain
cDomain.AddRange(restriction.Domain.Values.Where(c => !(c.Equals(Constant.Null) || c.Equals(Constant.NotNull))));
CellConstantSet values;
bool found = cDomainMap.TryGetValue(slot.MemberPath, out values);
if (!found)
{
cDomainMap[slot.MemberPath] = cDomain;
}
else
{
values.AddRange(cDomain);
}
}
}
return cDomainMap;
}
//True = domain is restricted, False = domain is not restricted (because there is no condition)
private static bool GetRestrictedOrUnrestrictedDomain(MemberProjectedSlot slot, CellQuery cellQuery, EdmItemCollection edmItemCollection, out CellConstantSet domain)
{
CellConstantSet domainValues = DeriveDomainFromMemberPath(slot.MemberPath, edmItemCollection, true /* leaveDomainUnbounded */);
//Note, out domain is set even in the case where method call returns false
return TryGetDomainRestrictedByWhereClause(domainValues, slot, cellQuery, out domain);
}
// effects: returns a dictionary that maps each S-side slot whose domain can be restricted to such an enumerated domain
// The resulting domain is a union of
// (a) constants appearing in conditions on that slot on S-side
// (b) constants appearing in conditions on the respective slot on C-side, if the given slot
// is projected (on the C-side) and no conditions are placed on it on S-side
// (c) default value of the slot based on metadata
internal static Dictionary<MemberPath, CellConstantSet>
ComputeConstantDomainSetsForSlotsInUpdateViews(IEnumerable<Cell> cells, EdmItemCollection edmItemCollection)
{
Dictionary<MemberPath, CellConstantSet> updateDomainMap = new Dictionary<MemberPath, CellConstantSet>(MemberPath.EqualityComparer);
foreach (Cell cell in cells)
{
CellQuery cQuery = cell.CQuery;
CellQuery sQuery = cell.SQuery;
foreach (MemberProjectedSlot sSlot in sQuery.GetConjunctsFromWhereClause().Select(oneOfConst => oneOfConst.RestrictedMemberSlot))
{
// obtain initial slot domain and restrict it if the slot has conditions
CellConstantSet restrictedDomain;
bool wasDomainRestricted = GetRestrictedOrUnrestrictedDomain(sSlot, sQuery, edmItemCollection, out restrictedDomain);
// Suppose that we have a cell:
// Proj(ID, A) WHERE(A=5) FROM E = Proj(ID, B) FROM T
// In the above cell, B on the S-side is 5 and we add that to its range. But if B had a restriction,
// we do not add 5. Note that do we not have a problem w.r.t. possibleValues since if A=5 and B=1, we have an
// empty cell -- we should catch that as an error. If A = 5 and B = 5 is present then restrictedDomain
// and domainValues are the same
// if no restriction on the S-side and the slot is projected then take the domain from the C-side
if (!wasDomainRestricted)
{
int projectedPosition = sQuery.GetProjectedPosition(sSlot);
if (projectedPosition >= 0)
{
// get the domain of the respective C-side slot
MemberProjectedSlot cSlot = cQuery.ProjectedSlotAt(projectedPosition) as MemberProjectedSlot;
Debug.Assert(cSlot != null, "Assuming constants are not projected");
wasDomainRestricted = GetRestrictedOrUnrestrictedDomain(cSlot, cQuery, edmItemCollection, out restrictedDomain);
if (!wasDomainRestricted)
{
continue;
}
}
}
// Add the default value to the domain
MemberPath sSlotMemberPath = sSlot.MemberPath;
Constant defaultValue;
if (TryGetDefaultValueForMemberPath(sSlotMemberPath, out defaultValue))
{
restrictedDomain.Add(defaultValue);
}
// add all constants appearing in the domain to sDomainMap
CellConstantSet sSlotDomain;
if (!updateDomainMap.TryGetValue(sSlotMemberPath, out sSlotDomain))
{
updateDomainMap[sSlotMemberPath] = restrictedDomain;
}
else
{
sSlotDomain.AddRange(restrictedDomain);
}
}
}
return updateDomainMap;
}
// requires: domain not have any Negated constants other than NotNull
// Also, cellQuery contains all final oneOfConsts or all partial oneOfConsts
// cellquery must contain a whereclause of the form "True", "OneOfConst" or "
// "OneOfConst AND ... AND OneOfConst"
// slot must present in cellQuery and incomingDomain is the domain for it
// effects: Returns the set of values that slot can take as restricted by cellQuery's whereClause
private static bool TryGetDomainRestrictedByWhereClause(IEnumerable<Constant> domain, MemberProjectedSlot slot, CellQuery cellQuery, out CellConstantSet result)
{
var conditionsForSlot = cellQuery.GetConjunctsFromWhereClause()
.Where(restriction => MemberPath.EqualityComparer.Equals(restriction.RestrictedMemberSlot.MemberPath, slot.MemberPath))
.Select(restriction => new CellConstantSet(restriction.Domain.Values, Constant.EqualityComparer));
//Debug.Assert(!conditionsForSlot.Skip(1).Any(), "More than one Clause with the same path");
if (!conditionsForSlot.Any())
{
// If the slot was not mentioned in the query return the domain without restricting it
result = new CellConstantSet(domain);
return false;
}
// Now get all the possible values from domain and conditionValues
CellConstantSet possibleValues = DeterminePossibleValues(conditionsForSlot.SelectMany(m => m.Select(c => c)), domain);
Domain restrictedDomain = new Domain(domain, possibleValues);
foreach (var conditionValues in conditionsForSlot)
{
// Domain derived from Edm-Type INTERSECTED with Conditions
restrictedDomain = restrictedDomain.Intersect(new Domain(conditionValues, possibleValues));
}
result = new CellConstantSet(restrictedDomain.Values, Constant.EqualityComparer);
return !domain.SequenceEqual(result);
}
#endregion
#region Private helper methods
// effects: Intersects the values in second with this domain and
// returns the result
private Domain Intersect(Domain second)
{
CheckTwoDomainInvariants(this, second);
Domain result = new Domain(this);
result.m_domain.Intersect(second.m_domain);
return result;
}
// requires: constants has at most one NegatedCellConstant
// effects: Returns the NegatedCellConstant in this if any. Else
// returns null
private static NegatedConstant GetNegatedConstant(IEnumerable<Constant> constants)
{
NegatedConstant result = null;
foreach (Constant constant in constants)
{
NegatedConstant negated = constant as NegatedConstant;
if (negated != null)
{
Debug.Assert(result == null, "Multiple negated cell constants?");
result = negated;
}
}
return result;
}
// effects: Given a set of values in domain1 and domain2,
// Returns all possible positive values that are present in domain1 and domain2
private static CellConstantSet DeterminePossibleValues(IEnumerable<Constant> domain1, IEnumerable<Constant> domain2)
{
CellConstantSet union = new CellConstantSet(domain1, Constant.EqualityComparer).Union(domain2);
CellConstantSet result = DeterminePossibleValues(union);
return result;
}
// effects: Checks that two domains, domain1 and domain2, that are being compared/unioned/intersected, etc
// are compatible with each other
[Conditional("DEBUG")]
private static void CheckTwoDomainInvariants(Domain domain1, Domain domain2)
{
domain1.AssertInvariant();
domain2.AssertInvariant();
// The possible values must match
Debug.Assert(domain1.m_possibleValues.SetEquals(domain2.m_possibleValues), "domains must be compatible");
}
// effects: A helper method. Given two
// values, yields a list of CellConstants in the order of values
private static IEnumerable<Constant> CreateList(object value1, object value2)
{
yield return new ScalarConstant(value1);
yield return new ScalarConstant(value2);
}
// effects: Checks the invariants in "this"
internal void AssertInvariant()
{
// Make sure m_domain has at most one negatedCellConstant
// m_possibleValues has none
NegatedConstant negated = GetNegatedConstant(m_domain); // Can be null or not-null
negated = GetNegatedConstant(m_possibleValues);
Debug.Assert(negated == null, "m_possibleValues cannot contain negated constant");
Debug.Assert(m_domain.IsSubsetOf(AllPossibleValuesInternal),
"All domain values must be contained in possibleValues");
}
#endregion
#region String methods
// effects: Returns a user-friendly string that can be reported to an end-user
internal string ToUserString()
{
StringBuilder builder = new StringBuilder();
bool isFirst = true;
foreach (Constant constant in m_domain)
{
if (isFirst == false)
{
builder.Append(", ");
}
builder.Append(constant.ToUserString());
isFirst = false;
}
return builder.ToString();
}
internal override void ToCompactString(StringBuilder builder)
{
builder.Append(ToUserString());
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.PrivateUri.Tests
{
public class UriBuilderTests
{
//This test tests a case where the Core implementation of UriBuilder differs from Desktop Framework UriBuilder.
//The Query property will not longer prepend a ? character if the string being assigned is already prepended.
[Fact]
public static void TestQuery()
{
var uriBuilder = new UriBuilder(@"http://foo/bar/baz?date=today");
Assert.Equal("?date=today", uriBuilder.Query);
uriBuilder.Query = "?date=yesterday";
Assert.Equal(@"?date=yesterday", uriBuilder.Query);
uriBuilder.Query = "date=tomorrow";
Assert.Equal("?date=tomorrow", uriBuilder.Query);
uriBuilder.Query += @"&place=redmond";
Assert.Equal("?date=tomorrow&place=redmond", uriBuilder.Query);
uriBuilder.Query = null;
Assert.Equal("", uriBuilder.Query);
uriBuilder.Query = "";
Assert.Equal("", uriBuilder.Query);
uriBuilder.Query = "?";
Assert.Equal("?", uriBuilder.Query);
}
[Fact]
public void Ctor_Empty()
{
var uriBuilder = new UriBuilder();
VerifyUriBuilder(uriBuilder, scheme: "http", userName: "", password: "", host: "localhost", port: -1, path: "/", query: "", fragment: "");
}
[Theory]
[InlineData("http://host/", true, "http", "", "", "host", 80, "/", "", "")]
[InlineData("http://username@host/", true, "http", "username", "", "host", 80, "/", "", "")]
[InlineData("http://username:password@host/", true, "http", "username", "password", "host", 80, "/", "", "")]
[InlineData("http://host:90/", true, "http", "", "", "host", 90, "/", "", "")]
[InlineData("http://host/path", true, "http", "", "", "host", 80, "/path", "", "")]
[InlineData("http://host/?query", true, "http", "", "", "host", 80, "/", "?query", "")]
[InlineData("http://host/#fragment", true, "http", "", "", "host", 80, "/", "", "#fragment")]
[InlineData("http://username:password@host:90/path1/path2?query#fragment", true, "http", "username", "password", "host", 90, "/path1/path2", "?query", "#fragment")]
[InlineData("www.host.com", false, "http", "", "", "www.host.com", 80, "/", "", "")] // Relative
[InlineData("unknownscheme:", true, "unknownscheme", "", "", "", -1, "", "", "")] // No authority
public void Ctor_String(string uriString, bool createUri, string scheme, string username, string password, string host, int port, string path, string query, string fragment)
{
var uriBuilder = new UriBuilder(uriString);
VerifyUriBuilder(uriBuilder, scheme, username, password, host, port, path, query, fragment);
if (createUri)
{
uriBuilder = new UriBuilder(new Uri(uriString, UriKind.RelativeOrAbsolute));
VerifyUriBuilder(uriBuilder, scheme, username, password, host, port, path, query, fragment);
}
else
{
Assert.Throws<InvalidOperationException>(() => new UriBuilder(new Uri(uriString, UriKind.RelativeOrAbsolute)));
}
}
[Fact]
public void Ctor_String_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("uriString", () => new UriBuilder((string)null)); // UriString is null
Assert.Throws<UriFormatException>(() => new UriBuilder(@"http://host\")); // UriString is invalid
}
[Fact]
public void Ctor_Uri_Null()
{
AssertExtensions.Throws<ArgumentNullException>("uri", () => new UriBuilder((Uri)null)); // Uri is null
}
[Theory]
[InlineData("http", "host", "http", "host")]
[InlineData("HTTP", "host", "http", "host")]
[InlineData("http", "[::1]", "http", "[::1]")]
[InlineData("https", "::1]", "https", "[::1]]")]
[InlineData("http", "::1", "http", "[::1]")]
[InlineData("http1:http2", "host", "http1", "host")]
[InlineData("http", "", "http", "")]
[InlineData("", "host", "", "host")]
[InlineData("", "", "", "")]
[InlineData("http", null, "http", "")]
[InlineData(null, "", "", "")]
[InlineData(null, null, "", "")]
public void Ctor_String_String(string schemeName, string hostName, string expectedScheme, string expectedHost)
{
var uriBuilder = new UriBuilder(schemeName, hostName);
VerifyUriBuilder(uriBuilder, expectedScheme, "", "", expectedHost, -1, "/", "", "");
}
[Theory]
[InlineData("http", "host", 0, "http", "host")]
[InlineData("HTTP", "host", 20, "http", "host")]
[InlineData("http", "[::1]", 40, "http", "[::1]")]
[InlineData("https", "::1]", 60, "https", "[::1]]")]
[InlineData("http", "::1", 80, "http", "[::1]")]
[InlineData("http1:http2", "host", 100, "http1", "host")]
[InlineData("http", "", 120, "http", "")]
[InlineData("", "host", 140, "", "host")]
[InlineData("", "", 160, "", "")]
[InlineData("http", null, 180, "http", "")]
[InlineData(null, "", -1, "", "")]
[InlineData(null, null, 65535, "", "")]
public void Ctor_String_String_Int(string scheme, string host, int port, string expectedScheme, string expectedHost)
{
var uriBuilder = new UriBuilder(scheme, host, port);
VerifyUriBuilder(uriBuilder, expectedScheme, "", "", expectedHost, port, "/", "", "");
}
[Theory]
[InlineData("http", "host", 0, "/path", "http", "host", "/path")]
[InlineData("HTTP", "host", 20, "/path1/path2", "http", "host", "/path1/path2")]
[InlineData("http", "[::1]", 40, "/", "http", "[::1]", "/")]
[InlineData("https", "::1]", 60, "/path1/", "https", "[::1]]", "/path1/")]
[InlineData("http", "::1", 80, null, "http", "[::1]", "/")]
[InlineData("http1:http2", "host", 100, "path1", "http1", "host", "path1")]
[InlineData("http", "", 120, "path1/path2", "http", "", "path1/path2")]
[InlineData("", "host", 140, "path1/path2/path3/", "", "host", "path1/path2/path3/")]
[InlineData("", "", 160, @"\path1\path2\path3", "", "", "/path1/path2/path3")]
[InlineData("http", null, 180, @"path1\path2\", "http", "", "path1/path2/")]
[InlineData(null, "", -1, "\u1234", "", "", "%E1%88%B4")]
[InlineData(null, null, 65535, "\u1234\u2345", "", "", "%E1%88%B4%E2%8D%85")]
public void Ctor_String_String_Int_String(string schemeName, string hostName, int port, string pathValue, string expectedScheme, string expectedHost, string expectedPath)
{
var uriBuilder = new UriBuilder(schemeName, hostName, port, pathValue);
VerifyUriBuilder(uriBuilder, expectedScheme, "", "", expectedHost, port, expectedPath, "", "");
}
[Theory]
[InlineData("http", "host", 0, "/path", "?query#fragment", "http", "host", "/path", "?query", "#fragment")]
[InlineData("HTTP", "host", 20, "/path1/path2", "?query&query2=value#fragment", "http", "host", "/path1/path2", "?query&query2=value", "#fragment")]
[InlineData("http", "[::1]", 40, "/", "#fragment?query", "http", "[::1]", "/", "", "#fragment?query")]
[InlineData("https", "::1]", 60, "/path1/", "?query", "https", "[::1]]", "/path1/", "?query", "")]
[InlineData("http", "::1", 80, null, "#fragment", "http", "[::1]", "/", "", "#fragment")]
[InlineData("http", "", 120, "path1/path2", "?#", "http", "", "path1/path2", "", "")]
[InlineData("", "host", 140, "path1/path2/path3/", "?", "", "host", "path1/path2/path3/", "", "")]
[InlineData("", "", 160, @"\path1\path2\path3", "#", "", "", "/path1/path2/path3", "", "")]
[InlineData("http", null, 180, @"path1\path2\", "?\u1234#\u2345", "http", "", "path1/path2/", "?\u1234", "#\u2345")]
[InlineData(null, "", -1, "\u1234", "", "", "", "%E1%88%B4", "", "")]
[InlineData(null, null, 65535, "\u1234\u2345", null, "", "", "%E1%88%B4%E2%8D%85", "", "")]
public void Ctor_String_String_Int_String_String(string schemeName, string hostName, int port, string pathValue, string extraValue, string expectedScheme, string expectedHost, string expectedPath, string expectedQuery, string expectedFragment)
{
var uriBuilder = new UriBuilder(schemeName, hostName, port, pathValue, extraValue);
VerifyUriBuilder(uriBuilder, expectedScheme, "", "", expectedHost, port, expectedPath, expectedQuery, expectedFragment);
}
[Theory]
[InlineData("query#fragment")]
[InlineData("fragment?fragment")]
public void Ctor_InvalidExtraValue_ThrowsArgumentException(string extraValue)
{
AssertExtensions.Throws<ArgumentException>("extraValue", null, () => new UriBuilder("scheme", "host", 80, "path", extraValue));
}
[Theory]
[InlineData("https", "https")]
[InlineData("", "")]
[InlineData(null, "")]
public void Scheme_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder("http://userinfo@domain/path?query#fragment");
uriBuilder.Scheme = value;
Assert.Equal(expected, uriBuilder.Scheme);
}
[Theory]
[InlineData("\u1234http")]
[InlineData(".")]
[InlineData("-")]
public void InvalidScheme_ThrowsArgumentException(string schemeName)
{
AssertExtensions.Throws<ArgumentException>("value", null, () => new UriBuilder(schemeName, "host"));
AssertExtensions.Throws<ArgumentException>("value", null, () => new UriBuilder(schemeName, "host", 80));
AssertExtensions.Throws<ArgumentException>("value", null, () => new UriBuilder(schemeName, "host", 80, "path"));
AssertExtensions.Throws<ArgumentException>("value", null, () => new UriBuilder(schemeName, "host", 80, "?query#fragment"));
AssertExtensions.Throws<ArgumentException>("value", null, () => new UriBuilder().Scheme = schemeName);
}
[Theory]
[InlineData("username", "username")]
[InlineData("", "")]
[InlineData(null, "")]
public void UserName_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder("http://userinfo@domain/path?query#fragment");
uriBuilder.UserName = value;
Assert.Equal(expected, uriBuilder.UserName);
Uri oldUri = uriBuilder.Uri;
uriBuilder.UserName = value;
Assert.NotSame(uriBuilder.Uri, oldUri); // Should generate new uri
Assert.Equal(uriBuilder.UserName, uriBuilder.Uri.UserInfo);
}
[Theory]
[InlineData("password", "password")]
[InlineData("", "")]
[InlineData(null, "")]
public void Password_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder("http://userinfo1:userinfo2@domain/path?query#fragment");
uriBuilder.Password = value;
Assert.Equal(expected, uriBuilder.Password);
Uri oldUri = uriBuilder.Uri;
uriBuilder.Password = value;
Assert.NotSame(uriBuilder.Uri, oldUri);
}
[Theory]
[InlineData("host", "host")]
[InlineData("", "")]
[InlineData(null, "")]
public void Host_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder("http://userinfo@domain/path?query#fragment");
uriBuilder.Host = value;
Assert.Equal(expected, uriBuilder.Host);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(80)]
[InlineData(180)]
[InlineData(65535)]
public void Port_Get_Set(int port)
{
var uriBuilder = new UriBuilder("http://userinfo@domain/path?query#fragment");
uriBuilder.Port = port;
Assert.Equal(port, uriBuilder.Port);
}
[Theory]
[InlineData(-2)]
[InlineData(65536)]
public void InvalidPort_ThrowsArgumentOutOfRangeException(int portNumber)
{
Assert.Throws<ArgumentOutOfRangeException>(() => new UriBuilder("scheme", "host", portNumber));
Assert.Throws<ArgumentOutOfRangeException>(() => new UriBuilder("scheme", "host", portNumber, "path"));
Assert.Throws<ArgumentOutOfRangeException>(() => new UriBuilder("scheme", "host", portNumber, "path", "?query#fragment"));
Assert.Throws<ArgumentOutOfRangeException>(() => new UriBuilder().Port = portNumber);
}
[Theory]
[InlineData("/path1/path2", "/path1/path2")]
[InlineData(@"\path1\path2", "/path1/path2")]
[InlineData("", "/")]
[InlineData(null, "/")]
public void Path_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder("http://userinfo@domain/path?query#fragment");
uriBuilder.Path = value;
Assert.Equal(expected, uriBuilder.Path);
}
[Theory]
[InlineData("query", "?query")]
[InlineData("", "")]
[InlineData(null, "")]
public void Query_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder();
uriBuilder.Query = value;
Assert.Equal(expected, uriBuilder.Query);
Uri oldUri = uriBuilder.Uri;
uriBuilder.Query = value;
Assert.NotSame(uriBuilder.Uri, oldUri); // Should generate new uri
Assert.Equal(uriBuilder.Query, uriBuilder.Uri.Query);
}
[Theory]
[InlineData("#fragment", "#fragment")]
[InlineData("#", "#")]
public void Fragment_Get_Set_StartsWithPound(string value, string expected)
{
var uriBuilder = new UriBuilder();
uriBuilder.Fragment = value;
Assert.Equal(expected, uriBuilder.Fragment);
Uri oldUri = uriBuilder.Uri;
uriBuilder.Fragment = value;
Assert.NotSame(uriBuilder.Uri, oldUri); // Should generate new uri
Assert.Equal(uriBuilder.Fragment, uriBuilder.Uri.Fragment);
}
[Theory]
[InlineData("fragment", "#fragment")]
[InlineData("", "")]
[InlineData(null, "")]
public void Fragment_Get_Set(string value, string expected)
{
var uriBuilder = new UriBuilder();
uriBuilder.Fragment = value;
Assert.Equal(expected, uriBuilder.Fragment);
Uri oldUri = uriBuilder.Uri;
uriBuilder.Fragment = value;
Assert.NotSame(uriBuilder.Uri, oldUri); // Should generate new uri
Assert.Equal(uriBuilder.Fragment, uriBuilder.Uri.Fragment);
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new UriBuilder(), new UriBuilder(), true };
yield return new object[] { new UriBuilder(), null, false };
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), true };
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://domain.com:80/path/file?query#fragment"), true }; // Ignores userinfo
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment2"), true }; // Ignores fragment
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@host.com:80/path/file?query#fragment"), false };
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@domain.com:90/path/file?query#fragment"), false };
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@domain.com:80/path2/file?query#fragment"), false };
yield return new object[] { new UriBuilder("http://username:password@domain.com:80/path/file?query#fragment"), new UriBuilder("http://username:password@domain.com:80/path/file?query2#fragment"), false };
yield return new object[] { new UriBuilder("unknown:"), new UriBuilder("unknown:"), true };
yield return new object[] { new UriBuilder("unknown:"), new UriBuilder("different:"), false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals(UriBuilder uriBuilder1, UriBuilder uriBuilder2, bool expected)
{
Assert.Equal(expected, uriBuilder1.Equals(uriBuilder2));
if (uriBuilder2 != null)
{
Assert.Equal(expected, uriBuilder1.GetHashCode().Equals(uriBuilder2.GetHashCode()));
}
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { new UriBuilder(), "http://localhost/" };
yield return new object[] { new UriBuilder() { Scheme = "" }, "localhost/" };
yield return new object[] { new UriBuilder() { Scheme = "unknown" }, "unknown://localhost/" };
yield return new object[] { new UriBuilder() { Scheme = "unknown", Host = "" }, "unknown:/" };
yield return new object[] { new UriBuilder() { Scheme = "unknown", Host = "", Path = "path1/path2" }, "unknown:path1/path2" };
yield return new object[] { new UriBuilder() { UserName = "username" }, "http://username@localhost/" };
yield return new object[] { new UriBuilder() { UserName = "username", Password = "password" }, "http://username:password@localhost/" };
yield return new object[] { new UriBuilder() { Port = 80 }, "http://localhost:80/" };
yield return new object[] { new UriBuilder() { Port = 0 }, "http://localhost:0/" };
yield return new object[] { new UriBuilder() { Host = "", Port = 80 }, "http:///" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "" }, "http://host/" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "/" }, "http://host/" };
yield return new object[] { new UriBuilder() { Host = "host", Path = @"\" }, "http://host/" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "path" }, "http://host/path" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "path", Query = "query" }, "http://host/path?query" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "path", Fragment = "fragment" }, "http://host/path#fragment" };
yield return new object[] { new UriBuilder() { Host = "host", Path = "path", Query = "query", Fragment = "fragment" }, "http://host/path?query#fragment" };
yield return new object[] { new UriBuilder() { Host = "host", Query = "query" }, "http://host/?query" };
yield return new object[] { new UriBuilder() { Host = "host", Fragment = "fragment" }, "http://host/#fragment" };
yield return new object[] { new UriBuilder() { Host = "host", Query = "query", Fragment = "fragment" }, "http://host/?query#fragment" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public void ToString(UriBuilder uriBuilder, string expected)
{
Assert.Equal(expected, uriBuilder.ToString());
}
[Fact]
public void ToString_Invalid()
{
var uriBuilder = new UriBuilder();
uriBuilder.Password = "password";
Assert.Throws<UriFormatException>(() => uriBuilder.ToString()); // Uri has a password but no username
}
private static void VerifyUriBuilder(UriBuilder uriBuilder, string scheme, string userName, string password, string host, int port, string path, string query, string fragment)
{
Assert.Equal(scheme, uriBuilder.Scheme);
Assert.Equal(userName, uriBuilder.UserName);
Assert.Equal(password, uriBuilder.Password);
Assert.Equal(host, uriBuilder.Host);
Assert.Equal(port, uriBuilder.Port);
Assert.Equal(path, uriBuilder.Path);
Assert.Equal(query, uriBuilder.Query);
Assert.Equal(fragment, uriBuilder.Fragment);
}
}
}
| |
/*
* Copyright (c) 2006-2014, 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;
namespace OpenMetaverse
{
/// <summary>
/// A 128-bit Universally Unique Identifier, used throughout the Second
/// Life networking protocol
/// </summary>
[Serializable]
public struct UUID : IComparable<UUID>, IEquatable<UUID>
{
/// <summary>The System.Guid object this struct wraps around</summary>
public Guid Guid;
#region Constructors
/// <summary>
/// Constructor that takes a string UUID representation
/// </summary>
/// <param name="val">A string representation of a UUID, case
/// insensitive and can either be hyphenated or non-hyphenated</param>
/// <example>UUID("11f8aa9c-b071-4242-836b-13b7abe0d489")</example>
public UUID(string val)
{
if (String.IsNullOrEmpty(val))
Guid = new Guid();
else
Guid = new Guid(val);
}
/// <summary>
/// Constructor that takes a System.Guid object
/// </summary>
/// <param name="val">A Guid object that contains the unique identifier
/// to be represented by this UUID</param>
public UUID(Guid val)
{
Guid = val;
}
/// <summary>
/// Constructor that takes a byte array containing a UUID
/// </summary>
/// <param name="source">Byte array containing a 16 byte UUID</param>
/// <param name="pos">Beginning offset in the array</param>
public UUID(byte[] source, int pos)
{
Guid = UUID.Zero.Guid;
FromBytes(source, pos);
}
/// <summary>
/// Constructor that takes an unsigned 64-bit unsigned integer to
/// convert to a UUID
/// </summary>
/// <param name="val">64-bit unsigned integer to convert to a UUID</param>
public UUID(ulong val)
{
byte[] end = BitConverter.GetBytes(val);
if (!BitConverter.IsLittleEndian)
Array.Reverse(end);
Guid = new Guid(0, 0, 0, end);
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="val">UUID to copy</param>
public UUID(UUID val)
{
Guid = val.Guid;
}
#endregion Constructors
#region Public Methods
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(UUID id)
{
return Guid.CompareTo(id.Guid);
}
/// <summary>
/// Assigns this UUID from 16 bytes out of a byte array
/// </summary>
/// <param name="source">Byte array containing the UUID to assign this UUID to</param>
/// <param name="pos">Starting position of the UUID in the byte array</param>
public void FromBytes(byte[] source, int pos)
{
int a = (source[pos + 0] << 24) | (source[pos + 1] << 16) | (source[pos + 2] << 8) | source[pos + 3];
short b = (short)((source[pos + 4] << 8) | source[pos + 5]);
short c = (short)((source[pos + 6] << 8) | source[pos + 7]);
Guid = new Guid(a, b, c, source[pos + 8], source[pos + 9], source[pos + 10], source[pos + 11],
source[pos + 12], source[pos + 13], source[pos + 14], source[pos + 15]);
}
/// <summary>
/// Returns a copy of the raw bytes for this UUID
/// </summary>
/// <returns>A 16 byte array containing this UUID</returns>
public byte[] GetBytes()
{
byte[] output = new byte[16];
ToBytes(output, 0);
return output;
}
/// <summary>
/// Writes the raw bytes for this UUID to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 16 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
byte[] bytes = Guid.ToByteArray();
dest[pos + 0] = bytes[3];
dest[pos + 1] = bytes[2];
dest[pos + 2] = bytes[1];
dest[pos + 3] = bytes[0];
dest[pos + 4] = bytes[5];
dest[pos + 5] = bytes[4];
dest[pos + 6] = bytes[7];
dest[pos + 7] = bytes[6];
Buffer.BlockCopy(bytes, 8, dest, pos + 8, 8);
}
/// <summary>
/// Calculate an LLCRC (cyclic redundancy check) for this UUID
/// </summary>
/// <returns>The CRC checksum for this UUID</returns>
public uint CRC()
{
uint retval = 0;
byte[] bytes = GetBytes();
retval += (uint)((bytes[3] << 24) + (bytes[2] << 16) + (bytes[1] << 8) + bytes[0]);
retval += (uint)((bytes[7] << 24) + (bytes[6] << 16) + (bytes[5] << 8) + bytes[4]);
retval += (uint)((bytes[11] << 24) + (bytes[10] << 16) + (bytes[9] << 8) + bytes[8]);
retval += (uint)((bytes[15] << 24) + (bytes[14] << 16) + (bytes[13] << 8) + bytes[12]);
return retval;
}
/// <summary>
/// Create a 64-bit integer representation from the second half of this UUID
/// </summary>
/// <returns>An integer created from the last eight bytes of this UUID</returns>
public ulong GetULong()
{
byte[] bytes = Guid.ToByteArray();
return (ulong)
((ulong)bytes[8] +
((ulong)bytes[9] << 8) +
((ulong)bytes[10] << 16) +
((ulong)bytes[12] << 24) +
((ulong)bytes[13] << 32) +
((ulong)bytes[13] << 40) +
((ulong)bytes[14] << 48) +
((ulong)bytes[15] << 56));
}
#endregion Public Methods
#region Static Methods
/// <summary>
/// Generate a UUID from a string
/// </summary>
/// <param name="val">A string representation of a UUID, case
/// insensitive and can either be hyphenated or non-hyphenated</param>
/// <example>UUID.Parse("11f8aa9c-b071-4242-836b-13b7abe0d489")</example>
public static UUID Parse(string val)
{
return new UUID(val);
}
/// <summary>
/// Generate a UUID from a string
/// </summary>
/// <param name="val">A string representation of a UUID, case
/// insensitive and can either be hyphenated or non-hyphenated</param>
/// <param name="result">Will contain the parsed UUID if successful,
/// otherwise null</param>
/// <returns>True if the string was successfully parse, otherwise false</returns>
/// <example>UUID.TryParse("11f8aa9c-b071-4242-836b-13b7abe0d489", result)</example>
public static bool TryParse(string val, out UUID result)
{
if (String.IsNullOrEmpty(val) ||
(val[0] == '{' && val.Length != 38) ||
(val.Length != 36 && val.Length != 32))
{
result = UUID.Zero;
return false;
}
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = UUID.Zero;
return false;
}
}
/// <summary>
/// Combine two UUIDs together by taking the MD5 hash of a byte array
/// containing both UUIDs
/// </summary>
/// <param name="first">First UUID to combine</param>
/// <param name="second">Second UUID to combine</param>
/// <returns>The UUID product of the combination</returns>
public static UUID Combine(UUID first, UUID second)
{
// Construct the buffer that MD5ed
byte[] input = new byte[32];
Buffer.BlockCopy(first.GetBytes(), 0, input, 0, 16);
Buffer.BlockCopy(second.GetBytes(), 0, input, 16, 16);
return new UUID(Utils.MD5(input), 0);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static UUID Random()
{
return new UUID(Guid.NewGuid());
}
#endregion Static Methods
#region Overrides
/// <summary>
/// Return a hash code for this UUID, used by .NET for hash tables
/// </summary>
/// <returns>An integer composed of all the UUID bytes XORed together</returns>
public override int GetHashCode()
{
return Guid.GetHashCode();
}
/// <summary>
/// Comparison function
/// </summary>
/// <param name="o">An object to compare to this UUID</param>
/// <returns>True if the object is a UUID and both UUIDs are equal</returns>
public override bool Equals(object o)
{
if (!(o is UUID)) return false;
UUID uuid = (UUID)o;
return Guid == uuid.Guid;
}
/// <summary>
/// Comparison function
/// </summary>
/// <param name="uuid">UUID to compare to</param>
/// <returns>True if the UUIDs are equal, otherwise false</returns>
public bool Equals(UUID uuid)
{
return Guid == uuid.Guid;
}
/// <summary>
/// Get a hyphenated string representation of this UUID
/// </summary>
/// <returns>A string representation of this UUID, lowercase and
/// with hyphens</returns>
/// <example>11f8aa9c-b071-4242-836b-13b7abe0d489</example>
public override string ToString()
{
if (Guid == Guid.Empty)
return ZeroString;
else
return Guid.ToString();
}
#endregion Overrides
#region Operators
/// <summary>
/// Equals operator
/// </summary>
/// <param name="lhs">First UUID for comparison</param>
/// <param name="rhs">Second UUID for comparison</param>
/// <returns>True if the UUIDs are byte for byte equal, otherwise false</returns>
public static bool operator ==(UUID lhs, UUID rhs)
{
return lhs.Guid == rhs.Guid;
}
/// <summary>
/// Not equals operator
/// </summary>
/// <param name="lhs">First UUID for comparison</param>
/// <param name="rhs">Second UUID for comparison</param>
/// <returns>True if the UUIDs are not equal, otherwise true</returns>
public static bool operator !=(UUID lhs, UUID rhs)
{
return !(lhs == rhs);
}
/// <summary>
/// XOR operator
/// </summary>
/// <param name="lhs">First UUID</param>
/// <param name="rhs">Second UUID</param>
/// <returns>A UUID that is a XOR combination of the two input UUIDs</returns>
public static UUID operator ^(UUID lhs, UUID rhs)
{
byte[] lhsbytes = lhs.GetBytes();
byte[] rhsbytes = rhs.GetBytes();
byte[] output = new byte[16];
for (int i = 0; i < 16; i++)
{
output[i] = (byte)(lhsbytes[i] ^ rhsbytes[i]);
}
return new UUID(output, 0);
}
/// <summary>
/// String typecasting operator
/// </summary>
/// <param name="val">A UUID in string form. Case insensitive,
/// hyphenated or non-hyphenated</param>
/// <returns>A UUID built from the string representation</returns>
public static explicit operator UUID(string val)
{
return new UUID(val);
}
#endregion Operators
/// <summary>An UUID with a value of all zeroes</summary>
public static readonly UUID Zero = new UUID();
/// <summary>A cache of UUID.Zero as a string to optimize a common path</summary>
private static readonly string ZeroString = Guid.Empty.ToString();
}
}
| |
/* ====================================================================
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 NPOI.SS.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
namespace NPOI.XSSF.UserModel
{
/**
* Page Setup and page margins Settings for the worksheet.
*/
public class XSSFPrintSetup : IPrintSetup
{
private CT_Worksheet ctWorksheet;
private CT_PageSetup pageSetup;
private CT_PageMargins pageMargins;
public XSSFPrintSetup(CT_Worksheet worksheet)
{
this.ctWorksheet = worksheet;
if (ctWorksheet.IsSetPageSetup())
{
this.pageSetup = ctWorksheet.pageSetup;
}
else
{
this.pageSetup = ctWorksheet.AddNewPageSetup();
}
if (ctWorksheet.IsSetPageMargins())
{
this.pageMargins = ctWorksheet.pageMargins;
}
else
{
this.pageMargins = ctWorksheet.AddNewPageMargins();
}
}
/**
* Set the paper size as enum value.
*
* @param size value for the paper size.
*/
public void SetPaperSize(PaperSize size)
{
PaperSize = ((short)(size + 1));
}
/**
* Orientation of the page: landscape - portrait.
*
* @return Orientation of the page
* @see PrintOrientation
*/
public PrintOrientation Orientation
{
get
{
ST_Orientation? val = pageSetup.orientation;
return val == null ? PrintOrientation.DEFAULT : PrintOrientation.ValueOf((int)val);
}
set
{
ST_Orientation v = (ST_Orientation)(value.Value);
pageSetup.orientation = (v);
}
}
public PrintCellComments GetCellComment()
{
ST_CellComments? val = pageSetup.cellComments;
return val == null ? PrintCellComments.NONE : PrintCellComments.ValueOf((int)val);
}
/**
* Get print page order.
*
* @return PageOrder
*/
public PageOrder PageOrder
{
get
{
return PageOrder.ValueOf((int)pageSetup.pageOrder);
}
set
{
ST_PageOrder v = (ST_PageOrder)value.Value;
pageSetup.pageOrder = (v);
}
}
/**
* Returns the paper size.
*
* @return short - paper size
*/
public short PaperSize
{
get
{
return (short)pageSetup.paperSize;
}
set
{
pageSetup.paperSize = (uint)value;
}
}
/**
* Returns the paper size as enum.
*
* @return PaperSize paper size
* @see PaperSize
*/
public PaperSize GetPaperSizeEnum()
{
return (PaperSize)(PaperSize - 1);
}
/**
* Returns the scale.
*
* @return short - scale
*/
public short Scale
{
get
{
if(pageSetup.scale == 0)
{
return 100;
}
return (short)pageSetup.scale;
}
set
{
if (value < 10 || value > 400)
throw new POIXMLException("Scale value not accepted: you must choose a value between 10 and 400.");
pageSetup.scale = (uint)value;
}
}
/**
* Set the page numbering start.
* Page number for first printed page. If no value is specified, then 'automatic' is assumed.
*
* @return page number for first printed page
*/
public short PageStart
{
get
{
return (short)pageSetup.firstPageNumber;
}
set
{
pageSetup.firstPageNumber = (uint)value;
}
}
/**
* Returns the number of pages wide to fit sheet in.
*
* @return number of pages wide to fit sheet in
*/
public short FitWidth
{
get
{
return (short)pageSetup.fitToWidth;
}
set
{
pageSetup.fitToWidth = (uint)value;
}
}
/**
* Returns the number of pages high to fit the sheet in.
*
* @return number of pages high to fit the sheet in
*/
public short FitHeight
{
get
{
return (short)pageSetup.fitToHeight;
}
set
{
pageSetup.fitToHeight = (uint)value;
}
}
/**
* Returns the left to right print order.
*
* @return left to right print order
*/
public bool LeftToRight
{
get
{
return PageOrder == PageOrder.OVER_THEN_DOWN;
}
set
{
if (value)
PageOrder = (PageOrder.OVER_THEN_DOWN);
else
PageOrder = (PageOrder.DOWN_THEN_OVER);
}
}
/**
* Returns the landscape mode.
*
* @return landscape mode
*/
public bool Landscape
{
get
{
return Orientation == PrintOrientation.LANDSCAPE;
}
set
{
if (value)
Orientation =(PrintOrientation.LANDSCAPE);
else
Orientation = (PrintOrientation.PORTRAIT);
}
}
/**
* Use the printer's defaults Settings for page Setup values and don't use the default values
* specified in the schema. For example, if dpi is not present or specified in the XML, the
* application shall not assume 600dpi as specified in the schema as a default and instead
* shall let the printer specify the default dpi.
*
* @return valid Settings
*/
public bool ValidSettings
{
get
{
return pageSetup.usePrinterDefaults;
}
set
{
pageSetup.usePrinterDefaults = value;
}
}
/**
* Returns the black and white Setting.
*
* @return black and white Setting
*/
public bool NoColor
{
get
{
return pageSetup.blackAndWhite;
}
set
{
pageSetup.blackAndWhite = value;
}
}
/**
* Returns the draft mode.
*
* @return draft mode
*/
public bool Draft
{
get
{
return pageSetup.draft;
}
set
{
pageSetup.draft = value;
}
}
/**
* Returns the print notes.
*
* @return print notes
*/
public bool Notes
{
get
{
return GetCellComment() == PrintCellComments.AS_DISPLAYED;
}
set
{
if (value)
{
pageSetup.cellComments = (ST_CellComments.asDisplayed);
}
}
}
/**
* Returns the no orientation.
*
* @return no orientation
*/
public bool NoOrientation
{
get
{
return Orientation == PrintOrientation.DEFAULT;
}
set
{
if (value)
{
Orientation = (PrintOrientation.DEFAULT);
}
}
}
/**
* Returns the use page numbers.
*
* @return use page numbers
*/
public bool UsePage
{
get
{
return pageSetup.useFirstPageNumber;
}
set
{
pageSetup.useFirstPageNumber = (value);
}
}
/**
* Returns the horizontal resolution.
*
* @return horizontal resolution
*/
public short HResolution
{
get
{
return (short)pageSetup.horizontalDpi;
}
set
{
pageSetup.horizontalDpi = (uint)value;
}
}
/**
* Returns the vertical resolution.
*
* @return vertical resolution
*/
public short VResolution
{
get
{
return (short)pageSetup.verticalDpi;
}
set
{
pageSetup.verticalDpi = (uint)value;
}
}
/**
* Returns the header margin.
*
* @return header margin
*/
public double HeaderMargin
{
get
{
return pageMargins.header;
}
set
{
pageMargins.header = (value);
}
}
/**
* Returns the footer margin.
*
* @return footer margin
*/
public double FooterMargin
{
get
{
return pageMargins.footer;
}
set
{
pageMargins.footer = value;
}
}
/**
* Returns the number of copies.
*
* @return number of copies
*/
public short Copies
{
get
{
return (short)pageSetup.copies;
}
set
{
pageSetup.copies = (uint)value;
}
}
#region IPrintSetup Members
public DisplayCellErrorType CellError
{
get
{
return (DisplayCellErrorType)pageSetup.errors;
}
set
{
pageSetup.errors = (ST_PrintError)value;
}
}
public bool EndNote
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices.ComTypes;
using Azure.Core;
namespace Azure.Data.Tables
{
/// <summary>
/// A generic dictionary-like <see cref="ITableEntity"/> type which defines an arbitrary set of properties on an entity as key-value pairs.
/// </summary>
/// <remarks>
/// This type can be used with any of the generic entity interaction methods in <see cref="TableClient"/> where entity model type flexibility is desired.
/// For example, if your table contains a jagged schema, or you need to precisely update a subset of properties in a <see cref="TableUpdateMode.Merge"/> mode operation.
/// </remarks>
public sealed partial class TableEntity : ITableEntity
{
private readonly IDictionary<string, object> _properties;
/// <summary>
/// The partition key is a unique identifier for the partition within a given table and forms the first part of an entity's primary key.
/// </summary>
/// <value>A string containing the partition key for the entity.</value>
public string PartitionKey
{
get { return GetString(TableConstants.PropertyNames.PartitionKey); }
set { _properties[TableConstants.PropertyNames.PartitionKey] = value; }
}
/// <summary>
/// The row key is a unique identifier for an entity within a given partition. Together, the <see cref="PartitionKey" /> and RowKey uniquely identify an entity within a table.
/// </summary>
/// <value>A string containing the row key for the entity.</value>
public string RowKey
{
get { return GetString(TableConstants.PropertyNames.RowKey); }
set { _properties[TableConstants.PropertyNames.RowKey] = value; }
}
/// <summary>
/// The Timestamp property is a DateTimeOffset value that is maintained on the server side to record the time an entity was last modified.
/// The Table service uses the Timestamp property internally to provide optimistic concurrency. The value of Timestamp is a monotonically increasing value,
/// meaning that each time the entity is modified, the value of Timestamp increases for that entity. This property should not be set on insert or update operations (the value will be ignored).
/// </summary>
/// <value>A <see cref="DateTimeOffset"/> containing the timestamp of the entity.</value>
public DateTimeOffset? Timestamp
{
get { return GetValue<DateTimeOffset?>(TableConstants.PropertyNames.TimeStamp); }
set { _properties[TableConstants.PropertyNames.TimeStamp] = value; }
}
/// <summary>
/// Gets or sets the entity's ETag.
/// </summary>
/// <value>An <see cref="ETag"/> containing the ETag value for the entity.</value>
public ETag ETag
{
get { return new ETag(GetString(TableConstants.PropertyNames.ETag)); }
set { _properties[TableConstants.PropertyNames.ETag] = value.ToString(); }
}
/// <summary>
/// Creates an instance of the <see cref="TableEntity" /> class without any properties initialized.
/// </summary>
public TableEntity()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TableEntity"/> class with the specified partition key and row key.
/// </summary>
/// <param name="partitionKey">A string containing the partition key of the <see cref="TableEntity"/> to be initialized.</param>
/// <param name="rowKey">A string containing the row key of the <see cref="TableEntity"/> to be initialized.</param>
public TableEntity(string partitionKey, string rowKey)
: this(null)
{
PartitionKey = partitionKey;
RowKey = rowKey;
}
/// <summary>
/// Initializes a new instance of the <see cref="TableEntity"/> class with properties specified in <paramref name="values"/>.
/// </summary>
/// <param name="values">A <see cref="IDictionary"/> containing the initial values of the entity.</param>
public TableEntity(IDictionary<string, object> values)
{
_properties = values != null ?
new Dictionary<string, object>(values) :
new Dictionary<string, object>();
}
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="string"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="string" />.</exception>
public string GetString(string key) => GetValue<string>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="byte"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type byte array.</exception>
public byte[] GetBinary(string key) => GetValue<byte[]>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="string"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="bool" />.</exception>
public bool? GetBoolean(string key) => GetValue<bool?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="DateTime"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="DateTime" />.</exception>
public DateTime? GetDateTime(string key) => GetValue<DateTime?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="DateTimeOffset"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="DateTimeOffset" />.</exception>
public DateTimeOffset? GetDateTimeOffset(string key) => GetValue<DateTimeOffset?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="double"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="double" />.</exception>
public double? GetDouble(string key) => GetValue<double?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="Guid"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="Guid" />.</exception>
public Guid? GetGuid(string key) => GetValue<Guid?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="int"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="int" />.</exception>
public int? GetInt32(string key) => GetValue<int?>(key);
/// <summary>
/// Get the value of a <see cref="TableEntity"/>'s
/// <see cref="long"/> property called
/// <paramref name="key"/>.
/// </summary>
/// <param name="key">The name of the property.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <see cref="long" />.</exception>
public long? GetInt64(string key) => GetValue<long?>(key);
/// <summary>
/// Set a document property.
/// </summary>
/// <param name="key">The property name.</param>
/// <param name="value">The property value.</param>
/// <exception cref="InvalidOperationException">The given <paramref name="value"/> does not match the type of the existing value associated with given <paramref name="key"/>.</exception>
private void SetValue(string key, object value)
{
Argument.AssertNotNullOrEmpty(key, nameof(key));
if (value != null && _properties.TryGetValue(key, out object existingValue) && existingValue != null)
{
value = CoerceType(existingValue, value);
}
_properties[key] = value;
}
/// <summary>
/// Get an entity property.
/// </summary>
/// <typeparam name="T">The expected type of the property value.</typeparam>
/// <param name="key">The property name.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of given type <typeparamref name="T"/>.</exception>
private T GetValue<T>(string key) => (T)GetValue(key, typeof(T));
/// <summary>
/// Get an entity property.
/// </summary>
/// <param name="key">The property name.</param>
/// <param name="type">The expected type of the property value.</param>
/// <returns>The value of the property.</returns>
/// <exception cref="InvalidOperationException">Value associated with given <paramref name="key"/> is not of type <paramref name="type"/>.</exception>
private object GetValue(string key, Type type = null)
{
Argument.AssertNotNullOrEmpty(key, nameof(key));
if (!_properties.TryGetValue(key, out object value) || value == null)
{
return null;
}
if (type != null)
{
EnforceType(type, value.GetType());
}
return value;
}
/// <summary>
/// Ensures that the given type matches the type of the existing
/// property; throws an exception if the types do not match.
/// </summary>
private static void EnforceType(Type requestedType, Type givenType)
{
if (!requestedType.IsAssignableFrom(givenType))
{
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
$"Cannot return {requestedType} type for a {givenType} typed property."));
}
}
/// <summary>
/// Performs type coercion for numeric types.
/// <param name="newValue"/> of type int will be coerced to long or double if <param name="existingValue"/> is typed as long or double.
/// All other type assignment changes will be accepted as is.
/// </summary>
private static object CoerceType(object existingValue, object newValue)
{
if (!existingValue.GetType().IsAssignableFrom(newValue.GetType()))
{
return existingValue switch
{
double _ => newValue switch
{
// if we already had a double value, preserve it as double even if newValue was an int.
// example: entity["someDoubleValue"] = 5;
int newIntValue => (double)newIntValue,
_ => newValue
},
long _ => newValue switch
{
// if we already had a long value, preserve it as long even if newValue was an int.
// example: entity["someLongValue"] = 5;
int newIntValue => (long)newIntValue,
_ => newValue
},
_ => newValue
};
}
return newValue;
}
}
}
| |
//Unity 4.5 and above switched WWW to use Dictionary instead of Hashtable
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4
#define UNITY_USE_WWW_HASHTABLE
#endif
#if (UNITY_IPHONE || UNITY_ANDROID || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_METRO) && (UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UnityEngine.Cloud.Analytics
{
internal static class PlatformWrapper
{
public static IPlatformWrapper platform
{
get {
#if UNITY_ANDROID && !UNITY_EDITOR
return new AndroidWrapper();
#elif UNITY_IPHONE && !UNITY_EDITOR
return new iOSWrapper();
#elif UNITY_WEBGL
return new WebGLWrapper();
#elif UNITY_WEBPLAYER
return new WebPlayerWrapper();
#elif UNITY_METRO
return new WindowsMetroWrapper();
#else
return new BasePlatformWrapper();
#endif
}
}
}
internal class BasePlatformWrapper : IPlatformWrapper, IWWWFactory
{
private System.Random m_Random;
internal BasePlatformWrapper()
{
m_Random = new System.Random();
}
#region IPlatformWrapper
public virtual string appVersion
{
get { return null; }
}
public virtual string appBundleIdentifier
{
get { return null; }
}
public virtual string appInstallMode
{
get { return null; }
}
public virtual bool isRootedOrJailbroken
{
get { return false; }
}
#endregion
#region IApplication
public virtual string deviceMake
{
get { return Application.platform.ToString(); }
}
public virtual bool isNetworkReachable
{
get { return Application.internetReachability != NetworkReachability.NotReachable; }
}
public virtual bool isWebPlayer
{
get { return Application.isWebPlayer; }
}
public virtual bool isAndroidPlayer
{
get { return Application.platform == RuntimePlatform.Android; }
}
public virtual bool isIPhonePlayer
{
get { return Application.platform == RuntimePlatform.IPhonePlayer; }
}
public virtual bool isWebGLPlayer
{
get
{
#if UNITY_WEBGL
return Application.platform == RuntimePlatform.WebGLPlayer;
#else
return false;
#endif
}
}
public virtual bool isEditor
{
get { return Application.isEditor; }
}
public virtual int levelCount
{
get { return Application.levelCount; }
}
public virtual int loadedLevel
{
get { return Application.loadedLevel; }
}
public virtual string loadedLevelName
{
get { return Application.loadedLevelName; }
}
public virtual string persistentDataPath
{
#if (UNITY_STANDALONE_WIN&&!UNITY_EDITOR) || UNITY_EDITOR_WIN || UNITY_METRO || UNITY_WP8
get { return Application.persistentDataPath.Replace ('/', '\\'); }
#else
get { return Application.persistentDataPath; }
#endif
}
public virtual string platformName
{
get {
return Application.platform.ToString();
}
}
public virtual string unityVersion
{
get { return Application.unityVersion; }
}
public bool isDebugBuild
{
get { return Debug.isDebugBuild; }
}
#endregion
#region ISystemInfo
public long GetLongRandom()
{
var buffer = new byte[8];
m_Random.NextBytes(buffer);
return (long)(System.BitConverter.ToUInt64(buffer, 0) & System.Int64.MaxValue);
}
public virtual string NewGuid()
{
return System.Guid.NewGuid().ToString();
}
public virtual string Md5Hex(string input){
#if !UNITY_METRO
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(input);
// encrypt bytes
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
#else
return null;
#endif
}
public virtual string deviceModel
{
get { return SystemInfo.deviceModel; }
}
public virtual string deviceUniqueIdentifier
{
get {
#if UNITY_ANDROID && !UNITY_EDITOR
return "";
#else
return SystemInfo.deviceUniqueIdentifier;
#endif
}
}
public virtual string operatingSystem
{
get { return SystemInfo.operatingSystem; }
}
public virtual string processorType
{
get { return SystemInfo.processorType; }
}
public virtual int systemMemorySize
{
get { return SystemInfo.systemMemorySize; }
}
#endregion
#if UNITY_USE_WWW_HASHTABLE
public IWWW newWWW(string url, byte[] body, Dictionary<string, string> headers)
{
WWW www = new WWW(url, body, DictToHash(headers));
return new UnityWWW(www);
}
private Hashtable DictToHash(Dictionary<string, string> headers)
{
var result = new Hashtable();
foreach (var kvp in headers)
result[kvp.Key] = kvp.Value;
return result;
}
#else
public IWWW newWWW(string url, byte[] body, Dictionary<string, string> headers)
{
WWW www = new WWW(url, body, headers);
return new UnityWWW(www);
}
#endif
}
}
#endif
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI80;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI80
{
/// <summary>
/// OpenSession, CloseSession, CloseAllSessions and GetSessionInfo tests.
/// </summary>
[TestFixture()]
public class _06_SessionTest
{
/// <summary>
/// Basic OpenSession and CloseSession test.
/// </summary>
[Test()]
public void _01_BasicSessionTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Close session
session.CloseSession();
}
}
/// <summary>
/// Using statement test.
/// </summary>
[Test()]
public void _02_UsingSessionTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Session class can be used in using statement which defines a scope
// at the end of which the session will be closed automatically.
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// CloseSession via slot test.
/// </summary>
[Test()]
public void _03_CloseSessionViaSlotTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Alternatively session can be closed with CloseSession method of Slot class.
slot.CloseSession(session);
}
}
/// <summary>
/// CloseAllSessions test.
/// </summary>
[Test()]
public void _04_CloseAllSessionsTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
Assert.IsNotNull(session);
// All sessions can be closed with CloseAllSessions method of Slot class.
slot.CloseAllSessions();
}
}
/// <summary>
/// Read-only session test.
/// </summary>
[Test()]
public void _05_ReadOnlySessionTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// Read-write session test.
/// </summary>
[Test()]
public void _06_ReadWriteSessionTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW (read-write) session
using (Session session = slot.OpenSession(false))
{
// Do something interesting in RW session
}
}
}
/// <summary>
/// GetSessionInfo test.
/// </summary>
[Test()]
public void _07_SessionInfoTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Get session details
SessionInfo sessionInfo = session.GetSessionInfo();
// Do something interesting with session info
Assert.IsTrue(sessionInfo.SlotId == slot.SlotId);
Assert.IsNotNull(sessionInfo.SessionFlags);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ClientDependency.Core.Config;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.PropertyEditors;
using Umbraco.Web.Trees;
using Umbraco.Web.WebServices;
namespace Umbraco.Web.Editors
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
internal class BackOfficeServerVariables
{
private readonly UrlHelper _urlHelper;
private readonly ApplicationContext _applicationContext;
private readonly HttpContextBase _httpContext;
private readonly IOwinContext _owinContext;
public BackOfficeServerVariables(UrlHelper urlHelper, ApplicationContext applicationContext, IUmbracoSettingsSection umbracoSettings)
{
_urlHelper = urlHelper;
_applicationContext = applicationContext;
_httpContext = _urlHelper.RequestContext.HttpContext;
_owinContext = _httpContext.GetOwinContext();
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> BareMinimumServerVariables()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }}
};
//now do the filtering...
var defaults = GetServerVariables();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
var asDictionary = defaults[key] as IDictionary;
if (asDictionary != null)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>) defaults["umbracoUrls"])["serverVarsJs"] = _urlHelper.Action("ServerVariables", "BackOffice");
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> GetServerVariables()
{
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
//TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each url defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _urlHelper.Action("ExternalLogin", "BackOffice")},
{"externalLinkLoginsUrl", _urlHelper.Action("LinkLogin", "BackOffice")},
{"legacyTreeJs", _urlHelper.Action("LegacyTreeJs", "BackOffice")},
{"manifestAssetList", _urlHelper.Action("GetManifestAssetList", "BackOffice")},
{"gridConfig", _urlHelper.Action("GetGridConfig", "BackOffice")},
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _urlHelper.Action("Application", "BackOffice")},
//API URLs
{
"packagesRestApiBaseUrl", UmbracoConfig.For.UmbracoSettings().PackageRepositories.GetDefault().RestApiUrl
},
{
"redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"mediaApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"imagesApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(0))
},
{
"sectionApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, true))
},
{
"contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacroController>(
controller => controller.GetMacroParameters(0))
},
{
"authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"legacyApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LegacyController>(
controller => controller.DeleteLegacyItem(null, null, null))
},
{
"entityApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetEntityLog(0))
},
{
"memberApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageInstallApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageInstallController>(
controller => controller.Fetch(string.Empty))
},
{
"relationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"updateCheckApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"tagApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsController>(
controller => controller.GetAllTags(null))
},
{
"templateApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags(""))
},
{
"examineMgmtBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ExamineManagementApiController>(
controller => controller.GetIndexerDetails())
},
{
"xmlDataIntegrityBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<XmlDataIntegrityController>(
controller => controller.CheckContentXmlTable())
},
{
"healthCheckBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"helpApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
}
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", GlobalSettings.Path},
{"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')},
{"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')},
{
"imageFileTypes",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn},
{"usernameIsEmail", UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail},
{"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')},
{"allowPasswordReset", UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset},
{"loginBackgroundImage", UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage},
{"showUserInvite", EmailSender.CanSendRequiredEmail},
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
{"trees", GetTreePluginsMetaData()}
}
},
{
"isDebuggingEnabled", _httpContext.IsDebuggingEnabled
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
"providers", _owinContext.Authentication.GetExternalAuthenticationTypes()
.Where(p => p.Properties.ContainsKey("UmbracoBackOffice"))
.Select(p => new
{
authType = p.AuthenticationType, caption = p.Caption,
//TODO: Need to see if this exposes any sensitive data!
properties = p.Properties
})
.ToArray()
}
}
}
};
return defaultVals;
}
private IEnumerable<Dictionary<string, string>> GetTreePluginsMetaData()
{
var treeTypes = TreeControllerTypes.Value;
//get all plugin trees with their attributes
var treesWithAttributes = treeTypes.Select(x => new
{
tree = x,
attributes =
x.GetCustomAttributes(false)
}).ToArray();
var pluginTreesWithAttributes = treesWithAttributes
//don't resolve any tree decorated with CoreTreeAttribute
.Where(x => x.attributes.All(a => (a is CoreTreeAttribute) == false))
//we only care about trees with the PluginControllerAttribute
.Where(x => x.attributes.Any(a => a is PluginControllerAttribute))
.ToArray();
return (from p in pluginTreesWithAttributes
let treeAttr = p.attributes.OfType<TreeAttribute>().Single()
let pluginAttr = p.attributes.OfType<PluginControllerAttribute>().Single()
select new Dictionary<string, string>
{
{"alias", treeAttr.Alias}, {"packageFolder", pluginAttr.AreaName}
}).ToArray();
}
/// <summary>
/// A lazy reference to all tree controller types
/// </summary>
/// <remarks>
/// We are doing this because if we constantly resolve the tree controller types from the PluginManager it will re-scan and also re-log that
/// it's resolving which is unecessary and annoying.
/// </remarks>
private static readonly Lazy<IEnumerable<Type>> TreeControllerTypes = new Lazy<IEnumerable<Type>>(() => PluginManager.Current.ResolveAttributedTreeControllers().ToArray());
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
if (_applicationContext.IsConfigured == false)
return null;
var app = new Dictionary<string, object>
{
{"assemblyVersion", UmbracoVersion.AssemblyVersion}
};
var version = UmbracoVersion.GetSemanticVersion().ToSemanticString();
app.Add("cacheBuster", string.Format("{0}.{1}", version, ClientDependencySettings.Instance.Version).GenerateHash());
app.Add("version", version);
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private string GetMaxRequestLength()
{
var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section == null) return string.Empty;
return section.MaxRequestLength.ToString();
}
}
}
| |
/*
* 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.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Data;
using Npgsql;
using NpgsqlTypes;
namespace OpenSim.Data.PGSQL
{
public class PGSQLEstateStore : IEstateDataStore
{
private const string _migrationStore = "EstateStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private PGSQLManager _Database;
private string m_connectionString;
private FieldInfo[] _Fields;
private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
#region Public methods
public PGSQLEstateStore()
{
}
public PGSQLEstateStore(string connectionString)
{
Initialise(connectionString);
}
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
/// <summary>
/// Initialises the estatedata class.
/// </summary>
/// <param name="connectionString">connectionString.</param>
public void Initialise(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
m_connectionString = connectionString;
_Database = new PGSQLManager(connectionString);
}
//Migration settings
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "EstateStore");
m.Update();
}
//Interesting way to get parameters! Maybe implement that also with other types
Type t = typeof(EstateSettings);
_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in _Fields)
{
if (f.Name.Substring(0, 2) == "m_")
_FieldMap[f.Name.Substring(2)] = f;
}
}
/// <summary>
/// Loads the estate settings.
/// </summary>
/// <param name="regionID">region ID.</param>
/// <returns></returns>
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) +
"\" from estate_map left join estate_settings on estate_map.\"EstateID\" = estate_settings.\"EstateID\" " +
" where estate_settings.\"EstateID\" is not null and \"RegionID\" = :RegionID";
bool insertEstate = false;
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("RegionID", regionID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, v);
}
else if (f.FieldType == typeof(UUID))
{
UUID estUUID = UUID.Zero;
UUID.TryParse(v.ToString(), out estUUID);
f.SetValue(es, estUUID);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
else
{
insertEstate = true;
}
}
}
if (insertEstate && create)
{
DoCreate(es);
LinkRegion(regionID, (int)es.EstateID);
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public EstateSettings CreateNewEstate()
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
DoCreate(es);
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
private void DoCreate(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("insert into estate_settings (\"{0}\") values ( :{1} )", String.Join("\",\"", names.ToArray()), String.Join(", :", names.ToArray()));
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand insertCommand = new NpgsqlCommand(sql, conn))
{
insertCommand.CommandText = sql;
foreach (string name in names)
{
insertCommand.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es)));
}
//NpgsqlParameter idParameter = new NpgsqlParameter("ID", SqlDbType.Int);
//idParameter.Direction = ParameterDirection.Output;
//insertCommand.Parameters.Add(idParameter);
conn.Open();
es.EstateID = 100;
if (insertCommand.ExecuteNonQuery() > 0)
{
insertCommand.CommandText = "Select cast(lastval() as int) as ID ;";
using (NpgsqlDataReader result = insertCommand.ExecuteReader())
{
if (result.Read())
{
es.EstateID = (uint)result.GetInt32(0);
}
}
}
}
//TODO check if this is needed??
es.Save();
}
/// <summary>
/// Stores the estate settings.
/// </summary>
/// <param name="es">estate settings</param>
public void StoreEstateSettings(EstateSettings es)
{
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = string.Format("UPDATE estate_settings SET ");
foreach (string name in names)
{
sql += "\"" + name + "\" = :" + name + ", ";
}
sql = sql.Remove(sql.LastIndexOf(","));
sql += " WHERE \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
foreach (string name in names)
{
cmd.Parameters.Add(_Database.CreateParameter("" + name, _FieldMap[name].GetValue(es)));
}
cmd.Parameters.Add(_Database.CreateParameter("EstateID", es.EstateID));
conn.Open();
cmd.ExecuteNonQuery();
}
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
#endregion
#region Private methods
private string[] FieldList
{
get { return new List<string>(_FieldMap.Keys).ToArray(); }
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
string sql = "select \"bannedUUID\" from estateban where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
NpgsqlParameter idParameter = new NpgsqlParameter("EstateID", DbType.Int32);
idParameter.Value = es.EstateID;
cmd.Parameters.Add(idParameter);
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
EstateBan eb = new EstateBan();
eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
}
private UUID[] LoadUUIDList(uint estateID, string table)
{
List<UUID> uuids = new List<UUID>();
string sql = string.Format("select uuid from {0} where \"EstateID\" = :EstateID", table);
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("EstateID", estateID));
conn.Open();
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UUID uuid = new UUID();
UUID.TryParse(reader["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
}
}
return uuids.ToArray();
}
private void SaveBanList(EstateSettings es)
{
//Delete first
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "delete from estateban where \"EstateID\" = :EstateID";
cmd.Parameters.AddWithValue("EstateID", (int)es.EstateID);
cmd.ExecuteNonQuery();
//Insert after
cmd.CommandText = "insert into estateban (\"EstateID\", \"bannedUUID\",\"bannedIp\", \"bannedIpHostMask\", \"bannedNameMask\") values ( :EstateID, :bannedUUID, '','','' )";
cmd.Parameters.AddWithValue("bannedUUID", Guid.Empty);
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters["bannedUUID"].Value = b.BannedUserID.Guid;
cmd.ExecuteNonQuery();
}
}
}
}
private void SaveUUIDList(uint estateID, string table, UUID[] data)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = conn.CreateCommand())
{
cmd.Parameters.AddWithValue("EstateID", (int)estateID);
cmd.CommandText = string.Format("delete from {0} where \"EstateID\" = :EstateID", table);
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format("insert into {0} (\"EstateID\", uuid) values ( :EstateID, :uuid )", table);
cmd.Parameters.AddWithValue("uuid", Guid.Empty);
foreach (UUID uuid in data)
{
cmd.Parameters["uuid"].Value = uuid.ToString();
cmd.ExecuteNonQuery();
}
}
}
}
public EstateSettings LoadEstateSettings(int estateID)
{
EstateSettings es = new EstateSettings();
string sql = "select estate_settings.\"" + String.Join("\",estate_settings.\"", FieldList) + "\" from estate_settings where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateID", (int)estateID);
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
foreach (string name in FieldList)
{
FieldInfo f = _FieldMap[name];
object v = reader[name];
if (f.FieldType == typeof(bool))
{
f.SetValue(es, Convert.ToInt32(v) != 0);
}
else if (f.FieldType == typeof(UUID))
{
f.SetValue(es, new UUID((Guid)v)); // uuid);
}
else if (f.FieldType == typeof(string))
{
f.SetValue(es, v.ToString());
}
else if (f.FieldType == typeof(UInt32))
{
f.SetValue(es, Convert.ToUInt32(v));
}
else if (f.FieldType == typeof(Single))
{
f.SetValue(es, Convert.ToSingle(v));
}
else
f.SetValue(es, v);
}
}
}
}
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
//Set event
es.OnSave += StoreEstateSettings;
return es;
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
List<int> allEstateIds = GetEstatesAll();
foreach (int estateId in allEstateIds)
allEstateSettings.Add(LoadEstateSettings(estateId));
return allEstateSettings;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select \"EstateID\" from estate_settings where lower(\"EstateName\") = lower(:EstateName)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateName", search);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select \"EstateID\" from estate_settings";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select \"EstateID\" from estate_settings where \"EstateOwner\" = :EstateOwner";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateOwner", ownerID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
}
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
string deleteSQL = "delete from estate_map where \"RegionID\" = :RegionID";
string insertSQL = "insert into estate_map values (:RegionID, :EstateID)";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
NpgsqlTransaction transaction = conn.BeginTransaction();
try
{
using (NpgsqlCommand cmd = new NpgsqlCommand(deleteSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("RegionID", regionID.Guid);
cmd.ExecuteNonQuery();
}
using (NpgsqlCommand cmd = new NpgsqlCommand(insertSQL, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("RegionID", regionID.Guid);
cmd.Parameters.AddWithValue("EstateID", estateID);
int ret = cmd.ExecuteNonQuery();
if (ret != 0)
transaction.Commit();
else
transaction.Rollback();
return (ret != 0);
}
}
catch (Exception ex)
{
m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message);
transaction.Rollback();
}
}
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
string sql = "select \"RegionID\" from estate_map where \"EstateID\" = :EstateID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_connectionString))
{
conn.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("EstateID", estateID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(DBGuid.FromDB(reader["RegionID"]));
}
reader.Close();
}
}
}
return result;
}
public bool DeleteEstate(int estateID)
{
// TODO: Implementation!
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.ApiDesignGuidelines.Analyzers
{
/// <summary>
/// CA2225: Operator overloads have named alternates
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class OperatorOverloadsHaveNamedAlternatesAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2225";
internal const string DiagnosticKindText = "DiagnosticKind";
internal const string AddAlternateText = "AddAlternate";
internal const string FixVisibilityText = "FixVisibility";
internal const string IsTrueText = "IsTrue";
private const string OpTrueText = "op_True";
private const string OpFalseText = "op_False";
private const string MsdnUrl = "https://msdn.microsoft.com/en-us/library/ms182355.aspx";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageDefault), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageProperty = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageProperty), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageMultiple = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageMultiple), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableMessageVisibility = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesMessageVisibility), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.OperatorOverloadsHaveNamedAlternatesDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
internal static DiagnosticDescriptor DefaultRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageDefault,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: MsdnUrl,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor PropertyRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageProperty,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: MsdnUrl,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor MultipleRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageMultiple,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: MsdnUrl,
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor VisibilityRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageVisibility,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: MsdnUrl,
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, PropertyRule, MultipleRule, VisibilityRule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method);
}
private static void AnalyzeSymbol(SymbolAnalysisContext symbolContext)
{
var methodSymbol = (IMethodSymbol)symbolContext.Symbol;
if (methodSymbol.ContainingSymbol is ITypeSymbol typeSymbol && (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion))
{
string operatorName = methodSymbol.Name;
if (IsPropertyExpected(operatorName) && operatorName != OpFalseText)
{
// don't report a diagnostic on the `op_False` method because then the user would see two diagnostics for what is really one error
// special-case looking for `IsTrue` instance property
// named properties can't be overloaded so there will only ever be 0 or 1
IPropertySymbol property = typeSymbol.GetMembers(IsTrueText).OfType<IPropertySymbol>().SingleOrDefault();
if (property == null || property.Type.SpecialType != SpecialType.System_Boolean)
{
symbolContext.ReportDiagnostic(CreateDiagnostic(PropertyRule, GetSymbolLocation(methodSymbol), AddAlternateText, IsTrueText, operatorName));
}
else if (!property.IsPublic())
{
symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(property), FixVisibilityText, IsTrueText, operatorName));
}
}
else
{
ExpectedAlternateMethodGroup expectedGroup = GetExpectedAlternateMethodGroup(operatorName, methodSymbol.ReturnType);
if (expectedGroup == null)
{
// no alternate methods required
return;
}
var matchedMethods = new List<IMethodSymbol>();
var unmatchedMethods = new HashSet<string>() { expectedGroup.AlternateMethod1 };
if (expectedGroup.AlternateMethod2 != null)
{
unmatchedMethods.Add(expectedGroup.AlternateMethod2);
}
foreach (IMethodSymbol candidateMethod in typeSymbol.GetMembers().OfType<IMethodSymbol>())
{
if (candidateMethod.Name == expectedGroup.AlternateMethod1 || candidateMethod.Name == expectedGroup.AlternateMethod2)
{
// found an appropriately-named method
matchedMethods.Add(candidateMethod);
unmatchedMethods.Remove(candidateMethod.Name);
}
}
// only one public method match is required
if (matchedMethods.Any(m => m.IsPublic()))
{
// at least one public alternate method was found, do nothing
}
else
{
// either we found at least one method that should be public or we didn't find anything
IMethodSymbol notPublicMethod = matchedMethods.FirstOrDefault(m => !m.IsPublic());
if (notPublicMethod != null)
{
// report error for improper visibility directly on the method itself
symbolContext.ReportDiagnostic(CreateDiagnostic(VisibilityRule, GetSymbolLocation(notPublicMethod), FixVisibilityText, notPublicMethod.Name, operatorName));
}
else
{
// report error for missing methods on the operator overload
if (expectedGroup.AlternateMethod2 == null)
{
// only one alternate expected
symbolContext.ReportDiagnostic(CreateDiagnostic(DefaultRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, operatorName));
}
else
{
// one of two alternates expected
symbolContext.ReportDiagnostic(CreateDiagnostic(MultipleRule, GetSymbolLocation(methodSymbol), AddAlternateText, expectedGroup.AlternateMethod1, expectedGroup.AlternateMethod2, operatorName));
}
}
}
}
}
}
private static Location GetSymbolLocation(ISymbol symbol)
{
return symbol.OriginalDefinition.Locations.First();
}
private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Location location, string kind, params string[] messageArgs)
{
return Diagnostic.Create(descriptor, location, ImmutableDictionary.Create<string, string>().Add(DiagnosticKindText, kind), messageArgs);
}
internal static bool IsPropertyExpected(string operatorName)
{
switch (operatorName)
{
case OpTrueText:
case OpFalseText:
return true;
default:
return false;
}
}
internal static ExpectedAlternateMethodGroup GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType)
{
// list of operator alternate names: https://msdn.microsoft.com/en-us/library/ms182355.aspx
// the most common case; create a static method with the already specified types
Func<string, ExpectedAlternateMethodGroup> createSingle = methodName => new ExpectedAlternateMethodGroup(methodName);
switch (operatorName)
{
case "op_Addition":
case "op_AdditonAssignment":
return createSingle("Add");
case "op_BitwiseAnd":
case "op_BitwiseAndAssignment":
return createSingle("BitwiseAnd");
case "op_BitwiseOr":
case "op_BitwiseOrAssignment":
return createSingle("BitwiseOr");
case "op_Decrement":
return createSingle("Decrement");
case "op_Division":
case "op_DivisionAssignment":
return createSingle("Divide");
case "op_Equality":
case "op_Inequality":
return createSingle("Equals");
case "op_ExclusiveOr":
case "op_ExclusiveOrAssignment":
return createSingle("Xor");
case "op_GreaterThan":
case "op_GreaterThanOrEqual":
case "op_LessThan":
case "op_LessThanOrEqual":
return new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare");
case "op_Increment":
return createSingle("Increment");
case "op_LeftShift":
case "op_LeftShiftAssignment":
return createSingle("LeftShift");
case "op_LogicalAnd":
return createSingle("LogicalAnd");
case "op_LogicalOr":
return createSingle("LogicalOr");
case "op_LogicalNot":
return createSingle("LogicalNot");
case "op_Modulus":
case "op_ModulusAssignment":
return new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder");
case "op_MultiplicationAssignment":
case "op_Multiply":
return createSingle("Multiply");
case "op_OnesComplement":
return createSingle("OnesComplement");
case "op_RightShift":
case "op_RightShiftAssignment":
case "op_SignedRightShift":
case "op_UnsignedRightShift":
case "op_UnsignedRightShiftAssignment":
return createSingle("RightShift");
case "op_Subtraction":
case "op_SubtractionAssignment":
return createSingle("Subtract");
case "op_UnaryNegation":
return createSingle("Negate");
case "op_UnaryPlus":
return createSingle("Plus");
case "op_Implicit":
case "op_Explicit":
return new ExpectedAlternateMethodGroup(alternateMethod1: $"To{returnType.Name}", alternateMethod2: $"From{returnType.Name}");
default:
return null;
}
}
internal class ExpectedAlternateMethodGroup
{
public string AlternateMethod1 { get; }
public string AlternateMethod2 { get; }
public ExpectedAlternateMethodGroup(string alternateMethod1, string alternateMethod2 = null)
{
AlternateMethod1 = alternateMethod1;
AlternateMethod2 = alternateMethod2;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private HttpCookieContainerManager _httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile MruCache<Uri, Uri> _credentialCacheUriPrefixCache;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private IWebProxy _proxy;
private WebProxyFactory _proxyFactory;
private SecurityCredentialsManager _channelCredentials;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
private bool _keepAliveEnabled;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.HttpAuthDoesNotSupportRequestStreaming);
}
AllowCookies = bindingElement.AllowCookies;
if (AllowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton() && bindingElement.AuthenticationScheme != AuthenticationSchemes.IntegratedWindowsAuthentication)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
AuthenticationScheme = bindingElement.AuthenticationScheme;
MaxBufferSize = bindingElement.MaxBufferSize;
TransferMode = bindingElement.TransferMode;
_keepAliveEnabled = bindingElement.KeepAliveEnabled;
if (bindingElement.Proxy != null)
{
_proxy = bindingElement.Proxy;
}
else if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
_proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
_proxy = null;
_proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
_proxy = new WebProxy();
}
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();
WebSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
_httpClientCache = bindingElement.GetProperty<MruCache<string, HttpClient>>(context);
}
public bool AllowCookies { get; }
public AuthenticationSchemes AuthenticationScheme { get; }
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager { get; private set; }
public int MaxBufferSize { get; }
public TransferMode TransferMode { get; }
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings { get; }
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
private bool AuthenticationSchemeMayRequireResend()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
private Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (_credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (_credentialCacheUriPrefixCache == null)
{
_credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (_credentialCacheUriPrefixCache)
{
if (!_credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
_credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via,
SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider,
SecurityTokenContainer clientCertificateToken, TimeSpan timeout)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName ?? string.Empty;
bool foundHttpClient;
lock (_httpClientCache)
{
foundHttpClient = _httpClientCache.TryGetValue(connectionGroupName, out httpClient);
}
if (!foundHttpClient)
{
var clientHandler = GetHttpClientHandler(to, clientCertificateToken);
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
if (clientHandler.SupportsProxy)
{
if (_proxy != null)
{
clientHandler.Proxy = _proxy;
clientHandler.UseProxy = true;
}
else if (_proxyFactory != null)
{
clientHandler.Proxy = await _proxyFactory.CreateWebProxyAsync(authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value, proxyTokenProvider, timeout);
clientHandler.UseProxy = true;
}
}
clientHandler.UseCookies = AllowCookies;
if (AllowCookies)
{
clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer;
}
clientHandler.PreAuthenticate = true;
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials || credential == null)
{
clientHandler.UseDefaultCredentials = true;
}
else
{
if (Fx.IsUap)
{
clientHandler.Credentials = credential;
}
else
{
CredentialCache credentials = new CredentialCache();
Uri credentialCacheUriPrefix = GetCredentialCacheUriPrefix(via);
if (AuthenticationScheme == AuthenticationSchemes.IntegratedWindowsAuthentication)
{
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Negotiate),
credential);
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Ntlm),
credential);
}
else
{
credentials.Add(credentialCacheUriPrefix, AuthenticationSchemesHelper.ToString(AuthenticationScheme),
credential);
}
clientHandler.Credentials = credentials;
}
}
HttpMessageHandler handler = clientHandler;
if (_httpMessageHandlerFactory != null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}
httpClient = new HttpClient(handler);
if (!_keepAliveEnabled)
{
httpClient.DefaultRequestHeaders.ConnectionClose = true;
}
if (IsExpectContinueHeaderRequired && !Fx.IsUap)
{
httpClient.DefaultRequestHeaders.ExpectContinue = true;
}
// We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1
// prevents a call to CancellationToken.CancelAfter that HttpClient does internally which
// causes TimerQueue contention at high load.
httpClient.Timeout = Timeout.InfiniteTimeSpan;
lock (_httpClientCache)
{
HttpClient tempHttpClient;
if (_httpClientCache.TryGetValue(connectionGroupName, out tempHttpClient))
{
httpClient.Dispose();
httpClient = tempHttpClient;
}
else
{
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
}
return httpClient;
}
internal virtual bool IsExpectContinueHeaderRequired => AuthenticationSchemeMayRequireResend();
internal virtual HttpClientHandler GetHttpClientHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new HttpClientHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (AuthenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ClientCredentials.UserName.UserName));
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
case AuthenticationSchemes.IntegratedWindowsAuthentication:
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
case AuthenticationSchemes.IntegratedWindowsAuthentication:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
SecurityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
if (_proxyFactory != null && _proxyFactory.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
return true;
}
else
{
return false;
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.OnCloseAsync(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
if (_httpClientCache != null && !_httpClientCache.IsDisposed)
{
lock (_httpClientCache)
{
_httpClientCache.Dispose();
_httpClientCache = null;
}
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Fx.Assert(authScheme.IsSingleton() || authScheme == AuthenticationSchemes.IntegratedWindowsAuthentication, "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm ||
authScheme == AuthenticationSchemes.IntegratedWindowsAuthentication;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(AuthenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
if (_proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), _proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private SecurityTokenProviderContainer _tokenProvider;
private SecurityTokenProviderContainer _proxyTokenProvider;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
Factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory { get; }
protected ChannelParameterCollection ChannelParameters { get; private set; }
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (ChannelParameters == null)
{
ChannelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)ChannelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, ChannelParameters, timeoutHelper.RemainingTime(), out _tokenProvider, out _proxyTokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
SecurityTokenProviderContainer requestProxyTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, ChannelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider, out requestProxyTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
requestProxyTokenProvider = _proxyTokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, via, requestTokenProvider, requestProxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
if (_channel.Factory.MapIdentity(_to))
{
HttpTransportSecurityHelpers.AddIdentityMapping(_to, message);
}
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
// The _httpRequestMessage field will be set to null by Cleanup() due to faulting
// or aborting, so use a local copy for exception handling within this method.
HttpRequestMessage httpRequestMessage = _channel.GetHttpRequestMessage(_via);
_httpRequestMessage = httpRequestMessage;
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
if (Fx.IsUap)
{
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
}
bool success = false;
var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync();
try
{
using (timeoutToken.Register(s_cancelCts, _httpSendCts))
{
_httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
}
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (timeoutToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutToken and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper);
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Add(name, value);
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!_factory.AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
}
}
private class WebProxyFactory
{
private Uri _address;
private bool _bypassOnLocal;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
_address = address;
_bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton() && authenticationScheme != AuthenticationSchemes.IntegratedWindowsAuthentication)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(authenticationScheme), SR.Format(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
AuthenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme { get; }
public async Task<IWebProxy> CreateWebProxyAsync(AuthenticationLevel requestAuthenticationLevel, TokenImpersonationLevel requestImpersonationLevel, SecurityTokenProviderContainer tokenProvider, TimeSpan timeout)
{
WebProxy result = new WebProxy(_address, _bypassOnLocal);
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevelWrapper.Value, requestImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyImpersonationLevelMismatch, impersonationLevelWrapper.Value, requestImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) &&
(requestAuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyAuthenticationLevelMismatch, authenticationLevelWrapper.Value, requestAuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
if (AuthenticationScheme == AuthenticationSchemes.IntegratedWindowsAuthentication)
{
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Negotiate),
credential);
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationSchemes.Ntlm),
credential);
}
else
{
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationScheme),
credential);
}
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
// 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.
/*============================================================
**
Type: AssemblyNameHelpers
**
==============================================================*/
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace System.Reflection.Runtime.Assemblies
{
public static partial class AssemblyNameHelpers
{
public static String ComputeDisplayName(RuntimeAssemblyName a)
{
if (a.Name == String.Empty)
throw new FileLoadException();
StringBuilder sb = new StringBuilder();
if (a.Name != null)
{
sb.AppendQuoted(a.Name);
}
if (a.Version != null)
{
Version canonicalizedVersion = a.Version.CanonicalizeVersion();
if (canonicalizedVersion.Major != ushort.MaxValue)
{
sb.Append(", Version=");
sb.Append(canonicalizedVersion.Major);
sb.Append('.');
sb.Append(canonicalizedVersion.Minor);
sb.Append('.');
sb.Append(canonicalizedVersion.Build);
sb.Append('.');
sb.Append(canonicalizedVersion.Revision);
}
}
String cultureName = a.CultureName;
if (cultureName != null)
{
if (cultureName == String.Empty)
cultureName = "neutral";
sb.Append(", Culture=");
sb.AppendQuoted(cultureName);
}
byte[] pkt = a.PublicKeyOrToken;
if (pkt != null)
{
if (0 != (a.Flags & AssemblyNameFlags.PublicKey))
pkt = ComputePublicKeyToken(pkt);
if (pkt.Length > PUBLIC_KEY_TOKEN_LEN)
throw new ArgumentException();
sb.Append(", PublicKeyToken=");
if (pkt.Length == 0)
sb.Append("null");
else
{
foreach (byte b in pkt)
{
sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
}
}
if (0 != (a.Flags & AssemblyNameFlags.Retargetable))
sb.Append(", Retargetable=Yes");
AssemblyContentType contentType = a.Flags.ExtractAssemblyContentType();
if (contentType == AssemblyContentType.WindowsRuntime)
sb.Append(", ContentType=WindowsRuntime");
// NOTE: By design (desktop compat) AssemblyName.FullName and ToString() do not include ProcessorArchitecture.
return sb.ToString();
}
private static void AppendQuoted(this StringBuilder sb, String s)
{
bool needsQuoting = false;
const char quoteChar = '\"';
//@todo: App-compat: You can use double or single quotes to quote a name, and Fusion (or rather the IdentityAuthority) picks one
// by some algorithm. Rather than guess at it, I'll just use double-quote consistently.
if (s != s.Trim() || s.Contains("\"") || s.Contains("\'"))
needsQuoting = true;
if (needsQuoting)
sb.Append(quoteChar);
for (int i = 0; i < s.Length; i++)
{
bool addedEscape = false;
foreach (KeyValuePair<char, String> kv in AssemblyNameLexer.EscapeSequences)
{
String escapeReplacement = kv.Value;
if (!(s[i] == escapeReplacement[0]))
continue;
if ((s.Length - i) < escapeReplacement.Length)
continue;
String prefix = s.Substring(i, escapeReplacement.Length);
if (prefix == escapeReplacement)
{
sb.Append('\\');
sb.Append(kv.Key);
addedEscape = true;
}
}
if (!addedEscape)
sb.Append(s[i]);
}
if (needsQuoting)
sb.Append(quoteChar);
}
//
// Converts an AssemblyName to a RuntimeAssemblyName that is free from any future mutations on the AssemblyName.
//
public static RuntimeAssemblyName ToRuntimeAssemblyName(this AssemblyName assemblyName)
{
if (assemblyName.Name == null)
throw new ArgumentException();
AssemblyNameFlags flags = assemblyName.Flags;
AssemblyContentType contentType = assemblyName.ContentType;
ProcessorArchitecture processorArchitecture = assemblyName.ProcessorArchitecture;
AssemblyNameFlags combinedFlags = CombineAssemblyNameFlags(flags, contentType, processorArchitecture);
byte[] pkOriginal;
if (0 != (flags & AssemblyNameFlags.PublicKey))
pkOriginal = assemblyName.GetPublicKey();
else
pkOriginal = assemblyName.GetPublicKeyToken();
// AssemblyName's PKT property getters do NOT copy the array before giving it out. Make our own copy
// as the original is wide open to tampering by anyone.
byte[] pkCopy = null;
if (pkOriginal != null)
{
pkCopy = new byte[pkOriginal.Length];
((ICollection<byte>)pkOriginal).CopyTo(pkCopy, 0);
}
return new RuntimeAssemblyName(assemblyName.Name, assemblyName.Version, assemblyName.CultureName, combinedFlags, pkCopy);
}
public static Version CanonicalizeVersion(this Version version)
{
ushort major = (ushort)version.Major;
ushort minor = (ushort)version.Minor;
ushort build = (ushort)version.Build;
ushort revision = (ushort)version.Revision;
if (major == version.Major && minor == version.Minor && build == version.Build && revision == version.Revision)
return version;
return new Version(major, minor, build, revision);
}
//
// Ensure that the PublicKeyOrPublicKeyToken (if non-null) is the short token form.
//
public static RuntimeAssemblyName CanonicalizePublicKeyToken(this RuntimeAssemblyName name)
{
AssemblyNameFlags flags = name.Flags;
if ((flags & AssemblyNameFlags.PublicKey) == 0)
return name;
flags &= ~AssemblyNameFlags.PublicKey;
byte[] publicKeyOrToken = name.PublicKeyOrToken;
if (publicKeyOrToken != null)
publicKeyOrToken = ComputePublicKeyToken(publicKeyOrToken);
return new RuntimeAssemblyName(name.Name, name.Version, name.CultureName, flags, publicKeyOrToken);
}
//
// These helpers convert between the combined flags+contentType+processorArchitecture value and the separated parts.
//
// Since these are only for trusted callers, they do NOT check for out of bound bits.
//
internal static AssemblyContentType ExtractAssemblyContentType(this AssemblyNameFlags flags)
{
return (AssemblyContentType)((((int)flags) >> 9) & 0x7);
}
internal static ProcessorArchitecture ExtractProcessorArchitecture(this AssemblyNameFlags flags)
{
return (ProcessorArchitecture)((((int)flags) >> 4) & 0x7);
}
public static AssemblyNameFlags ExtractAssemblyNameFlags(this AssemblyNameFlags combinedFlags)
{
return combinedFlags & unchecked((AssemblyNameFlags)0xFFFFF10F);
}
internal static AssemblyNameFlags CombineAssemblyNameFlags(AssemblyNameFlags flags, AssemblyContentType contentType, ProcessorArchitecture processorArchitecture)
{
return (AssemblyNameFlags)(((int)flags) | (((int)contentType) << 9) | ((int)processorArchitecture << 4));
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
//
// Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
#endif
using PdfSharp;
using PdfSharp.Internal;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;
// WPFHACK
#pragma warning disable 162
namespace PdfSharp.Drawing
{
/// <summary>
/// Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
/// An abstract base class that provides functionality for the Bitmap and Metafile descended classes.
/// </summary>
public class XImage : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class.
/// </summary>
protected XImage()
{
}
#if GDI
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class from a GDI+ image.
/// </summary>
XImage(Image image)
{
this.gdiImage = image;
#if WPF
this.wpfImage = ImageHelper.CreateBitmapSource(image);
#endif
Initialize();
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XImage"/> class from a WPF image.
/// </summary>
XImage(BitmapSource image)
{
this.wpfImage = image;
Initialize();
}
#endif
XImage(string path)
{
path = Path.GetFullPath(path);
if (!File.Exists(path))
throw new FileNotFoundException(PSSR.FileNotFound(path), path);
this.path = path;
//FileStream file = new FileStream(filename, FileMode.Open);
//BitsLength = (int)file.Length;
//Bits = new byte[BitsLength];
//file.Read(Bits, 0, BitsLength);
//file.Close();
#if GDI
this.gdiImage = Image.FromFile(path);
#endif
#if WPF && !SILVERLIGHT
//BitmapSource.Create()
// BUG: BitmapImage locks the file
this.wpfImage = new BitmapImage(new Uri(path)); // AGHACK
#endif
#if false
float vres = this.image.VerticalResolution;
float hres = this.image.HorizontalResolution;
SizeF size = this.image.PhysicalDimension;
int flags = this.image.Flags;
Size sz = this.image.Size;
GraphicsUnit units = GraphicsUnit.Millimeter;
RectangleF rect = this.image.GetBounds(ref units);
int width = this.image.Width;
#endif
Initialize();
}
/// <summary>
/// Create image from a stream.
/// </summary>
public XImage(Stream stream)
{
// Create a dummy unique path
this.path = "*" + Guid.NewGuid().ToString("B");
#if GDI
this.gdiImage = Image.FromStream(stream);
#endif
#if WPF
throw new NotImplementedException();
//this.wpfImage = new BitmapImage(new Uri(path));
#endif
#if true_
float vres = this.image.VerticalResolution;
float hres = this.image.HorizontalResolution;
SizeF size = this.image.PhysicalDimension;
int flags = this.image.Flags;
Size sz = this.image.Size;
GraphicsUnit units = GraphicsUnit.Millimeter;
RectangleF rect = this.image.GetBounds(ref units);
int width = this.image.Width;
#endif
Initialize();
}
#if GDI
#if UseGdiObjects
/// <summary>
/// Implicit conversion from Image to XImage.
/// </summary>
public static implicit operator XImage(Image image)
{
return new XImage(image);
}
#endif
/// <summary>
/// Conversion from Image to XImage.
/// </summary>
public static XImage FromGdiPlusImage(Image image)
{
return new XImage(image);
}
#endif
#if WPF && !SILVERLIGHT
/// <summary>
/// Conversion from BitmapSource to XImage.
/// </summary>
public static XImage FromBitmapSource(BitmapSource image)
{
return new XImage(image);
}
#endif
/// <summary>
/// Creates an image from the specified file.
/// </summary>
/// <param name="path">The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param>
public static XImage FromFile(string path)
{
if (PdfReader.TestPdfFile(path) > 0)
return new XPdfForm(path);
return new XImage(path);
}
/// <summary>
/// Tests if a file exist. Supports PDF files with page number suffix.
/// </summary>
/// <param name="path">The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param>
public static bool ExistsFile(string path)
{
if (PdfReader.TestPdfFile(path) > 0)
return true;
return File.Exists(path);
}
void Initialize()
{
#if GDI
if (this.gdiImage != null)
{
// ImageFormat has no overridden Equals...
string guid = this.gdiImage.RawFormat.Guid.ToString("B").ToUpper();
switch (guid)
{
case "{B96B3CAA-0728-11D3-9D7B-0000F81EF32E}": // memoryBMP
case "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}": // bmp
case "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}": // png
this.format = XImageFormat.Png;
break;
case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg
this.format = XImageFormat.Jpeg;
break;
case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif
this.format = XImageFormat.Gif;
break;
case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff
this.format = XImageFormat.Tiff;
break;
case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon
this.format = XImageFormat.Icon;
break;
case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf
case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf
case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif
case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD
case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX
default:
throw new InvalidOperationException("Unsupported image format.");
}
return;
}
#endif
#if WPF
#if !SILVERLIGHT
if (this.wpfImage != null)
{
string pixelFormat = this.wpfImage.Format.ToString();
string filename = GetImageFilename(this.wpfImage);
// WPF treats all images as images.
// We give JPEG images a special treatment.
// Test if it's a JPEG:
bool isJpeg = IsJpeg; // TestJpeg(filename);
if (isJpeg)
{
this.format = XImageFormat.Jpeg;
return;
}
switch (pixelFormat)
{
case "Bgr32":
case "Bgra32":
case "Pbgra32":
this.format = XImageFormat.Png;
break;
//case "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}": // jpeg
// this.format = XImageFormat.Jpeg;
// break;
//case "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}": // gif
case "BlackWhite":
case "Indexed1":
case "Indexed4":
case "Indexed8":
case "Gray8":
this.format = XImageFormat.Gif;
break;
//case "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}": // tiff
// this.format = XImageFormat.Tiff;
// break;
//case "{B96B3CB5-0728-11D3-9D7B-0000F81EF32E}": // icon
// this.format = XImageFormat.Icon;
// break;
//case "{B96B3CAC-0728-11D3-9D7B-0000F81EF32E}": // emf
//case "{B96B3CAD-0728-11D3-9D7B-0000F81EF32E}": // wmf
//case "{B96B3CB2-0728-11D3-9D7B-0000F81EF32E}": // exif
//case "{B96B3CB3-0728-11D3-9D7B-0000F81EF32E}": // photoCD
//case "{B96B3CB4-0728-11D3-9D7B-0000F81EF32E}": // flashPIX
default:
Debug.Assert(false, "Unknown pixel format: " + pixelFormat);
this.format = XImageFormat.Gif;
break;// throw new InvalidOperationException("Unsupported image format.");
}
}
#else
// AGHACK
#endif
#endif
}
#if WPF
/// <summary>
/// Gets the image filename.
/// </summary>
/// <param name="bitmapSource">The bitmap source.</param>
internal static string GetImageFilename(BitmapSource bitmapSource)
{
string filename = bitmapSource.ToString();
filename = UrlDecodeStringFromStringInternal(filename);
if (filename.StartsWith("file:///"))
filename = filename.Substring(8); // Remove all 3 slashes!
else if (filename.StartsWith("file://"))
filename = filename.Substring(5); // Keep 2 slashes (UNC path)
return filename;
}
private static string UrlDecodeStringFromStringInternal(string s/*, Encoding e*/)
{
int length = s.Length;
string result = "";
for (int i = 0; i < length; i++)
{
char ch = s[i];
if (ch == '+')
{
ch = ' ';
}
else if ((ch == '%') && (i < (length - 2)))
{
if ((s[i + 1] == 'u') && (i < (length - 5)))
{
int num3 = HexToInt(s[i + 2]);
int num4 = HexToInt(s[i + 3]);
int num5 = HexToInt(s[i + 4]);
int num6 = HexToInt(s[i + 5]);
if (((num3 < 0) || (num4 < 0)) || ((num5 < 0) || (num6 < 0)))
{
goto AddByte;
}
ch = (char)((((num3 << 12) | (num4 << 8)) | (num5 << 4)) | num6);
i += 5;
result += ch;
continue;
}
int num7 = HexToInt(s[i + 1]);
int num8 = HexToInt(s[i + 2]);
if ((num7 >= 0) && (num8 >= 0))
{
byte b = (byte)((num7 << 4) | num8);
i += 2;
result += (char)b;
continue;
}
}
AddByte:
if ((ch & 0xff80) == 0)
{
result += ch;
}
else
{
result += ch;
}
}
return result;
}
private static int HexToInt(char h)
{
if ((h >= '0') && (h <= '9'))
{
return (h - '0');
}
if ((h >= 'a') && (h <= 'f'))
{
return ((h - 'a') + 10);
}
if ((h >= 'A') && (h <= 'F'))
{
return ((h - 'A') + 10);
}
return -1;
}
#endif
#if WPF
/// <summary>
/// Tests if a file is a JPEG.
/// </summary>
/// <param name="filename">The filename.</param>
internal static bool TestJpeg(string filename)
{
byte[] imageBits = null;
return ReadJpegFile(filename, 16, ref imageBits);
}
/// <summary>
/// Reads the JPEG file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="maxRead">The maximum count of bytes to be read.</param>
/// <param name="imageBits">The bytes read from the file.</param>
/// <returns>False, if file could not be read or is not a JPEG file.</returns>
internal static bool ReadJpegFile(string filename, int maxRead, ref byte[] imageBits)
{
if (File.Exists(filename))
{
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
catch
{
return false;
}
if (fs.Length < 16)
{
fs.Close();
return false;
}
int len = maxRead == -1 ? (int)fs.Length : maxRead;
imageBits = new byte[len];
fs.Read(imageBits, 0, len);
fs.Close();
if (imageBits[0] == 0xff &&
imageBits[1] == 0xd8 &&
imageBits[2] == 0xff &&
imageBits[3] == 0xe0 &&
imageBits[6] == 0x4a &&
imageBits[7] == 0x46 &&
imageBits[8] == 0x49 &&
imageBits[9] == 0x46 &&
imageBits[10] == 0x0)
{
return true;
}
// TODO: Exif: find JFIF header
if (imageBits[0] == 0xff &&
imageBits[1] == 0xd8 &&
imageBits[2] == 0xff &&
imageBits[3] == 0xe1 /*&&
imageBits[6] == 0x4a &&
imageBits[7] == 0x46 &&
imageBits[8] == 0x49 &&
imageBits[9] == 0x46 &&
imageBits[10] == 0x0*/)
{
// Hack: store the file in PDF if extension matches ...
string str = filename.ToLower();
if (str.EndsWith(".jpg") || str.EndsWith(".jpeg"))
return true;
}
}
return false;
}
#endif
/// <summary>
/// Under construction
/// </summary>
public void Dispose()
{
Dispose(true);
//GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes underlying GDI+ object.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
this.disposed = true;
#if GDI
if (this.gdiImage != null)
{
this.gdiImage.Dispose();
this.gdiImage = null;
}
#endif
#if WPF
if (wpfImage != null)
{
wpfImage = null;
}
#endif
}
bool disposed;
/// <summary>
/// Gets the width of the image.
/// </summary>
[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
public virtual double Width
{
get
{
#if GDI && WPF
double gdiWidth = this.gdiImage.Width;
double wpfWidth = this.wpfImage.PixelWidth;
Debug.Assert(gdiWidth == wpfWidth);
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelWidth;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image.
/// </summary>
[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
public virtual double Height
{
get
{
#if GDI && WPF
double gdiHeight = this.gdiImage.Height;
double wpfHeight = this.wpfImage.PixelHeight;
Debug.Assert(gdiHeight == wpfHeight);
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelHeight;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the width of the image in point.
/// </summary>
public virtual double PointWidth
{
get
{
#if GDI && WPF
double gdiWidth = this.gdiImage.Width * 72 / this.gdiImage.HorizontalResolution;
double wpfWidth = this.wpfImage.Width * 72.0 / 96.0;
//Debug.Assert(gdiWidth == wpfWidth);
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiWidth, wpfWidth, 5));
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width * 72 / this.gdiImage.HorizontalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
Debug.Assert(Math.Abs(this.wpfImage.PixelWidth * 72 / this.wpfImage.DpiX - this.wpfImage.Width * 72.0 / 96.0) < 0.001);
return this.wpfImage.Width * 72.0 / 96.0;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image in point.
/// </summary>
public virtual double PointHeight
{
get
{
#if GDI && WPF
double gdiHeight = this.gdiImage.Height * 72 / this.gdiImage.HorizontalResolution;
double wpfHeight = this.wpfImage.Height * 72.0 / 96.0;
Debug.Assert(DoubleUtil.AreRoughlyEqual(gdiHeight, wpfHeight, 5));
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height * 72 / this.gdiImage.HorizontalResolution;
#endif
#if WPF || SILVERLIGHT && !GDI
#if !SILVERLIGHT
Debug.Assert(Math.Abs(this.wpfImage.PixelHeight * 72 / this.wpfImage.DpiY - this.wpfImage.Height * 72.0 / 96.0) < 0.001);
return this.wpfImage.Height * 72.0 / 96.0;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the width of the image in pixels.
/// </summary>
public virtual int PixelWidth
{
get
{
#if GDI && WPF
int gdiWidth = this.gdiImage.Width;
int wpfWidth = this.wpfImage.PixelWidth;
Debug.Assert(gdiWidth == wpfWidth);
return wpfWidth;
#endif
#if GDI && !WPF
return this.gdiImage.Width;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelWidth;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the height of the image in pixels.
/// </summary>
public virtual int PixelHeight
{
get
{
#if GDI && WPF
int gdiHeight = this.gdiImage.Height;
int wpfHeight = this.wpfImage.PixelHeight;
Debug.Assert(gdiHeight == wpfHeight);
return wpfHeight;
#endif
#if GDI && !WPF
return this.gdiImage.Height;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.PixelHeight;
#else
// AGHACK
return 100;
#endif
#endif
}
}
/// <summary>
/// Gets the size in point of the image.
/// </summary>
public virtual XSize Size
{
get { return new XSize(PointWidth, PointHeight); }
}
/// <summary>
/// Gets the horizontal resolution of the image.
/// </summary>
public virtual double HorizontalResolution
{
get
{
#if GDI && WPF
double gdiResolution = this.gdiImage.HorizontalResolution;
double wpfResolution = this.wpfImage.PixelWidth * 96.0 / this.wpfImage.Width;
Debug.Assert(gdiResolution == wpfResolution);
return wpfResolution;
#endif
#if GDI && !WPF
return this.gdiImage.HorizontalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.DpiX; //.PixelWidth * 96.0 / this.wpfImage.Width;
#else
// AGHACK
return 96;
#endif
#endif
}
}
/// <summary>
/// Gets the vertical resolution of the image.
/// </summary>
public virtual double VerticalResolution
{
get
{
#if GDI && WPF
double gdiResolution = this.gdiImage.VerticalResolution;
double wpfResolution = this.wpfImage.PixelHeight * 96.0 / this.wpfImage.Height;
Debug.Assert(gdiResolution == wpfResolution);
return wpfResolution;
#endif
#if GDI && !WPF
return this.gdiImage.VerticalResolution;
#endif
#if WPF && !GDI
#if !SILVERLIGHT
return this.wpfImage.DpiY; //.PixelHeight * 96.0 / this.wpfImage.Height;
#else
// AGHACK
return 96;
#endif
#endif
}
}
/// <summary>
/// Gets or sets a flag indicating whether image interpolation is to be performed.
/// </summary>
public virtual bool Interpolate
{
get { return this.interpolate; }
set { this.interpolate = value; }
}
bool interpolate = true;
/// <summary>
/// Gets the format of the image.
/// </summary>
public XImageFormat Format
{
get { return this.format; }
}
XImageFormat format;
#if WPF
/// <summary>
/// Gets a value indicating whether this image is JPEG.
/// </summary>
/// <value><c>true</c> if this image is JPEG; otherwise, <c>false</c>.</value>
public virtual bool IsJpeg
{
#if !SILVERLIGHT
//get { if (!isJpeg.HasValue) InitializeGdiHelper(); return isJpeg.HasValue ? isJpeg.Value : false; }
get { if (!isJpeg.HasValue) InitializeJpegQuickTest(); return isJpeg.HasValue ? isJpeg.Value : false; }
//set { isJpeg = value; }
#else
get { return false; } // AGHACK
#endif
}
private bool? isJpeg;
/// <summary>
/// Gets a value indicating whether this image is cmyk.
/// </summary>
/// <value><c>true</c> if this image is cmyk; otherwise, <c>false</c>.</value>
public virtual bool IsCmyk
{
#if !SILVERLIGHT
get { if (!isCmyk.HasValue) InitializeGdiHelper(); return isCmyk.HasValue ? isCmyk.Value : false; }
//set { isCmyk = value; }
#else
get { return false; } // AGHACK
#endif
}
private bool? isCmyk;
#if !SILVERLIGHT
/// <summary>
/// Gets the JPEG memory stream (if IsJpeg returns true).
/// </summary>
/// <value>The memory.</value>
public virtual MemoryStream Memory
{
get { if (!isCmyk.HasValue) InitializeGdiHelper(); return memory; }
//set { memory = value; }
}
MemoryStream memory = null;
/// <summary>
/// Determines if an image is JPEG w/o creating an Image object.
/// </summary>
private void InitializeJpegQuickTest()
{
isJpeg = TestJpeg(GetImageFilename(wpfImage));
}
/// <summary>
/// Initializes the GDI helper.
/// We use GDI+ to detect if image is JPEG.
/// If so, we also determine if it's CMYK and we read the image bytes.
/// </summary>
private void InitializeGdiHelper()
{
if (!isCmyk.HasValue)
{
try
{
using (System.Drawing.Image image = new System.Drawing.Bitmap(GetImageFilename(wpfImage)))
{
string guid = image.RawFormat.Guid.ToString("B").ToUpper();
isJpeg = guid == "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
isCmyk = (image.Flags & ((int)System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk | (int)System.Drawing.Imaging.ImageFlags.ColorSpaceYcck)) != 0;
if (isJpeg.Value)
{
memory = new MemoryStream();
image.Save(memory, System.Drawing.Imaging.ImageFormat.Jpeg);
if ((int)memory.Length == 0)
{
memory = null;
}
}
}
}
catch { }
}
}
#endif
#endif
#if DEBUG_
// TEST
internal void CreateAllImages(string name)
{
if (this.image != null)
{
this.image.Save(name + ".bmp", ImageFormat.Bmp);
this.image.Save(name + ".emf", ImageFormat.Emf);
this.image.Save(name + ".exif", ImageFormat.Exif);
this.image.Save(name + ".gif", ImageFormat.Gif);
this.image.Save(name + ".ico", ImageFormat.Icon);
this.image.Save(name + ".jpg", ImageFormat.Jpeg);
this.image.Save(name + ".png", ImageFormat.Png);
this.image.Save(name + ".tif", ImageFormat.Tiff);
this.image.Save(name + ".wmf", ImageFormat.Wmf);
this.image.Save(name + "2.bmp", ImageFormat.MemoryBmp);
}
}
#endif
#if GDI
internal Image gdiImage;
#endif
#if WPF
internal BitmapSource wpfImage;
#endif
/// <summary>
/// If path starts with '*' the image is created from a stream and the path is a GUID.
/// </summary>
internal string path;
/// <summary>
/// Cache PdfImageTable.ImageSelector to speed up finding the right PdfImage
/// if this image is used more than once.
/// </summary>
internal PdfImageTable.ImageSelector selector;
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Soomla.Levelup {
/// <summary>
/// This is the top level container for the unity-levelup model and definitions.
/// It stores the configurations of the game's world-hierarchy and provides
/// lookup functions for levelup model elements.
/// </summary>
public class SoomlaLevelUp {
public static readonly string DB_KEY_PREFIX = "soomla.levelup.";
private const string TAG = "SOOMLA SoomlaLevelUp";
/// <summary>
/// The instance of <c>SoomlaLevelUp</c> for this game.
/// </summary>
private static SoomlaLevelUp instance = null;
/// <summary>
/// Initial <c>World</c> to begin the game.
/// </summary>
public static World InitialWorld;
/// <summary>
/// Initializes the specified <c>InitialWorld</c> and rewards.
/// </summary>
/// <param name="initialWorld">Initial world.</param>
public static void Initialize(World initialWorld) {
InitialWorld = initialWorld;
save();
WorldStorage.InitLevelUp();
}
/// <summary>
/// Retrieves the reward with the given ID.
/// </summary>
/// <returns>The reward that was fetched.</returns>
/// <param name="rewardId">ID of the <c>Reward</c> to be fetched.</param>
public static Reward GetReward(string rewardId) {
return Reward.GetReward (rewardId);
}
/// <summary>
/// Retrieves the <c>Score</c> with the given score ID.
/// </summary>
/// <returns>The score.</returns>
/// <param name="scoreId">ID of the <c>Score</c> to be fetched.</param>
public static Score GetScore(string scoreId) {
Score retScore = null;
InitialWorld.Scores.TryGetValue(scoreId, out retScore);
if (retScore == null) {
retScore = fetchScoreFromWorlds(scoreId, InitialWorld.InnerWorldsMap);
}
return retScore;
}
/// <summary>
/// Retrieves the <c>World</c> with the given world ID.
/// </summary>
/// <returns>The world.</returns>
/// <param name="worldId">World ID of the <c>Score</c> to be fetched.</param>
public static World GetWorld(string worldId) {
if (InitialWorld.ID == worldId) {
return InitialWorld;
}
return fetchWorld(worldId, InitialWorld.InnerWorldsMap);
}
public static Level GetLevel(string levelId) {
return GetWorld(levelId) as Level;
}
/// <summary>
/// Retrieves the <c>Gate</c> with the given ID.
/// </summary>
/// <returns>The gate.</returns>
/// <param name="gateId">ID of the <c>Gate</c> to be fetched.</param>
public static Gate GetGate(string gateId) {
Gate gate = fetchGate(gateId, InitialWorld.Gate);
if( gate != null){
return gate;
}
gate = fetchGate(gateId, InitialWorld.Missions);
if (gate != null) {
return gate;
}
return fetchGate(gateId, InitialWorld.InnerWorldsList);
}
/// <summary>
/// Retrieves the <c>Mission</c> with the given ID.
/// </summary>
/// <returns>The mission.</returns>
/// <param name="missionId">ID of the <c>Mission</c> to be fetched.</param>
public static Mission GetMission(string missionId) {
Mission mission = (from m in InitialWorld.Missions
where m.ID == missionId
select m).SingleOrDefault();
if (mission == null) {
return fetchMission(missionId, InitialWorld.InnerWorldsList);
}
return mission;
}
/// <summary>
/// Counts all the <c>Level</c>s in all <c>World</c>s and inner <c>World</c>s
/// starting from the <c>InitialWorld</c>.
/// </summary>
/// <returns>The number of levels in all worlds and their inner worlds.</returns>
public static int GetLevelCount() {
return GetLevelCountInWorld(InitialWorld);
}
/// <summary>
/// Counts all the <c>Level</c>s in all <c>World</c>s and inner <c>World</c>s
/// starting from the given <c>World</c>.
/// </summary>
/// <param name="world">The world to examine.</param>
/// <returns>The number of levels in the given world and its inner worlds.</returns>
public static int GetLevelCountInWorld(World world) {
int count = 0;
foreach (World initialWorld in world.InnerWorldsMap.Values) {
count += getRecursiveCount(initialWorld, (World innerWorld) => {
return innerWorld.GetType() == typeof(Level);
});
}
return count;
}
/// <summary>
/// Counts all <c>World</c>s and their inner <c>World</c>s with or without their
/// <c>Level</c>s according to the given <c>withLevels</c>.
/// </summary>
/// <param name="withLevels">Indicates whether to count <c>Level</c>s also.</param>
/// <returns>The number of <c>World</c>s, and optionally their inner <c>Level</c>s.</returns>
public static int GetWorldCount(bool withLevels) {
return getRecursiveCount(InitialWorld, (World innerWorld) => {
return withLevels ?
(innerWorld.GetType() == typeof(World) || innerWorld.GetType() == typeof(Level)) :
(innerWorld.GetType() == typeof(World));
});
}
/// <summary>
/// Counts all completed <c>Level</c>s.
/// </summary>
/// <returns>The number of completed <c>Level</c>s and their inner completed
/// <c>Level</c>s.</returns>
public static int GetCompletedLevelCount() {
return getRecursiveCount(InitialWorld, (World innerWorld) => {
return innerWorld.GetType() == typeof(Level) && innerWorld.IsCompleted();
});
}
/// <summary>
/// Counts the number of completed <c>World</c>s.
/// </summary>
/// <returns>The number of completed <c>World</c>s and their inner completed
/// <c>World</c>s.</returns>
public static int GetCompletedWorldCount() {
return getRecursiveCount(InitialWorld, (World innerWorld) => {
return innerWorld.GetType() == typeof(World) && innerWorld.IsCompleted();
});
}
/// <summary>
/// Retrieves this instance of <c>SoomlaLevelUp</c>. Used when initializing SoomlaLevelUp.
/// </summary>
/// <returns>This instance of <c>SoomlaLevelUp</c>.</returns>
static SoomlaLevelUp Instance() {
if (instance == null) {
instance = new SoomlaLevelUp();
}
return instance;
}
/** PRIVATE FUNCTIONS **/
private SoomlaLevelUp() {}
static void save() {
string lu_json = toJSONObject().print();
SoomlaUtils.LogDebug(TAG, "saving SoomlaLevelUp to DB. json is: " + lu_json);
string key = DB_KEY_PREFIX + "model";
KeyValueStorage.SetValue(key, lu_json);
}
static JSONObject toJSONObject() {
JSONObject obj = new JSONObject(JSONObject.Type.OBJECT);
obj.AddField(LUJSONConsts.LU_MAIN_WORLD, InitialWorld.toJSONObject());
JSONObject rewardsArr = new JSONObject(JSONObject.Type.ARRAY);
foreach(Reward reward in Reward.GetRewards())
rewardsArr.Add(reward.toJSONObject());
obj.AddField(JSONConsts.SOOM_REWARDS, rewardsArr);
return obj;
}
static Score fetchScoreFromWorlds(string scoreId, Dictionary<string, World> worlds) {
Score retScore = null;
foreach (World world in worlds.Values) {
world.Scores.TryGetValue(scoreId, out retScore);
if (retScore == null) {
retScore = fetchScoreFromWorlds(scoreId, world.InnerWorldsMap);
}
if (retScore != null) {
break;
}
}
return retScore;
}
static World fetchWorld(string worldId, Dictionary<string, World> worlds) {
World retWorld;
worlds.TryGetValue(worldId, out retWorld);
if (retWorld == null) {
foreach (World world in worlds.Values) {
retWorld = fetchWorld(worldId, world.InnerWorldsMap);
if (retWorld != null) {
break;
}
}
}
return retWorld;
}
static Mission fetchMission(string missionId, IEnumerable<World> worlds) {
foreach (World world in worlds) {
Mission mission = fetchMission(missionId, world.Missions);
if (mission != null) {
return mission;
}
mission = fetchMission(missionId, world.InnerWorldsList);
if (mission != null) {
return mission;
}
}
return null;
}
static Mission fetchMission(string missionId, IEnumerable<Mission> missions) {
Mission retMission = null;
foreach (var mission in missions) {
retMission = fetchMission(missionId, mission);
if (retMission != null) {
return retMission;
}
}
return retMission;
}
static Mission fetchMission(string missionId, Mission targetMission) {
if (targetMission == null) {
return null;
}
if ((targetMission != null) && (targetMission.ID == missionId)) {
return targetMission;
}
Mission result = null;
Challenge challenge = targetMission as Challenge;
if (challenge != null) {
return fetchMission(missionId, challenge.Missions);
}
return result;
}
static Gate fetchGate(string gateId, IEnumerable<World> worlds) {
if (worlds == null) {
return null;
}
Gate retGate = null;
foreach (var world in worlds) {
retGate = fetchGate(gateId, world.Gate);
if (retGate != null) {
return retGate;
}
}
if (retGate == null) {
foreach (World world in worlds) {
retGate = fetchGate(gateId, world.Missions);
if (retGate != null) {
break;
}
retGate = fetchGate(gateId, world.InnerWorldsList);
if (retGate != null) {
break;
}
}
}
return retGate;
}
static Gate fetchGate(string gateId, List<Mission> missions) {
Gate retGate = null;
foreach (var mission in missions) {
retGate = fetchGate(gateId, mission.Gate);
if (retGate != null) {
return retGate;
}
}
if (retGate == null) {
foreach (Mission mission in missions) {
if (mission is Challenge) {
retGate = fetchGate(gateId, ((Challenge)mission).Missions);
if (retGate != null) {
break;
}
}
}
}
return retGate;
}
static Gate fetchGate(string gateId, Gate targetGate) {
if (targetGate == null) {
return null;
}
if ((targetGate != null) && (targetGate.ID == gateId)) {
return targetGate;
}
Gate result = null;
GatesList gatesList = targetGate as GatesList;
if (gatesList != null) {
for (int i = 0; i < gatesList.Count; i++) {
result = fetchGate(gateId, gatesList[i]);
if (result != null) {
return result;
}
}
}
return result;
}
static int getRecursiveCount(World world, Func<World, bool> isAccepted) {
int count = 0;
// If the predicate is true, increment
if (isAccepted(world)) {
count++;
}
foreach (World innerWorld in world.InnerWorldsMap.Values) {
// Recursively count for inner world
count += getRecursiveCount(innerWorld, isAccepted);
}
return count;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Routing;
using System.Xml;
using System.Xml.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Configuration
{
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
// we have this two tasks logged:
// http://issues.umbraco.org/issue/U4-58
// http://issues.umbraco.org/issue/U4-115
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
/// <summary>
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
/// </summary>
internal class GlobalSettings
{
#region Private static fields
private static Version _version;
private static readonly object Locker = new object();
//make this volatile so that we can ensure thread safety with a double check lock
private static volatile string _reservedUrlsCache;
private static string _reservedPathsCache;
private static StartsWithContainer _reservedList = new StartsWithContainer();
private static string _reservedPaths;
private static string _reservedUrls;
//ensure the built on (non-changeable) reserved paths are there at all times
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
#endregion
/// <summary>
/// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config)
/// </summary>
private static void ResetInternal()
{
_reservedUrlsCache = null;
_reservedPaths = null;
_reservedUrls = null;
}
/// <summary>
/// Resets settings that were set programmatically, to their initial values.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal static void Reset()
{
ResetInternal();
}
/// <summary>
/// Gets the reserved urls from web.config.
/// </summary>
/// <value>The reserved urls.</value>
public static string ReservedUrls
{
get
{
if (_reservedUrls == null)
{
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
: string.Empty;
//ensure the built on (non-changeable) reserved paths are there at all times
_reservedUrls = StaticReservedUrls + urls;
}
return _reservedUrls;
}
internal set { _reservedUrls = value; }
}
/// <summary>
/// Gets the reserved paths from web.config
/// </summary>
/// <value>The reserved paths.</value>
public static string ReservedPaths
{
get
{
if (_reservedPaths == null)
{
var reservedPaths = StaticReservedPaths;
//always add the umbraco path to the list
if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
&& !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace())
{
reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(',');
}
var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths")
? ConfigurationManager.AppSettings["umbracoReservedPaths"]
: string.Empty;
_reservedPaths = reservedPaths + allPaths;
}
return _reservedPaths;
}
internal set { _reservedPaths = value; }
}
/// <summary>
/// Gets the name of the content XML file.
/// </summary>
/// <value>The content XML.</value>
public static string ContentXmlFile
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML")
? ConfigurationManager.AppSettings["umbracoContentXML"]
: string.Empty;
}
}
/// <summary>
/// Gets the path to the storage directory (/data by default).
/// </summary>
/// <value>The storage directory.</value>
public static string StorageDirectory
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
: string.Empty;
}
}
/// <summary>
/// Gets the path to umbraco's root directory (/umbraco by default).
/// </summary>
/// <value>The path.</value>
public static string Path
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
: string.Empty;
}
}
/// <summary>
/// This returns the string of the MVC Area route.
/// </summary>
/// <remarks>
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
///
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
///
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
/// </remarks>
internal static string UmbracoMvcArea
{
get
{
if (Path.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
}
return Path.TrimStart(SystemDirectories.Root).TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
}
}
/// <summary>
/// Gets the path to umbraco's client directory (/umbraco_client by default).
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
/// folder since the CSS paths to images depend on it.
/// </summary>
/// <value>The path.</value>
public static string ClientPath
{
get
{
return Path + "/../umbraco_client";
}
}
/// <summary>
/// Gets the database connection string
/// </summary>
/// <value>The database connection string.</value>
[Obsolete("Use System.ConfigurationManager.ConnectionStrings to get the connection with the key Umbraco.Core.Configuration.GlobalSettings.UmbracoConnectionName instead")]
public static string DbDsn
{
get
{
var settings = ConfigurationManager.ConnectionStrings[UmbracoConnectionName];
var connectionString = string.Empty;
if (settings != null)
{
connectionString = settings.ConnectionString;
// The SqlCe connectionString is formatted slightly differently, so we need to updat it
if (settings.ProviderName.Contains("SqlServerCe"))
connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString);
}
return connectionString;
}
set
{
if (DbDsn != value)
{
if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower()))
{
ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection();
}
else
{
ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value);
}
}
}
}
public const string UmbracoConnectionName = "umbracoDbDSN";
public const string UmbracoMigrationName = "Umbraco";
/// <summary>
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
/// </summary>
/// <value>The configuration status.</value>
public static string ConfigurationStatus
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus")
? ConfigurationManager.AppSettings["umbracoConfigurationStatus"]
: string.Empty;
}
set
{
SaveSetting("umbracoConfigurationStatus", value);
}
}
/// <summary>
/// Saves a setting into the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be saved.</param>
/// <param name="value">Value of the setting to be saved.</param>
internal static void SaveSetting(string key, string value)
{
var fileName = GetFullWebConfigFileName();
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.Descendants("appSettings").Single();
// Update appSetting if it exists, or else create a new appSetting for the given key and value
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting == null)
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
else
setting.Attribute("value").Value = value;
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// Removes a setting from the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be removed.</param>
internal static void RemoveSetting(string key)
{
var fileName = GetFullWebConfigFileName();
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.Descendants("appSettings").Single();
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting != null)
{
setting.Remove();
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
}
private static string GetFullWebConfigFileName()
{
var webConfig = new WebConfigurationFileMap();
var vDir = FullpathToRoot;
foreach (VirtualDirectoryMapping v in webConfig.VirtualDirectories)
{
if (v.IsAppRoot)
vDir = v.PhysicalDirectory;
}
var fileName = System.IO.Path.Combine(vDir, "web.config");
return fileName;
}
/// <summary>
/// Gets the full path to root.
/// </summary>
/// <value>The fullpath to root.</value>
public static string FullpathToRoot
{
get { return IOHelper.GetRootDirectorySafe(); }
}
/// <summary>
/// Gets a value indicating whether umbraco is running in [debug mode].
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public static bool DebugMode
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoDebugMode"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the current version of umbraco is configured.
/// </summary>
/// <value><c>true</c> if configured; otherwise, <c>false</c>.</value>
public static bool Configured
{
get
{
try
{
string configStatus = ConfigurationStatus;
string currentVersion = UmbracoVersion.Current.ToString(3);
if (currentVersion != configStatus)
{
LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'");
}
return (configStatus == currentVersion);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the time out in minutes.
/// </summary>
/// <value>The time out in minutes.</value>
public static int TimeOutInMinutes
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]);
}
catch
{
return 20;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco uses directory urls.
/// </summary>
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
public static bool UseDirectoryUrls
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should skip version-checking.
/// </summary>
/// <value>The version check period in days (0 = never).</value>
public static int VersionCheckPeriod
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]);
}
catch
{
return 7;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should disbable xslt extensions
/// </summary>
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
public static string DisableXsltExtensions
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
: string.Empty;
}
}
/// <summary>
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
/// </summary>
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
public static string EditXhtmlMode
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoEditXhtmlMode")
? ConfigurationManager.AppSettings["umbracoEditXhtmlMode"]
: string.Empty;
}
}
/// <summary>
/// Gets the default UI language.
/// </summary>
/// <value>The default UI language.</value>
public static string DefaultUILanguage
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage")
? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]
: string.Empty;
}
}
/// <summary>
/// Gets the profile URL.
/// </summary>
/// <value>The profile URL.</value>
public static string ProfileUrl
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
: string.Empty;
}
}
/// <summary>
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
/// </summary>
/// <value>
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
/// </value>
public static bool HideTopLevelNodeFromPath
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the current version.
/// </summary>
/// <value>The current version.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string CurrentVersion
{
get
{
return UmbracoVersion.Current.ToString(3);
}
}
/// <summary>
/// Gets the major version number.
/// </summary>
/// <value>The major version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMajor
{
get
{
return UmbracoVersion.Current.Major;
}
}
/// <summary>
/// Gets the minor version number.
/// </summary>
/// <value>The minor version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMinor
{
get
{
return UmbracoVersion.Current.Minor;
}
}
/// <summary>
/// Gets the patch version number.
/// </summary>
/// <value>The patch version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionPatch
{
get
{
return UmbracoVersion.Current.Build;
}
}
/// <summary>
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string VersionComment
{
get
{
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
}
}
/// <summary>
/// Requests the is in umbraco application directory structure.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static bool RequestIsInUmbracoApplication(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsLiveEditRedirector(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1;
}
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsLiveEditRedirector(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1;
}
/// <summary>
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
/// </summary>
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
public static bool UseSSL
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the umbraco license.
/// </summary>
/// <value>The license.</value>
public static string License
{
get
{
string license =
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
var versionDoc = new XmlDocument();
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
versionDoc.Load(versionReader);
versionReader.Close();
// check for license
try
{
string licenseUrl =
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
string licenseValidation =
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
string licensedTo =
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
if (licensedTo != "" && licenseUrl != "")
{
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
licenseUrl;
}
}
catch
{
}
return license;
}
}
/// <summary>
/// Determines whether the current request is reserved based on the route table and
/// whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url"></param>
/// <param name="httpContext"></param>
/// <param name="routes">The route collection to lookup the request in</param>
/// <returns></returns>
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (routes == null) throw new ArgumentNullException("routes");
//check if the current request matches a route, if so then it is reserved.
var route = routes.GetRouteData(httpContext);
if (route != null)
return true;
//continue with the standard ignore routine
return IsReservedPathOrUrl(url);
}
/// <summary>
/// Determines whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <returns>
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
/// </returns>
public static bool IsReservedPathOrUrl(string url)
{
if (_reservedUrlsCache == null)
{
lock (Locker)
{
if (_reservedUrlsCache == null)
{
// store references to strings to determine changes
_reservedPathsCache = GlobalSettings.ReservedPaths;
_reservedUrlsCache = GlobalSettings.ReservedUrls;
string _root = SystemDirectories.Root.Trim().ToLower();
// add URLs and paths to a new list
StartsWithContainer _newReservedList = new StartsWithContainer();
foreach (string reservedUrl in _reservedUrlsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
//resolves the url to support tilde chars
string reservedUrlTrimmed = IOHelper.ResolveUrl(reservedUrl).Trim().ToLower();
if (reservedUrlTrimmed.Length > 0)
_newReservedList.Add(reservedUrlTrimmed);
}
foreach (string reservedPath in _reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
bool trimEnd = !reservedPath.EndsWith("/");
//resolves the url to support tilde chars
string reservedPathTrimmed = IOHelper.ResolveUrl(reservedPath).Trim().ToLower();
if (reservedPathTrimmed.Length > 0)
_newReservedList.Add(reservedPathTrimmed + (reservedPathTrimmed.EndsWith("/") ? "" : "/"));
}
// use the new list from now on
_reservedList = _newReservedList;
}
}
}
//The url should be cleaned up before checking:
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
// * We shouldn't be comparing the query at all
var pathPart = url.Split('?')[0];
if (!pathPart.Contains(".") && !pathPart.EndsWith("/"))
{
pathPart += "/";
}
// return true if url starts with an element of the reserved list
return _reservedList.StartsWith(pathPart.ToLowerInvariant());
}
/// <summary>
/// Structure that checks in logarithmic time
/// if a given string starts with one of the added keys.
/// </summary>
private class StartsWithContainer
{
/// <summary>Internal sorted list of keys.</summary>
public SortedList<string, string> _list
= new SortedList<string, string>(StartsWithComparator.Instance);
/// <summary>
/// Adds the specified new key.
/// </summary>
/// <param name="newKey">The new key.</param>
public void Add(string newKey)
{
// if the list already contains an element that begins with newKey, return
if (String.IsNullOrEmpty(newKey) || StartsWith(newKey))
return;
// create a new collection, so the old one can still be accessed
SortedList<string, string> newList
= new SortedList<string, string>(_list.Count + 1, StartsWithComparator.Instance);
// add only keys that don't already start with newKey, others are unnecessary
foreach (string key in _list.Keys)
if (!key.StartsWith(newKey))
newList.Add(key, null);
// add the new key
newList.Add(newKey, null);
// update the list (thread safe, _list was never in incomplete state)
_list = newList;
}
/// <summary>
/// Checks if the given string starts with any of the added keys.
/// </summary>
/// <param name="target">The target.</param>
/// <returns>true if a key is found that matches the start of target</returns>
/// <remarks>
/// Runs in O(s*log(n)), with n the number of keys and s the length of target.
/// </remarks>
public bool StartsWith(string target)
{
return _list.ContainsKey(target);
}
/// <summary>Comparator that tests if a string starts with another.</summary>
/// <remarks>Not a real comparator, since it is not reflexive. (x==y does not imply y==x)</remarks>
private sealed class StartsWithComparator : IComparer<string>
{
/// <summary>Default string comparer.</summary>
private readonly static Comparer<string> _stringComparer = Comparer<string>.Default;
/// <summary>Gets an instance of the StartsWithComparator.</summary>
public static readonly StartsWithComparator Instance = new StartsWithComparator();
/// <summary>
/// Tests if whole begins with all characters of part.
/// </summary>
/// <param name="part">The part.</param>
/// <param name="whole">The whole.</param>
/// <returns>
/// Returns 0 if whole starts with part, otherwise performs standard string comparison.
/// </returns>
public int Compare(string part, string whole)
{
// let the default string comparer deal with null or when part is not smaller then whole
if (part == null || whole == null || part.Length >= whole.Length)
return _stringComparer.Compare(part, whole);
////ensure both have a / on the end
//part = part.EndsWith("/") ? part : part + "/";
//whole = whole.EndsWith("/") ? whole : whole + "/";
//if (part.Length >= whole.Length)
// return _stringComparer.Compare(part, whole);
// loop through all characters that part and whole have in common
int pos = 0;
bool match;
do
{
match = (part[pos] == whole[pos]);
} while (match && ++pos < part.Length);
// return result of last comparison
return match ? 0 : (part[pos] < whole[pos] ? -1 : 1);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.